1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 70 // See if this is an aligned allocation/deallocation function that is 71 // unavailable. 72 if (TreatUnavailableAsInvalid && 73 isUnavailableAlignedAllocationFunction(*FD)) 74 return false; 75 } 76 77 // See if this function is unavailable. 78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 80 return false; 81 82 return true; 83 } 84 85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 86 // Warn if this is used but marked unused. 87 if (const auto *A = D->getAttr<UnusedAttr>()) { 88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 89 // should diagnose them. 90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 93 if (DC && !DC->hasAttr<UnusedAttr>()) 94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 95 } 96 } 97 } 98 99 /// Emit a note explaining that this function is deleted. 100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 101 assert(Decl->isDeleted()); 102 103 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 104 105 if (Method && Method->isDeleted() && Method->isDefaulted()) { 106 // If the method was explicitly defaulted, point at that declaration. 107 if (!Method->isImplicit()) 108 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 109 110 // Try to diagnose why this special member function was implicitly 111 // deleted. This might fail, if that reason no longer applies. 112 CXXSpecialMember CSM = getSpecialMember(Method); 113 if (CSM != CXXInvalid) 114 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 115 116 return; 117 } 118 119 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 120 if (Ctor && Ctor->isInheritingConstructor()) 121 return NoteDeletedInheritingConstructor(Ctor); 122 123 Diag(Decl->getLocation(), diag::note_availability_specified_here) 124 << Decl << 1; 125 } 126 127 /// Determine whether a FunctionDecl was ever declared with an 128 /// explicit storage class. 129 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 130 for (auto I : D->redecls()) { 131 if (I->getStorageClass() != SC_None) 132 return true; 133 } 134 return false; 135 } 136 137 /// Check whether we're in an extern inline function and referring to a 138 /// variable or function with internal linkage (C11 6.7.4p3). 139 /// 140 /// This is only a warning because we used to silently accept this code, but 141 /// in many cases it will not behave correctly. This is not enabled in C++ mode 142 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 143 /// and so while there may still be user mistakes, most of the time we can't 144 /// prove that there are errors. 145 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 146 const NamedDecl *D, 147 SourceLocation Loc) { 148 // This is disabled under C++; there are too many ways for this to fire in 149 // contexts where the warning is a false positive, or where it is technically 150 // correct but benign. 151 if (S.getLangOpts().CPlusPlus) 152 return; 153 154 // Check if this is an inlined function or method. 155 FunctionDecl *Current = S.getCurFunctionDecl(); 156 if (!Current) 157 return; 158 if (!Current->isInlined()) 159 return; 160 if (!Current->isExternallyVisible()) 161 return; 162 163 // Check if the decl has internal linkage. 164 if (D->getFormalLinkage() != InternalLinkage) 165 return; 166 167 // Downgrade from ExtWarn to Extension if 168 // (1) the supposedly external inline function is in the main file, 169 // and probably won't be included anywhere else. 170 // (2) the thing we're referencing is a pure function. 171 // (3) the thing we're referencing is another inline function. 172 // This last can give us false negatives, but it's better than warning on 173 // wrappers for simple C library functions. 174 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 175 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 176 if (!DowngradeWarning && UsedFn) 177 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 178 179 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 180 : diag::ext_internal_in_extern_inline) 181 << /*IsVar=*/!UsedFn << D; 182 183 S.MaybeSuggestAddingStaticToDecl(Current); 184 185 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 186 << D; 187 } 188 189 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 190 const FunctionDecl *First = Cur->getFirstDecl(); 191 192 // Suggest "static" on the function, if possible. 193 if (!hasAnyExplicitStorageClass(First)) { 194 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 195 Diag(DeclBegin, diag::note_convert_inline_to_static) 196 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 197 } 198 } 199 200 /// Determine whether the use of this declaration is valid, and 201 /// emit any corresponding diagnostics. 202 /// 203 /// This routine diagnoses various problems with referencing 204 /// declarations that can occur when using a declaration. For example, 205 /// it might warn if a deprecated or unavailable declaration is being 206 /// used, or produce an error (and return true) if a C++0x deleted 207 /// function is being used. 208 /// 209 /// \returns true if there was an error (this declaration cannot be 210 /// referenced), false otherwise. 211 /// 212 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 213 const ObjCInterfaceDecl *UnknownObjCClass, 214 bool ObjCPropertyAccess, 215 bool AvoidPartialAvailabilityChecks, 216 ObjCInterfaceDecl *ClassReceiver) { 217 SourceLocation Loc = Locs.front(); 218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 219 // If there were any diagnostics suppressed by template argument deduction, 220 // emit them now. 221 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 222 if (Pos != SuppressedDiagnostics.end()) { 223 for (const PartialDiagnosticAt &Suppressed : Pos->second) 224 Diag(Suppressed.first, Suppressed.second); 225 226 // Clear out the list of suppressed diagnostics, so that we don't emit 227 // them again for this specialization. However, we don't obsolete this 228 // entry from the table, because we want to avoid ever emitting these 229 // diagnostics again. 230 Pos->second.clear(); 231 } 232 233 // C++ [basic.start.main]p3: 234 // The function 'main' shall not be used within a program. 235 if (cast<FunctionDecl>(D)->isMain()) 236 Diag(Loc, diag::ext_main_used); 237 238 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 239 } 240 241 // See if this is an auto-typed variable whose initializer we are parsing. 242 if (ParsingInitForAutoVars.count(D)) { 243 if (isa<BindingDecl>(D)) { 244 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 245 << D->getDeclName(); 246 } else { 247 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 248 << D->getDeclName() << cast<VarDecl>(D)->getType(); 249 } 250 return true; 251 } 252 253 // See if this is a deleted function. 254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 255 if (FD->isDeleted()) { 256 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 257 if (Ctor && Ctor->isInheritingConstructor()) 258 Diag(Loc, diag::err_deleted_inherited_ctor_use) 259 << Ctor->getParent() 260 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 261 else 262 Diag(Loc, diag::err_deleted_function_use); 263 NoteDeletedFunction(FD); 264 return true; 265 } 266 267 // If the function has a deduced return type, and we can't deduce it, 268 // then we can't use it either. 269 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 270 DeduceReturnType(FD, Loc)) 271 return true; 272 273 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 274 return true; 275 } 276 277 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 278 // Lambdas are only default-constructible or assignable in C++2a onwards. 279 if (MD->getParent()->isLambda() && 280 ((isa<CXXConstructorDecl>(MD) && 281 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 282 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 283 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 284 << !isa<CXXConstructorDecl>(MD); 285 } 286 } 287 288 auto getReferencedObjCProp = [](const NamedDecl *D) -> 289 const ObjCPropertyDecl * { 290 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 291 return MD->findPropertyDecl(); 292 return nullptr; 293 }; 294 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 295 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 296 return true; 297 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 298 return true; 299 } 300 301 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 302 // Only the variables omp_in and omp_out are allowed in the combiner. 303 // Only the variables omp_priv and omp_orig are allowed in the 304 // initializer-clause. 305 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 306 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 307 isa<VarDecl>(D)) { 308 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 309 << getCurFunction()->HasOMPDeclareReductionCombiner; 310 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 311 return true; 312 } 313 314 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 315 // List-items in map clauses on this construct may only refer to the declared 316 // variable var and entities that could be referenced by a procedure defined 317 // at the same location 318 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 319 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 320 isa<VarDecl>(D)) { 321 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 322 << DMD->getVarName().getAsString(); 323 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 324 return true; 325 } 326 327 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 328 AvoidPartialAvailabilityChecks, ClassReceiver); 329 330 DiagnoseUnusedOfDecl(*this, D, Loc); 331 332 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 333 334 return false; 335 } 336 337 /// DiagnoseSentinelCalls - This routine checks whether a call or 338 /// message-send is to a declaration with the sentinel attribute, and 339 /// if so, it checks that the requirements of the sentinel are 340 /// satisfied. 341 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 342 ArrayRef<Expr *> Args) { 343 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 344 if (!attr) 345 return; 346 347 // The number of formal parameters of the declaration. 348 unsigned numFormalParams; 349 350 // The kind of declaration. This is also an index into a %select in 351 // the diagnostic. 352 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 353 354 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 355 numFormalParams = MD->param_size(); 356 calleeType = CT_Method; 357 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 358 numFormalParams = FD->param_size(); 359 calleeType = CT_Function; 360 } else if (isa<VarDecl>(D)) { 361 QualType type = cast<ValueDecl>(D)->getType(); 362 const FunctionType *fn = nullptr; 363 if (const PointerType *ptr = type->getAs<PointerType>()) { 364 fn = ptr->getPointeeType()->getAs<FunctionType>(); 365 if (!fn) return; 366 calleeType = CT_Function; 367 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 368 fn = ptr->getPointeeType()->castAs<FunctionType>(); 369 calleeType = CT_Block; 370 } else { 371 return; 372 } 373 374 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 375 numFormalParams = proto->getNumParams(); 376 } else { 377 numFormalParams = 0; 378 } 379 } else { 380 return; 381 } 382 383 // "nullPos" is the number of formal parameters at the end which 384 // effectively count as part of the variadic arguments. This is 385 // useful if you would prefer to not have *any* formal parameters, 386 // but the language forces you to have at least one. 387 unsigned nullPos = attr->getNullPos(); 388 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 389 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 390 391 // The number of arguments which should follow the sentinel. 392 unsigned numArgsAfterSentinel = attr->getSentinel(); 393 394 // If there aren't enough arguments for all the formal parameters, 395 // the sentinel, and the args after the sentinel, complain. 396 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 397 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 398 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 399 return; 400 } 401 402 // Otherwise, find the sentinel expression. 403 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 404 if (!sentinelExpr) return; 405 if (sentinelExpr->isValueDependent()) return; 406 if (Context.isSentinelNullExpr(sentinelExpr)) return; 407 408 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 409 // or 'NULL' if those are actually defined in the context. Only use 410 // 'nil' for ObjC methods, where it's much more likely that the 411 // variadic arguments form a list of object pointers. 412 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 413 std::string NullValue; 414 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 415 NullValue = "nil"; 416 else if (getLangOpts().CPlusPlus11) 417 NullValue = "nullptr"; 418 else if (PP.isMacroDefined("NULL")) 419 NullValue = "NULL"; 420 else 421 NullValue = "(void*) 0"; 422 423 if (MissingNilLoc.isInvalid()) 424 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 425 else 426 Diag(MissingNilLoc, diag::warn_missing_sentinel) 427 << int(calleeType) 428 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 429 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 430 } 431 432 SourceRange Sema::getExprRange(Expr *E) const { 433 return E ? E->getSourceRange() : SourceRange(); 434 } 435 436 //===----------------------------------------------------------------------===// 437 // Standard Promotions and Conversions 438 //===----------------------------------------------------------------------===// 439 440 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 441 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 442 // Handle any placeholder expressions which made it here. 443 if (E->getType()->isPlaceholderType()) { 444 ExprResult result = CheckPlaceholderExpr(E); 445 if (result.isInvalid()) return ExprError(); 446 E = result.get(); 447 } 448 449 QualType Ty = E->getType(); 450 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 451 452 if (Ty->isFunctionType()) { 453 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 454 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 455 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 456 return ExprError(); 457 458 E = ImpCastExprToType(E, Context.getPointerType(Ty), 459 CK_FunctionToPointerDecay).get(); 460 } else if (Ty->isArrayType()) { 461 // In C90 mode, arrays only promote to pointers if the array expression is 462 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 463 // type 'array of type' is converted to an expression that has type 'pointer 464 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 465 // that has type 'array of type' ...". The relevant change is "an lvalue" 466 // (C90) to "an expression" (C99). 467 // 468 // C++ 4.2p1: 469 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 470 // T" can be converted to an rvalue of type "pointer to T". 471 // 472 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 473 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 474 CK_ArrayToPointerDecay).get(); 475 } 476 return E; 477 } 478 479 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 480 // Check to see if we are dereferencing a null pointer. If so, 481 // and if not volatile-qualified, this is undefined behavior that the 482 // optimizer will delete, so warn about it. People sometimes try to use this 483 // to get a deterministic trap and are surprised by clang's behavior. This 484 // only handles the pattern "*null", which is a very syntactic check. 485 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 486 if (UO && UO->getOpcode() == UO_Deref && 487 UO->getSubExpr()->getType()->isPointerType()) { 488 const LangAS AS = 489 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 490 if ((!isTargetAddressSpace(AS) || 491 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 492 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 493 S.Context, Expr::NPC_ValueDependentIsNotNull) && 494 !UO->getType().isVolatileQualified()) { 495 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 496 S.PDiag(diag::warn_indirection_through_null) 497 << UO->getSubExpr()->getSourceRange()); 498 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 499 S.PDiag(diag::note_indirection_through_null)); 500 } 501 } 502 } 503 504 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 505 SourceLocation AssignLoc, 506 const Expr* RHS) { 507 const ObjCIvarDecl *IV = OIRE->getDecl(); 508 if (!IV) 509 return; 510 511 DeclarationName MemberName = IV->getDeclName(); 512 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 513 if (!Member || !Member->isStr("isa")) 514 return; 515 516 const Expr *Base = OIRE->getBase(); 517 QualType BaseType = Base->getType(); 518 if (OIRE->isArrow()) 519 BaseType = BaseType->getPointeeType(); 520 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 521 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 522 ObjCInterfaceDecl *ClassDeclared = nullptr; 523 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 524 if (!ClassDeclared->getSuperClass() 525 && (*ClassDeclared->ivar_begin()) == IV) { 526 if (RHS) { 527 NamedDecl *ObjectSetClass = 528 S.LookupSingleName(S.TUScope, 529 &S.Context.Idents.get("object_setClass"), 530 SourceLocation(), S.LookupOrdinaryName); 531 if (ObjectSetClass) { 532 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 533 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 534 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 535 "object_setClass(") 536 << FixItHint::CreateReplacement( 537 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 538 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 539 } 540 else 541 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 542 } else { 543 NamedDecl *ObjectGetClass = 544 S.LookupSingleName(S.TUScope, 545 &S.Context.Idents.get("object_getClass"), 546 SourceLocation(), S.LookupOrdinaryName); 547 if (ObjectGetClass) 548 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 549 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 550 "object_getClass(") 551 << FixItHint::CreateReplacement( 552 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 553 else 554 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 555 } 556 S.Diag(IV->getLocation(), diag::note_ivar_decl); 557 } 558 } 559 } 560 561 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 562 // Handle any placeholder expressions which made it here. 563 if (E->getType()->isPlaceholderType()) { 564 ExprResult result = CheckPlaceholderExpr(E); 565 if (result.isInvalid()) return ExprError(); 566 E = result.get(); 567 } 568 569 // C++ [conv.lval]p1: 570 // A glvalue of a non-function, non-array type T can be 571 // converted to a prvalue. 572 if (!E->isGLValue()) return E; 573 574 QualType T = E->getType(); 575 assert(!T.isNull() && "r-value conversion on typeless expression?"); 576 577 // We don't want to throw lvalue-to-rvalue casts on top of 578 // expressions of certain types in C++. 579 if (getLangOpts().CPlusPlus && 580 (E->getType() == Context.OverloadTy || 581 T->isDependentType() || 582 T->isRecordType())) 583 return E; 584 585 // The C standard is actually really unclear on this point, and 586 // DR106 tells us what the result should be but not why. It's 587 // generally best to say that void types just doesn't undergo 588 // lvalue-to-rvalue at all. Note that expressions of unqualified 589 // 'void' type are never l-values, but qualified void can be. 590 if (T->isVoidType()) 591 return E; 592 593 // OpenCL usually rejects direct accesses to values of 'half' type. 594 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 595 T->isHalfType()) { 596 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 597 << 0 << T; 598 return ExprError(); 599 } 600 601 CheckForNullPointerDereference(*this, E); 602 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 603 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 604 &Context.Idents.get("object_getClass"), 605 SourceLocation(), LookupOrdinaryName); 606 if (ObjectGetClass) 607 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 608 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 609 << FixItHint::CreateReplacement( 610 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 611 else 612 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 613 } 614 else if (const ObjCIvarRefExpr *OIRE = 615 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 616 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 617 618 // C++ [conv.lval]p1: 619 // [...] If T is a non-class type, the type of the prvalue is the 620 // cv-unqualified version of T. Otherwise, the type of the 621 // rvalue is T. 622 // 623 // C99 6.3.2.1p2: 624 // If the lvalue has qualified type, the value has the unqualified 625 // version of the type of the lvalue; otherwise, the value has the 626 // type of the lvalue. 627 if (T.hasQualifiers()) 628 T = T.getUnqualifiedType(); 629 630 // Under the MS ABI, lock down the inheritance model now. 631 if (T->isMemberPointerType() && 632 Context.getTargetInfo().getCXXABI().isMicrosoft()) 633 (void)isCompleteType(E->getExprLoc(), T); 634 635 ExprResult Res = CheckLValueToRValueConversionOperand(E); 636 if (Res.isInvalid()) 637 return Res; 638 E = Res.get(); 639 640 // Loading a __weak object implicitly retains the value, so we need a cleanup to 641 // balance that. 642 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 643 Cleanup.setExprNeedsCleanups(true); 644 645 // C++ [conv.lval]p3: 646 // If T is cv std::nullptr_t, the result is a null pointer constant. 647 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 648 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 649 650 // C11 6.3.2.1p2: 651 // ... if the lvalue has atomic type, the value has the non-atomic version 652 // of the type of the lvalue ... 653 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 654 T = Atomic->getValueType().getUnqualifiedType(); 655 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 656 nullptr, VK_RValue); 657 } 658 659 return Res; 660 } 661 662 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 663 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 664 if (Res.isInvalid()) 665 return ExprError(); 666 Res = DefaultLvalueConversion(Res.get()); 667 if (Res.isInvalid()) 668 return ExprError(); 669 return Res; 670 } 671 672 /// CallExprUnaryConversions - a special case of an unary conversion 673 /// performed on a function designator of a call expression. 674 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 675 QualType Ty = E->getType(); 676 ExprResult Res = E; 677 // Only do implicit cast for a function type, but not for a pointer 678 // to function type. 679 if (Ty->isFunctionType()) { 680 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 681 CK_FunctionToPointerDecay).get(); 682 if (Res.isInvalid()) 683 return ExprError(); 684 } 685 Res = DefaultLvalueConversion(Res.get()); 686 if (Res.isInvalid()) 687 return ExprError(); 688 return Res.get(); 689 } 690 691 /// UsualUnaryConversions - Performs various conversions that are common to most 692 /// operators (C99 6.3). The conversions of array and function types are 693 /// sometimes suppressed. For example, the array->pointer conversion doesn't 694 /// apply if the array is an argument to the sizeof or address (&) operators. 695 /// In these instances, this routine should *not* be called. 696 ExprResult Sema::UsualUnaryConversions(Expr *E) { 697 // First, convert to an r-value. 698 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 699 if (Res.isInvalid()) 700 return ExprError(); 701 E = Res.get(); 702 703 QualType Ty = E->getType(); 704 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 705 706 // Half FP have to be promoted to float unless it is natively supported 707 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 708 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 709 710 // Try to perform integral promotions if the object has a theoretically 711 // promotable type. 712 if (Ty->isIntegralOrUnscopedEnumerationType()) { 713 // C99 6.3.1.1p2: 714 // 715 // The following may be used in an expression wherever an int or 716 // unsigned int may be used: 717 // - an object or expression with an integer type whose integer 718 // conversion rank is less than or equal to the rank of int 719 // and unsigned int. 720 // - A bit-field of type _Bool, int, signed int, or unsigned int. 721 // 722 // If an int can represent all values of the original type, the 723 // value is converted to an int; otherwise, it is converted to an 724 // unsigned int. These are called the integer promotions. All 725 // other types are unchanged by the integer promotions. 726 727 QualType PTy = Context.isPromotableBitField(E); 728 if (!PTy.isNull()) { 729 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 730 return E; 731 } 732 if (Ty->isPromotableIntegerType()) { 733 QualType PT = Context.getPromotedIntegerType(Ty); 734 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 735 return E; 736 } 737 } 738 return E; 739 } 740 741 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 742 /// do not have a prototype. Arguments that have type float or __fp16 743 /// are promoted to double. All other argument types are converted by 744 /// UsualUnaryConversions(). 745 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 746 QualType Ty = E->getType(); 747 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 748 749 ExprResult Res = UsualUnaryConversions(E); 750 if (Res.isInvalid()) 751 return ExprError(); 752 E = Res.get(); 753 754 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 755 // promote to double. 756 // Note that default argument promotion applies only to float (and 757 // half/fp16); it does not apply to _Float16. 758 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 759 if (BTy && (BTy->getKind() == BuiltinType::Half || 760 BTy->getKind() == BuiltinType::Float)) { 761 if (getLangOpts().OpenCL && 762 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 763 if (BTy->getKind() == BuiltinType::Half) { 764 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 765 } 766 } else { 767 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 768 } 769 } 770 771 // C++ performs lvalue-to-rvalue conversion as a default argument 772 // promotion, even on class types, but note: 773 // C++11 [conv.lval]p2: 774 // When an lvalue-to-rvalue conversion occurs in an unevaluated 775 // operand or a subexpression thereof the value contained in the 776 // referenced object is not accessed. Otherwise, if the glvalue 777 // has a class type, the conversion copy-initializes a temporary 778 // of type T from the glvalue and the result of the conversion 779 // is a prvalue for the temporary. 780 // FIXME: add some way to gate this entire thing for correctness in 781 // potentially potentially evaluated contexts. 782 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 783 ExprResult Temp = PerformCopyInitialization( 784 InitializedEntity::InitializeTemporary(E->getType()), 785 E->getExprLoc(), E); 786 if (Temp.isInvalid()) 787 return ExprError(); 788 E = Temp.get(); 789 } 790 791 return E; 792 } 793 794 /// Determine the degree of POD-ness for an expression. 795 /// Incomplete types are considered POD, since this check can be performed 796 /// when we're in an unevaluated context. 797 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 798 if (Ty->isIncompleteType()) { 799 // C++11 [expr.call]p7: 800 // After these conversions, if the argument does not have arithmetic, 801 // enumeration, pointer, pointer to member, or class type, the program 802 // is ill-formed. 803 // 804 // Since we've already performed array-to-pointer and function-to-pointer 805 // decay, the only such type in C++ is cv void. This also handles 806 // initializer lists as variadic arguments. 807 if (Ty->isVoidType()) 808 return VAK_Invalid; 809 810 if (Ty->isObjCObjectType()) 811 return VAK_Invalid; 812 return VAK_Valid; 813 } 814 815 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 816 return VAK_Invalid; 817 818 if (Ty.isCXX98PODType(Context)) 819 return VAK_Valid; 820 821 // C++11 [expr.call]p7: 822 // Passing a potentially-evaluated argument of class type (Clause 9) 823 // having a non-trivial copy constructor, a non-trivial move constructor, 824 // or a non-trivial destructor, with no corresponding parameter, 825 // is conditionally-supported with implementation-defined semantics. 826 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 827 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 828 if (!Record->hasNonTrivialCopyConstructor() && 829 !Record->hasNonTrivialMoveConstructor() && 830 !Record->hasNonTrivialDestructor()) 831 return VAK_ValidInCXX11; 832 833 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 834 return VAK_Valid; 835 836 if (Ty->isObjCObjectType()) 837 return VAK_Invalid; 838 839 if (getLangOpts().MSVCCompat) 840 return VAK_MSVCUndefined; 841 842 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 843 // permitted to reject them. We should consider doing so. 844 return VAK_Undefined; 845 } 846 847 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 848 // Don't allow one to pass an Objective-C interface to a vararg. 849 const QualType &Ty = E->getType(); 850 VarArgKind VAK = isValidVarArgType(Ty); 851 852 // Complain about passing non-POD types through varargs. 853 switch (VAK) { 854 case VAK_ValidInCXX11: 855 DiagRuntimeBehavior( 856 E->getBeginLoc(), nullptr, 857 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 858 LLVM_FALLTHROUGH; 859 case VAK_Valid: 860 if (Ty->isRecordType()) { 861 // This is unlikely to be what the user intended. If the class has a 862 // 'c_str' member function, the user probably meant to call that. 863 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 864 PDiag(diag::warn_pass_class_arg_to_vararg) 865 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 866 } 867 break; 868 869 case VAK_Undefined: 870 case VAK_MSVCUndefined: 871 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 872 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 873 << getLangOpts().CPlusPlus11 << Ty << CT); 874 break; 875 876 case VAK_Invalid: 877 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 878 Diag(E->getBeginLoc(), 879 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 880 << Ty << CT; 881 else if (Ty->isObjCObjectType()) 882 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 883 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 884 << Ty << CT); 885 else 886 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 887 << isa<InitListExpr>(E) << Ty << CT; 888 break; 889 } 890 } 891 892 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 893 /// will create a trap if the resulting type is not a POD type. 894 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 895 FunctionDecl *FDecl) { 896 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 897 // Strip the unbridged-cast placeholder expression off, if applicable. 898 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 899 (CT == VariadicMethod || 900 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 901 E = stripARCUnbridgedCast(E); 902 903 // Otherwise, do normal placeholder checking. 904 } else { 905 ExprResult ExprRes = CheckPlaceholderExpr(E); 906 if (ExprRes.isInvalid()) 907 return ExprError(); 908 E = ExprRes.get(); 909 } 910 } 911 912 ExprResult ExprRes = DefaultArgumentPromotion(E); 913 if (ExprRes.isInvalid()) 914 return ExprError(); 915 E = ExprRes.get(); 916 917 // Diagnostics regarding non-POD argument types are 918 // emitted along with format string checking in Sema::CheckFunctionCall(). 919 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 920 // Turn this into a trap. 921 CXXScopeSpec SS; 922 SourceLocation TemplateKWLoc; 923 UnqualifiedId Name; 924 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 925 E->getBeginLoc()); 926 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 927 /*HasTrailingLParen=*/true, 928 /*IsAddressOfOperand=*/false); 929 if (TrapFn.isInvalid()) 930 return ExprError(); 931 932 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 933 None, E->getEndLoc()); 934 if (Call.isInvalid()) 935 return ExprError(); 936 937 ExprResult Comma = 938 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 939 if (Comma.isInvalid()) 940 return ExprError(); 941 return Comma.get(); 942 } 943 944 if (!getLangOpts().CPlusPlus && 945 RequireCompleteType(E->getExprLoc(), E->getType(), 946 diag::err_call_incomplete_argument)) 947 return ExprError(); 948 949 return E; 950 } 951 952 /// Converts an integer to complex float type. Helper function of 953 /// UsualArithmeticConversions() 954 /// 955 /// \return false if the integer expression is an integer type and is 956 /// successfully converted to the complex type. 957 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 958 ExprResult &ComplexExpr, 959 QualType IntTy, 960 QualType ComplexTy, 961 bool SkipCast) { 962 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 963 if (SkipCast) return false; 964 if (IntTy->isIntegerType()) { 965 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 966 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 967 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 968 CK_FloatingRealToComplex); 969 } else { 970 assert(IntTy->isComplexIntegerType()); 971 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 972 CK_IntegralComplexToFloatingComplex); 973 } 974 return false; 975 } 976 977 /// Handle arithmetic conversion with complex types. Helper function of 978 /// UsualArithmeticConversions() 979 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 980 ExprResult &RHS, QualType LHSType, 981 QualType RHSType, 982 bool IsCompAssign) { 983 // if we have an integer operand, the result is the complex type. 984 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 985 /*skipCast*/false)) 986 return LHSType; 987 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 988 /*skipCast*/IsCompAssign)) 989 return RHSType; 990 991 // This handles complex/complex, complex/float, or float/complex. 992 // When both operands are complex, the shorter operand is converted to the 993 // type of the longer, and that is the type of the result. This corresponds 994 // to what is done when combining two real floating-point operands. 995 // The fun begins when size promotion occur across type domains. 996 // From H&S 6.3.4: When one operand is complex and the other is a real 997 // floating-point type, the less precise type is converted, within it's 998 // real or complex domain, to the precision of the other type. For example, 999 // when combining a "long double" with a "double _Complex", the 1000 // "double _Complex" is promoted to "long double _Complex". 1001 1002 // Compute the rank of the two types, regardless of whether they are complex. 1003 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1004 1005 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1006 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1007 QualType LHSElementType = 1008 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1009 QualType RHSElementType = 1010 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1011 1012 QualType ResultType = S.Context.getComplexType(LHSElementType); 1013 if (Order < 0) { 1014 // Promote the precision of the LHS if not an assignment. 1015 ResultType = S.Context.getComplexType(RHSElementType); 1016 if (!IsCompAssign) { 1017 if (LHSComplexType) 1018 LHS = 1019 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1020 else 1021 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1022 } 1023 } else if (Order > 0) { 1024 // Promote the precision of the RHS. 1025 if (RHSComplexType) 1026 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1027 else 1028 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1029 } 1030 return ResultType; 1031 } 1032 1033 /// Handle arithmetic conversion from integer to float. Helper function 1034 /// of UsualArithmeticConversions() 1035 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1036 ExprResult &IntExpr, 1037 QualType FloatTy, QualType IntTy, 1038 bool ConvertFloat, bool ConvertInt) { 1039 if (IntTy->isIntegerType()) { 1040 if (ConvertInt) 1041 // Convert intExpr to the lhs floating point type. 1042 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1043 CK_IntegralToFloating); 1044 return FloatTy; 1045 } 1046 1047 // Convert both sides to the appropriate complex float. 1048 assert(IntTy->isComplexIntegerType()); 1049 QualType result = S.Context.getComplexType(FloatTy); 1050 1051 // _Complex int -> _Complex float 1052 if (ConvertInt) 1053 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1054 CK_IntegralComplexToFloatingComplex); 1055 1056 // float -> _Complex float 1057 if (ConvertFloat) 1058 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1059 CK_FloatingRealToComplex); 1060 1061 return result; 1062 } 1063 1064 /// Handle arithmethic conversion with floating point types. Helper 1065 /// function of UsualArithmeticConversions() 1066 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1067 ExprResult &RHS, QualType LHSType, 1068 QualType RHSType, bool IsCompAssign) { 1069 bool LHSFloat = LHSType->isRealFloatingType(); 1070 bool RHSFloat = RHSType->isRealFloatingType(); 1071 1072 // If we have two real floating types, convert the smaller operand 1073 // to the bigger result. 1074 if (LHSFloat && RHSFloat) { 1075 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1076 if (order > 0) { 1077 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1078 return LHSType; 1079 } 1080 1081 assert(order < 0 && "illegal float comparison"); 1082 if (!IsCompAssign) 1083 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1084 return RHSType; 1085 } 1086 1087 if (LHSFloat) { 1088 // Half FP has to be promoted to float unless it is natively supported 1089 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1090 LHSType = S.Context.FloatTy; 1091 1092 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1093 /*ConvertFloat=*/!IsCompAssign, 1094 /*ConvertInt=*/ true); 1095 } 1096 assert(RHSFloat); 1097 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1098 /*convertInt=*/ true, 1099 /*convertFloat=*/!IsCompAssign); 1100 } 1101 1102 /// Diagnose attempts to convert between __float128 and long double if 1103 /// there is no support for such conversion. Helper function of 1104 /// UsualArithmeticConversions(). 1105 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1106 QualType RHSType) { 1107 /* No issue converting if at least one of the types is not a floating point 1108 type or the two types have the same rank. 1109 */ 1110 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1111 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1112 return false; 1113 1114 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1115 "The remaining types must be floating point types."); 1116 1117 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1118 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1119 1120 QualType LHSElemType = LHSComplex ? 1121 LHSComplex->getElementType() : LHSType; 1122 QualType RHSElemType = RHSComplex ? 1123 RHSComplex->getElementType() : RHSType; 1124 1125 // No issue if the two types have the same representation 1126 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1127 &S.Context.getFloatTypeSemantics(RHSElemType)) 1128 return false; 1129 1130 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1131 RHSElemType == S.Context.LongDoubleTy); 1132 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1133 RHSElemType == S.Context.Float128Ty); 1134 1135 // We've handled the situation where __float128 and long double have the same 1136 // representation. We allow all conversions for all possible long double types 1137 // except PPC's double double. 1138 return Float128AndLongDouble && 1139 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1140 &llvm::APFloat::PPCDoubleDouble()); 1141 } 1142 1143 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1144 1145 namespace { 1146 /// These helper callbacks are placed in an anonymous namespace to 1147 /// permit their use as function template parameters. 1148 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1149 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1150 } 1151 1152 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1153 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1154 CK_IntegralComplexCast); 1155 } 1156 } 1157 1158 /// Handle integer arithmetic conversions. Helper function of 1159 /// UsualArithmeticConversions() 1160 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1161 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1162 ExprResult &RHS, QualType LHSType, 1163 QualType RHSType, bool IsCompAssign) { 1164 // The rules for this case are in C99 6.3.1.8 1165 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1166 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1167 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1168 if (LHSSigned == RHSSigned) { 1169 // Same signedness; use the higher-ranked type 1170 if (order >= 0) { 1171 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1172 return LHSType; 1173 } else if (!IsCompAssign) 1174 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1175 return RHSType; 1176 } else if (order != (LHSSigned ? 1 : -1)) { 1177 // The unsigned type has greater than or equal rank to the 1178 // signed type, so use the unsigned type 1179 if (RHSSigned) { 1180 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1181 return LHSType; 1182 } else if (!IsCompAssign) 1183 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1184 return RHSType; 1185 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1186 // The two types are different widths; if we are here, that 1187 // means the signed type is larger than the unsigned type, so 1188 // use the signed type. 1189 if (LHSSigned) { 1190 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1191 return LHSType; 1192 } else if (!IsCompAssign) 1193 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1194 return RHSType; 1195 } else { 1196 // The signed type is higher-ranked than the unsigned type, 1197 // but isn't actually any bigger (like unsigned int and long 1198 // on most 32-bit systems). Use the unsigned type corresponding 1199 // to the signed type. 1200 QualType result = 1201 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1202 RHS = (*doRHSCast)(S, RHS.get(), result); 1203 if (!IsCompAssign) 1204 LHS = (*doLHSCast)(S, LHS.get(), result); 1205 return result; 1206 } 1207 } 1208 1209 /// Handle conversions with GCC complex int extension. Helper function 1210 /// of UsualArithmeticConversions() 1211 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1212 ExprResult &RHS, QualType LHSType, 1213 QualType RHSType, 1214 bool IsCompAssign) { 1215 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1216 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1217 1218 if (LHSComplexInt && RHSComplexInt) { 1219 QualType LHSEltType = LHSComplexInt->getElementType(); 1220 QualType RHSEltType = RHSComplexInt->getElementType(); 1221 QualType ScalarType = 1222 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1223 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1224 1225 return S.Context.getComplexType(ScalarType); 1226 } 1227 1228 if (LHSComplexInt) { 1229 QualType LHSEltType = LHSComplexInt->getElementType(); 1230 QualType ScalarType = 1231 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1232 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1233 QualType ComplexType = S.Context.getComplexType(ScalarType); 1234 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1235 CK_IntegralRealToComplex); 1236 1237 return ComplexType; 1238 } 1239 1240 assert(RHSComplexInt); 1241 1242 QualType RHSEltType = RHSComplexInt->getElementType(); 1243 QualType ScalarType = 1244 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1245 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1246 QualType ComplexType = S.Context.getComplexType(ScalarType); 1247 1248 if (!IsCompAssign) 1249 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1250 CK_IntegralRealToComplex); 1251 return ComplexType; 1252 } 1253 1254 /// Return the rank of a given fixed point or integer type. The value itself 1255 /// doesn't matter, but the values must be increasing with proper increasing 1256 /// rank as described in N1169 4.1.1. 1257 static unsigned GetFixedPointRank(QualType Ty) { 1258 const auto *BTy = Ty->getAs<BuiltinType>(); 1259 assert(BTy && "Expected a builtin type."); 1260 1261 switch (BTy->getKind()) { 1262 case BuiltinType::ShortFract: 1263 case BuiltinType::UShortFract: 1264 case BuiltinType::SatShortFract: 1265 case BuiltinType::SatUShortFract: 1266 return 1; 1267 case BuiltinType::Fract: 1268 case BuiltinType::UFract: 1269 case BuiltinType::SatFract: 1270 case BuiltinType::SatUFract: 1271 return 2; 1272 case BuiltinType::LongFract: 1273 case BuiltinType::ULongFract: 1274 case BuiltinType::SatLongFract: 1275 case BuiltinType::SatULongFract: 1276 return 3; 1277 case BuiltinType::ShortAccum: 1278 case BuiltinType::UShortAccum: 1279 case BuiltinType::SatShortAccum: 1280 case BuiltinType::SatUShortAccum: 1281 return 4; 1282 case BuiltinType::Accum: 1283 case BuiltinType::UAccum: 1284 case BuiltinType::SatAccum: 1285 case BuiltinType::SatUAccum: 1286 return 5; 1287 case BuiltinType::LongAccum: 1288 case BuiltinType::ULongAccum: 1289 case BuiltinType::SatLongAccum: 1290 case BuiltinType::SatULongAccum: 1291 return 6; 1292 default: 1293 if (BTy->isInteger()) 1294 return 0; 1295 llvm_unreachable("Unexpected fixed point or integer type"); 1296 } 1297 } 1298 1299 /// handleFixedPointConversion - Fixed point operations between fixed 1300 /// point types and integers or other fixed point types do not fall under 1301 /// usual arithmetic conversion since these conversions could result in loss 1302 /// of precsision (N1169 4.1.4). These operations should be calculated with 1303 /// the full precision of their result type (N1169 4.1.6.2.1). 1304 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1305 QualType RHSTy) { 1306 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1307 "Expected at least one of the operands to be a fixed point type"); 1308 assert((LHSTy->isFixedPointOrIntegerType() || 1309 RHSTy->isFixedPointOrIntegerType()) && 1310 "Special fixed point arithmetic operation conversions are only " 1311 "applied to ints or other fixed point types"); 1312 1313 // If one operand has signed fixed-point type and the other operand has 1314 // unsigned fixed-point type, then the unsigned fixed-point operand is 1315 // converted to its corresponding signed fixed-point type and the resulting 1316 // type is the type of the converted operand. 1317 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1318 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1319 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1320 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1321 1322 // The result type is the type with the highest rank, whereby a fixed-point 1323 // conversion rank is always greater than an integer conversion rank; if the 1324 // type of either of the operands is a saturating fixedpoint type, the result 1325 // type shall be the saturating fixed-point type corresponding to the type 1326 // with the highest rank; the resulting value is converted (taking into 1327 // account rounding and overflow) to the precision of the resulting type. 1328 // Same ranks between signed and unsigned types are resolved earlier, so both 1329 // types are either signed or both unsigned at this point. 1330 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1331 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1332 1333 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1334 1335 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1336 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1337 1338 return ResultTy; 1339 } 1340 1341 /// UsualArithmeticConversions - Performs various conversions that are common to 1342 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1343 /// routine returns the first non-arithmetic type found. The client is 1344 /// responsible for emitting appropriate error diagnostics. 1345 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1346 bool IsCompAssign) { 1347 if (!IsCompAssign) { 1348 LHS = UsualUnaryConversions(LHS.get()); 1349 if (LHS.isInvalid()) 1350 return QualType(); 1351 } 1352 1353 RHS = UsualUnaryConversions(RHS.get()); 1354 if (RHS.isInvalid()) 1355 return QualType(); 1356 1357 // For conversion purposes, we ignore any qualifiers. 1358 // For example, "const float" and "float" are equivalent. 1359 QualType LHSType = 1360 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1361 QualType RHSType = 1362 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1363 1364 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1365 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1366 LHSType = AtomicLHS->getValueType(); 1367 1368 // If both types are identical, no conversion is needed. 1369 if (LHSType == RHSType) 1370 return LHSType; 1371 1372 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1373 // The caller can deal with this (e.g. pointer + int). 1374 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1375 return QualType(); 1376 1377 // Apply unary and bitfield promotions to the LHS's type. 1378 QualType LHSUnpromotedType = LHSType; 1379 if (LHSType->isPromotableIntegerType()) 1380 LHSType = Context.getPromotedIntegerType(LHSType); 1381 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1382 if (!LHSBitfieldPromoteTy.isNull()) 1383 LHSType = LHSBitfieldPromoteTy; 1384 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1385 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1386 1387 // If both types are identical, no conversion is needed. 1388 if (LHSType == RHSType) 1389 return LHSType; 1390 1391 // At this point, we have two different arithmetic types. 1392 1393 // Diagnose attempts to convert between __float128 and long double where 1394 // such conversions currently can't be handled. 1395 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1396 return QualType(); 1397 1398 // Handle complex types first (C99 6.3.1.8p1). 1399 if (LHSType->isComplexType() || RHSType->isComplexType()) 1400 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1401 IsCompAssign); 1402 1403 // Now handle "real" floating types (i.e. float, double, long double). 1404 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1405 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1406 IsCompAssign); 1407 1408 // Handle GCC complex int extension. 1409 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1410 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1411 IsCompAssign); 1412 1413 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1414 return handleFixedPointConversion(*this, LHSType, RHSType); 1415 1416 // Finally, we have two differing integer types. 1417 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1418 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1419 } 1420 1421 //===----------------------------------------------------------------------===// 1422 // Semantic Analysis for various Expression Types 1423 //===----------------------------------------------------------------------===// 1424 1425 1426 ExprResult 1427 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1428 SourceLocation DefaultLoc, 1429 SourceLocation RParenLoc, 1430 Expr *ControllingExpr, 1431 ArrayRef<ParsedType> ArgTypes, 1432 ArrayRef<Expr *> ArgExprs) { 1433 unsigned NumAssocs = ArgTypes.size(); 1434 assert(NumAssocs == ArgExprs.size()); 1435 1436 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1437 for (unsigned i = 0; i < NumAssocs; ++i) { 1438 if (ArgTypes[i]) 1439 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1440 else 1441 Types[i] = nullptr; 1442 } 1443 1444 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1445 ControllingExpr, 1446 llvm::makeArrayRef(Types, NumAssocs), 1447 ArgExprs); 1448 delete [] Types; 1449 return ER; 1450 } 1451 1452 ExprResult 1453 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1454 SourceLocation DefaultLoc, 1455 SourceLocation RParenLoc, 1456 Expr *ControllingExpr, 1457 ArrayRef<TypeSourceInfo *> Types, 1458 ArrayRef<Expr *> Exprs) { 1459 unsigned NumAssocs = Types.size(); 1460 assert(NumAssocs == Exprs.size()); 1461 1462 // Decay and strip qualifiers for the controlling expression type, and handle 1463 // placeholder type replacement. See committee discussion from WG14 DR423. 1464 { 1465 EnterExpressionEvaluationContext Unevaluated( 1466 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1467 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1468 if (R.isInvalid()) 1469 return ExprError(); 1470 ControllingExpr = R.get(); 1471 } 1472 1473 // The controlling expression is an unevaluated operand, so side effects are 1474 // likely unintended. 1475 if (!inTemplateInstantiation() && 1476 ControllingExpr->HasSideEffects(Context, false)) 1477 Diag(ControllingExpr->getExprLoc(), 1478 diag::warn_side_effects_unevaluated_context); 1479 1480 bool TypeErrorFound = false, 1481 IsResultDependent = ControllingExpr->isTypeDependent(), 1482 ContainsUnexpandedParameterPack 1483 = ControllingExpr->containsUnexpandedParameterPack(); 1484 1485 for (unsigned i = 0; i < NumAssocs; ++i) { 1486 if (Exprs[i]->containsUnexpandedParameterPack()) 1487 ContainsUnexpandedParameterPack = true; 1488 1489 if (Types[i]) { 1490 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1491 ContainsUnexpandedParameterPack = true; 1492 1493 if (Types[i]->getType()->isDependentType()) { 1494 IsResultDependent = true; 1495 } else { 1496 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1497 // complete object type other than a variably modified type." 1498 unsigned D = 0; 1499 if (Types[i]->getType()->isIncompleteType()) 1500 D = diag::err_assoc_type_incomplete; 1501 else if (!Types[i]->getType()->isObjectType()) 1502 D = diag::err_assoc_type_nonobject; 1503 else if (Types[i]->getType()->isVariablyModifiedType()) 1504 D = diag::err_assoc_type_variably_modified; 1505 1506 if (D != 0) { 1507 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1508 << Types[i]->getTypeLoc().getSourceRange() 1509 << Types[i]->getType(); 1510 TypeErrorFound = true; 1511 } 1512 1513 // C11 6.5.1.1p2 "No two generic associations in the same generic 1514 // selection shall specify compatible types." 1515 for (unsigned j = i+1; j < NumAssocs; ++j) 1516 if (Types[j] && !Types[j]->getType()->isDependentType() && 1517 Context.typesAreCompatible(Types[i]->getType(), 1518 Types[j]->getType())) { 1519 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1520 diag::err_assoc_compatible_types) 1521 << Types[j]->getTypeLoc().getSourceRange() 1522 << Types[j]->getType() 1523 << Types[i]->getType(); 1524 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1525 diag::note_compat_assoc) 1526 << Types[i]->getTypeLoc().getSourceRange() 1527 << Types[i]->getType(); 1528 TypeErrorFound = true; 1529 } 1530 } 1531 } 1532 } 1533 if (TypeErrorFound) 1534 return ExprError(); 1535 1536 // If we determined that the generic selection is result-dependent, don't 1537 // try to compute the result expression. 1538 if (IsResultDependent) 1539 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1540 Exprs, DefaultLoc, RParenLoc, 1541 ContainsUnexpandedParameterPack); 1542 1543 SmallVector<unsigned, 1> CompatIndices; 1544 unsigned DefaultIndex = -1U; 1545 for (unsigned i = 0; i < NumAssocs; ++i) { 1546 if (!Types[i]) 1547 DefaultIndex = i; 1548 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1549 Types[i]->getType())) 1550 CompatIndices.push_back(i); 1551 } 1552 1553 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1554 // type compatible with at most one of the types named in its generic 1555 // association list." 1556 if (CompatIndices.size() > 1) { 1557 // We strip parens here because the controlling expression is typically 1558 // parenthesized in macro definitions. 1559 ControllingExpr = ControllingExpr->IgnoreParens(); 1560 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1561 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1562 << (unsigned)CompatIndices.size(); 1563 for (unsigned I : CompatIndices) { 1564 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1565 diag::note_compat_assoc) 1566 << Types[I]->getTypeLoc().getSourceRange() 1567 << Types[I]->getType(); 1568 } 1569 return ExprError(); 1570 } 1571 1572 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1573 // its controlling expression shall have type compatible with exactly one of 1574 // the types named in its generic association list." 1575 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1576 // We strip parens here because the controlling expression is typically 1577 // parenthesized in macro definitions. 1578 ControllingExpr = ControllingExpr->IgnoreParens(); 1579 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1580 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1581 return ExprError(); 1582 } 1583 1584 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1585 // type name that is compatible with the type of the controlling expression, 1586 // then the result expression of the generic selection is the expression 1587 // in that generic association. Otherwise, the result expression of the 1588 // generic selection is the expression in the default generic association." 1589 unsigned ResultIndex = 1590 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1591 1592 return GenericSelectionExpr::Create( 1593 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1594 ContainsUnexpandedParameterPack, ResultIndex); 1595 } 1596 1597 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1598 /// location of the token and the offset of the ud-suffix within it. 1599 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1600 unsigned Offset) { 1601 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1602 S.getLangOpts()); 1603 } 1604 1605 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1606 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1607 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1608 IdentifierInfo *UDSuffix, 1609 SourceLocation UDSuffixLoc, 1610 ArrayRef<Expr*> Args, 1611 SourceLocation LitEndLoc) { 1612 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1613 1614 QualType ArgTy[2]; 1615 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1616 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1617 if (ArgTy[ArgIdx]->isArrayType()) 1618 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1619 } 1620 1621 DeclarationName OpName = 1622 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1623 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1624 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1625 1626 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1627 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1628 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1629 /*AllowStringTemplate*/ false, 1630 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1631 return ExprError(); 1632 1633 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1634 } 1635 1636 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1637 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1638 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1639 /// multiple tokens. However, the common case is that StringToks points to one 1640 /// string. 1641 /// 1642 ExprResult 1643 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1644 assert(!StringToks.empty() && "Must have at least one string!"); 1645 1646 StringLiteralParser Literal(StringToks, PP); 1647 if (Literal.hadError) 1648 return ExprError(); 1649 1650 SmallVector<SourceLocation, 4> StringTokLocs; 1651 for (const Token &Tok : StringToks) 1652 StringTokLocs.push_back(Tok.getLocation()); 1653 1654 QualType CharTy = Context.CharTy; 1655 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1656 if (Literal.isWide()) { 1657 CharTy = Context.getWideCharType(); 1658 Kind = StringLiteral::Wide; 1659 } else if (Literal.isUTF8()) { 1660 if (getLangOpts().Char8) 1661 CharTy = Context.Char8Ty; 1662 Kind = StringLiteral::UTF8; 1663 } else if (Literal.isUTF16()) { 1664 CharTy = Context.Char16Ty; 1665 Kind = StringLiteral::UTF16; 1666 } else if (Literal.isUTF32()) { 1667 CharTy = Context.Char32Ty; 1668 Kind = StringLiteral::UTF32; 1669 } else if (Literal.isPascal()) { 1670 CharTy = Context.UnsignedCharTy; 1671 } 1672 1673 // Warn on initializing an array of char from a u8 string literal; this 1674 // becomes ill-formed in C++2a. 1675 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1676 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1677 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1678 1679 // Create removals for all 'u8' prefixes in the string literal(s). This 1680 // ensures C++2a compatibility (but may change the program behavior when 1681 // built by non-Clang compilers for which the execution character set is 1682 // not always UTF-8). 1683 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1684 SourceLocation RemovalDiagLoc; 1685 for (const Token &Tok : StringToks) { 1686 if (Tok.getKind() == tok::utf8_string_literal) { 1687 if (RemovalDiagLoc.isInvalid()) 1688 RemovalDiagLoc = Tok.getLocation(); 1689 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1690 Tok.getLocation(), 1691 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1692 getSourceManager(), getLangOpts()))); 1693 } 1694 } 1695 Diag(RemovalDiagLoc, RemovalDiag); 1696 } 1697 1698 QualType StrTy = 1699 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1700 1701 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1702 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1703 Kind, Literal.Pascal, StrTy, 1704 &StringTokLocs[0], 1705 StringTokLocs.size()); 1706 if (Literal.getUDSuffix().empty()) 1707 return Lit; 1708 1709 // We're building a user-defined literal. 1710 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1711 SourceLocation UDSuffixLoc = 1712 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1713 Literal.getUDSuffixOffset()); 1714 1715 // Make sure we're allowed user-defined literals here. 1716 if (!UDLScope) 1717 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1718 1719 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1720 // operator "" X (str, len) 1721 QualType SizeType = Context.getSizeType(); 1722 1723 DeclarationName OpName = 1724 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1725 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1726 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1727 1728 QualType ArgTy[] = { 1729 Context.getArrayDecayedType(StrTy), SizeType 1730 }; 1731 1732 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1733 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1734 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1735 /*AllowStringTemplate*/ true, 1736 /*DiagnoseMissing*/ true)) { 1737 1738 case LOLR_Cooked: { 1739 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1740 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1741 StringTokLocs[0]); 1742 Expr *Args[] = { Lit, LenArg }; 1743 1744 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1745 } 1746 1747 case LOLR_StringTemplate: { 1748 TemplateArgumentListInfo ExplicitArgs; 1749 1750 unsigned CharBits = Context.getIntWidth(CharTy); 1751 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1752 llvm::APSInt Value(CharBits, CharIsUnsigned); 1753 1754 TemplateArgument TypeArg(CharTy); 1755 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1756 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1757 1758 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1759 Value = Lit->getCodeUnit(I); 1760 TemplateArgument Arg(Context, Value, CharTy); 1761 TemplateArgumentLocInfo ArgInfo; 1762 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1763 } 1764 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1765 &ExplicitArgs); 1766 } 1767 case LOLR_Raw: 1768 case LOLR_Template: 1769 case LOLR_ErrorNoDiagnostic: 1770 llvm_unreachable("unexpected literal operator lookup result"); 1771 case LOLR_Error: 1772 return ExprError(); 1773 } 1774 llvm_unreachable("unexpected literal operator lookup result"); 1775 } 1776 1777 DeclRefExpr * 1778 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1779 SourceLocation Loc, 1780 const CXXScopeSpec *SS) { 1781 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1782 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1783 } 1784 1785 DeclRefExpr * 1786 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1787 const DeclarationNameInfo &NameInfo, 1788 const CXXScopeSpec *SS, NamedDecl *FoundD, 1789 SourceLocation TemplateKWLoc, 1790 const TemplateArgumentListInfo *TemplateArgs) { 1791 NestedNameSpecifierLoc NNS = 1792 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1793 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1794 TemplateArgs); 1795 } 1796 1797 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1798 // A declaration named in an unevaluated operand never constitutes an odr-use. 1799 if (isUnevaluatedContext()) 1800 return NOUR_Unevaluated; 1801 1802 // C++2a [basic.def.odr]p4: 1803 // A variable x whose name appears as a potentially-evaluated expression e 1804 // is odr-used by e unless [...] x is a reference that is usable in 1805 // constant expressions. 1806 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1807 if (VD->getType()->isReferenceType() && 1808 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1809 VD->isUsableInConstantExpressions(Context)) 1810 return NOUR_Constant; 1811 } 1812 1813 // All remaining non-variable cases constitute an odr-use. For variables, we 1814 // need to wait and see how the expression is used. 1815 return NOUR_None; 1816 } 1817 1818 /// BuildDeclRefExpr - Build an expression that references a 1819 /// declaration that does not require a closure capture. 1820 DeclRefExpr * 1821 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1822 const DeclarationNameInfo &NameInfo, 1823 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1824 SourceLocation TemplateKWLoc, 1825 const TemplateArgumentListInfo *TemplateArgs) { 1826 bool RefersToCapturedVariable = 1827 isa<VarDecl>(D) && 1828 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1829 1830 DeclRefExpr *E = DeclRefExpr::Create( 1831 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1832 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1833 MarkDeclRefReferenced(E); 1834 1835 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1836 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1837 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1838 getCurFunction()->recordUseOfWeak(E); 1839 1840 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1841 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1842 FD = IFD->getAnonField(); 1843 if (FD) { 1844 UnusedPrivateFields.remove(FD); 1845 // Just in case we're building an illegal pointer-to-member. 1846 if (FD->isBitField()) 1847 E->setObjectKind(OK_BitField); 1848 } 1849 1850 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1851 // designates a bit-field. 1852 if (auto *BD = dyn_cast<BindingDecl>(D)) 1853 if (auto *BE = BD->getBinding()) 1854 E->setObjectKind(BE->getObjectKind()); 1855 1856 return E; 1857 } 1858 1859 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1860 /// possibly a list of template arguments. 1861 /// 1862 /// If this produces template arguments, it is permitted to call 1863 /// DecomposeTemplateName. 1864 /// 1865 /// This actually loses a lot of source location information for 1866 /// non-standard name kinds; we should consider preserving that in 1867 /// some way. 1868 void 1869 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1870 TemplateArgumentListInfo &Buffer, 1871 DeclarationNameInfo &NameInfo, 1872 const TemplateArgumentListInfo *&TemplateArgs) { 1873 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1874 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1875 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1876 1877 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1878 Id.TemplateId->NumArgs); 1879 translateTemplateArguments(TemplateArgsPtr, Buffer); 1880 1881 TemplateName TName = Id.TemplateId->Template.get(); 1882 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1883 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1884 TemplateArgs = &Buffer; 1885 } else { 1886 NameInfo = GetNameFromUnqualifiedId(Id); 1887 TemplateArgs = nullptr; 1888 } 1889 } 1890 1891 static void emitEmptyLookupTypoDiagnostic( 1892 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1893 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1894 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1895 DeclContext *Ctx = 1896 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1897 if (!TC) { 1898 // Emit a special diagnostic for failed member lookups. 1899 // FIXME: computing the declaration context might fail here (?) 1900 if (Ctx) 1901 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1902 << SS.getRange(); 1903 else 1904 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1905 return; 1906 } 1907 1908 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1909 bool DroppedSpecifier = 1910 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1911 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1912 ? diag::note_implicit_param_decl 1913 : diag::note_previous_decl; 1914 if (!Ctx) 1915 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1916 SemaRef.PDiag(NoteID)); 1917 else 1918 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1919 << Typo << Ctx << DroppedSpecifier 1920 << SS.getRange(), 1921 SemaRef.PDiag(NoteID)); 1922 } 1923 1924 /// Diagnose an empty lookup. 1925 /// 1926 /// \return false if new lookup candidates were found 1927 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1928 CorrectionCandidateCallback &CCC, 1929 TemplateArgumentListInfo *ExplicitTemplateArgs, 1930 ArrayRef<Expr *> Args, TypoExpr **Out) { 1931 DeclarationName Name = R.getLookupName(); 1932 1933 unsigned diagnostic = diag::err_undeclared_var_use; 1934 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1935 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1936 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1937 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1938 diagnostic = diag::err_undeclared_use; 1939 diagnostic_suggest = diag::err_undeclared_use_suggest; 1940 } 1941 1942 // If the original lookup was an unqualified lookup, fake an 1943 // unqualified lookup. This is useful when (for example) the 1944 // original lookup would not have found something because it was a 1945 // dependent name. 1946 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1947 while (DC) { 1948 if (isa<CXXRecordDecl>(DC)) { 1949 LookupQualifiedName(R, DC); 1950 1951 if (!R.empty()) { 1952 // Don't give errors about ambiguities in this lookup. 1953 R.suppressDiagnostics(); 1954 1955 // During a default argument instantiation the CurContext points 1956 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1957 // function parameter list, hence add an explicit check. 1958 bool isDefaultArgument = 1959 !CodeSynthesisContexts.empty() && 1960 CodeSynthesisContexts.back().Kind == 1961 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1962 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1963 bool isInstance = CurMethod && 1964 CurMethod->isInstance() && 1965 DC == CurMethod->getParent() && !isDefaultArgument; 1966 1967 // Give a code modification hint to insert 'this->'. 1968 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1969 // Actually quite difficult! 1970 if (getLangOpts().MSVCCompat) 1971 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1972 if (isInstance) { 1973 Diag(R.getNameLoc(), diagnostic) << Name 1974 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1975 CheckCXXThisCapture(R.getNameLoc()); 1976 } else { 1977 Diag(R.getNameLoc(), diagnostic) << Name; 1978 } 1979 1980 // Do we really want to note all of these? 1981 for (NamedDecl *D : R) 1982 Diag(D->getLocation(), diag::note_dependent_var_use); 1983 1984 // Return true if we are inside a default argument instantiation 1985 // and the found name refers to an instance member function, otherwise 1986 // the function calling DiagnoseEmptyLookup will try to create an 1987 // implicit member call and this is wrong for default argument. 1988 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1989 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1990 return true; 1991 } 1992 1993 // Tell the callee to try to recover. 1994 return false; 1995 } 1996 1997 R.clear(); 1998 } 1999 2000 DC = DC->getLookupParent(); 2001 } 2002 2003 // We didn't find anything, so try to correct for a typo. 2004 TypoCorrection Corrected; 2005 if (S && Out) { 2006 SourceLocation TypoLoc = R.getNameLoc(); 2007 assert(!ExplicitTemplateArgs && 2008 "Diagnosing an empty lookup with explicit template args!"); 2009 *Out = CorrectTypoDelayed( 2010 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2011 [=](const TypoCorrection &TC) { 2012 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2013 diagnostic, diagnostic_suggest); 2014 }, 2015 nullptr, CTK_ErrorRecovery); 2016 if (*Out) 2017 return true; 2018 } else if (S && 2019 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2020 S, &SS, CCC, CTK_ErrorRecovery))) { 2021 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2022 bool DroppedSpecifier = 2023 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2024 R.setLookupName(Corrected.getCorrection()); 2025 2026 bool AcceptableWithRecovery = false; 2027 bool AcceptableWithoutRecovery = false; 2028 NamedDecl *ND = Corrected.getFoundDecl(); 2029 if (ND) { 2030 if (Corrected.isOverloaded()) { 2031 OverloadCandidateSet OCS(R.getNameLoc(), 2032 OverloadCandidateSet::CSK_Normal); 2033 OverloadCandidateSet::iterator Best; 2034 for (NamedDecl *CD : Corrected) { 2035 if (FunctionTemplateDecl *FTD = 2036 dyn_cast<FunctionTemplateDecl>(CD)) 2037 AddTemplateOverloadCandidate( 2038 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2039 Args, OCS); 2040 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2041 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2042 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2043 Args, OCS); 2044 } 2045 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2046 case OR_Success: 2047 ND = Best->FoundDecl; 2048 Corrected.setCorrectionDecl(ND); 2049 break; 2050 default: 2051 // FIXME: Arbitrarily pick the first declaration for the note. 2052 Corrected.setCorrectionDecl(ND); 2053 break; 2054 } 2055 } 2056 R.addDecl(ND); 2057 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2058 CXXRecordDecl *Record = nullptr; 2059 if (Corrected.getCorrectionSpecifier()) { 2060 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2061 Record = Ty->getAsCXXRecordDecl(); 2062 } 2063 if (!Record) 2064 Record = cast<CXXRecordDecl>( 2065 ND->getDeclContext()->getRedeclContext()); 2066 R.setNamingClass(Record); 2067 } 2068 2069 auto *UnderlyingND = ND->getUnderlyingDecl(); 2070 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2071 isa<FunctionTemplateDecl>(UnderlyingND); 2072 // FIXME: If we ended up with a typo for a type name or 2073 // Objective-C class name, we're in trouble because the parser 2074 // is in the wrong place to recover. Suggest the typo 2075 // correction, but don't make it a fix-it since we're not going 2076 // to recover well anyway. 2077 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2078 getAsTypeTemplateDecl(UnderlyingND) || 2079 isa<ObjCInterfaceDecl>(UnderlyingND); 2080 } else { 2081 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2082 // because we aren't able to recover. 2083 AcceptableWithoutRecovery = true; 2084 } 2085 2086 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2087 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2088 ? diag::note_implicit_param_decl 2089 : diag::note_previous_decl; 2090 if (SS.isEmpty()) 2091 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2092 PDiag(NoteID), AcceptableWithRecovery); 2093 else 2094 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2095 << Name << computeDeclContext(SS, false) 2096 << DroppedSpecifier << SS.getRange(), 2097 PDiag(NoteID), AcceptableWithRecovery); 2098 2099 // Tell the callee whether to try to recover. 2100 return !AcceptableWithRecovery; 2101 } 2102 } 2103 R.clear(); 2104 2105 // Emit a special diagnostic for failed member lookups. 2106 // FIXME: computing the declaration context might fail here (?) 2107 if (!SS.isEmpty()) { 2108 Diag(R.getNameLoc(), diag::err_no_member) 2109 << Name << computeDeclContext(SS, false) 2110 << SS.getRange(); 2111 return true; 2112 } 2113 2114 // Give up, we can't recover. 2115 Diag(R.getNameLoc(), diagnostic) << Name; 2116 return true; 2117 } 2118 2119 /// In Microsoft mode, if we are inside a template class whose parent class has 2120 /// dependent base classes, and we can't resolve an unqualified identifier, then 2121 /// assume the identifier is a member of a dependent base class. We can only 2122 /// recover successfully in static methods, instance methods, and other contexts 2123 /// where 'this' is available. This doesn't precisely match MSVC's 2124 /// instantiation model, but it's close enough. 2125 static Expr * 2126 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2127 DeclarationNameInfo &NameInfo, 2128 SourceLocation TemplateKWLoc, 2129 const TemplateArgumentListInfo *TemplateArgs) { 2130 // Only try to recover from lookup into dependent bases in static methods or 2131 // contexts where 'this' is available. 2132 QualType ThisType = S.getCurrentThisType(); 2133 const CXXRecordDecl *RD = nullptr; 2134 if (!ThisType.isNull()) 2135 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2136 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2137 RD = MD->getParent(); 2138 if (!RD || !RD->hasAnyDependentBases()) 2139 return nullptr; 2140 2141 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2142 // is available, suggest inserting 'this->' as a fixit. 2143 SourceLocation Loc = NameInfo.getLoc(); 2144 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2145 DB << NameInfo.getName() << RD; 2146 2147 if (!ThisType.isNull()) { 2148 DB << FixItHint::CreateInsertion(Loc, "this->"); 2149 return CXXDependentScopeMemberExpr::Create( 2150 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2151 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2152 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2153 } 2154 2155 // Synthesize a fake NNS that points to the derived class. This will 2156 // perform name lookup during template instantiation. 2157 CXXScopeSpec SS; 2158 auto *NNS = 2159 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2160 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2161 return DependentScopeDeclRefExpr::Create( 2162 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2163 TemplateArgs); 2164 } 2165 2166 ExprResult 2167 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2168 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2169 bool HasTrailingLParen, bool IsAddressOfOperand, 2170 CorrectionCandidateCallback *CCC, 2171 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2172 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2173 "cannot be direct & operand and have a trailing lparen"); 2174 if (SS.isInvalid()) 2175 return ExprError(); 2176 2177 TemplateArgumentListInfo TemplateArgsBuffer; 2178 2179 // Decompose the UnqualifiedId into the following data. 2180 DeclarationNameInfo NameInfo; 2181 const TemplateArgumentListInfo *TemplateArgs; 2182 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2183 2184 DeclarationName Name = NameInfo.getName(); 2185 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2186 SourceLocation NameLoc = NameInfo.getLoc(); 2187 2188 if (II && II->isEditorPlaceholder()) { 2189 // FIXME: When typed placeholders are supported we can create a typed 2190 // placeholder expression node. 2191 return ExprError(); 2192 } 2193 2194 // C++ [temp.dep.expr]p3: 2195 // An id-expression is type-dependent if it contains: 2196 // -- an identifier that was declared with a dependent type, 2197 // (note: handled after lookup) 2198 // -- a template-id that is dependent, 2199 // (note: handled in BuildTemplateIdExpr) 2200 // -- a conversion-function-id that specifies a dependent type, 2201 // -- a nested-name-specifier that contains a class-name that 2202 // names a dependent type. 2203 // Determine whether this is a member of an unknown specialization; 2204 // we need to handle these differently. 2205 bool DependentID = false; 2206 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2207 Name.getCXXNameType()->isDependentType()) { 2208 DependentID = true; 2209 } else if (SS.isSet()) { 2210 if (DeclContext *DC = computeDeclContext(SS, false)) { 2211 if (RequireCompleteDeclContext(SS, DC)) 2212 return ExprError(); 2213 } else { 2214 DependentID = true; 2215 } 2216 } 2217 2218 if (DependentID) 2219 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2220 IsAddressOfOperand, TemplateArgs); 2221 2222 // Perform the required lookup. 2223 LookupResult R(*this, NameInfo, 2224 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2225 ? LookupObjCImplicitSelfParam 2226 : LookupOrdinaryName); 2227 if (TemplateKWLoc.isValid() || TemplateArgs) { 2228 // Lookup the template name again to correctly establish the context in 2229 // which it was found. This is really unfortunate as we already did the 2230 // lookup to determine that it was a template name in the first place. If 2231 // this becomes a performance hit, we can work harder to preserve those 2232 // results until we get here but it's likely not worth it. 2233 bool MemberOfUnknownSpecialization; 2234 AssumedTemplateKind AssumedTemplate; 2235 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2236 MemberOfUnknownSpecialization, TemplateKWLoc, 2237 &AssumedTemplate)) 2238 return ExprError(); 2239 2240 if (MemberOfUnknownSpecialization || 2241 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2242 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2243 IsAddressOfOperand, TemplateArgs); 2244 } else { 2245 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2246 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2247 2248 // If the result might be in a dependent base class, this is a dependent 2249 // id-expression. 2250 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2251 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2252 IsAddressOfOperand, TemplateArgs); 2253 2254 // If this reference is in an Objective-C method, then we need to do 2255 // some special Objective-C lookup, too. 2256 if (IvarLookupFollowUp) { 2257 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2258 if (E.isInvalid()) 2259 return ExprError(); 2260 2261 if (Expr *Ex = E.getAs<Expr>()) 2262 return Ex; 2263 } 2264 } 2265 2266 if (R.isAmbiguous()) 2267 return ExprError(); 2268 2269 // This could be an implicitly declared function reference (legal in C90, 2270 // extension in C99, forbidden in C++). 2271 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2272 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2273 if (D) R.addDecl(D); 2274 } 2275 2276 // Determine whether this name might be a candidate for 2277 // argument-dependent lookup. 2278 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2279 2280 if (R.empty() && !ADL) { 2281 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2282 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2283 TemplateKWLoc, TemplateArgs)) 2284 return E; 2285 } 2286 2287 // Don't diagnose an empty lookup for inline assembly. 2288 if (IsInlineAsmIdentifier) 2289 return ExprError(); 2290 2291 // If this name wasn't predeclared and if this is not a function 2292 // call, diagnose the problem. 2293 TypoExpr *TE = nullptr; 2294 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2295 : nullptr); 2296 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2297 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2298 "Typo correction callback misconfigured"); 2299 if (CCC) { 2300 // Make sure the callback knows what the typo being diagnosed is. 2301 CCC->setTypoName(II); 2302 if (SS.isValid()) 2303 CCC->setTypoNNS(SS.getScopeRep()); 2304 } 2305 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2306 // a template name, but we happen to have always already looked up the name 2307 // before we get here if it must be a template name. 2308 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2309 None, &TE)) { 2310 if (TE && KeywordReplacement) { 2311 auto &State = getTypoExprState(TE); 2312 auto BestTC = State.Consumer->getNextCorrection(); 2313 if (BestTC.isKeyword()) { 2314 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2315 if (State.DiagHandler) 2316 State.DiagHandler(BestTC); 2317 KeywordReplacement->startToken(); 2318 KeywordReplacement->setKind(II->getTokenID()); 2319 KeywordReplacement->setIdentifierInfo(II); 2320 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2321 // Clean up the state associated with the TypoExpr, since it has 2322 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2323 clearDelayedTypo(TE); 2324 // Signal that a correction to a keyword was performed by returning a 2325 // valid-but-null ExprResult. 2326 return (Expr*)nullptr; 2327 } 2328 State.Consumer->resetCorrectionStream(); 2329 } 2330 return TE ? TE : ExprError(); 2331 } 2332 2333 assert(!R.empty() && 2334 "DiagnoseEmptyLookup returned false but added no results"); 2335 2336 // If we found an Objective-C instance variable, let 2337 // LookupInObjCMethod build the appropriate expression to 2338 // reference the ivar. 2339 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2340 R.clear(); 2341 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2342 // In a hopelessly buggy code, Objective-C instance variable 2343 // lookup fails and no expression will be built to reference it. 2344 if (!E.isInvalid() && !E.get()) 2345 return ExprError(); 2346 return E; 2347 } 2348 } 2349 2350 // This is guaranteed from this point on. 2351 assert(!R.empty() || ADL); 2352 2353 // Check whether this might be a C++ implicit instance member access. 2354 // C++ [class.mfct.non-static]p3: 2355 // When an id-expression that is not part of a class member access 2356 // syntax and not used to form a pointer to member is used in the 2357 // body of a non-static member function of class X, if name lookup 2358 // resolves the name in the id-expression to a non-static non-type 2359 // member of some class C, the id-expression is transformed into a 2360 // class member access expression using (*this) as the 2361 // postfix-expression to the left of the . operator. 2362 // 2363 // But we don't actually need to do this for '&' operands if R 2364 // resolved to a function or overloaded function set, because the 2365 // expression is ill-formed if it actually works out to be a 2366 // non-static member function: 2367 // 2368 // C++ [expr.ref]p4: 2369 // Otherwise, if E1.E2 refers to a non-static member function. . . 2370 // [t]he expression can be used only as the left-hand operand of a 2371 // member function call. 2372 // 2373 // There are other safeguards against such uses, but it's important 2374 // to get this right here so that we don't end up making a 2375 // spuriously dependent expression if we're inside a dependent 2376 // instance method. 2377 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2378 bool MightBeImplicitMember; 2379 if (!IsAddressOfOperand) 2380 MightBeImplicitMember = true; 2381 else if (!SS.isEmpty()) 2382 MightBeImplicitMember = false; 2383 else if (R.isOverloadedResult()) 2384 MightBeImplicitMember = false; 2385 else if (R.isUnresolvableResult()) 2386 MightBeImplicitMember = true; 2387 else 2388 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2389 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2390 isa<MSPropertyDecl>(R.getFoundDecl()); 2391 2392 if (MightBeImplicitMember) 2393 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2394 R, TemplateArgs, S); 2395 } 2396 2397 if (TemplateArgs || TemplateKWLoc.isValid()) { 2398 2399 // In C++1y, if this is a variable template id, then check it 2400 // in BuildTemplateIdExpr(). 2401 // The single lookup result must be a variable template declaration. 2402 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2403 Id.TemplateId->Kind == TNK_Var_template) { 2404 assert(R.getAsSingle<VarTemplateDecl>() && 2405 "There should only be one declaration found."); 2406 } 2407 2408 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2409 } 2410 2411 return BuildDeclarationNameExpr(SS, R, ADL); 2412 } 2413 2414 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2415 /// declaration name, generally during template instantiation. 2416 /// There's a large number of things which don't need to be done along 2417 /// this path. 2418 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2419 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2420 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2421 DeclContext *DC = computeDeclContext(SS, false); 2422 if (!DC) 2423 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2424 NameInfo, /*TemplateArgs=*/nullptr); 2425 2426 if (RequireCompleteDeclContext(SS, DC)) 2427 return ExprError(); 2428 2429 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2430 LookupQualifiedName(R, DC); 2431 2432 if (R.isAmbiguous()) 2433 return ExprError(); 2434 2435 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2436 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2437 NameInfo, /*TemplateArgs=*/nullptr); 2438 2439 if (R.empty()) { 2440 Diag(NameInfo.getLoc(), diag::err_no_member) 2441 << NameInfo.getName() << DC << SS.getRange(); 2442 return ExprError(); 2443 } 2444 2445 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2446 // Diagnose a missing typename if this resolved unambiguously to a type in 2447 // a dependent context. If we can recover with a type, downgrade this to 2448 // a warning in Microsoft compatibility mode. 2449 unsigned DiagID = diag::err_typename_missing; 2450 if (RecoveryTSI && getLangOpts().MSVCCompat) 2451 DiagID = diag::ext_typename_missing; 2452 SourceLocation Loc = SS.getBeginLoc(); 2453 auto D = Diag(Loc, DiagID); 2454 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2455 << SourceRange(Loc, NameInfo.getEndLoc()); 2456 2457 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2458 // context. 2459 if (!RecoveryTSI) 2460 return ExprError(); 2461 2462 // Only issue the fixit if we're prepared to recover. 2463 D << FixItHint::CreateInsertion(Loc, "typename "); 2464 2465 // Recover by pretending this was an elaborated type. 2466 QualType Ty = Context.getTypeDeclType(TD); 2467 TypeLocBuilder TLB; 2468 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2469 2470 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2471 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2472 QTL.setElaboratedKeywordLoc(SourceLocation()); 2473 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2474 2475 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2476 2477 return ExprEmpty(); 2478 } 2479 2480 // Defend against this resolving to an implicit member access. We usually 2481 // won't get here if this might be a legitimate a class member (we end up in 2482 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2483 // a pointer-to-member or in an unevaluated context in C++11. 2484 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2485 return BuildPossibleImplicitMemberExpr(SS, 2486 /*TemplateKWLoc=*/SourceLocation(), 2487 R, /*TemplateArgs=*/nullptr, S); 2488 2489 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2490 } 2491 2492 /// The parser has read a name in, and Sema has detected that we're currently 2493 /// inside an ObjC method. Perform some additional checks and determine if we 2494 /// should form a reference to an ivar. 2495 /// 2496 /// Ideally, most of this would be done by lookup, but there's 2497 /// actually quite a lot of extra work involved. 2498 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2499 IdentifierInfo *II) { 2500 SourceLocation Loc = Lookup.getNameLoc(); 2501 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2502 2503 // Check for error condition which is already reported. 2504 if (!CurMethod) 2505 return DeclResult(true); 2506 2507 // There are two cases to handle here. 1) scoped lookup could have failed, 2508 // in which case we should look for an ivar. 2) scoped lookup could have 2509 // found a decl, but that decl is outside the current instance method (i.e. 2510 // a global variable). In these two cases, we do a lookup for an ivar with 2511 // this name, if the lookup sucedes, we replace it our current decl. 2512 2513 // If we're in a class method, we don't normally want to look for 2514 // ivars. But if we don't find anything else, and there's an 2515 // ivar, that's an error. 2516 bool IsClassMethod = CurMethod->isClassMethod(); 2517 2518 bool LookForIvars; 2519 if (Lookup.empty()) 2520 LookForIvars = true; 2521 else if (IsClassMethod) 2522 LookForIvars = false; 2523 else 2524 LookForIvars = (Lookup.isSingleResult() && 2525 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2526 ObjCInterfaceDecl *IFace = nullptr; 2527 if (LookForIvars) { 2528 IFace = CurMethod->getClassInterface(); 2529 ObjCInterfaceDecl *ClassDeclared; 2530 ObjCIvarDecl *IV = nullptr; 2531 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2532 // Diagnose using an ivar in a class method. 2533 if (IsClassMethod) { 2534 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2535 return DeclResult(true); 2536 } 2537 2538 // Diagnose the use of an ivar outside of the declaring class. 2539 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2540 !declaresSameEntity(ClassDeclared, IFace) && 2541 !getLangOpts().DebuggerSupport) 2542 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2543 2544 // Success. 2545 return IV; 2546 } 2547 } else if (CurMethod->isInstanceMethod()) { 2548 // We should warn if a local variable hides an ivar. 2549 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2550 ObjCInterfaceDecl *ClassDeclared; 2551 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2552 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2553 declaresSameEntity(IFace, ClassDeclared)) 2554 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2555 } 2556 } 2557 } else if (Lookup.isSingleResult() && 2558 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2559 // If accessing a stand-alone ivar in a class method, this is an error. 2560 if (const ObjCIvarDecl *IV = 2561 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2562 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2563 return DeclResult(true); 2564 } 2565 } 2566 2567 // Didn't encounter an error, didn't find an ivar. 2568 return DeclResult(false); 2569 } 2570 2571 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2572 ObjCIvarDecl *IV) { 2573 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2574 assert(CurMethod && CurMethod->isInstanceMethod() && 2575 "should not reference ivar from this context"); 2576 2577 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2578 assert(IFace && "should not reference ivar from this context"); 2579 2580 // If we're referencing an invalid decl, just return this as a silent 2581 // error node. The error diagnostic was already emitted on the decl. 2582 if (IV->isInvalidDecl()) 2583 return ExprError(); 2584 2585 // Check if referencing a field with __attribute__((deprecated)). 2586 if (DiagnoseUseOfDecl(IV, Loc)) 2587 return ExprError(); 2588 2589 // FIXME: This should use a new expr for a direct reference, don't 2590 // turn this into Self->ivar, just return a BareIVarExpr or something. 2591 IdentifierInfo &II = Context.Idents.get("self"); 2592 UnqualifiedId SelfName; 2593 SelfName.setIdentifier(&II, SourceLocation()); 2594 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2595 CXXScopeSpec SelfScopeSpec; 2596 SourceLocation TemplateKWLoc; 2597 ExprResult SelfExpr = 2598 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2599 /*HasTrailingLParen=*/false, 2600 /*IsAddressOfOperand=*/false); 2601 if (SelfExpr.isInvalid()) 2602 return ExprError(); 2603 2604 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2605 if (SelfExpr.isInvalid()) 2606 return ExprError(); 2607 2608 MarkAnyDeclReferenced(Loc, IV, true); 2609 2610 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2611 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2612 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2613 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2614 2615 ObjCIvarRefExpr *Result = new (Context) 2616 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2617 IV->getLocation(), SelfExpr.get(), true, true); 2618 2619 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2620 if (!isUnevaluatedContext() && 2621 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2622 getCurFunction()->recordUseOfWeak(Result); 2623 } 2624 if (getLangOpts().ObjCAutoRefCount) 2625 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2626 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2627 2628 return Result; 2629 } 2630 2631 /// The parser has read a name in, and Sema has detected that we're currently 2632 /// inside an ObjC method. Perform some additional checks and determine if we 2633 /// should form a reference to an ivar. If so, build an expression referencing 2634 /// that ivar. 2635 ExprResult 2636 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2637 IdentifierInfo *II, bool AllowBuiltinCreation) { 2638 // FIXME: Integrate this lookup step into LookupParsedName. 2639 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2640 if (Ivar.isInvalid()) 2641 return ExprError(); 2642 if (Ivar.isUsable()) 2643 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2644 cast<ObjCIvarDecl>(Ivar.get())); 2645 2646 if (Lookup.empty() && II && AllowBuiltinCreation) 2647 LookupBuiltin(Lookup); 2648 2649 // Sentinel value saying that we didn't do anything special. 2650 return ExprResult(false); 2651 } 2652 2653 /// Cast a base object to a member's actual type. 2654 /// 2655 /// Logically this happens in three phases: 2656 /// 2657 /// * First we cast from the base type to the naming class. 2658 /// The naming class is the class into which we were looking 2659 /// when we found the member; it's the qualifier type if a 2660 /// qualifier was provided, and otherwise it's the base type. 2661 /// 2662 /// * Next we cast from the naming class to the declaring class. 2663 /// If the member we found was brought into a class's scope by 2664 /// a using declaration, this is that class; otherwise it's 2665 /// the class declaring the member. 2666 /// 2667 /// * Finally we cast from the declaring class to the "true" 2668 /// declaring class of the member. This conversion does not 2669 /// obey access control. 2670 ExprResult 2671 Sema::PerformObjectMemberConversion(Expr *From, 2672 NestedNameSpecifier *Qualifier, 2673 NamedDecl *FoundDecl, 2674 NamedDecl *Member) { 2675 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2676 if (!RD) 2677 return From; 2678 2679 QualType DestRecordType; 2680 QualType DestType; 2681 QualType FromRecordType; 2682 QualType FromType = From->getType(); 2683 bool PointerConversions = false; 2684 if (isa<FieldDecl>(Member)) { 2685 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2686 auto FromPtrType = FromType->getAs<PointerType>(); 2687 DestRecordType = Context.getAddrSpaceQualType( 2688 DestRecordType, FromPtrType 2689 ? FromType->getPointeeType().getAddressSpace() 2690 : FromType.getAddressSpace()); 2691 2692 if (FromPtrType) { 2693 DestType = Context.getPointerType(DestRecordType); 2694 FromRecordType = FromPtrType->getPointeeType(); 2695 PointerConversions = true; 2696 } else { 2697 DestType = DestRecordType; 2698 FromRecordType = FromType; 2699 } 2700 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2701 if (Method->isStatic()) 2702 return From; 2703 2704 DestType = Method->getThisType(); 2705 DestRecordType = DestType->getPointeeType(); 2706 2707 if (FromType->getAs<PointerType>()) { 2708 FromRecordType = FromType->getPointeeType(); 2709 PointerConversions = true; 2710 } else { 2711 FromRecordType = FromType; 2712 DestType = DestRecordType; 2713 } 2714 2715 LangAS FromAS = FromRecordType.getAddressSpace(); 2716 LangAS DestAS = DestRecordType.getAddressSpace(); 2717 if (FromAS != DestAS) { 2718 QualType FromRecordTypeWithoutAS = 2719 Context.removeAddrSpaceQualType(FromRecordType); 2720 QualType FromTypeWithDestAS = 2721 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2722 if (PointerConversions) 2723 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2724 From = ImpCastExprToType(From, FromTypeWithDestAS, 2725 CK_AddressSpaceConversion, From->getValueKind()) 2726 .get(); 2727 } 2728 } else { 2729 // No conversion necessary. 2730 return From; 2731 } 2732 2733 if (DestType->isDependentType() || FromType->isDependentType()) 2734 return From; 2735 2736 // If the unqualified types are the same, no conversion is necessary. 2737 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2738 return From; 2739 2740 SourceRange FromRange = From->getSourceRange(); 2741 SourceLocation FromLoc = FromRange.getBegin(); 2742 2743 ExprValueKind VK = From->getValueKind(); 2744 2745 // C++ [class.member.lookup]p8: 2746 // [...] Ambiguities can often be resolved by qualifying a name with its 2747 // class name. 2748 // 2749 // If the member was a qualified name and the qualified referred to a 2750 // specific base subobject type, we'll cast to that intermediate type 2751 // first and then to the object in which the member is declared. That allows 2752 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2753 // 2754 // class Base { public: int x; }; 2755 // class Derived1 : public Base { }; 2756 // class Derived2 : public Base { }; 2757 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2758 // 2759 // void VeryDerived::f() { 2760 // x = 17; // error: ambiguous base subobjects 2761 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2762 // } 2763 if (Qualifier && Qualifier->getAsType()) { 2764 QualType QType = QualType(Qualifier->getAsType(), 0); 2765 assert(QType->isRecordType() && "lookup done with non-record type"); 2766 2767 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2768 2769 // In C++98, the qualifier type doesn't actually have to be a base 2770 // type of the object type, in which case we just ignore it. 2771 // Otherwise build the appropriate casts. 2772 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2773 CXXCastPath BasePath; 2774 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2775 FromLoc, FromRange, &BasePath)) 2776 return ExprError(); 2777 2778 if (PointerConversions) 2779 QType = Context.getPointerType(QType); 2780 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2781 VK, &BasePath).get(); 2782 2783 FromType = QType; 2784 FromRecordType = QRecordType; 2785 2786 // If the qualifier type was the same as the destination type, 2787 // we're done. 2788 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2789 return From; 2790 } 2791 } 2792 2793 bool IgnoreAccess = false; 2794 2795 // If we actually found the member through a using declaration, cast 2796 // down to the using declaration's type. 2797 // 2798 // Pointer equality is fine here because only one declaration of a 2799 // class ever has member declarations. 2800 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2801 assert(isa<UsingShadowDecl>(FoundDecl)); 2802 QualType URecordType = Context.getTypeDeclType( 2803 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2804 2805 // We only need to do this if the naming-class to declaring-class 2806 // conversion is non-trivial. 2807 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2808 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2809 CXXCastPath BasePath; 2810 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2811 FromLoc, FromRange, &BasePath)) 2812 return ExprError(); 2813 2814 QualType UType = URecordType; 2815 if (PointerConversions) 2816 UType = Context.getPointerType(UType); 2817 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2818 VK, &BasePath).get(); 2819 FromType = UType; 2820 FromRecordType = URecordType; 2821 } 2822 2823 // We don't do access control for the conversion from the 2824 // declaring class to the true declaring class. 2825 IgnoreAccess = true; 2826 } 2827 2828 CXXCastPath BasePath; 2829 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2830 FromLoc, FromRange, &BasePath, 2831 IgnoreAccess)) 2832 return ExprError(); 2833 2834 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2835 VK, &BasePath); 2836 } 2837 2838 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2839 const LookupResult &R, 2840 bool HasTrailingLParen) { 2841 // Only when used directly as the postfix-expression of a call. 2842 if (!HasTrailingLParen) 2843 return false; 2844 2845 // Never if a scope specifier was provided. 2846 if (SS.isSet()) 2847 return false; 2848 2849 // Only in C++ or ObjC++. 2850 if (!getLangOpts().CPlusPlus) 2851 return false; 2852 2853 // Turn off ADL when we find certain kinds of declarations during 2854 // normal lookup: 2855 for (NamedDecl *D : R) { 2856 // C++0x [basic.lookup.argdep]p3: 2857 // -- a declaration of a class member 2858 // Since using decls preserve this property, we check this on the 2859 // original decl. 2860 if (D->isCXXClassMember()) 2861 return false; 2862 2863 // C++0x [basic.lookup.argdep]p3: 2864 // -- a block-scope function declaration that is not a 2865 // using-declaration 2866 // NOTE: we also trigger this for function templates (in fact, we 2867 // don't check the decl type at all, since all other decl types 2868 // turn off ADL anyway). 2869 if (isa<UsingShadowDecl>(D)) 2870 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2871 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2872 return false; 2873 2874 // C++0x [basic.lookup.argdep]p3: 2875 // -- a declaration that is neither a function or a function 2876 // template 2877 // And also for builtin functions. 2878 if (isa<FunctionDecl>(D)) { 2879 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2880 2881 // But also builtin functions. 2882 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2883 return false; 2884 } else if (!isa<FunctionTemplateDecl>(D)) 2885 return false; 2886 } 2887 2888 return true; 2889 } 2890 2891 2892 /// Diagnoses obvious problems with the use of the given declaration 2893 /// as an expression. This is only actually called for lookups that 2894 /// were not overloaded, and it doesn't promise that the declaration 2895 /// will in fact be used. 2896 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2897 if (D->isInvalidDecl()) 2898 return true; 2899 2900 if (isa<TypedefNameDecl>(D)) { 2901 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2902 return true; 2903 } 2904 2905 if (isa<ObjCInterfaceDecl>(D)) { 2906 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2907 return true; 2908 } 2909 2910 if (isa<NamespaceDecl>(D)) { 2911 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2912 return true; 2913 } 2914 2915 return false; 2916 } 2917 2918 // Certain multiversion types should be treated as overloaded even when there is 2919 // only one result. 2920 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2921 assert(R.isSingleResult() && "Expected only a single result"); 2922 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2923 return FD && 2924 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2925 } 2926 2927 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2928 LookupResult &R, bool NeedsADL, 2929 bool AcceptInvalidDecl) { 2930 // If this is a single, fully-resolved result and we don't need ADL, 2931 // just build an ordinary singleton decl ref. 2932 if (!NeedsADL && R.isSingleResult() && 2933 !R.getAsSingle<FunctionTemplateDecl>() && 2934 !ShouldLookupResultBeMultiVersionOverload(R)) 2935 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2936 R.getRepresentativeDecl(), nullptr, 2937 AcceptInvalidDecl); 2938 2939 // We only need to check the declaration if there's exactly one 2940 // result, because in the overloaded case the results can only be 2941 // functions and function templates. 2942 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2943 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2944 return ExprError(); 2945 2946 // Otherwise, just build an unresolved lookup expression. Suppress 2947 // any lookup-related diagnostics; we'll hash these out later, when 2948 // we've picked a target. 2949 R.suppressDiagnostics(); 2950 2951 UnresolvedLookupExpr *ULE 2952 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2953 SS.getWithLocInContext(Context), 2954 R.getLookupNameInfo(), 2955 NeedsADL, R.isOverloadedResult(), 2956 R.begin(), R.end()); 2957 2958 return ULE; 2959 } 2960 2961 static void 2962 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2963 ValueDecl *var, DeclContext *DC); 2964 2965 /// Complete semantic analysis for a reference to the given declaration. 2966 ExprResult Sema::BuildDeclarationNameExpr( 2967 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2968 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2969 bool AcceptInvalidDecl) { 2970 assert(D && "Cannot refer to a NULL declaration"); 2971 assert(!isa<FunctionTemplateDecl>(D) && 2972 "Cannot refer unambiguously to a function template"); 2973 2974 SourceLocation Loc = NameInfo.getLoc(); 2975 if (CheckDeclInExpr(*this, Loc, D)) 2976 return ExprError(); 2977 2978 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2979 // Specifically diagnose references to class templates that are missing 2980 // a template argument list. 2981 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2982 return ExprError(); 2983 } 2984 2985 // Make sure that we're referring to a value. 2986 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2987 if (!VD) { 2988 Diag(Loc, diag::err_ref_non_value) 2989 << D << SS.getRange(); 2990 Diag(D->getLocation(), diag::note_declared_at); 2991 return ExprError(); 2992 } 2993 2994 // Check whether this declaration can be used. Note that we suppress 2995 // this check when we're going to perform argument-dependent lookup 2996 // on this function name, because this might not be the function 2997 // that overload resolution actually selects. 2998 if (DiagnoseUseOfDecl(VD, Loc)) 2999 return ExprError(); 3000 3001 // Only create DeclRefExpr's for valid Decl's. 3002 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3003 return ExprError(); 3004 3005 // Handle members of anonymous structs and unions. If we got here, 3006 // and the reference is to a class member indirect field, then this 3007 // must be the subject of a pointer-to-member expression. 3008 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3009 if (!indirectField->isCXXClassMember()) 3010 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3011 indirectField); 3012 3013 { 3014 QualType type = VD->getType(); 3015 if (type.isNull()) 3016 return ExprError(); 3017 if (auto *FPT = type->getAs<FunctionProtoType>()) { 3018 // C++ [except.spec]p17: 3019 // An exception-specification is considered to be needed when: 3020 // - in an expression, the function is the unique lookup result or 3021 // the selected member of a set of overloaded functions. 3022 ResolveExceptionSpec(Loc, FPT); 3023 type = VD->getType(); 3024 } 3025 ExprValueKind valueKind = VK_RValue; 3026 3027 switch (D->getKind()) { 3028 // Ignore all the non-ValueDecl kinds. 3029 #define ABSTRACT_DECL(kind) 3030 #define VALUE(type, base) 3031 #define DECL(type, base) \ 3032 case Decl::type: 3033 #include "clang/AST/DeclNodes.inc" 3034 llvm_unreachable("invalid value decl kind"); 3035 3036 // These shouldn't make it here. 3037 case Decl::ObjCAtDefsField: 3038 llvm_unreachable("forming non-member reference to ivar?"); 3039 3040 // Enum constants are always r-values and never references. 3041 // Unresolved using declarations are dependent. 3042 case Decl::EnumConstant: 3043 case Decl::UnresolvedUsingValue: 3044 case Decl::OMPDeclareReduction: 3045 case Decl::OMPDeclareMapper: 3046 valueKind = VK_RValue; 3047 break; 3048 3049 // Fields and indirect fields that got here must be for 3050 // pointer-to-member expressions; we just call them l-values for 3051 // internal consistency, because this subexpression doesn't really 3052 // exist in the high-level semantics. 3053 case Decl::Field: 3054 case Decl::IndirectField: 3055 case Decl::ObjCIvar: 3056 assert(getLangOpts().CPlusPlus && 3057 "building reference to field in C?"); 3058 3059 // These can't have reference type in well-formed programs, but 3060 // for internal consistency we do this anyway. 3061 type = type.getNonReferenceType(); 3062 valueKind = VK_LValue; 3063 break; 3064 3065 // Non-type template parameters are either l-values or r-values 3066 // depending on the type. 3067 case Decl::NonTypeTemplateParm: { 3068 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3069 type = reftype->getPointeeType(); 3070 valueKind = VK_LValue; // even if the parameter is an r-value reference 3071 break; 3072 } 3073 3074 // For non-references, we need to strip qualifiers just in case 3075 // the template parameter was declared as 'const int' or whatever. 3076 valueKind = VK_RValue; 3077 type = type.getUnqualifiedType(); 3078 break; 3079 } 3080 3081 case Decl::Var: 3082 case Decl::VarTemplateSpecialization: 3083 case Decl::VarTemplatePartialSpecialization: 3084 case Decl::Decomposition: 3085 case Decl::OMPCapturedExpr: 3086 // In C, "extern void blah;" is valid and is an r-value. 3087 if (!getLangOpts().CPlusPlus && 3088 !type.hasQualifiers() && 3089 type->isVoidType()) { 3090 valueKind = VK_RValue; 3091 break; 3092 } 3093 LLVM_FALLTHROUGH; 3094 3095 case Decl::ImplicitParam: 3096 case Decl::ParmVar: { 3097 // These are always l-values. 3098 valueKind = VK_LValue; 3099 type = type.getNonReferenceType(); 3100 3101 // FIXME: Does the addition of const really only apply in 3102 // potentially-evaluated contexts? Since the variable isn't actually 3103 // captured in an unevaluated context, it seems that the answer is no. 3104 if (!isUnevaluatedContext()) { 3105 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3106 if (!CapturedType.isNull()) 3107 type = CapturedType; 3108 } 3109 3110 break; 3111 } 3112 3113 case Decl::Binding: { 3114 // These are always lvalues. 3115 valueKind = VK_LValue; 3116 type = type.getNonReferenceType(); 3117 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3118 // decides how that's supposed to work. 3119 auto *BD = cast<BindingDecl>(VD); 3120 if (BD->getDeclContext() != CurContext) { 3121 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3122 if (DD && DD->hasLocalStorage()) 3123 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3124 } 3125 break; 3126 } 3127 3128 case Decl::Function: { 3129 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3130 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3131 type = Context.BuiltinFnTy; 3132 valueKind = VK_RValue; 3133 break; 3134 } 3135 } 3136 3137 const FunctionType *fty = type->castAs<FunctionType>(); 3138 3139 // If we're referring to a function with an __unknown_anytype 3140 // result type, make the entire expression __unknown_anytype. 3141 if (fty->getReturnType() == Context.UnknownAnyTy) { 3142 type = Context.UnknownAnyTy; 3143 valueKind = VK_RValue; 3144 break; 3145 } 3146 3147 // Functions are l-values in C++. 3148 if (getLangOpts().CPlusPlus) { 3149 valueKind = VK_LValue; 3150 break; 3151 } 3152 3153 // C99 DR 316 says that, if a function type comes from a 3154 // function definition (without a prototype), that type is only 3155 // used for checking compatibility. Therefore, when referencing 3156 // the function, we pretend that we don't have the full function 3157 // type. 3158 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3159 isa<FunctionProtoType>(fty)) 3160 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3161 fty->getExtInfo()); 3162 3163 // Functions are r-values in C. 3164 valueKind = VK_RValue; 3165 break; 3166 } 3167 3168 case Decl::CXXDeductionGuide: 3169 llvm_unreachable("building reference to deduction guide"); 3170 3171 case Decl::MSProperty: 3172 valueKind = VK_LValue; 3173 break; 3174 3175 case Decl::CXXMethod: 3176 // If we're referring to a method with an __unknown_anytype 3177 // result type, make the entire expression __unknown_anytype. 3178 // This should only be possible with a type written directly. 3179 if (const FunctionProtoType *proto 3180 = dyn_cast<FunctionProtoType>(VD->getType())) 3181 if (proto->getReturnType() == Context.UnknownAnyTy) { 3182 type = Context.UnknownAnyTy; 3183 valueKind = VK_RValue; 3184 break; 3185 } 3186 3187 // C++ methods are l-values if static, r-values if non-static. 3188 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3189 valueKind = VK_LValue; 3190 break; 3191 } 3192 LLVM_FALLTHROUGH; 3193 3194 case Decl::CXXConversion: 3195 case Decl::CXXDestructor: 3196 case Decl::CXXConstructor: 3197 valueKind = VK_RValue; 3198 break; 3199 } 3200 3201 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3202 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3203 TemplateArgs); 3204 } 3205 } 3206 3207 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3208 SmallString<32> &Target) { 3209 Target.resize(CharByteWidth * (Source.size() + 1)); 3210 char *ResultPtr = &Target[0]; 3211 const llvm::UTF8 *ErrorPtr; 3212 bool success = 3213 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3214 (void)success; 3215 assert(success); 3216 Target.resize(ResultPtr - &Target[0]); 3217 } 3218 3219 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3220 PredefinedExpr::IdentKind IK) { 3221 // Pick the current block, lambda, captured statement or function. 3222 Decl *currentDecl = nullptr; 3223 if (const BlockScopeInfo *BSI = getCurBlock()) 3224 currentDecl = BSI->TheDecl; 3225 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3226 currentDecl = LSI->CallOperator; 3227 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3228 currentDecl = CSI->TheCapturedDecl; 3229 else 3230 currentDecl = getCurFunctionOrMethodDecl(); 3231 3232 if (!currentDecl) { 3233 Diag(Loc, diag::ext_predef_outside_function); 3234 currentDecl = Context.getTranslationUnitDecl(); 3235 } 3236 3237 QualType ResTy; 3238 StringLiteral *SL = nullptr; 3239 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3240 ResTy = Context.DependentTy; 3241 else { 3242 // Pre-defined identifiers are of type char[x], where x is the length of 3243 // the string. 3244 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3245 unsigned Length = Str.length(); 3246 3247 llvm::APInt LengthI(32, Length + 1); 3248 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3249 ResTy = 3250 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3251 SmallString<32> RawChars; 3252 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3253 Str, RawChars); 3254 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3255 ArrayType::Normal, 3256 /*IndexTypeQuals*/ 0); 3257 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3258 /*Pascal*/ false, ResTy, Loc); 3259 } else { 3260 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3261 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3262 ArrayType::Normal, 3263 /*IndexTypeQuals*/ 0); 3264 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3265 /*Pascal*/ false, ResTy, Loc); 3266 } 3267 } 3268 3269 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3270 } 3271 3272 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3273 PredefinedExpr::IdentKind IK; 3274 3275 switch (Kind) { 3276 default: llvm_unreachable("Unknown simple primary expr!"); 3277 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3278 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3279 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3280 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3281 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3282 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3283 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3284 } 3285 3286 return BuildPredefinedExpr(Loc, IK); 3287 } 3288 3289 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3290 SmallString<16> CharBuffer; 3291 bool Invalid = false; 3292 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3293 if (Invalid) 3294 return ExprError(); 3295 3296 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3297 PP, Tok.getKind()); 3298 if (Literal.hadError()) 3299 return ExprError(); 3300 3301 QualType Ty; 3302 if (Literal.isWide()) 3303 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3304 else if (Literal.isUTF8() && getLangOpts().Char8) 3305 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3306 else if (Literal.isUTF16()) 3307 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3308 else if (Literal.isUTF32()) 3309 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3310 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3311 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3312 else 3313 Ty = Context.CharTy; // 'x' -> char in C++ 3314 3315 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3316 if (Literal.isWide()) 3317 Kind = CharacterLiteral::Wide; 3318 else if (Literal.isUTF16()) 3319 Kind = CharacterLiteral::UTF16; 3320 else if (Literal.isUTF32()) 3321 Kind = CharacterLiteral::UTF32; 3322 else if (Literal.isUTF8()) 3323 Kind = CharacterLiteral::UTF8; 3324 3325 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3326 Tok.getLocation()); 3327 3328 if (Literal.getUDSuffix().empty()) 3329 return Lit; 3330 3331 // We're building a user-defined literal. 3332 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3333 SourceLocation UDSuffixLoc = 3334 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3335 3336 // Make sure we're allowed user-defined literals here. 3337 if (!UDLScope) 3338 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3339 3340 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3341 // operator "" X (ch) 3342 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3343 Lit, Tok.getLocation()); 3344 } 3345 3346 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3347 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3348 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3349 Context.IntTy, Loc); 3350 } 3351 3352 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3353 QualType Ty, SourceLocation Loc) { 3354 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3355 3356 using llvm::APFloat; 3357 APFloat Val(Format); 3358 3359 APFloat::opStatus result = Literal.GetFloatValue(Val); 3360 3361 // Overflow is always an error, but underflow is only an error if 3362 // we underflowed to zero (APFloat reports denormals as underflow). 3363 if ((result & APFloat::opOverflow) || 3364 ((result & APFloat::opUnderflow) && Val.isZero())) { 3365 unsigned diagnostic; 3366 SmallString<20> buffer; 3367 if (result & APFloat::opOverflow) { 3368 diagnostic = diag::warn_float_overflow; 3369 APFloat::getLargest(Format).toString(buffer); 3370 } else { 3371 diagnostic = diag::warn_float_underflow; 3372 APFloat::getSmallest(Format).toString(buffer); 3373 } 3374 3375 S.Diag(Loc, diagnostic) 3376 << Ty 3377 << StringRef(buffer.data(), buffer.size()); 3378 } 3379 3380 bool isExact = (result == APFloat::opOK); 3381 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3382 } 3383 3384 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3385 assert(E && "Invalid expression"); 3386 3387 if (E->isValueDependent()) 3388 return false; 3389 3390 QualType QT = E->getType(); 3391 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3392 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3393 return true; 3394 } 3395 3396 llvm::APSInt ValueAPS; 3397 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3398 3399 if (R.isInvalid()) 3400 return true; 3401 3402 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3403 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3404 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3405 << ValueAPS.toString(10) << ValueIsPositive; 3406 return true; 3407 } 3408 3409 return false; 3410 } 3411 3412 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3413 // Fast path for a single digit (which is quite common). A single digit 3414 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3415 if (Tok.getLength() == 1) { 3416 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3417 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3418 } 3419 3420 SmallString<128> SpellingBuffer; 3421 // NumericLiteralParser wants to overread by one character. Add padding to 3422 // the buffer in case the token is copied to the buffer. If getSpelling() 3423 // returns a StringRef to the memory buffer, it should have a null char at 3424 // the EOF, so it is also safe. 3425 SpellingBuffer.resize(Tok.getLength() + 1); 3426 3427 // Get the spelling of the token, which eliminates trigraphs, etc. 3428 bool Invalid = false; 3429 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3430 if (Invalid) 3431 return ExprError(); 3432 3433 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3434 if (Literal.hadError) 3435 return ExprError(); 3436 3437 if (Literal.hasUDSuffix()) { 3438 // We're building a user-defined literal. 3439 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3440 SourceLocation UDSuffixLoc = 3441 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3442 3443 // Make sure we're allowed user-defined literals here. 3444 if (!UDLScope) 3445 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3446 3447 QualType CookedTy; 3448 if (Literal.isFloatingLiteral()) { 3449 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3450 // long double, the literal is treated as a call of the form 3451 // operator "" X (f L) 3452 CookedTy = Context.LongDoubleTy; 3453 } else { 3454 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3455 // unsigned long long, the literal is treated as a call of the form 3456 // operator "" X (n ULL) 3457 CookedTy = Context.UnsignedLongLongTy; 3458 } 3459 3460 DeclarationName OpName = 3461 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3462 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3463 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3464 3465 SourceLocation TokLoc = Tok.getLocation(); 3466 3467 // Perform literal operator lookup to determine if we're building a raw 3468 // literal or a cooked one. 3469 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3470 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3471 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3472 /*AllowStringTemplate*/ false, 3473 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3474 case LOLR_ErrorNoDiagnostic: 3475 // Lookup failure for imaginary constants isn't fatal, there's still the 3476 // GNU extension producing _Complex types. 3477 break; 3478 case LOLR_Error: 3479 return ExprError(); 3480 case LOLR_Cooked: { 3481 Expr *Lit; 3482 if (Literal.isFloatingLiteral()) { 3483 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3484 } else { 3485 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3486 if (Literal.GetIntegerValue(ResultVal)) 3487 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3488 << /* Unsigned */ 1; 3489 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3490 Tok.getLocation()); 3491 } 3492 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3493 } 3494 3495 case LOLR_Raw: { 3496 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3497 // literal is treated as a call of the form 3498 // operator "" X ("n") 3499 unsigned Length = Literal.getUDSuffixOffset(); 3500 QualType StrTy = Context.getConstantArrayType( 3501 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3502 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3503 Expr *Lit = StringLiteral::Create( 3504 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3505 /*Pascal*/false, StrTy, &TokLoc, 1); 3506 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3507 } 3508 3509 case LOLR_Template: { 3510 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3511 // template), L is treated as a call fo the form 3512 // operator "" X <'c1', 'c2', ... 'ck'>() 3513 // where n is the source character sequence c1 c2 ... ck. 3514 TemplateArgumentListInfo ExplicitArgs; 3515 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3516 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3517 llvm::APSInt Value(CharBits, CharIsUnsigned); 3518 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3519 Value = TokSpelling[I]; 3520 TemplateArgument Arg(Context, Value, Context.CharTy); 3521 TemplateArgumentLocInfo ArgInfo; 3522 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3523 } 3524 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3525 &ExplicitArgs); 3526 } 3527 case LOLR_StringTemplate: 3528 llvm_unreachable("unexpected literal operator lookup result"); 3529 } 3530 } 3531 3532 Expr *Res; 3533 3534 if (Literal.isFixedPointLiteral()) { 3535 QualType Ty; 3536 3537 if (Literal.isAccum) { 3538 if (Literal.isHalf) { 3539 Ty = Context.ShortAccumTy; 3540 } else if (Literal.isLong) { 3541 Ty = Context.LongAccumTy; 3542 } else { 3543 Ty = Context.AccumTy; 3544 } 3545 } else if (Literal.isFract) { 3546 if (Literal.isHalf) { 3547 Ty = Context.ShortFractTy; 3548 } else if (Literal.isLong) { 3549 Ty = Context.LongFractTy; 3550 } else { 3551 Ty = Context.FractTy; 3552 } 3553 } 3554 3555 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3556 3557 bool isSigned = !Literal.isUnsigned; 3558 unsigned scale = Context.getFixedPointScale(Ty); 3559 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3560 3561 llvm::APInt Val(bit_width, 0, isSigned); 3562 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3563 bool ValIsZero = Val.isNullValue() && !Overflowed; 3564 3565 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3566 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3567 // Clause 6.4.4 - The value of a constant shall be in the range of 3568 // representable values for its type, with exception for constants of a 3569 // fract type with a value of exactly 1; such a constant shall denote 3570 // the maximal value for the type. 3571 --Val; 3572 else if (Val.ugt(MaxVal) || Overflowed) 3573 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3574 3575 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3576 Tok.getLocation(), scale); 3577 } else if (Literal.isFloatingLiteral()) { 3578 QualType Ty; 3579 if (Literal.isHalf){ 3580 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3581 Ty = Context.HalfTy; 3582 else { 3583 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3584 return ExprError(); 3585 } 3586 } else if (Literal.isFloat) 3587 Ty = Context.FloatTy; 3588 else if (Literal.isLong) 3589 Ty = Context.LongDoubleTy; 3590 else if (Literal.isFloat16) 3591 Ty = Context.Float16Ty; 3592 else if (Literal.isFloat128) 3593 Ty = Context.Float128Ty; 3594 else 3595 Ty = Context.DoubleTy; 3596 3597 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3598 3599 if (Ty == Context.DoubleTy) { 3600 if (getLangOpts().SinglePrecisionConstants) { 3601 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3602 if (BTy->getKind() != BuiltinType::Float) { 3603 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3604 } 3605 } else if (getLangOpts().OpenCL && 3606 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3607 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3608 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3609 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3610 } 3611 } 3612 } else if (!Literal.isIntegerLiteral()) { 3613 return ExprError(); 3614 } else { 3615 QualType Ty; 3616 3617 // 'long long' is a C99 or C++11 feature. 3618 if (!getLangOpts().C99 && Literal.isLongLong) { 3619 if (getLangOpts().CPlusPlus) 3620 Diag(Tok.getLocation(), 3621 getLangOpts().CPlusPlus11 ? 3622 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3623 else 3624 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3625 } 3626 3627 // Get the value in the widest-possible width. 3628 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3629 llvm::APInt ResultVal(MaxWidth, 0); 3630 3631 if (Literal.GetIntegerValue(ResultVal)) { 3632 // If this value didn't fit into uintmax_t, error and force to ull. 3633 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3634 << /* Unsigned */ 1; 3635 Ty = Context.UnsignedLongLongTy; 3636 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3637 "long long is not intmax_t?"); 3638 } else { 3639 // If this value fits into a ULL, try to figure out what else it fits into 3640 // according to the rules of C99 6.4.4.1p5. 3641 3642 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3643 // be an unsigned int. 3644 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3645 3646 // Check from smallest to largest, picking the smallest type we can. 3647 unsigned Width = 0; 3648 3649 // Microsoft specific integer suffixes are explicitly sized. 3650 if (Literal.MicrosoftInteger) { 3651 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3652 Width = 8; 3653 Ty = Context.CharTy; 3654 } else { 3655 Width = Literal.MicrosoftInteger; 3656 Ty = Context.getIntTypeForBitwidth(Width, 3657 /*Signed=*/!Literal.isUnsigned); 3658 } 3659 } 3660 3661 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3662 // Are int/unsigned possibilities? 3663 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3664 3665 // Does it fit in a unsigned int? 3666 if (ResultVal.isIntN(IntSize)) { 3667 // Does it fit in a signed int? 3668 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3669 Ty = Context.IntTy; 3670 else if (AllowUnsigned) 3671 Ty = Context.UnsignedIntTy; 3672 Width = IntSize; 3673 } 3674 } 3675 3676 // Are long/unsigned long possibilities? 3677 if (Ty.isNull() && !Literal.isLongLong) { 3678 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3679 3680 // Does it fit in a unsigned long? 3681 if (ResultVal.isIntN(LongSize)) { 3682 // Does it fit in a signed long? 3683 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3684 Ty = Context.LongTy; 3685 else if (AllowUnsigned) 3686 Ty = Context.UnsignedLongTy; 3687 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3688 // is compatible. 3689 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3690 const unsigned LongLongSize = 3691 Context.getTargetInfo().getLongLongWidth(); 3692 Diag(Tok.getLocation(), 3693 getLangOpts().CPlusPlus 3694 ? Literal.isLong 3695 ? diag::warn_old_implicitly_unsigned_long_cxx 3696 : /*C++98 UB*/ diag:: 3697 ext_old_implicitly_unsigned_long_cxx 3698 : diag::warn_old_implicitly_unsigned_long) 3699 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3700 : /*will be ill-formed*/ 1); 3701 Ty = Context.UnsignedLongTy; 3702 } 3703 Width = LongSize; 3704 } 3705 } 3706 3707 // Check long long if needed. 3708 if (Ty.isNull()) { 3709 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3710 3711 // Does it fit in a unsigned long long? 3712 if (ResultVal.isIntN(LongLongSize)) { 3713 // Does it fit in a signed long long? 3714 // To be compatible with MSVC, hex integer literals ending with the 3715 // LL or i64 suffix are always signed in Microsoft mode. 3716 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3717 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3718 Ty = Context.LongLongTy; 3719 else if (AllowUnsigned) 3720 Ty = Context.UnsignedLongLongTy; 3721 Width = LongLongSize; 3722 } 3723 } 3724 3725 // If we still couldn't decide a type, we probably have something that 3726 // does not fit in a signed long long, but has no U suffix. 3727 if (Ty.isNull()) { 3728 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3729 Ty = Context.UnsignedLongLongTy; 3730 Width = Context.getTargetInfo().getLongLongWidth(); 3731 } 3732 3733 if (ResultVal.getBitWidth() != Width) 3734 ResultVal = ResultVal.trunc(Width); 3735 } 3736 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3737 } 3738 3739 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3740 if (Literal.isImaginary) { 3741 Res = new (Context) ImaginaryLiteral(Res, 3742 Context.getComplexType(Res->getType())); 3743 3744 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3745 } 3746 return Res; 3747 } 3748 3749 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3750 assert(E && "ActOnParenExpr() missing expr"); 3751 return new (Context) ParenExpr(L, R, E); 3752 } 3753 3754 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3755 SourceLocation Loc, 3756 SourceRange ArgRange) { 3757 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3758 // scalar or vector data type argument..." 3759 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3760 // type (C99 6.2.5p18) or void. 3761 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3762 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3763 << T << ArgRange; 3764 return true; 3765 } 3766 3767 assert((T->isVoidType() || !T->isIncompleteType()) && 3768 "Scalar types should always be complete"); 3769 return false; 3770 } 3771 3772 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3773 SourceLocation Loc, 3774 SourceRange ArgRange, 3775 UnaryExprOrTypeTrait TraitKind) { 3776 // Invalid types must be hard errors for SFINAE in C++. 3777 if (S.LangOpts.CPlusPlus) 3778 return true; 3779 3780 // C99 6.5.3.4p1: 3781 if (T->isFunctionType() && 3782 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3783 TraitKind == UETT_PreferredAlignOf)) { 3784 // sizeof(function)/alignof(function) is allowed as an extension. 3785 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3786 << TraitKind << ArgRange; 3787 return false; 3788 } 3789 3790 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3791 // this is an error (OpenCL v1.1 s6.3.k) 3792 if (T->isVoidType()) { 3793 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3794 : diag::ext_sizeof_alignof_void_type; 3795 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3796 return false; 3797 } 3798 3799 return true; 3800 } 3801 3802 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3803 SourceLocation Loc, 3804 SourceRange ArgRange, 3805 UnaryExprOrTypeTrait TraitKind) { 3806 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3807 // runtime doesn't allow it. 3808 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3809 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3810 << T << (TraitKind == UETT_SizeOf) 3811 << ArgRange; 3812 return true; 3813 } 3814 3815 return false; 3816 } 3817 3818 /// Check whether E is a pointer from a decayed array type (the decayed 3819 /// pointer type is equal to T) and emit a warning if it is. 3820 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3821 Expr *E) { 3822 // Don't warn if the operation changed the type. 3823 if (T != E->getType()) 3824 return; 3825 3826 // Now look for array decays. 3827 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3828 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3829 return; 3830 3831 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3832 << ICE->getType() 3833 << ICE->getSubExpr()->getType(); 3834 } 3835 3836 /// Check the constraints on expression operands to unary type expression 3837 /// and type traits. 3838 /// 3839 /// Completes any types necessary and validates the constraints on the operand 3840 /// expression. The logic mostly mirrors the type-based overload, but may modify 3841 /// the expression as it completes the type for that expression through template 3842 /// instantiation, etc. 3843 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3844 UnaryExprOrTypeTrait ExprKind) { 3845 QualType ExprTy = E->getType(); 3846 assert(!ExprTy->isReferenceType()); 3847 3848 bool IsUnevaluatedOperand = 3849 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3850 ExprKind == UETT_PreferredAlignOf); 3851 if (IsUnevaluatedOperand) { 3852 ExprResult Result = CheckUnevaluatedOperand(E); 3853 if (Result.isInvalid()) 3854 return true; 3855 E = Result.get(); 3856 } 3857 3858 if (ExprKind == UETT_VecStep) 3859 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3860 E->getSourceRange()); 3861 3862 // Whitelist some types as extensions 3863 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3864 E->getSourceRange(), ExprKind)) 3865 return false; 3866 3867 // 'alignof' applied to an expression only requires the base element type of 3868 // the expression to be complete. 'sizeof' requires the expression's type to 3869 // be complete (and will attempt to complete it if it's an array of unknown 3870 // bound). 3871 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3872 if (RequireCompleteType(E->getExprLoc(), 3873 Context.getBaseElementType(E->getType()), 3874 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3875 E->getSourceRange())) 3876 return true; 3877 } else { 3878 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3879 ExprKind, E->getSourceRange())) 3880 return true; 3881 } 3882 3883 // Completing the expression's type may have changed it. 3884 ExprTy = E->getType(); 3885 assert(!ExprTy->isReferenceType()); 3886 3887 if (ExprTy->isFunctionType()) { 3888 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3889 << ExprKind << E->getSourceRange(); 3890 return true; 3891 } 3892 3893 // The operand for sizeof and alignof is in an unevaluated expression context, 3894 // so side effects could result in unintended consequences. 3895 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3896 E->HasSideEffects(Context, false)) 3897 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3898 3899 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3900 E->getSourceRange(), ExprKind)) 3901 return true; 3902 3903 if (ExprKind == UETT_SizeOf) { 3904 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3905 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3906 QualType OType = PVD->getOriginalType(); 3907 QualType Type = PVD->getType(); 3908 if (Type->isPointerType() && OType->isArrayType()) { 3909 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3910 << Type << OType; 3911 Diag(PVD->getLocation(), diag::note_declared_at); 3912 } 3913 } 3914 } 3915 3916 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3917 // decays into a pointer and returns an unintended result. This is most 3918 // likely a typo for "sizeof(array) op x". 3919 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3920 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3921 BO->getLHS()); 3922 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3923 BO->getRHS()); 3924 } 3925 } 3926 3927 return false; 3928 } 3929 3930 /// Check the constraints on operands to unary expression and type 3931 /// traits. 3932 /// 3933 /// This will complete any types necessary, and validate the various constraints 3934 /// on those operands. 3935 /// 3936 /// The UsualUnaryConversions() function is *not* called by this routine. 3937 /// C99 6.3.2.1p[2-4] all state: 3938 /// Except when it is the operand of the sizeof operator ... 3939 /// 3940 /// C++ [expr.sizeof]p4 3941 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3942 /// standard conversions are not applied to the operand of sizeof. 3943 /// 3944 /// This policy is followed for all of the unary trait expressions. 3945 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3946 SourceLocation OpLoc, 3947 SourceRange ExprRange, 3948 UnaryExprOrTypeTrait ExprKind) { 3949 if (ExprType->isDependentType()) 3950 return false; 3951 3952 // C++ [expr.sizeof]p2: 3953 // When applied to a reference or a reference type, the result 3954 // is the size of the referenced type. 3955 // C++11 [expr.alignof]p3: 3956 // When alignof is applied to a reference type, the result 3957 // shall be the alignment of the referenced type. 3958 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3959 ExprType = Ref->getPointeeType(); 3960 3961 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3962 // When alignof or _Alignof is applied to an array type, the result 3963 // is the alignment of the element type. 3964 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3965 ExprKind == UETT_OpenMPRequiredSimdAlign) 3966 ExprType = Context.getBaseElementType(ExprType); 3967 3968 if (ExprKind == UETT_VecStep) 3969 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3970 3971 // Whitelist some types as extensions 3972 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3973 ExprKind)) 3974 return false; 3975 3976 if (RequireCompleteType(OpLoc, ExprType, 3977 diag::err_sizeof_alignof_incomplete_type, 3978 ExprKind, ExprRange)) 3979 return true; 3980 3981 if (ExprType->isFunctionType()) { 3982 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3983 << ExprKind << ExprRange; 3984 return true; 3985 } 3986 3987 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3988 ExprKind)) 3989 return true; 3990 3991 return false; 3992 } 3993 3994 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3995 // Cannot know anything else if the expression is dependent. 3996 if (E->isTypeDependent()) 3997 return false; 3998 3999 if (E->getObjectKind() == OK_BitField) { 4000 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4001 << 1 << E->getSourceRange(); 4002 return true; 4003 } 4004 4005 ValueDecl *D = nullptr; 4006 Expr *Inner = E->IgnoreParens(); 4007 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4008 D = DRE->getDecl(); 4009 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4010 D = ME->getMemberDecl(); 4011 } 4012 4013 // If it's a field, require the containing struct to have a 4014 // complete definition so that we can compute the layout. 4015 // 4016 // This can happen in C++11 onwards, either by naming the member 4017 // in a way that is not transformed into a member access expression 4018 // (in an unevaluated operand, for instance), or by naming the member 4019 // in a trailing-return-type. 4020 // 4021 // For the record, since __alignof__ on expressions is a GCC 4022 // extension, GCC seems to permit this but always gives the 4023 // nonsensical answer 0. 4024 // 4025 // We don't really need the layout here --- we could instead just 4026 // directly check for all the appropriate alignment-lowing 4027 // attributes --- but that would require duplicating a lot of 4028 // logic that just isn't worth duplicating for such a marginal 4029 // use-case. 4030 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4031 // Fast path this check, since we at least know the record has a 4032 // definition if we can find a member of it. 4033 if (!FD->getParent()->isCompleteDefinition()) { 4034 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4035 << E->getSourceRange(); 4036 return true; 4037 } 4038 4039 // Otherwise, if it's a field, and the field doesn't have 4040 // reference type, then it must have a complete type (or be a 4041 // flexible array member, which we explicitly want to 4042 // white-list anyway), which makes the following checks trivial. 4043 if (!FD->getType()->isReferenceType()) 4044 return false; 4045 } 4046 4047 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4048 } 4049 4050 bool Sema::CheckVecStepExpr(Expr *E) { 4051 E = E->IgnoreParens(); 4052 4053 // Cannot know anything else if the expression is dependent. 4054 if (E->isTypeDependent()) 4055 return false; 4056 4057 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4058 } 4059 4060 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4061 CapturingScopeInfo *CSI) { 4062 assert(T->isVariablyModifiedType()); 4063 assert(CSI != nullptr); 4064 4065 // We're going to walk down into the type and look for VLA expressions. 4066 do { 4067 const Type *Ty = T.getTypePtr(); 4068 switch (Ty->getTypeClass()) { 4069 #define TYPE(Class, Base) 4070 #define ABSTRACT_TYPE(Class, Base) 4071 #define NON_CANONICAL_TYPE(Class, Base) 4072 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4073 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4074 #include "clang/AST/TypeNodes.inc" 4075 T = QualType(); 4076 break; 4077 // These types are never variably-modified. 4078 case Type::Builtin: 4079 case Type::Complex: 4080 case Type::Vector: 4081 case Type::ExtVector: 4082 case Type::Record: 4083 case Type::Enum: 4084 case Type::Elaborated: 4085 case Type::TemplateSpecialization: 4086 case Type::ObjCObject: 4087 case Type::ObjCInterface: 4088 case Type::ObjCObjectPointer: 4089 case Type::ObjCTypeParam: 4090 case Type::Pipe: 4091 llvm_unreachable("type class is never variably-modified!"); 4092 case Type::Adjusted: 4093 T = cast<AdjustedType>(Ty)->getOriginalType(); 4094 break; 4095 case Type::Decayed: 4096 T = cast<DecayedType>(Ty)->getPointeeType(); 4097 break; 4098 case Type::Pointer: 4099 T = cast<PointerType>(Ty)->getPointeeType(); 4100 break; 4101 case Type::BlockPointer: 4102 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4103 break; 4104 case Type::LValueReference: 4105 case Type::RValueReference: 4106 T = cast<ReferenceType>(Ty)->getPointeeType(); 4107 break; 4108 case Type::MemberPointer: 4109 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4110 break; 4111 case Type::ConstantArray: 4112 case Type::IncompleteArray: 4113 // Losing element qualification here is fine. 4114 T = cast<ArrayType>(Ty)->getElementType(); 4115 break; 4116 case Type::VariableArray: { 4117 // Losing element qualification here is fine. 4118 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4119 4120 // Unknown size indication requires no size computation. 4121 // Otherwise, evaluate and record it. 4122 auto Size = VAT->getSizeExpr(); 4123 if (Size && !CSI->isVLATypeCaptured(VAT) && 4124 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4125 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4126 4127 T = VAT->getElementType(); 4128 break; 4129 } 4130 case Type::FunctionProto: 4131 case Type::FunctionNoProto: 4132 T = cast<FunctionType>(Ty)->getReturnType(); 4133 break; 4134 case Type::Paren: 4135 case Type::TypeOf: 4136 case Type::UnaryTransform: 4137 case Type::Attributed: 4138 case Type::SubstTemplateTypeParm: 4139 case Type::PackExpansion: 4140 case Type::MacroQualified: 4141 // Keep walking after single level desugaring. 4142 T = T.getSingleStepDesugaredType(Context); 4143 break; 4144 case Type::Typedef: 4145 T = cast<TypedefType>(Ty)->desugar(); 4146 break; 4147 case Type::Decltype: 4148 T = cast<DecltypeType>(Ty)->desugar(); 4149 break; 4150 case Type::Auto: 4151 case Type::DeducedTemplateSpecialization: 4152 T = cast<DeducedType>(Ty)->getDeducedType(); 4153 break; 4154 case Type::TypeOfExpr: 4155 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4156 break; 4157 case Type::Atomic: 4158 T = cast<AtomicType>(Ty)->getValueType(); 4159 break; 4160 } 4161 } while (!T.isNull() && T->isVariablyModifiedType()); 4162 } 4163 4164 /// Build a sizeof or alignof expression given a type operand. 4165 ExprResult 4166 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4167 SourceLocation OpLoc, 4168 UnaryExprOrTypeTrait ExprKind, 4169 SourceRange R) { 4170 if (!TInfo) 4171 return ExprError(); 4172 4173 QualType T = TInfo->getType(); 4174 4175 if (!T->isDependentType() && 4176 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4177 return ExprError(); 4178 4179 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4180 if (auto *TT = T->getAs<TypedefType>()) { 4181 for (auto I = FunctionScopes.rbegin(), 4182 E = std::prev(FunctionScopes.rend()); 4183 I != E; ++I) { 4184 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4185 if (CSI == nullptr) 4186 break; 4187 DeclContext *DC = nullptr; 4188 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4189 DC = LSI->CallOperator; 4190 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4191 DC = CRSI->TheCapturedDecl; 4192 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4193 DC = BSI->TheDecl; 4194 if (DC) { 4195 if (DC->containsDecl(TT->getDecl())) 4196 break; 4197 captureVariablyModifiedType(Context, T, CSI); 4198 } 4199 } 4200 } 4201 } 4202 4203 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4204 return new (Context) UnaryExprOrTypeTraitExpr( 4205 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4206 } 4207 4208 /// Build a sizeof or alignof expression given an expression 4209 /// operand. 4210 ExprResult 4211 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4212 UnaryExprOrTypeTrait ExprKind) { 4213 ExprResult PE = CheckPlaceholderExpr(E); 4214 if (PE.isInvalid()) 4215 return ExprError(); 4216 4217 E = PE.get(); 4218 4219 // Verify that the operand is valid. 4220 bool isInvalid = false; 4221 if (E->isTypeDependent()) { 4222 // Delay type-checking for type-dependent expressions. 4223 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4224 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4225 } else if (ExprKind == UETT_VecStep) { 4226 isInvalid = CheckVecStepExpr(E); 4227 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4228 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4229 isInvalid = true; 4230 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4231 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4232 isInvalid = true; 4233 } else { 4234 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4235 } 4236 4237 if (isInvalid) 4238 return ExprError(); 4239 4240 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4241 PE = TransformToPotentiallyEvaluated(E); 4242 if (PE.isInvalid()) return ExprError(); 4243 E = PE.get(); 4244 } 4245 4246 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4247 return new (Context) UnaryExprOrTypeTraitExpr( 4248 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4249 } 4250 4251 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4252 /// expr and the same for @c alignof and @c __alignof 4253 /// Note that the ArgRange is invalid if isType is false. 4254 ExprResult 4255 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4256 UnaryExprOrTypeTrait ExprKind, bool IsType, 4257 void *TyOrEx, SourceRange ArgRange) { 4258 // If error parsing type, ignore. 4259 if (!TyOrEx) return ExprError(); 4260 4261 if (IsType) { 4262 TypeSourceInfo *TInfo; 4263 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4264 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4265 } 4266 4267 Expr *ArgEx = (Expr *)TyOrEx; 4268 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4269 return Result; 4270 } 4271 4272 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4273 bool IsReal) { 4274 if (V.get()->isTypeDependent()) 4275 return S.Context.DependentTy; 4276 4277 // _Real and _Imag are only l-values for normal l-values. 4278 if (V.get()->getObjectKind() != OK_Ordinary) { 4279 V = S.DefaultLvalueConversion(V.get()); 4280 if (V.isInvalid()) 4281 return QualType(); 4282 } 4283 4284 // These operators return the element type of a complex type. 4285 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4286 return CT->getElementType(); 4287 4288 // Otherwise they pass through real integer and floating point types here. 4289 if (V.get()->getType()->isArithmeticType()) 4290 return V.get()->getType(); 4291 4292 // Test for placeholders. 4293 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4294 if (PR.isInvalid()) return QualType(); 4295 if (PR.get() != V.get()) { 4296 V = PR; 4297 return CheckRealImagOperand(S, V, Loc, IsReal); 4298 } 4299 4300 // Reject anything else. 4301 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4302 << (IsReal ? "__real" : "__imag"); 4303 return QualType(); 4304 } 4305 4306 4307 4308 ExprResult 4309 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4310 tok::TokenKind Kind, Expr *Input) { 4311 UnaryOperatorKind Opc; 4312 switch (Kind) { 4313 default: llvm_unreachable("Unknown unary op!"); 4314 case tok::plusplus: Opc = UO_PostInc; break; 4315 case tok::minusminus: Opc = UO_PostDec; break; 4316 } 4317 4318 // Since this might is a postfix expression, get rid of ParenListExprs. 4319 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4320 if (Result.isInvalid()) return ExprError(); 4321 Input = Result.get(); 4322 4323 return BuildUnaryOp(S, OpLoc, Opc, Input); 4324 } 4325 4326 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4327 /// 4328 /// \return true on error 4329 static bool checkArithmeticOnObjCPointer(Sema &S, 4330 SourceLocation opLoc, 4331 Expr *op) { 4332 assert(op->getType()->isObjCObjectPointerType()); 4333 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4334 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4335 return false; 4336 4337 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4338 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4339 << op->getSourceRange(); 4340 return true; 4341 } 4342 4343 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4344 auto *BaseNoParens = Base->IgnoreParens(); 4345 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4346 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4347 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4348 } 4349 4350 ExprResult 4351 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4352 Expr *idx, SourceLocation rbLoc) { 4353 if (base && !base->getType().isNull() && 4354 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4355 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4356 /*Length=*/nullptr, rbLoc); 4357 4358 // Since this might be a postfix expression, get rid of ParenListExprs. 4359 if (isa<ParenListExpr>(base)) { 4360 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4361 if (result.isInvalid()) return ExprError(); 4362 base = result.get(); 4363 } 4364 4365 // A comma-expression as the index is deprecated in C++2a onwards. 4366 if (getLangOpts().CPlusPlus2a && 4367 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4368 (isa<CXXOperatorCallExpr>(idx) && 4369 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4370 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4371 << SourceRange(base->getBeginLoc(), rbLoc); 4372 } 4373 4374 // Handle any non-overload placeholder types in the base and index 4375 // expressions. We can't handle overloads here because the other 4376 // operand might be an overloadable type, in which case the overload 4377 // resolution for the operator overload should get the first crack 4378 // at the overload. 4379 bool IsMSPropertySubscript = false; 4380 if (base->getType()->isNonOverloadPlaceholderType()) { 4381 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4382 if (!IsMSPropertySubscript) { 4383 ExprResult result = CheckPlaceholderExpr(base); 4384 if (result.isInvalid()) 4385 return ExprError(); 4386 base = result.get(); 4387 } 4388 } 4389 if (idx->getType()->isNonOverloadPlaceholderType()) { 4390 ExprResult result = CheckPlaceholderExpr(idx); 4391 if (result.isInvalid()) return ExprError(); 4392 idx = result.get(); 4393 } 4394 4395 // Build an unanalyzed expression if either operand is type-dependent. 4396 if (getLangOpts().CPlusPlus && 4397 (base->isTypeDependent() || idx->isTypeDependent())) { 4398 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4399 VK_LValue, OK_Ordinary, rbLoc); 4400 } 4401 4402 // MSDN, property (C++) 4403 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4404 // This attribute can also be used in the declaration of an empty array in a 4405 // class or structure definition. For example: 4406 // __declspec(property(get=GetX, put=PutX)) int x[]; 4407 // The above statement indicates that x[] can be used with one or more array 4408 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4409 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4410 if (IsMSPropertySubscript) { 4411 // Build MS property subscript expression if base is MS property reference 4412 // or MS property subscript. 4413 return new (Context) MSPropertySubscriptExpr( 4414 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4415 } 4416 4417 // Use C++ overloaded-operator rules if either operand has record 4418 // type. The spec says to do this if either type is *overloadable*, 4419 // but enum types can't declare subscript operators or conversion 4420 // operators, so there's nothing interesting for overload resolution 4421 // to do if there aren't any record types involved. 4422 // 4423 // ObjC pointers have their own subscripting logic that is not tied 4424 // to overload resolution and so should not take this path. 4425 if (getLangOpts().CPlusPlus && 4426 (base->getType()->isRecordType() || 4427 (!base->getType()->isObjCObjectPointerType() && 4428 idx->getType()->isRecordType()))) { 4429 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4430 } 4431 4432 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4433 4434 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4435 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4436 4437 return Res; 4438 } 4439 4440 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4441 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4442 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4443 4444 // For expressions like `&(*s).b`, the base is recorded and what should be 4445 // checked. 4446 const MemberExpr *Member = nullptr; 4447 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4448 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4449 4450 LastRecord.PossibleDerefs.erase(StrippedExpr); 4451 } 4452 4453 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4454 QualType ResultTy = E->getType(); 4455 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4456 4457 // Bail if the element is an array since it is not memory access. 4458 if (isa<ArrayType>(ResultTy)) 4459 return; 4460 4461 if (ResultTy->hasAttr(attr::NoDeref)) { 4462 LastRecord.PossibleDerefs.insert(E); 4463 return; 4464 } 4465 4466 // Check if the base type is a pointer to a member access of a struct 4467 // marked with noderef. 4468 const Expr *Base = E->getBase(); 4469 QualType BaseTy = Base->getType(); 4470 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4471 // Not a pointer access 4472 return; 4473 4474 const MemberExpr *Member = nullptr; 4475 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4476 Member->isArrow()) 4477 Base = Member->getBase(); 4478 4479 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4480 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4481 LastRecord.PossibleDerefs.insert(E); 4482 } 4483 } 4484 4485 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4486 Expr *LowerBound, 4487 SourceLocation ColonLoc, Expr *Length, 4488 SourceLocation RBLoc) { 4489 if (Base->getType()->isPlaceholderType() && 4490 !Base->getType()->isSpecificPlaceholderType( 4491 BuiltinType::OMPArraySection)) { 4492 ExprResult Result = CheckPlaceholderExpr(Base); 4493 if (Result.isInvalid()) 4494 return ExprError(); 4495 Base = Result.get(); 4496 } 4497 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4498 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4499 if (Result.isInvalid()) 4500 return ExprError(); 4501 Result = DefaultLvalueConversion(Result.get()); 4502 if (Result.isInvalid()) 4503 return ExprError(); 4504 LowerBound = Result.get(); 4505 } 4506 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4507 ExprResult Result = CheckPlaceholderExpr(Length); 4508 if (Result.isInvalid()) 4509 return ExprError(); 4510 Result = DefaultLvalueConversion(Result.get()); 4511 if (Result.isInvalid()) 4512 return ExprError(); 4513 Length = Result.get(); 4514 } 4515 4516 // Build an unanalyzed expression if either operand is type-dependent. 4517 if (Base->isTypeDependent() || 4518 (LowerBound && 4519 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4520 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4521 return new (Context) 4522 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4523 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4524 } 4525 4526 // Perform default conversions. 4527 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4528 QualType ResultTy; 4529 if (OriginalTy->isAnyPointerType()) { 4530 ResultTy = OriginalTy->getPointeeType(); 4531 } else if (OriginalTy->isArrayType()) { 4532 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4533 } else { 4534 return ExprError( 4535 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4536 << Base->getSourceRange()); 4537 } 4538 // C99 6.5.2.1p1 4539 if (LowerBound) { 4540 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4541 LowerBound); 4542 if (Res.isInvalid()) 4543 return ExprError(Diag(LowerBound->getExprLoc(), 4544 diag::err_omp_typecheck_section_not_integer) 4545 << 0 << LowerBound->getSourceRange()); 4546 LowerBound = Res.get(); 4547 4548 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4549 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4550 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4551 << 0 << LowerBound->getSourceRange(); 4552 } 4553 if (Length) { 4554 auto Res = 4555 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4556 if (Res.isInvalid()) 4557 return ExprError(Diag(Length->getExprLoc(), 4558 diag::err_omp_typecheck_section_not_integer) 4559 << 1 << Length->getSourceRange()); 4560 Length = Res.get(); 4561 4562 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4563 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4564 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4565 << 1 << Length->getSourceRange(); 4566 } 4567 4568 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4569 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4570 // type. Note that functions are not objects, and that (in C99 parlance) 4571 // incomplete types are not object types. 4572 if (ResultTy->isFunctionType()) { 4573 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4574 << ResultTy << Base->getSourceRange(); 4575 return ExprError(); 4576 } 4577 4578 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4579 diag::err_omp_section_incomplete_type, Base)) 4580 return ExprError(); 4581 4582 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4583 Expr::EvalResult Result; 4584 if (LowerBound->EvaluateAsInt(Result, Context)) { 4585 // OpenMP 4.5, [2.4 Array Sections] 4586 // The array section must be a subset of the original array. 4587 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4588 if (LowerBoundValue.isNegative()) { 4589 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4590 << LowerBound->getSourceRange(); 4591 return ExprError(); 4592 } 4593 } 4594 } 4595 4596 if (Length) { 4597 Expr::EvalResult Result; 4598 if (Length->EvaluateAsInt(Result, Context)) { 4599 // OpenMP 4.5, [2.4 Array Sections] 4600 // The length must evaluate to non-negative integers. 4601 llvm::APSInt LengthValue = Result.Val.getInt(); 4602 if (LengthValue.isNegative()) { 4603 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4604 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4605 << Length->getSourceRange(); 4606 return ExprError(); 4607 } 4608 } 4609 } else if (ColonLoc.isValid() && 4610 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4611 !OriginalTy->isVariableArrayType()))) { 4612 // OpenMP 4.5, [2.4 Array Sections] 4613 // When the size of the array dimension is not known, the length must be 4614 // specified explicitly. 4615 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4616 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4617 return ExprError(); 4618 } 4619 4620 if (!Base->getType()->isSpecificPlaceholderType( 4621 BuiltinType::OMPArraySection)) { 4622 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4623 if (Result.isInvalid()) 4624 return ExprError(); 4625 Base = Result.get(); 4626 } 4627 return new (Context) 4628 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4629 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4630 } 4631 4632 ExprResult 4633 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4634 Expr *Idx, SourceLocation RLoc) { 4635 Expr *LHSExp = Base; 4636 Expr *RHSExp = Idx; 4637 4638 ExprValueKind VK = VK_LValue; 4639 ExprObjectKind OK = OK_Ordinary; 4640 4641 // Per C++ core issue 1213, the result is an xvalue if either operand is 4642 // a non-lvalue array, and an lvalue otherwise. 4643 if (getLangOpts().CPlusPlus11) { 4644 for (auto *Op : {LHSExp, RHSExp}) { 4645 Op = Op->IgnoreImplicit(); 4646 if (Op->getType()->isArrayType() && !Op->isLValue()) 4647 VK = VK_XValue; 4648 } 4649 } 4650 4651 // Perform default conversions. 4652 if (!LHSExp->getType()->getAs<VectorType>()) { 4653 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4654 if (Result.isInvalid()) 4655 return ExprError(); 4656 LHSExp = Result.get(); 4657 } 4658 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4659 if (Result.isInvalid()) 4660 return ExprError(); 4661 RHSExp = Result.get(); 4662 4663 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4664 4665 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4666 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4667 // in the subscript position. As a result, we need to derive the array base 4668 // and index from the expression types. 4669 Expr *BaseExpr, *IndexExpr; 4670 QualType ResultType; 4671 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4672 BaseExpr = LHSExp; 4673 IndexExpr = RHSExp; 4674 ResultType = Context.DependentTy; 4675 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4676 BaseExpr = LHSExp; 4677 IndexExpr = RHSExp; 4678 ResultType = PTy->getPointeeType(); 4679 } else if (const ObjCObjectPointerType *PTy = 4680 LHSTy->getAs<ObjCObjectPointerType>()) { 4681 BaseExpr = LHSExp; 4682 IndexExpr = RHSExp; 4683 4684 // Use custom logic if this should be the pseudo-object subscript 4685 // expression. 4686 if (!LangOpts.isSubscriptPointerArithmetic()) 4687 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4688 nullptr); 4689 4690 ResultType = PTy->getPointeeType(); 4691 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4692 // Handle the uncommon case of "123[Ptr]". 4693 BaseExpr = RHSExp; 4694 IndexExpr = LHSExp; 4695 ResultType = PTy->getPointeeType(); 4696 } else if (const ObjCObjectPointerType *PTy = 4697 RHSTy->getAs<ObjCObjectPointerType>()) { 4698 // Handle the uncommon case of "123[Ptr]". 4699 BaseExpr = RHSExp; 4700 IndexExpr = LHSExp; 4701 ResultType = PTy->getPointeeType(); 4702 if (!LangOpts.isSubscriptPointerArithmetic()) { 4703 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4704 << ResultType << BaseExpr->getSourceRange(); 4705 return ExprError(); 4706 } 4707 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4708 BaseExpr = LHSExp; // vectors: V[123] 4709 IndexExpr = RHSExp; 4710 // We apply C++ DR1213 to vector subscripting too. 4711 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4712 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4713 if (Materialized.isInvalid()) 4714 return ExprError(); 4715 LHSExp = Materialized.get(); 4716 } 4717 VK = LHSExp->getValueKind(); 4718 if (VK != VK_RValue) 4719 OK = OK_VectorComponent; 4720 4721 ResultType = VTy->getElementType(); 4722 QualType BaseType = BaseExpr->getType(); 4723 Qualifiers BaseQuals = BaseType.getQualifiers(); 4724 Qualifiers MemberQuals = ResultType.getQualifiers(); 4725 Qualifiers Combined = BaseQuals + MemberQuals; 4726 if (Combined != MemberQuals) 4727 ResultType = Context.getQualifiedType(ResultType, Combined); 4728 } else if (LHSTy->isArrayType()) { 4729 // If we see an array that wasn't promoted by 4730 // DefaultFunctionArrayLvalueConversion, it must be an array that 4731 // wasn't promoted because of the C90 rule that doesn't 4732 // allow promoting non-lvalue arrays. Warn, then 4733 // force the promotion here. 4734 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4735 << LHSExp->getSourceRange(); 4736 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4737 CK_ArrayToPointerDecay).get(); 4738 LHSTy = LHSExp->getType(); 4739 4740 BaseExpr = LHSExp; 4741 IndexExpr = RHSExp; 4742 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4743 } else if (RHSTy->isArrayType()) { 4744 // Same as previous, except for 123[f().a] case 4745 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4746 << RHSExp->getSourceRange(); 4747 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4748 CK_ArrayToPointerDecay).get(); 4749 RHSTy = RHSExp->getType(); 4750 4751 BaseExpr = RHSExp; 4752 IndexExpr = LHSExp; 4753 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4754 } else { 4755 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4756 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4757 } 4758 // C99 6.5.2.1p1 4759 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4760 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4761 << IndexExpr->getSourceRange()); 4762 4763 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4764 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4765 && !IndexExpr->isTypeDependent()) 4766 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4767 4768 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4769 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4770 // type. Note that Functions are not objects, and that (in C99 parlance) 4771 // incomplete types are not object types. 4772 if (ResultType->isFunctionType()) { 4773 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4774 << ResultType << BaseExpr->getSourceRange(); 4775 return ExprError(); 4776 } 4777 4778 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4779 // GNU extension: subscripting on pointer to void 4780 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4781 << BaseExpr->getSourceRange(); 4782 4783 // C forbids expressions of unqualified void type from being l-values. 4784 // See IsCForbiddenLValueType. 4785 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4786 } else if (!ResultType->isDependentType() && 4787 RequireCompleteType(LLoc, ResultType, 4788 diag::err_subscript_incomplete_type, BaseExpr)) 4789 return ExprError(); 4790 4791 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4792 !ResultType.isCForbiddenLValueType()); 4793 4794 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4795 FunctionScopes.size() > 1) { 4796 if (auto *TT = 4797 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4798 for (auto I = FunctionScopes.rbegin(), 4799 E = std::prev(FunctionScopes.rend()); 4800 I != E; ++I) { 4801 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4802 if (CSI == nullptr) 4803 break; 4804 DeclContext *DC = nullptr; 4805 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4806 DC = LSI->CallOperator; 4807 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4808 DC = CRSI->TheCapturedDecl; 4809 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4810 DC = BSI->TheDecl; 4811 if (DC) { 4812 if (DC->containsDecl(TT->getDecl())) 4813 break; 4814 captureVariablyModifiedType( 4815 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4816 } 4817 } 4818 } 4819 } 4820 4821 return new (Context) 4822 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4823 } 4824 4825 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4826 ParmVarDecl *Param) { 4827 if (Param->hasUnparsedDefaultArg()) { 4828 Diag(CallLoc, 4829 diag::err_use_of_default_argument_to_function_declared_later) << 4830 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4831 Diag(UnparsedDefaultArgLocs[Param], 4832 diag::note_default_argument_declared_here); 4833 return true; 4834 } 4835 4836 if (Param->hasUninstantiatedDefaultArg()) { 4837 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4838 4839 EnterExpressionEvaluationContext EvalContext( 4840 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4841 4842 // Instantiate the expression. 4843 // 4844 // FIXME: Pass in a correct Pattern argument, otherwise 4845 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4846 // 4847 // template<typename T> 4848 // struct A { 4849 // static int FooImpl(); 4850 // 4851 // template<typename Tp> 4852 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4853 // // template argument list [[T], [Tp]], should be [[Tp]]. 4854 // friend A<Tp> Foo(int a); 4855 // }; 4856 // 4857 // template<typename T> 4858 // A<T> Foo(int a = A<T>::FooImpl()); 4859 MultiLevelTemplateArgumentList MutiLevelArgList 4860 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4861 4862 InstantiatingTemplate Inst(*this, CallLoc, Param, 4863 MutiLevelArgList.getInnermost()); 4864 if (Inst.isInvalid()) 4865 return true; 4866 if (Inst.isAlreadyInstantiating()) { 4867 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4868 Param->setInvalidDecl(); 4869 return true; 4870 } 4871 4872 ExprResult Result; 4873 { 4874 // C++ [dcl.fct.default]p5: 4875 // The names in the [default argument] expression are bound, and 4876 // the semantic constraints are checked, at the point where the 4877 // default argument expression appears. 4878 ContextRAII SavedContext(*this, FD); 4879 LocalInstantiationScope Local(*this); 4880 runWithSufficientStackSpace(CallLoc, [&] { 4881 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4882 /*DirectInit*/false); 4883 }); 4884 } 4885 if (Result.isInvalid()) 4886 return true; 4887 4888 // Check the expression as an initializer for the parameter. 4889 InitializedEntity Entity 4890 = InitializedEntity::InitializeParameter(Context, Param); 4891 InitializationKind Kind = InitializationKind::CreateCopy( 4892 Param->getLocation(), 4893 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4894 Expr *ResultE = Result.getAs<Expr>(); 4895 4896 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4897 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4898 if (Result.isInvalid()) 4899 return true; 4900 4901 Result = 4902 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4903 /*DiscardedValue*/ false); 4904 if (Result.isInvalid()) 4905 return true; 4906 4907 // Remember the instantiated default argument. 4908 Param->setDefaultArg(Result.getAs<Expr>()); 4909 if (ASTMutationListener *L = getASTMutationListener()) { 4910 L->DefaultArgumentInstantiated(Param); 4911 } 4912 } 4913 4914 // If the default argument expression is not set yet, we are building it now. 4915 if (!Param->hasInit()) { 4916 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4917 Param->setInvalidDecl(); 4918 return true; 4919 } 4920 4921 // If the default expression creates temporaries, we need to 4922 // push them to the current stack of expression temporaries so they'll 4923 // be properly destroyed. 4924 // FIXME: We should really be rebuilding the default argument with new 4925 // bound temporaries; see the comment in PR5810. 4926 // We don't need to do that with block decls, though, because 4927 // blocks in default argument expression can never capture anything. 4928 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4929 // Set the "needs cleanups" bit regardless of whether there are 4930 // any explicit objects. 4931 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4932 4933 // Append all the objects to the cleanup list. Right now, this 4934 // should always be a no-op, because blocks in default argument 4935 // expressions should never be able to capture anything. 4936 assert(!Init->getNumObjects() && 4937 "default argument expression has capturing blocks?"); 4938 } 4939 4940 // We already type-checked the argument, so we know it works. 4941 // Just mark all of the declarations in this potentially-evaluated expression 4942 // as being "referenced". 4943 EnterExpressionEvaluationContext EvalContext( 4944 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4945 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4946 /*SkipLocalVariables=*/true); 4947 return false; 4948 } 4949 4950 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4951 FunctionDecl *FD, ParmVarDecl *Param) { 4952 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4953 return ExprError(); 4954 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4955 } 4956 4957 Sema::VariadicCallType 4958 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4959 Expr *Fn) { 4960 if (Proto && Proto->isVariadic()) { 4961 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4962 return VariadicConstructor; 4963 else if (Fn && Fn->getType()->isBlockPointerType()) 4964 return VariadicBlock; 4965 else if (FDecl) { 4966 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4967 if (Method->isInstance()) 4968 return VariadicMethod; 4969 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4970 return VariadicMethod; 4971 return VariadicFunction; 4972 } 4973 return VariadicDoesNotApply; 4974 } 4975 4976 namespace { 4977 class FunctionCallCCC final : public FunctionCallFilterCCC { 4978 public: 4979 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4980 unsigned NumArgs, MemberExpr *ME) 4981 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4982 FunctionName(FuncName) {} 4983 4984 bool ValidateCandidate(const TypoCorrection &candidate) override { 4985 if (!candidate.getCorrectionSpecifier() || 4986 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4987 return false; 4988 } 4989 4990 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4991 } 4992 4993 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4994 return std::make_unique<FunctionCallCCC>(*this); 4995 } 4996 4997 private: 4998 const IdentifierInfo *const FunctionName; 4999 }; 5000 } 5001 5002 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5003 FunctionDecl *FDecl, 5004 ArrayRef<Expr *> Args) { 5005 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5006 DeclarationName FuncName = FDecl->getDeclName(); 5007 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5008 5009 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5010 if (TypoCorrection Corrected = S.CorrectTypo( 5011 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5012 S.getScopeForContext(S.CurContext), nullptr, CCC, 5013 Sema::CTK_ErrorRecovery)) { 5014 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5015 if (Corrected.isOverloaded()) { 5016 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5017 OverloadCandidateSet::iterator Best; 5018 for (NamedDecl *CD : Corrected) { 5019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5020 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5021 OCS); 5022 } 5023 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5024 case OR_Success: 5025 ND = Best->FoundDecl; 5026 Corrected.setCorrectionDecl(ND); 5027 break; 5028 default: 5029 break; 5030 } 5031 } 5032 ND = ND->getUnderlyingDecl(); 5033 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5034 return Corrected; 5035 } 5036 } 5037 return TypoCorrection(); 5038 } 5039 5040 /// ConvertArgumentsForCall - Converts the arguments specified in 5041 /// Args/NumArgs to the parameter types of the function FDecl with 5042 /// function prototype Proto. Call is the call expression itself, and 5043 /// Fn is the function expression. For a C++ member function, this 5044 /// routine does not attempt to convert the object argument. Returns 5045 /// true if the call is ill-formed. 5046 bool 5047 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5048 FunctionDecl *FDecl, 5049 const FunctionProtoType *Proto, 5050 ArrayRef<Expr *> Args, 5051 SourceLocation RParenLoc, 5052 bool IsExecConfig) { 5053 // Bail out early if calling a builtin with custom typechecking. 5054 if (FDecl) 5055 if (unsigned ID = FDecl->getBuiltinID()) 5056 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5057 return false; 5058 5059 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5060 // assignment, to the types of the corresponding parameter, ... 5061 unsigned NumParams = Proto->getNumParams(); 5062 bool Invalid = false; 5063 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5064 unsigned FnKind = Fn->getType()->isBlockPointerType() 5065 ? 1 /* block */ 5066 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5067 : 0 /* function */); 5068 5069 // If too few arguments are available (and we don't have default 5070 // arguments for the remaining parameters), don't make the call. 5071 if (Args.size() < NumParams) { 5072 if (Args.size() < MinArgs) { 5073 TypoCorrection TC; 5074 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5075 unsigned diag_id = 5076 MinArgs == NumParams && !Proto->isVariadic() 5077 ? diag::err_typecheck_call_too_few_args_suggest 5078 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5079 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5080 << static_cast<unsigned>(Args.size()) 5081 << TC.getCorrectionRange()); 5082 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5083 Diag(RParenLoc, 5084 MinArgs == NumParams && !Proto->isVariadic() 5085 ? diag::err_typecheck_call_too_few_args_one 5086 : diag::err_typecheck_call_too_few_args_at_least_one) 5087 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5088 else 5089 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5090 ? diag::err_typecheck_call_too_few_args 5091 : diag::err_typecheck_call_too_few_args_at_least) 5092 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5093 << Fn->getSourceRange(); 5094 5095 // Emit the location of the prototype. 5096 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5097 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5098 5099 return true; 5100 } 5101 // We reserve space for the default arguments when we create 5102 // the call expression, before calling ConvertArgumentsForCall. 5103 assert((Call->getNumArgs() == NumParams) && 5104 "We should have reserved space for the default arguments before!"); 5105 } 5106 5107 // If too many are passed and not variadic, error on the extras and drop 5108 // them. 5109 if (Args.size() > NumParams) { 5110 if (!Proto->isVariadic()) { 5111 TypoCorrection TC; 5112 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5113 unsigned diag_id = 5114 MinArgs == NumParams && !Proto->isVariadic() 5115 ? diag::err_typecheck_call_too_many_args_suggest 5116 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5117 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5118 << static_cast<unsigned>(Args.size()) 5119 << TC.getCorrectionRange()); 5120 } else if (NumParams == 1 && FDecl && 5121 FDecl->getParamDecl(0)->getDeclName()) 5122 Diag(Args[NumParams]->getBeginLoc(), 5123 MinArgs == NumParams 5124 ? diag::err_typecheck_call_too_many_args_one 5125 : diag::err_typecheck_call_too_many_args_at_most_one) 5126 << FnKind << FDecl->getParamDecl(0) 5127 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5128 << SourceRange(Args[NumParams]->getBeginLoc(), 5129 Args.back()->getEndLoc()); 5130 else 5131 Diag(Args[NumParams]->getBeginLoc(), 5132 MinArgs == NumParams 5133 ? diag::err_typecheck_call_too_many_args 5134 : diag::err_typecheck_call_too_many_args_at_most) 5135 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5136 << Fn->getSourceRange() 5137 << SourceRange(Args[NumParams]->getBeginLoc(), 5138 Args.back()->getEndLoc()); 5139 5140 // Emit the location of the prototype. 5141 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5142 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5143 5144 // This deletes the extra arguments. 5145 Call->shrinkNumArgs(NumParams); 5146 return true; 5147 } 5148 } 5149 SmallVector<Expr *, 8> AllArgs; 5150 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5151 5152 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5153 AllArgs, CallType); 5154 if (Invalid) 5155 return true; 5156 unsigned TotalNumArgs = AllArgs.size(); 5157 for (unsigned i = 0; i < TotalNumArgs; ++i) 5158 Call->setArg(i, AllArgs[i]); 5159 5160 return false; 5161 } 5162 5163 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5164 const FunctionProtoType *Proto, 5165 unsigned FirstParam, ArrayRef<Expr *> Args, 5166 SmallVectorImpl<Expr *> &AllArgs, 5167 VariadicCallType CallType, bool AllowExplicit, 5168 bool IsListInitialization) { 5169 unsigned NumParams = Proto->getNumParams(); 5170 bool Invalid = false; 5171 size_t ArgIx = 0; 5172 // Continue to check argument types (even if we have too few/many args). 5173 for (unsigned i = FirstParam; i < NumParams; i++) { 5174 QualType ProtoArgType = Proto->getParamType(i); 5175 5176 Expr *Arg; 5177 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5178 if (ArgIx < Args.size()) { 5179 Arg = Args[ArgIx++]; 5180 5181 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5182 diag::err_call_incomplete_argument, Arg)) 5183 return true; 5184 5185 // Strip the unbridged-cast placeholder expression off, if applicable. 5186 bool CFAudited = false; 5187 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5188 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5189 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5190 Arg = stripARCUnbridgedCast(Arg); 5191 else if (getLangOpts().ObjCAutoRefCount && 5192 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5193 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5194 CFAudited = true; 5195 5196 if (Proto->getExtParameterInfo(i).isNoEscape()) 5197 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5198 BE->getBlockDecl()->setDoesNotEscape(); 5199 5200 InitializedEntity Entity = 5201 Param ? InitializedEntity::InitializeParameter(Context, Param, 5202 ProtoArgType) 5203 : InitializedEntity::InitializeParameter( 5204 Context, ProtoArgType, Proto->isParamConsumed(i)); 5205 5206 // Remember that parameter belongs to a CF audited API. 5207 if (CFAudited) 5208 Entity.setParameterCFAudited(); 5209 5210 ExprResult ArgE = PerformCopyInitialization( 5211 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5212 if (ArgE.isInvalid()) 5213 return true; 5214 5215 Arg = ArgE.getAs<Expr>(); 5216 } else { 5217 assert(Param && "can't use default arguments without a known callee"); 5218 5219 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5220 if (ArgExpr.isInvalid()) 5221 return true; 5222 5223 Arg = ArgExpr.getAs<Expr>(); 5224 } 5225 5226 // Check for array bounds violations for each argument to the call. This 5227 // check only triggers warnings when the argument isn't a more complex Expr 5228 // with its own checking, such as a BinaryOperator. 5229 CheckArrayAccess(Arg); 5230 5231 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5232 CheckStaticArrayArgument(CallLoc, Param, Arg); 5233 5234 AllArgs.push_back(Arg); 5235 } 5236 5237 // If this is a variadic call, handle args passed through "...". 5238 if (CallType != VariadicDoesNotApply) { 5239 // Assume that extern "C" functions with variadic arguments that 5240 // return __unknown_anytype aren't *really* variadic. 5241 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5242 FDecl->isExternC()) { 5243 for (Expr *A : Args.slice(ArgIx)) { 5244 QualType paramType; // ignored 5245 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5246 Invalid |= arg.isInvalid(); 5247 AllArgs.push_back(arg.get()); 5248 } 5249 5250 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5251 } else { 5252 for (Expr *A : Args.slice(ArgIx)) { 5253 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5254 Invalid |= Arg.isInvalid(); 5255 AllArgs.push_back(Arg.get()); 5256 } 5257 } 5258 5259 // Check for array bounds violations. 5260 for (Expr *A : Args.slice(ArgIx)) 5261 CheckArrayAccess(A); 5262 } 5263 return Invalid; 5264 } 5265 5266 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5267 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5268 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5269 TL = DTL.getOriginalLoc(); 5270 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5271 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5272 << ATL.getLocalSourceRange(); 5273 } 5274 5275 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5276 /// array parameter, check that it is non-null, and that if it is formed by 5277 /// array-to-pointer decay, the underlying array is sufficiently large. 5278 /// 5279 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5280 /// array type derivation, then for each call to the function, the value of the 5281 /// corresponding actual argument shall provide access to the first element of 5282 /// an array with at least as many elements as specified by the size expression. 5283 void 5284 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5285 ParmVarDecl *Param, 5286 const Expr *ArgExpr) { 5287 // Static array parameters are not supported in C++. 5288 if (!Param || getLangOpts().CPlusPlus) 5289 return; 5290 5291 QualType OrigTy = Param->getOriginalType(); 5292 5293 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5294 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5295 return; 5296 5297 if (ArgExpr->isNullPointerConstant(Context, 5298 Expr::NPC_NeverValueDependent)) { 5299 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5300 DiagnoseCalleeStaticArrayParam(*this, Param); 5301 return; 5302 } 5303 5304 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5305 if (!CAT) 5306 return; 5307 5308 const ConstantArrayType *ArgCAT = 5309 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5310 if (!ArgCAT) 5311 return; 5312 5313 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5314 ArgCAT->getElementType())) { 5315 if (ArgCAT->getSize().ult(CAT->getSize())) { 5316 Diag(CallLoc, diag::warn_static_array_too_small) 5317 << ArgExpr->getSourceRange() 5318 << (unsigned)ArgCAT->getSize().getZExtValue() 5319 << (unsigned)CAT->getSize().getZExtValue() << 0; 5320 DiagnoseCalleeStaticArrayParam(*this, Param); 5321 } 5322 return; 5323 } 5324 5325 Optional<CharUnits> ArgSize = 5326 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5327 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5328 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5329 Diag(CallLoc, diag::warn_static_array_too_small) 5330 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5331 << (unsigned)ParmSize->getQuantity() << 1; 5332 DiagnoseCalleeStaticArrayParam(*this, Param); 5333 } 5334 } 5335 5336 /// Given a function expression of unknown-any type, try to rebuild it 5337 /// to have a function type. 5338 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5339 5340 /// Is the given type a placeholder that we need to lower out 5341 /// immediately during argument processing? 5342 static bool isPlaceholderToRemoveAsArg(QualType type) { 5343 // Placeholders are never sugared. 5344 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5345 if (!placeholder) return false; 5346 5347 switch (placeholder->getKind()) { 5348 // Ignore all the non-placeholder types. 5349 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5350 case BuiltinType::Id: 5351 #include "clang/Basic/OpenCLImageTypes.def" 5352 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5353 case BuiltinType::Id: 5354 #include "clang/Basic/OpenCLExtensionTypes.def" 5355 // In practice we'll never use this, since all SVE types are sugared 5356 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5357 #define SVE_TYPE(Name, Id, SingletonId) \ 5358 case BuiltinType::Id: 5359 #include "clang/Basic/AArch64SVEACLETypes.def" 5360 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5361 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5362 #include "clang/AST/BuiltinTypes.def" 5363 return false; 5364 5365 // We cannot lower out overload sets; they might validly be resolved 5366 // by the call machinery. 5367 case BuiltinType::Overload: 5368 return false; 5369 5370 // Unbridged casts in ARC can be handled in some call positions and 5371 // should be left in place. 5372 case BuiltinType::ARCUnbridgedCast: 5373 return false; 5374 5375 // Pseudo-objects should be converted as soon as possible. 5376 case BuiltinType::PseudoObject: 5377 return true; 5378 5379 // The debugger mode could theoretically but currently does not try 5380 // to resolve unknown-typed arguments based on known parameter types. 5381 case BuiltinType::UnknownAny: 5382 return true; 5383 5384 // These are always invalid as call arguments and should be reported. 5385 case BuiltinType::BoundMember: 5386 case BuiltinType::BuiltinFn: 5387 case BuiltinType::OMPArraySection: 5388 return true; 5389 5390 } 5391 llvm_unreachable("bad builtin type kind"); 5392 } 5393 5394 /// Check an argument list for placeholders that we won't try to 5395 /// handle later. 5396 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5397 // Apply this processing to all the arguments at once instead of 5398 // dying at the first failure. 5399 bool hasInvalid = false; 5400 for (size_t i = 0, e = args.size(); i != e; i++) { 5401 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5402 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5403 if (result.isInvalid()) hasInvalid = true; 5404 else args[i] = result.get(); 5405 } else if (hasInvalid) { 5406 (void)S.CorrectDelayedTyposInExpr(args[i]); 5407 } 5408 } 5409 return hasInvalid; 5410 } 5411 5412 /// If a builtin function has a pointer argument with no explicit address 5413 /// space, then it should be able to accept a pointer to any address 5414 /// space as input. In order to do this, we need to replace the 5415 /// standard builtin declaration with one that uses the same address space 5416 /// as the call. 5417 /// 5418 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5419 /// it does not contain any pointer arguments without 5420 /// an address space qualifer. Otherwise the rewritten 5421 /// FunctionDecl is returned. 5422 /// TODO: Handle pointer return types. 5423 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5424 FunctionDecl *FDecl, 5425 MultiExprArg ArgExprs) { 5426 5427 QualType DeclType = FDecl->getType(); 5428 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5429 5430 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5431 ArgExprs.size() < FT->getNumParams()) 5432 return nullptr; 5433 5434 bool NeedsNewDecl = false; 5435 unsigned i = 0; 5436 SmallVector<QualType, 8> OverloadParams; 5437 5438 for (QualType ParamType : FT->param_types()) { 5439 5440 // Convert array arguments to pointer to simplify type lookup. 5441 ExprResult ArgRes = 5442 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5443 if (ArgRes.isInvalid()) 5444 return nullptr; 5445 Expr *Arg = ArgRes.get(); 5446 QualType ArgType = Arg->getType(); 5447 if (!ParamType->isPointerType() || 5448 ParamType.getQualifiers().hasAddressSpace() || 5449 !ArgType->isPointerType() || 5450 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5451 OverloadParams.push_back(ParamType); 5452 continue; 5453 } 5454 5455 QualType PointeeType = ParamType->getPointeeType(); 5456 if (PointeeType.getQualifiers().hasAddressSpace()) 5457 continue; 5458 5459 NeedsNewDecl = true; 5460 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5461 5462 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5463 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5464 } 5465 5466 if (!NeedsNewDecl) 5467 return nullptr; 5468 5469 FunctionProtoType::ExtProtoInfo EPI; 5470 EPI.Variadic = FT->isVariadic(); 5471 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5472 OverloadParams, EPI); 5473 DeclContext *Parent = FDecl->getParent(); 5474 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5475 FDecl->getLocation(), 5476 FDecl->getLocation(), 5477 FDecl->getIdentifier(), 5478 OverloadTy, 5479 /*TInfo=*/nullptr, 5480 SC_Extern, false, 5481 /*hasPrototype=*/true); 5482 SmallVector<ParmVarDecl*, 16> Params; 5483 FT = cast<FunctionProtoType>(OverloadTy); 5484 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5485 QualType ParamType = FT->getParamType(i); 5486 ParmVarDecl *Parm = 5487 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5488 SourceLocation(), nullptr, ParamType, 5489 /*TInfo=*/nullptr, SC_None, nullptr); 5490 Parm->setScopeInfo(0, i); 5491 Params.push_back(Parm); 5492 } 5493 OverloadDecl->setParams(Params); 5494 return OverloadDecl; 5495 } 5496 5497 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5498 FunctionDecl *Callee, 5499 MultiExprArg ArgExprs) { 5500 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5501 // similar attributes) really don't like it when functions are called with an 5502 // invalid number of args. 5503 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5504 /*PartialOverloading=*/false) && 5505 !Callee->isVariadic()) 5506 return; 5507 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5508 return; 5509 5510 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5511 S.Diag(Fn->getBeginLoc(), 5512 isa<CXXMethodDecl>(Callee) 5513 ? diag::err_ovl_no_viable_member_function_in_call 5514 : diag::err_ovl_no_viable_function_in_call) 5515 << Callee << Callee->getSourceRange(); 5516 S.Diag(Callee->getLocation(), 5517 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5518 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5519 return; 5520 } 5521 } 5522 5523 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5524 const UnresolvedMemberExpr *const UME, Sema &S) { 5525 5526 const auto GetFunctionLevelDCIfCXXClass = 5527 [](Sema &S) -> const CXXRecordDecl * { 5528 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5529 if (!DC || !DC->getParent()) 5530 return nullptr; 5531 5532 // If the call to some member function was made from within a member 5533 // function body 'M' return return 'M's parent. 5534 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5535 return MD->getParent()->getCanonicalDecl(); 5536 // else the call was made from within a default member initializer of a 5537 // class, so return the class. 5538 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5539 return RD->getCanonicalDecl(); 5540 return nullptr; 5541 }; 5542 // If our DeclContext is neither a member function nor a class (in the 5543 // case of a lambda in a default member initializer), we can't have an 5544 // enclosing 'this'. 5545 5546 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5547 if (!CurParentClass) 5548 return false; 5549 5550 // The naming class for implicit member functions call is the class in which 5551 // name lookup starts. 5552 const CXXRecordDecl *const NamingClass = 5553 UME->getNamingClass()->getCanonicalDecl(); 5554 assert(NamingClass && "Must have naming class even for implicit access"); 5555 5556 // If the unresolved member functions were found in a 'naming class' that is 5557 // related (either the same or derived from) to the class that contains the 5558 // member function that itself contained the implicit member access. 5559 5560 return CurParentClass == NamingClass || 5561 CurParentClass->isDerivedFrom(NamingClass); 5562 } 5563 5564 static void 5565 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5566 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5567 5568 if (!UME) 5569 return; 5570 5571 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5572 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5573 // already been captured, or if this is an implicit member function call (if 5574 // it isn't, an attempt to capture 'this' should already have been made). 5575 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5576 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5577 return; 5578 5579 // Check if the naming class in which the unresolved members were found is 5580 // related (same as or is a base of) to the enclosing class. 5581 5582 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5583 return; 5584 5585 5586 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5587 // If the enclosing function is not dependent, then this lambda is 5588 // capture ready, so if we can capture this, do so. 5589 if (!EnclosingFunctionCtx->isDependentContext()) { 5590 // If the current lambda and all enclosing lambdas can capture 'this' - 5591 // then go ahead and capture 'this' (since our unresolved overload set 5592 // contains at least one non-static member function). 5593 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5594 S.CheckCXXThisCapture(CallLoc); 5595 } else if (S.CurContext->isDependentContext()) { 5596 // ... since this is an implicit member reference, that might potentially 5597 // involve a 'this' capture, mark 'this' for potential capture in 5598 // enclosing lambdas. 5599 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5600 CurLSI->addPotentialThisCapture(CallLoc); 5601 } 5602 } 5603 5604 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5605 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5606 Expr *ExecConfig) { 5607 ExprResult Call = 5608 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5609 if (Call.isInvalid()) 5610 return Call; 5611 5612 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5613 // language modes. 5614 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5615 if (ULE->hasExplicitTemplateArgs() && 5616 ULE->decls_begin() == ULE->decls_end()) { 5617 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5618 ? diag::warn_cxx17_compat_adl_only_template_id 5619 : diag::ext_adl_only_template_id) 5620 << ULE->getName(); 5621 } 5622 } 5623 5624 return Call; 5625 } 5626 5627 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5628 /// This provides the location of the left/right parens and a list of comma 5629 /// locations. 5630 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5631 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5632 Expr *ExecConfig, bool IsExecConfig) { 5633 // Since this might be a postfix expression, get rid of ParenListExprs. 5634 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5635 if (Result.isInvalid()) return ExprError(); 5636 Fn = Result.get(); 5637 5638 if (checkArgsForPlaceholders(*this, ArgExprs)) 5639 return ExprError(); 5640 5641 if (getLangOpts().CPlusPlus) { 5642 // If this is a pseudo-destructor expression, build the call immediately. 5643 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5644 if (!ArgExprs.empty()) { 5645 // Pseudo-destructor calls should not have any arguments. 5646 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5647 << FixItHint::CreateRemoval( 5648 SourceRange(ArgExprs.front()->getBeginLoc(), 5649 ArgExprs.back()->getEndLoc())); 5650 } 5651 5652 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5653 VK_RValue, RParenLoc); 5654 } 5655 if (Fn->getType() == Context.PseudoObjectTy) { 5656 ExprResult result = CheckPlaceholderExpr(Fn); 5657 if (result.isInvalid()) return ExprError(); 5658 Fn = result.get(); 5659 } 5660 5661 // Determine whether this is a dependent call inside a C++ template, 5662 // in which case we won't do any semantic analysis now. 5663 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5664 if (ExecConfig) { 5665 return CUDAKernelCallExpr::Create( 5666 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5667 Context.DependentTy, VK_RValue, RParenLoc); 5668 } else { 5669 5670 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5671 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5672 Fn->getBeginLoc()); 5673 5674 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5675 VK_RValue, RParenLoc); 5676 } 5677 } 5678 5679 // Determine whether this is a call to an object (C++ [over.call.object]). 5680 if (Fn->getType()->isRecordType()) 5681 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5682 RParenLoc); 5683 5684 if (Fn->getType() == Context.UnknownAnyTy) { 5685 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5686 if (result.isInvalid()) return ExprError(); 5687 Fn = result.get(); 5688 } 5689 5690 if (Fn->getType() == Context.BoundMemberTy) { 5691 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5692 RParenLoc); 5693 } 5694 } 5695 5696 // Check for overloaded calls. This can happen even in C due to extensions. 5697 if (Fn->getType() == Context.OverloadTy) { 5698 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5699 5700 // We aren't supposed to apply this logic if there's an '&' involved. 5701 if (!find.HasFormOfMemberPointer) { 5702 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5703 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5704 VK_RValue, RParenLoc); 5705 OverloadExpr *ovl = find.Expression; 5706 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5707 return BuildOverloadedCallExpr( 5708 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5709 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5710 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5711 RParenLoc); 5712 } 5713 } 5714 5715 // If we're directly calling a function, get the appropriate declaration. 5716 if (Fn->getType() == Context.UnknownAnyTy) { 5717 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5718 if (result.isInvalid()) return ExprError(); 5719 Fn = result.get(); 5720 } 5721 5722 Expr *NakedFn = Fn->IgnoreParens(); 5723 5724 bool CallingNDeclIndirectly = false; 5725 NamedDecl *NDecl = nullptr; 5726 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5727 if (UnOp->getOpcode() == UO_AddrOf) { 5728 CallingNDeclIndirectly = true; 5729 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5730 } 5731 } 5732 5733 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5734 NDecl = DRE->getDecl(); 5735 5736 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5737 if (FDecl && FDecl->getBuiltinID()) { 5738 // Rewrite the function decl for this builtin by replacing parameters 5739 // with no explicit address space with the address space of the arguments 5740 // in ArgExprs. 5741 if ((FDecl = 5742 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5743 NDecl = FDecl; 5744 Fn = DeclRefExpr::Create( 5745 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5746 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5747 nullptr, DRE->isNonOdrUse()); 5748 } 5749 } 5750 } else if (isa<MemberExpr>(NakedFn)) 5751 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5752 5753 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5754 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5755 FD, /*Complain=*/true, Fn->getBeginLoc())) 5756 return ExprError(); 5757 5758 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5759 return ExprError(); 5760 5761 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5762 } 5763 5764 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5765 ExecConfig, IsExecConfig); 5766 } 5767 5768 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5769 /// 5770 /// __builtin_astype( value, dst type ) 5771 /// 5772 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5773 SourceLocation BuiltinLoc, 5774 SourceLocation RParenLoc) { 5775 ExprValueKind VK = VK_RValue; 5776 ExprObjectKind OK = OK_Ordinary; 5777 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5778 QualType SrcTy = E->getType(); 5779 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5780 return ExprError(Diag(BuiltinLoc, 5781 diag::err_invalid_astype_of_different_size) 5782 << DstTy 5783 << SrcTy 5784 << E->getSourceRange()); 5785 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5786 } 5787 5788 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5789 /// provided arguments. 5790 /// 5791 /// __builtin_convertvector( value, dst type ) 5792 /// 5793 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5794 SourceLocation BuiltinLoc, 5795 SourceLocation RParenLoc) { 5796 TypeSourceInfo *TInfo; 5797 GetTypeFromParser(ParsedDestTy, &TInfo); 5798 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5799 } 5800 5801 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5802 /// i.e. an expression not of \p OverloadTy. The expression should 5803 /// unary-convert to an expression of function-pointer or 5804 /// block-pointer type. 5805 /// 5806 /// \param NDecl the declaration being called, if available 5807 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5808 SourceLocation LParenLoc, 5809 ArrayRef<Expr *> Args, 5810 SourceLocation RParenLoc, Expr *Config, 5811 bool IsExecConfig, ADLCallKind UsesADL) { 5812 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5813 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5814 5815 // Functions with 'interrupt' attribute cannot be called directly. 5816 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5817 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5818 return ExprError(); 5819 } 5820 5821 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5822 // so there's some risk when calling out to non-interrupt handler functions 5823 // that the callee might not preserve them. This is easy to diagnose here, 5824 // but can be very challenging to debug. 5825 if (auto *Caller = getCurFunctionDecl()) 5826 if (Caller->hasAttr<ARMInterruptAttr>()) { 5827 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5828 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5829 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5830 } 5831 5832 // Promote the function operand. 5833 // We special-case function promotion here because we only allow promoting 5834 // builtin functions to function pointers in the callee of a call. 5835 ExprResult Result; 5836 QualType ResultTy; 5837 if (BuiltinID && 5838 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5839 // Extract the return type from the (builtin) function pointer type. 5840 // FIXME Several builtins still have setType in 5841 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5842 // Builtins.def to ensure they are correct before removing setType calls. 5843 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5844 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5845 ResultTy = FDecl->getCallResultType(); 5846 } else { 5847 Result = CallExprUnaryConversions(Fn); 5848 ResultTy = Context.BoolTy; 5849 } 5850 if (Result.isInvalid()) 5851 return ExprError(); 5852 Fn = Result.get(); 5853 5854 // Check for a valid function type, but only if it is not a builtin which 5855 // requires custom type checking. These will be handled by 5856 // CheckBuiltinFunctionCall below just after creation of the call expression. 5857 const FunctionType *FuncT = nullptr; 5858 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5859 retry: 5860 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5861 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5862 // have type pointer to function". 5863 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5864 if (!FuncT) 5865 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5866 << Fn->getType() << Fn->getSourceRange()); 5867 } else if (const BlockPointerType *BPT = 5868 Fn->getType()->getAs<BlockPointerType>()) { 5869 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5870 } else { 5871 // Handle calls to expressions of unknown-any type. 5872 if (Fn->getType() == Context.UnknownAnyTy) { 5873 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5874 if (rewrite.isInvalid()) 5875 return ExprError(); 5876 Fn = rewrite.get(); 5877 goto retry; 5878 } 5879 5880 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5881 << Fn->getType() << Fn->getSourceRange()); 5882 } 5883 } 5884 5885 // Get the number of parameters in the function prototype, if any. 5886 // We will allocate space for max(Args.size(), NumParams) arguments 5887 // in the call expression. 5888 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5889 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5890 5891 CallExpr *TheCall; 5892 if (Config) { 5893 assert(UsesADL == ADLCallKind::NotADL && 5894 "CUDAKernelCallExpr should not use ADL"); 5895 TheCall = 5896 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5897 ResultTy, VK_RValue, RParenLoc, NumParams); 5898 } else { 5899 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5900 RParenLoc, NumParams, UsesADL); 5901 } 5902 5903 if (!getLangOpts().CPlusPlus) { 5904 // Forget about the nulled arguments since typo correction 5905 // do not handle them well. 5906 TheCall->shrinkNumArgs(Args.size()); 5907 // C cannot always handle TypoExpr nodes in builtin calls and direct 5908 // function calls as their argument checking don't necessarily handle 5909 // dependent types properly, so make sure any TypoExprs have been 5910 // dealt with. 5911 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5912 if (!Result.isUsable()) return ExprError(); 5913 CallExpr *TheOldCall = TheCall; 5914 TheCall = dyn_cast<CallExpr>(Result.get()); 5915 bool CorrectedTypos = TheCall != TheOldCall; 5916 if (!TheCall) return Result; 5917 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5918 5919 // A new call expression node was created if some typos were corrected. 5920 // However it may not have been constructed with enough storage. In this 5921 // case, rebuild the node with enough storage. The waste of space is 5922 // immaterial since this only happens when some typos were corrected. 5923 if (CorrectedTypos && Args.size() < NumParams) { 5924 if (Config) 5925 TheCall = CUDAKernelCallExpr::Create( 5926 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5927 RParenLoc, NumParams); 5928 else 5929 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5930 RParenLoc, NumParams, UsesADL); 5931 } 5932 // We can now handle the nulled arguments for the default arguments. 5933 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5934 } 5935 5936 // Bail out early if calling a builtin with custom type checking. 5937 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5938 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5939 5940 if (getLangOpts().CUDA) { 5941 if (Config) { 5942 // CUDA: Kernel calls must be to global functions 5943 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5944 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5945 << FDecl << Fn->getSourceRange()); 5946 5947 // CUDA: Kernel function must have 'void' return type 5948 if (!FuncT->getReturnType()->isVoidType() && 5949 !FuncT->getReturnType()->getAs<AutoType>() && 5950 !FuncT->getReturnType()->isInstantiationDependentType()) 5951 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5952 << Fn->getType() << Fn->getSourceRange()); 5953 } else { 5954 // CUDA: Calls to global functions must be configured 5955 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5956 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5957 << FDecl << Fn->getSourceRange()); 5958 } 5959 } 5960 5961 // Check for a valid return type 5962 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5963 FDecl)) 5964 return ExprError(); 5965 5966 // We know the result type of the call, set it. 5967 TheCall->setType(FuncT->getCallResultType(Context)); 5968 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5969 5970 if (Proto) { 5971 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5972 IsExecConfig)) 5973 return ExprError(); 5974 } else { 5975 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5976 5977 if (FDecl) { 5978 // Check if we have too few/too many template arguments, based 5979 // on our knowledge of the function definition. 5980 const FunctionDecl *Def = nullptr; 5981 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5982 Proto = Def->getType()->getAs<FunctionProtoType>(); 5983 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5984 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5985 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5986 } 5987 5988 // If the function we're calling isn't a function prototype, but we have 5989 // a function prototype from a prior declaratiom, use that prototype. 5990 if (!FDecl->hasPrototype()) 5991 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5992 } 5993 5994 // Promote the arguments (C99 6.5.2.2p6). 5995 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5996 Expr *Arg = Args[i]; 5997 5998 if (Proto && i < Proto->getNumParams()) { 5999 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6000 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6001 ExprResult ArgE = 6002 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6003 if (ArgE.isInvalid()) 6004 return true; 6005 6006 Arg = ArgE.getAs<Expr>(); 6007 6008 } else { 6009 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6010 6011 if (ArgE.isInvalid()) 6012 return true; 6013 6014 Arg = ArgE.getAs<Expr>(); 6015 } 6016 6017 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6018 diag::err_call_incomplete_argument, Arg)) 6019 return ExprError(); 6020 6021 TheCall->setArg(i, Arg); 6022 } 6023 } 6024 6025 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6026 if (!Method->isStatic()) 6027 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6028 << Fn->getSourceRange()); 6029 6030 // Check for sentinels 6031 if (NDecl) 6032 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6033 6034 // Do special checking on direct calls to functions. 6035 if (FDecl) { 6036 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6037 return ExprError(); 6038 6039 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6040 6041 if (BuiltinID) 6042 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6043 } else if (NDecl) { 6044 if (CheckPointerCall(NDecl, TheCall, Proto)) 6045 return ExprError(); 6046 } else { 6047 if (CheckOtherCall(TheCall, Proto)) 6048 return ExprError(); 6049 } 6050 6051 return MaybeBindToTemporary(TheCall); 6052 } 6053 6054 ExprResult 6055 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6056 SourceLocation RParenLoc, Expr *InitExpr) { 6057 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6058 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6059 6060 TypeSourceInfo *TInfo; 6061 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6062 if (!TInfo) 6063 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6064 6065 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6066 } 6067 6068 ExprResult 6069 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6070 SourceLocation RParenLoc, Expr *LiteralExpr) { 6071 QualType literalType = TInfo->getType(); 6072 6073 if (literalType->isArrayType()) { 6074 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6075 diag::err_illegal_decl_array_incomplete_type, 6076 SourceRange(LParenLoc, 6077 LiteralExpr->getSourceRange().getEnd()))) 6078 return ExprError(); 6079 if (literalType->isVariableArrayType()) 6080 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6081 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6082 } else if (!literalType->isDependentType() && 6083 RequireCompleteType(LParenLoc, literalType, 6084 diag::err_typecheck_decl_incomplete_type, 6085 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6086 return ExprError(); 6087 6088 InitializedEntity Entity 6089 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6090 InitializationKind Kind 6091 = InitializationKind::CreateCStyleCast(LParenLoc, 6092 SourceRange(LParenLoc, RParenLoc), 6093 /*InitList=*/true); 6094 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6095 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6096 &literalType); 6097 if (Result.isInvalid()) 6098 return ExprError(); 6099 LiteralExpr = Result.get(); 6100 6101 bool isFileScope = !CurContext->isFunctionOrMethod(); 6102 6103 // In C, compound literals are l-values for some reason. 6104 // For GCC compatibility, in C++, file-scope array compound literals with 6105 // constant initializers are also l-values, and compound literals are 6106 // otherwise prvalues. 6107 // 6108 // (GCC also treats C++ list-initialized file-scope array prvalues with 6109 // constant initializers as l-values, but that's non-conforming, so we don't 6110 // follow it there.) 6111 // 6112 // FIXME: It would be better to handle the lvalue cases as materializing and 6113 // lifetime-extending a temporary object, but our materialized temporaries 6114 // representation only supports lifetime extension from a variable, not "out 6115 // of thin air". 6116 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6117 // is bound to the result of applying array-to-pointer decay to the compound 6118 // literal. 6119 // FIXME: GCC supports compound literals of reference type, which should 6120 // obviously have a value kind derived from the kind of reference involved. 6121 ExprValueKind VK = 6122 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6123 ? VK_RValue 6124 : VK_LValue; 6125 6126 if (isFileScope) 6127 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6128 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6129 Expr *Init = ILE->getInit(i); 6130 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6131 } 6132 6133 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6134 VK, LiteralExpr, isFileScope); 6135 if (isFileScope) { 6136 if (!LiteralExpr->isTypeDependent() && 6137 !LiteralExpr->isValueDependent() && 6138 !literalType->isDependentType()) // C99 6.5.2.5p3 6139 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6140 return ExprError(); 6141 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6142 literalType.getAddressSpace() != LangAS::Default) { 6143 // Embedded-C extensions to C99 6.5.2.5: 6144 // "If the compound literal occurs inside the body of a function, the 6145 // type name shall not be qualified by an address-space qualifier." 6146 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6147 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6148 return ExprError(); 6149 } 6150 6151 // Compound literals that have automatic storage duration are destroyed at 6152 // the end of the scope. Emit diagnostics if it is or contains a C union type 6153 // that is non-trivial to destruct. 6154 if (!isFileScope) 6155 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6156 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6157 NTCUC_CompoundLiteral, NTCUK_Destruct); 6158 6159 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6160 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6161 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6162 E->getInitializer()->getExprLoc()); 6163 6164 return MaybeBindToTemporary(E); 6165 } 6166 6167 ExprResult 6168 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6169 SourceLocation RBraceLoc) { 6170 // Only produce each kind of designated initialization diagnostic once. 6171 SourceLocation FirstDesignator; 6172 bool DiagnosedArrayDesignator = false; 6173 bool DiagnosedNestedDesignator = false; 6174 bool DiagnosedMixedDesignator = false; 6175 6176 // Check that any designated initializers are syntactically valid in the 6177 // current language mode. 6178 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6179 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6180 if (FirstDesignator.isInvalid()) 6181 FirstDesignator = DIE->getBeginLoc(); 6182 6183 if (!getLangOpts().CPlusPlus) 6184 break; 6185 6186 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6187 DiagnosedNestedDesignator = true; 6188 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6189 << DIE->getDesignatorsSourceRange(); 6190 } 6191 6192 for (auto &Desig : DIE->designators()) { 6193 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6194 DiagnosedArrayDesignator = true; 6195 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6196 << Desig.getSourceRange(); 6197 } 6198 } 6199 6200 if (!DiagnosedMixedDesignator && 6201 !isa<DesignatedInitExpr>(InitArgList[0])) { 6202 DiagnosedMixedDesignator = true; 6203 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6204 << DIE->getSourceRange(); 6205 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6206 << InitArgList[0]->getSourceRange(); 6207 } 6208 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6209 isa<DesignatedInitExpr>(InitArgList[0])) { 6210 DiagnosedMixedDesignator = true; 6211 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6212 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6213 << DIE->getSourceRange(); 6214 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6215 << InitArgList[I]->getSourceRange(); 6216 } 6217 } 6218 6219 if (FirstDesignator.isValid()) { 6220 // Only diagnose designated initiaization as a C++20 extension if we didn't 6221 // already diagnose use of (non-C++20) C99 designator syntax. 6222 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6223 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6224 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6225 ? diag::warn_cxx17_compat_designated_init 6226 : diag::ext_cxx_designated_init); 6227 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6228 Diag(FirstDesignator, diag::ext_designated_init); 6229 } 6230 } 6231 6232 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6233 } 6234 6235 ExprResult 6236 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6237 SourceLocation RBraceLoc) { 6238 // Semantic analysis for initializers is done by ActOnDeclarator() and 6239 // CheckInitializer() - it requires knowledge of the object being initialized. 6240 6241 // Immediately handle non-overload placeholders. Overloads can be 6242 // resolved contextually, but everything else here can't. 6243 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6244 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6245 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6246 6247 // Ignore failures; dropping the entire initializer list because 6248 // of one failure would be terrible for indexing/etc. 6249 if (result.isInvalid()) continue; 6250 6251 InitArgList[I] = result.get(); 6252 } 6253 } 6254 6255 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6256 RBraceLoc); 6257 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6258 return E; 6259 } 6260 6261 /// Do an explicit extend of the given block pointer if we're in ARC. 6262 void Sema::maybeExtendBlockObject(ExprResult &E) { 6263 assert(E.get()->getType()->isBlockPointerType()); 6264 assert(E.get()->isRValue()); 6265 6266 // Only do this in an r-value context. 6267 if (!getLangOpts().ObjCAutoRefCount) return; 6268 6269 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6270 CK_ARCExtendBlockObject, E.get(), 6271 /*base path*/ nullptr, VK_RValue); 6272 Cleanup.setExprNeedsCleanups(true); 6273 } 6274 6275 /// Prepare a conversion of the given expression to an ObjC object 6276 /// pointer type. 6277 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6278 QualType type = E.get()->getType(); 6279 if (type->isObjCObjectPointerType()) { 6280 return CK_BitCast; 6281 } else if (type->isBlockPointerType()) { 6282 maybeExtendBlockObject(E); 6283 return CK_BlockPointerToObjCPointerCast; 6284 } else { 6285 assert(type->isPointerType()); 6286 return CK_CPointerToObjCPointerCast; 6287 } 6288 } 6289 6290 /// Prepares for a scalar cast, performing all the necessary stages 6291 /// except the final cast and returning the kind required. 6292 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6293 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6294 // Also, callers should have filtered out the invalid cases with 6295 // pointers. Everything else should be possible. 6296 6297 QualType SrcTy = Src.get()->getType(); 6298 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6299 return CK_NoOp; 6300 6301 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6302 case Type::STK_MemberPointer: 6303 llvm_unreachable("member pointer type in C"); 6304 6305 case Type::STK_CPointer: 6306 case Type::STK_BlockPointer: 6307 case Type::STK_ObjCObjectPointer: 6308 switch (DestTy->getScalarTypeKind()) { 6309 case Type::STK_CPointer: { 6310 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6311 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6312 if (SrcAS != DestAS) 6313 return CK_AddressSpaceConversion; 6314 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6315 return CK_NoOp; 6316 return CK_BitCast; 6317 } 6318 case Type::STK_BlockPointer: 6319 return (SrcKind == Type::STK_BlockPointer 6320 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6321 case Type::STK_ObjCObjectPointer: 6322 if (SrcKind == Type::STK_ObjCObjectPointer) 6323 return CK_BitCast; 6324 if (SrcKind == Type::STK_CPointer) 6325 return CK_CPointerToObjCPointerCast; 6326 maybeExtendBlockObject(Src); 6327 return CK_BlockPointerToObjCPointerCast; 6328 case Type::STK_Bool: 6329 return CK_PointerToBoolean; 6330 case Type::STK_Integral: 6331 return CK_PointerToIntegral; 6332 case Type::STK_Floating: 6333 case Type::STK_FloatingComplex: 6334 case Type::STK_IntegralComplex: 6335 case Type::STK_MemberPointer: 6336 case Type::STK_FixedPoint: 6337 llvm_unreachable("illegal cast from pointer"); 6338 } 6339 llvm_unreachable("Should have returned before this"); 6340 6341 case Type::STK_FixedPoint: 6342 switch (DestTy->getScalarTypeKind()) { 6343 case Type::STK_FixedPoint: 6344 return CK_FixedPointCast; 6345 case Type::STK_Bool: 6346 return CK_FixedPointToBoolean; 6347 case Type::STK_Integral: 6348 return CK_FixedPointToIntegral; 6349 case Type::STK_Floating: 6350 case Type::STK_IntegralComplex: 6351 case Type::STK_FloatingComplex: 6352 Diag(Src.get()->getExprLoc(), 6353 diag::err_unimplemented_conversion_with_fixed_point_type) 6354 << DestTy; 6355 return CK_IntegralCast; 6356 case Type::STK_CPointer: 6357 case Type::STK_ObjCObjectPointer: 6358 case Type::STK_BlockPointer: 6359 case Type::STK_MemberPointer: 6360 llvm_unreachable("illegal cast to pointer type"); 6361 } 6362 llvm_unreachable("Should have returned before this"); 6363 6364 case Type::STK_Bool: // casting from bool is like casting from an integer 6365 case Type::STK_Integral: 6366 switch (DestTy->getScalarTypeKind()) { 6367 case Type::STK_CPointer: 6368 case Type::STK_ObjCObjectPointer: 6369 case Type::STK_BlockPointer: 6370 if (Src.get()->isNullPointerConstant(Context, 6371 Expr::NPC_ValueDependentIsNull)) 6372 return CK_NullToPointer; 6373 return CK_IntegralToPointer; 6374 case Type::STK_Bool: 6375 return CK_IntegralToBoolean; 6376 case Type::STK_Integral: 6377 return CK_IntegralCast; 6378 case Type::STK_Floating: 6379 return CK_IntegralToFloating; 6380 case Type::STK_IntegralComplex: 6381 Src = ImpCastExprToType(Src.get(), 6382 DestTy->castAs<ComplexType>()->getElementType(), 6383 CK_IntegralCast); 6384 return CK_IntegralRealToComplex; 6385 case Type::STK_FloatingComplex: 6386 Src = ImpCastExprToType(Src.get(), 6387 DestTy->castAs<ComplexType>()->getElementType(), 6388 CK_IntegralToFloating); 6389 return CK_FloatingRealToComplex; 6390 case Type::STK_MemberPointer: 6391 llvm_unreachable("member pointer type in C"); 6392 case Type::STK_FixedPoint: 6393 return CK_IntegralToFixedPoint; 6394 } 6395 llvm_unreachable("Should have returned before this"); 6396 6397 case Type::STK_Floating: 6398 switch (DestTy->getScalarTypeKind()) { 6399 case Type::STK_Floating: 6400 return CK_FloatingCast; 6401 case Type::STK_Bool: 6402 return CK_FloatingToBoolean; 6403 case Type::STK_Integral: 6404 return CK_FloatingToIntegral; 6405 case Type::STK_FloatingComplex: 6406 Src = ImpCastExprToType(Src.get(), 6407 DestTy->castAs<ComplexType>()->getElementType(), 6408 CK_FloatingCast); 6409 return CK_FloatingRealToComplex; 6410 case Type::STK_IntegralComplex: 6411 Src = ImpCastExprToType(Src.get(), 6412 DestTy->castAs<ComplexType>()->getElementType(), 6413 CK_FloatingToIntegral); 6414 return CK_IntegralRealToComplex; 6415 case Type::STK_CPointer: 6416 case Type::STK_ObjCObjectPointer: 6417 case Type::STK_BlockPointer: 6418 llvm_unreachable("valid float->pointer cast?"); 6419 case Type::STK_MemberPointer: 6420 llvm_unreachable("member pointer type in C"); 6421 case Type::STK_FixedPoint: 6422 Diag(Src.get()->getExprLoc(), 6423 diag::err_unimplemented_conversion_with_fixed_point_type) 6424 << SrcTy; 6425 return CK_IntegralCast; 6426 } 6427 llvm_unreachable("Should have returned before this"); 6428 6429 case Type::STK_FloatingComplex: 6430 switch (DestTy->getScalarTypeKind()) { 6431 case Type::STK_FloatingComplex: 6432 return CK_FloatingComplexCast; 6433 case Type::STK_IntegralComplex: 6434 return CK_FloatingComplexToIntegralComplex; 6435 case Type::STK_Floating: { 6436 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6437 if (Context.hasSameType(ET, DestTy)) 6438 return CK_FloatingComplexToReal; 6439 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6440 return CK_FloatingCast; 6441 } 6442 case Type::STK_Bool: 6443 return CK_FloatingComplexToBoolean; 6444 case Type::STK_Integral: 6445 Src = ImpCastExprToType(Src.get(), 6446 SrcTy->castAs<ComplexType>()->getElementType(), 6447 CK_FloatingComplexToReal); 6448 return CK_FloatingToIntegral; 6449 case Type::STK_CPointer: 6450 case Type::STK_ObjCObjectPointer: 6451 case Type::STK_BlockPointer: 6452 llvm_unreachable("valid complex float->pointer cast?"); 6453 case Type::STK_MemberPointer: 6454 llvm_unreachable("member pointer type in C"); 6455 case Type::STK_FixedPoint: 6456 Diag(Src.get()->getExprLoc(), 6457 diag::err_unimplemented_conversion_with_fixed_point_type) 6458 << SrcTy; 6459 return CK_IntegralCast; 6460 } 6461 llvm_unreachable("Should have returned before this"); 6462 6463 case Type::STK_IntegralComplex: 6464 switch (DestTy->getScalarTypeKind()) { 6465 case Type::STK_FloatingComplex: 6466 return CK_IntegralComplexToFloatingComplex; 6467 case Type::STK_IntegralComplex: 6468 return CK_IntegralComplexCast; 6469 case Type::STK_Integral: { 6470 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6471 if (Context.hasSameType(ET, DestTy)) 6472 return CK_IntegralComplexToReal; 6473 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6474 return CK_IntegralCast; 6475 } 6476 case Type::STK_Bool: 6477 return CK_IntegralComplexToBoolean; 6478 case Type::STK_Floating: 6479 Src = ImpCastExprToType(Src.get(), 6480 SrcTy->castAs<ComplexType>()->getElementType(), 6481 CK_IntegralComplexToReal); 6482 return CK_IntegralToFloating; 6483 case Type::STK_CPointer: 6484 case Type::STK_ObjCObjectPointer: 6485 case Type::STK_BlockPointer: 6486 llvm_unreachable("valid complex int->pointer cast?"); 6487 case Type::STK_MemberPointer: 6488 llvm_unreachable("member pointer type in C"); 6489 case Type::STK_FixedPoint: 6490 Diag(Src.get()->getExprLoc(), 6491 diag::err_unimplemented_conversion_with_fixed_point_type) 6492 << SrcTy; 6493 return CK_IntegralCast; 6494 } 6495 llvm_unreachable("Should have returned before this"); 6496 } 6497 6498 llvm_unreachable("Unhandled scalar cast"); 6499 } 6500 6501 static bool breakDownVectorType(QualType type, uint64_t &len, 6502 QualType &eltType) { 6503 // Vectors are simple. 6504 if (const VectorType *vecType = type->getAs<VectorType>()) { 6505 len = vecType->getNumElements(); 6506 eltType = vecType->getElementType(); 6507 assert(eltType->isScalarType()); 6508 return true; 6509 } 6510 6511 // We allow lax conversion to and from non-vector types, but only if 6512 // they're real types (i.e. non-complex, non-pointer scalar types). 6513 if (!type->isRealType()) return false; 6514 6515 len = 1; 6516 eltType = type; 6517 return true; 6518 } 6519 6520 /// Are the two types lax-compatible vector types? That is, given 6521 /// that one of them is a vector, do they have equal storage sizes, 6522 /// where the storage size is the number of elements times the element 6523 /// size? 6524 /// 6525 /// This will also return false if either of the types is neither a 6526 /// vector nor a real type. 6527 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6528 assert(destTy->isVectorType() || srcTy->isVectorType()); 6529 6530 // Disallow lax conversions between scalars and ExtVectors (these 6531 // conversions are allowed for other vector types because common headers 6532 // depend on them). Most scalar OP ExtVector cases are handled by the 6533 // splat path anyway, which does what we want (convert, not bitcast). 6534 // What this rules out for ExtVectors is crazy things like char4*float. 6535 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6536 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6537 6538 uint64_t srcLen, destLen; 6539 QualType srcEltTy, destEltTy; 6540 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6541 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6542 6543 // ASTContext::getTypeSize will return the size rounded up to a 6544 // power of 2, so instead of using that, we need to use the raw 6545 // element size multiplied by the element count. 6546 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6547 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6548 6549 return (srcLen * srcEltSize == destLen * destEltSize); 6550 } 6551 6552 /// Is this a legal conversion between two types, one of which is 6553 /// known to be a vector type? 6554 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6555 assert(destTy->isVectorType() || srcTy->isVectorType()); 6556 6557 switch (Context.getLangOpts().getLaxVectorConversions()) { 6558 case LangOptions::LaxVectorConversionKind::None: 6559 return false; 6560 6561 case LangOptions::LaxVectorConversionKind::Integer: 6562 if (!srcTy->isIntegralOrEnumerationType()) { 6563 auto *Vec = srcTy->getAs<VectorType>(); 6564 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6565 return false; 6566 } 6567 if (!destTy->isIntegralOrEnumerationType()) { 6568 auto *Vec = destTy->getAs<VectorType>(); 6569 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6570 return false; 6571 } 6572 // OK, integer (vector) -> integer (vector) bitcast. 6573 break; 6574 6575 case LangOptions::LaxVectorConversionKind::All: 6576 break; 6577 } 6578 6579 return areLaxCompatibleVectorTypes(srcTy, destTy); 6580 } 6581 6582 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6583 CastKind &Kind) { 6584 assert(VectorTy->isVectorType() && "Not a vector type!"); 6585 6586 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6587 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6588 return Diag(R.getBegin(), 6589 Ty->isVectorType() ? 6590 diag::err_invalid_conversion_between_vectors : 6591 diag::err_invalid_conversion_between_vector_and_integer) 6592 << VectorTy << Ty << R; 6593 } else 6594 return Diag(R.getBegin(), 6595 diag::err_invalid_conversion_between_vector_and_scalar) 6596 << VectorTy << Ty << R; 6597 6598 Kind = CK_BitCast; 6599 return false; 6600 } 6601 6602 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6603 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6604 6605 if (DestElemTy == SplattedExpr->getType()) 6606 return SplattedExpr; 6607 6608 assert(DestElemTy->isFloatingType() || 6609 DestElemTy->isIntegralOrEnumerationType()); 6610 6611 CastKind CK; 6612 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6613 // OpenCL requires that we convert `true` boolean expressions to -1, but 6614 // only when splatting vectors. 6615 if (DestElemTy->isFloatingType()) { 6616 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6617 // in two steps: boolean to signed integral, then to floating. 6618 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6619 CK_BooleanToSignedIntegral); 6620 SplattedExpr = CastExprRes.get(); 6621 CK = CK_IntegralToFloating; 6622 } else { 6623 CK = CK_BooleanToSignedIntegral; 6624 } 6625 } else { 6626 ExprResult CastExprRes = SplattedExpr; 6627 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6628 if (CastExprRes.isInvalid()) 6629 return ExprError(); 6630 SplattedExpr = CastExprRes.get(); 6631 } 6632 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6633 } 6634 6635 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6636 Expr *CastExpr, CastKind &Kind) { 6637 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6638 6639 QualType SrcTy = CastExpr->getType(); 6640 6641 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6642 // an ExtVectorType. 6643 // In OpenCL, casts between vectors of different types are not allowed. 6644 // (See OpenCL 6.2). 6645 if (SrcTy->isVectorType()) { 6646 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6647 (getLangOpts().OpenCL && 6648 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6649 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6650 << DestTy << SrcTy << R; 6651 return ExprError(); 6652 } 6653 Kind = CK_BitCast; 6654 return CastExpr; 6655 } 6656 6657 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6658 // conversion will take place first from scalar to elt type, and then 6659 // splat from elt type to vector. 6660 if (SrcTy->isPointerType()) 6661 return Diag(R.getBegin(), 6662 diag::err_invalid_conversion_between_vector_and_scalar) 6663 << DestTy << SrcTy << R; 6664 6665 Kind = CK_VectorSplat; 6666 return prepareVectorSplat(DestTy, CastExpr); 6667 } 6668 6669 ExprResult 6670 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6671 Declarator &D, ParsedType &Ty, 6672 SourceLocation RParenLoc, Expr *CastExpr) { 6673 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6674 "ActOnCastExpr(): missing type or expr"); 6675 6676 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6677 if (D.isInvalidType()) 6678 return ExprError(); 6679 6680 if (getLangOpts().CPlusPlus) { 6681 // Check that there are no default arguments (C++ only). 6682 CheckExtraCXXDefaultArguments(D); 6683 } else { 6684 // Make sure any TypoExprs have been dealt with. 6685 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6686 if (!Res.isUsable()) 6687 return ExprError(); 6688 CastExpr = Res.get(); 6689 } 6690 6691 checkUnusedDeclAttributes(D); 6692 6693 QualType castType = castTInfo->getType(); 6694 Ty = CreateParsedType(castType, castTInfo); 6695 6696 bool isVectorLiteral = false; 6697 6698 // Check for an altivec or OpenCL literal, 6699 // i.e. all the elements are integer constants. 6700 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6701 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6702 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6703 && castType->isVectorType() && (PE || PLE)) { 6704 if (PLE && PLE->getNumExprs() == 0) { 6705 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6706 return ExprError(); 6707 } 6708 if (PE || PLE->getNumExprs() == 1) { 6709 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6710 if (!E->getType()->isVectorType()) 6711 isVectorLiteral = true; 6712 } 6713 else 6714 isVectorLiteral = true; 6715 } 6716 6717 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6718 // then handle it as such. 6719 if (isVectorLiteral) 6720 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6721 6722 // If the Expr being casted is a ParenListExpr, handle it specially. 6723 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6724 // sequence of BinOp comma operators. 6725 if (isa<ParenListExpr>(CastExpr)) { 6726 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6727 if (Result.isInvalid()) return ExprError(); 6728 CastExpr = Result.get(); 6729 } 6730 6731 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6732 !getSourceManager().isInSystemMacro(LParenLoc)) 6733 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6734 6735 CheckTollFreeBridgeCast(castType, CastExpr); 6736 6737 CheckObjCBridgeRelatedCast(castType, CastExpr); 6738 6739 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6740 6741 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6742 } 6743 6744 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6745 SourceLocation RParenLoc, Expr *E, 6746 TypeSourceInfo *TInfo) { 6747 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6748 "Expected paren or paren list expression"); 6749 6750 Expr **exprs; 6751 unsigned numExprs; 6752 Expr *subExpr; 6753 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6754 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6755 LiteralLParenLoc = PE->getLParenLoc(); 6756 LiteralRParenLoc = PE->getRParenLoc(); 6757 exprs = PE->getExprs(); 6758 numExprs = PE->getNumExprs(); 6759 } else { // isa<ParenExpr> by assertion at function entrance 6760 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6761 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6762 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6763 exprs = &subExpr; 6764 numExprs = 1; 6765 } 6766 6767 QualType Ty = TInfo->getType(); 6768 assert(Ty->isVectorType() && "Expected vector type"); 6769 6770 SmallVector<Expr *, 8> initExprs; 6771 const VectorType *VTy = Ty->castAs<VectorType>(); 6772 unsigned numElems = VTy->getNumElements(); 6773 6774 // '(...)' form of vector initialization in AltiVec: the number of 6775 // initializers must be one or must match the size of the vector. 6776 // If a single value is specified in the initializer then it will be 6777 // replicated to all the components of the vector 6778 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6779 // The number of initializers must be one or must match the size of the 6780 // vector. If a single value is specified in the initializer then it will 6781 // be replicated to all the components of the vector 6782 if (numExprs == 1) { 6783 QualType ElemTy = VTy->getElementType(); 6784 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6785 if (Literal.isInvalid()) 6786 return ExprError(); 6787 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6788 PrepareScalarCast(Literal, ElemTy)); 6789 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6790 } 6791 else if (numExprs < numElems) { 6792 Diag(E->getExprLoc(), 6793 diag::err_incorrect_number_of_vector_initializers); 6794 return ExprError(); 6795 } 6796 else 6797 initExprs.append(exprs, exprs + numExprs); 6798 } 6799 else { 6800 // For OpenCL, when the number of initializers is a single value, 6801 // it will be replicated to all components of the vector. 6802 if (getLangOpts().OpenCL && 6803 VTy->getVectorKind() == VectorType::GenericVector && 6804 numExprs == 1) { 6805 QualType ElemTy = VTy->getElementType(); 6806 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6807 if (Literal.isInvalid()) 6808 return ExprError(); 6809 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6810 PrepareScalarCast(Literal, ElemTy)); 6811 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6812 } 6813 6814 initExprs.append(exprs, exprs + numExprs); 6815 } 6816 // FIXME: This means that pretty-printing the final AST will produce curly 6817 // braces instead of the original commas. 6818 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6819 initExprs, LiteralRParenLoc); 6820 initE->setType(Ty); 6821 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6822 } 6823 6824 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6825 /// the ParenListExpr into a sequence of comma binary operators. 6826 ExprResult 6827 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6828 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6829 if (!E) 6830 return OrigExpr; 6831 6832 ExprResult Result(E->getExpr(0)); 6833 6834 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6835 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6836 E->getExpr(i)); 6837 6838 if (Result.isInvalid()) return ExprError(); 6839 6840 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6841 } 6842 6843 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6844 SourceLocation R, 6845 MultiExprArg Val) { 6846 return ParenListExpr::Create(Context, L, Val, R); 6847 } 6848 6849 /// Emit a specialized diagnostic when one expression is a null pointer 6850 /// constant and the other is not a pointer. Returns true if a diagnostic is 6851 /// emitted. 6852 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6853 SourceLocation QuestionLoc) { 6854 Expr *NullExpr = LHSExpr; 6855 Expr *NonPointerExpr = RHSExpr; 6856 Expr::NullPointerConstantKind NullKind = 6857 NullExpr->isNullPointerConstant(Context, 6858 Expr::NPC_ValueDependentIsNotNull); 6859 6860 if (NullKind == Expr::NPCK_NotNull) { 6861 NullExpr = RHSExpr; 6862 NonPointerExpr = LHSExpr; 6863 NullKind = 6864 NullExpr->isNullPointerConstant(Context, 6865 Expr::NPC_ValueDependentIsNotNull); 6866 } 6867 6868 if (NullKind == Expr::NPCK_NotNull) 6869 return false; 6870 6871 if (NullKind == Expr::NPCK_ZeroExpression) 6872 return false; 6873 6874 if (NullKind == Expr::NPCK_ZeroLiteral) { 6875 // In this case, check to make sure that we got here from a "NULL" 6876 // string in the source code. 6877 NullExpr = NullExpr->IgnoreParenImpCasts(); 6878 SourceLocation loc = NullExpr->getExprLoc(); 6879 if (!findMacroSpelling(loc, "NULL")) 6880 return false; 6881 } 6882 6883 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6884 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6885 << NonPointerExpr->getType() << DiagType 6886 << NonPointerExpr->getSourceRange(); 6887 return true; 6888 } 6889 6890 /// Return false if the condition expression is valid, true otherwise. 6891 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6892 QualType CondTy = Cond->getType(); 6893 6894 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6895 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6896 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6897 << CondTy << Cond->getSourceRange(); 6898 return true; 6899 } 6900 6901 // C99 6.5.15p2 6902 if (CondTy->isScalarType()) return false; 6903 6904 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6905 << CondTy << Cond->getSourceRange(); 6906 return true; 6907 } 6908 6909 /// Handle when one or both operands are void type. 6910 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6911 ExprResult &RHS) { 6912 Expr *LHSExpr = LHS.get(); 6913 Expr *RHSExpr = RHS.get(); 6914 6915 if (!LHSExpr->getType()->isVoidType()) 6916 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6917 << RHSExpr->getSourceRange(); 6918 if (!RHSExpr->getType()->isVoidType()) 6919 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6920 << LHSExpr->getSourceRange(); 6921 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6922 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6923 return S.Context.VoidTy; 6924 } 6925 6926 /// Return false if the NullExpr can be promoted to PointerTy, 6927 /// true otherwise. 6928 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6929 QualType PointerTy) { 6930 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6931 !NullExpr.get()->isNullPointerConstant(S.Context, 6932 Expr::NPC_ValueDependentIsNull)) 6933 return true; 6934 6935 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6936 return false; 6937 } 6938 6939 /// Checks compatibility between two pointers and return the resulting 6940 /// type. 6941 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6942 ExprResult &RHS, 6943 SourceLocation Loc) { 6944 QualType LHSTy = LHS.get()->getType(); 6945 QualType RHSTy = RHS.get()->getType(); 6946 6947 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6948 // Two identical pointers types are always compatible. 6949 return LHSTy; 6950 } 6951 6952 QualType lhptee, rhptee; 6953 6954 // Get the pointee types. 6955 bool IsBlockPointer = false; 6956 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6957 lhptee = LHSBTy->getPointeeType(); 6958 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6959 IsBlockPointer = true; 6960 } else { 6961 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6962 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6963 } 6964 6965 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6966 // differently qualified versions of compatible types, the result type is 6967 // a pointer to an appropriately qualified version of the composite 6968 // type. 6969 6970 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6971 // clause doesn't make sense for our extensions. E.g. address space 2 should 6972 // be incompatible with address space 3: they may live on different devices or 6973 // anything. 6974 Qualifiers lhQual = lhptee.getQualifiers(); 6975 Qualifiers rhQual = rhptee.getQualifiers(); 6976 6977 LangAS ResultAddrSpace = LangAS::Default; 6978 LangAS LAddrSpace = lhQual.getAddressSpace(); 6979 LangAS RAddrSpace = rhQual.getAddressSpace(); 6980 6981 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6982 // spaces is disallowed. 6983 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6984 ResultAddrSpace = LAddrSpace; 6985 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6986 ResultAddrSpace = RAddrSpace; 6987 else { 6988 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6989 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6990 << RHS.get()->getSourceRange(); 6991 return QualType(); 6992 } 6993 6994 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6995 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6996 lhQual.removeCVRQualifiers(); 6997 rhQual.removeCVRQualifiers(); 6998 6999 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7000 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7001 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7002 // qual types are compatible iff 7003 // * corresponded types are compatible 7004 // * CVR qualifiers are equal 7005 // * address spaces are equal 7006 // Thus for conditional operator we merge CVR and address space unqualified 7007 // pointees and if there is a composite type we return a pointer to it with 7008 // merged qualifiers. 7009 LHSCastKind = 7010 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7011 RHSCastKind = 7012 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7013 lhQual.removeAddressSpace(); 7014 rhQual.removeAddressSpace(); 7015 7016 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7017 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7018 7019 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7020 7021 if (CompositeTy.isNull()) { 7022 // In this situation, we assume void* type. No especially good 7023 // reason, but this is what gcc does, and we do have to pick 7024 // to get a consistent AST. 7025 QualType incompatTy; 7026 incompatTy = S.Context.getPointerType( 7027 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7028 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7029 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7030 7031 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7032 // for casts between types with incompatible address space qualifiers. 7033 // For the following code the compiler produces casts between global and 7034 // local address spaces of the corresponded innermost pointees: 7035 // local int *global *a; 7036 // global int *global *b; 7037 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7038 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7039 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7040 << RHS.get()->getSourceRange(); 7041 7042 return incompatTy; 7043 } 7044 7045 // The pointer types are compatible. 7046 // In case of OpenCL ResultTy should have the address space qualifier 7047 // which is a superset of address spaces of both the 2nd and the 3rd 7048 // operands of the conditional operator. 7049 QualType ResultTy = [&, ResultAddrSpace]() { 7050 if (S.getLangOpts().OpenCL) { 7051 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7052 CompositeQuals.setAddressSpace(ResultAddrSpace); 7053 return S.Context 7054 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7055 .withCVRQualifiers(MergedCVRQual); 7056 } 7057 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7058 }(); 7059 if (IsBlockPointer) 7060 ResultTy = S.Context.getBlockPointerType(ResultTy); 7061 else 7062 ResultTy = S.Context.getPointerType(ResultTy); 7063 7064 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7065 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7066 return ResultTy; 7067 } 7068 7069 /// Return the resulting type when the operands are both block pointers. 7070 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7071 ExprResult &LHS, 7072 ExprResult &RHS, 7073 SourceLocation Loc) { 7074 QualType LHSTy = LHS.get()->getType(); 7075 QualType RHSTy = RHS.get()->getType(); 7076 7077 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7078 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7079 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7080 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7081 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7082 return destType; 7083 } 7084 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7085 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7086 << RHS.get()->getSourceRange(); 7087 return QualType(); 7088 } 7089 7090 // We have 2 block pointer types. 7091 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7092 } 7093 7094 /// Return the resulting type when the operands are both pointers. 7095 static QualType 7096 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7097 ExprResult &RHS, 7098 SourceLocation Loc) { 7099 // get the pointer types 7100 QualType LHSTy = LHS.get()->getType(); 7101 QualType RHSTy = RHS.get()->getType(); 7102 7103 // get the "pointed to" types 7104 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7105 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7106 7107 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7108 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7109 // Figure out necessary qualifiers (C99 6.5.15p6) 7110 QualType destPointee 7111 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7112 QualType destType = S.Context.getPointerType(destPointee); 7113 // Add qualifiers if necessary. 7114 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7115 // Promote to void*. 7116 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7117 return destType; 7118 } 7119 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7120 QualType destPointee 7121 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7122 QualType destType = S.Context.getPointerType(destPointee); 7123 // Add qualifiers if necessary. 7124 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7125 // Promote to void*. 7126 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7127 return destType; 7128 } 7129 7130 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7131 } 7132 7133 /// Return false if the first expression is not an integer and the second 7134 /// expression is not a pointer, true otherwise. 7135 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7136 Expr* PointerExpr, SourceLocation Loc, 7137 bool IsIntFirstExpr) { 7138 if (!PointerExpr->getType()->isPointerType() || 7139 !Int.get()->getType()->isIntegerType()) 7140 return false; 7141 7142 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7143 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7144 7145 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7146 << Expr1->getType() << Expr2->getType() 7147 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7148 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7149 CK_IntegralToPointer); 7150 return true; 7151 } 7152 7153 /// Simple conversion between integer and floating point types. 7154 /// 7155 /// Used when handling the OpenCL conditional operator where the 7156 /// condition is a vector while the other operands are scalar. 7157 /// 7158 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7159 /// types are either integer or floating type. Between the two 7160 /// operands, the type with the higher rank is defined as the "result 7161 /// type". The other operand needs to be promoted to the same type. No 7162 /// other type promotion is allowed. We cannot use 7163 /// UsualArithmeticConversions() for this purpose, since it always 7164 /// promotes promotable types. 7165 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7166 ExprResult &RHS, 7167 SourceLocation QuestionLoc) { 7168 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7169 if (LHS.isInvalid()) 7170 return QualType(); 7171 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7172 if (RHS.isInvalid()) 7173 return QualType(); 7174 7175 // For conversion purposes, we ignore any qualifiers. 7176 // For example, "const float" and "float" are equivalent. 7177 QualType LHSType = 7178 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7179 QualType RHSType = 7180 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7181 7182 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7183 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7184 << LHSType << LHS.get()->getSourceRange(); 7185 return QualType(); 7186 } 7187 7188 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7189 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7190 << RHSType << RHS.get()->getSourceRange(); 7191 return QualType(); 7192 } 7193 7194 // If both types are identical, no conversion is needed. 7195 if (LHSType == RHSType) 7196 return LHSType; 7197 7198 // Now handle "real" floating types (i.e. float, double, long double). 7199 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7200 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7201 /*IsCompAssign = */ false); 7202 7203 // Finally, we have two differing integer types. 7204 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7205 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7206 } 7207 7208 /// Convert scalar operands to a vector that matches the 7209 /// condition in length. 7210 /// 7211 /// Used when handling the OpenCL conditional operator where the 7212 /// condition is a vector while the other operands are scalar. 7213 /// 7214 /// We first compute the "result type" for the scalar operands 7215 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7216 /// into a vector of that type where the length matches the condition 7217 /// vector type. s6.11.6 requires that the element types of the result 7218 /// and the condition must have the same number of bits. 7219 static QualType 7220 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7221 QualType CondTy, SourceLocation QuestionLoc) { 7222 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7223 if (ResTy.isNull()) return QualType(); 7224 7225 const VectorType *CV = CondTy->getAs<VectorType>(); 7226 assert(CV); 7227 7228 // Determine the vector result type 7229 unsigned NumElements = CV->getNumElements(); 7230 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7231 7232 // Ensure that all types have the same number of bits 7233 if (S.Context.getTypeSize(CV->getElementType()) 7234 != S.Context.getTypeSize(ResTy)) { 7235 // Since VectorTy is created internally, it does not pretty print 7236 // with an OpenCL name. Instead, we just print a description. 7237 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7238 SmallString<64> Str; 7239 llvm::raw_svector_ostream OS(Str); 7240 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7241 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7242 << CondTy << OS.str(); 7243 return QualType(); 7244 } 7245 7246 // Convert operands to the vector result type 7247 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7248 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7249 7250 return VectorTy; 7251 } 7252 7253 /// Return false if this is a valid OpenCL condition vector 7254 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7255 SourceLocation QuestionLoc) { 7256 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7257 // integral type. 7258 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7259 assert(CondTy); 7260 QualType EleTy = CondTy->getElementType(); 7261 if (EleTy->isIntegerType()) return false; 7262 7263 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7264 << Cond->getType() << Cond->getSourceRange(); 7265 return true; 7266 } 7267 7268 /// Return false if the vector condition type and the vector 7269 /// result type are compatible. 7270 /// 7271 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7272 /// number of elements, and their element types have the same number 7273 /// of bits. 7274 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7275 SourceLocation QuestionLoc) { 7276 const VectorType *CV = CondTy->getAs<VectorType>(); 7277 const VectorType *RV = VecResTy->getAs<VectorType>(); 7278 assert(CV && RV); 7279 7280 if (CV->getNumElements() != RV->getNumElements()) { 7281 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7282 << CondTy << VecResTy; 7283 return true; 7284 } 7285 7286 QualType CVE = CV->getElementType(); 7287 QualType RVE = RV->getElementType(); 7288 7289 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7290 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7291 << CondTy << VecResTy; 7292 return true; 7293 } 7294 7295 return false; 7296 } 7297 7298 /// Return the resulting type for the conditional operator in 7299 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7300 /// s6.3.i) when the condition is a vector type. 7301 static QualType 7302 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7303 ExprResult &LHS, ExprResult &RHS, 7304 SourceLocation QuestionLoc) { 7305 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7306 if (Cond.isInvalid()) 7307 return QualType(); 7308 QualType CondTy = Cond.get()->getType(); 7309 7310 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7311 return QualType(); 7312 7313 // If either operand is a vector then find the vector type of the 7314 // result as specified in OpenCL v1.1 s6.3.i. 7315 if (LHS.get()->getType()->isVectorType() || 7316 RHS.get()->getType()->isVectorType()) { 7317 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7318 /*isCompAssign*/false, 7319 /*AllowBothBool*/true, 7320 /*AllowBoolConversions*/false); 7321 if (VecResTy.isNull()) return QualType(); 7322 // The result type must match the condition type as specified in 7323 // OpenCL v1.1 s6.11.6. 7324 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7325 return QualType(); 7326 return VecResTy; 7327 } 7328 7329 // Both operands are scalar. 7330 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7331 } 7332 7333 /// Return true if the Expr is block type 7334 static bool checkBlockType(Sema &S, const Expr *E) { 7335 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7336 QualType Ty = CE->getCallee()->getType(); 7337 if (Ty->isBlockPointerType()) { 7338 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7339 return true; 7340 } 7341 } 7342 return false; 7343 } 7344 7345 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7346 /// In that case, LHS = cond. 7347 /// C99 6.5.15 7348 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7349 ExprResult &RHS, ExprValueKind &VK, 7350 ExprObjectKind &OK, 7351 SourceLocation QuestionLoc) { 7352 7353 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7354 if (!LHSResult.isUsable()) return QualType(); 7355 LHS = LHSResult; 7356 7357 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7358 if (!RHSResult.isUsable()) return QualType(); 7359 RHS = RHSResult; 7360 7361 // C++ is sufficiently different to merit its own checker. 7362 if (getLangOpts().CPlusPlus) 7363 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7364 7365 VK = VK_RValue; 7366 OK = OK_Ordinary; 7367 7368 // The OpenCL operator with a vector condition is sufficiently 7369 // different to merit its own checker. 7370 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7371 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7372 7373 // First, check the condition. 7374 Cond = UsualUnaryConversions(Cond.get()); 7375 if (Cond.isInvalid()) 7376 return QualType(); 7377 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7378 return QualType(); 7379 7380 // Now check the two expressions. 7381 if (LHS.get()->getType()->isVectorType() || 7382 RHS.get()->getType()->isVectorType()) 7383 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7384 /*AllowBothBool*/true, 7385 /*AllowBoolConversions*/false); 7386 7387 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7388 if (LHS.isInvalid() || RHS.isInvalid()) 7389 return QualType(); 7390 7391 QualType LHSTy = LHS.get()->getType(); 7392 QualType RHSTy = RHS.get()->getType(); 7393 7394 // Diagnose attempts to convert between __float128 and long double where 7395 // such conversions currently can't be handled. 7396 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7397 Diag(QuestionLoc, 7398 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7399 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7400 return QualType(); 7401 } 7402 7403 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7404 // selection operator (?:). 7405 if (getLangOpts().OpenCL && 7406 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7407 return QualType(); 7408 } 7409 7410 // If both operands have arithmetic type, do the usual arithmetic conversions 7411 // to find a common type: C99 6.5.15p3,5. 7412 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7413 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7414 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7415 7416 return ResTy; 7417 } 7418 7419 // If both operands are the same structure or union type, the result is that 7420 // type. 7421 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7422 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7423 if (LHSRT->getDecl() == RHSRT->getDecl()) 7424 // "If both the operands have structure or union type, the result has 7425 // that type." This implies that CV qualifiers are dropped. 7426 return LHSTy.getUnqualifiedType(); 7427 // FIXME: Type of conditional expression must be complete in C mode. 7428 } 7429 7430 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7431 // The following || allows only one side to be void (a GCC-ism). 7432 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7433 return checkConditionalVoidType(*this, LHS, RHS); 7434 } 7435 7436 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7437 // the type of the other operand." 7438 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7439 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7440 7441 // All objective-c pointer type analysis is done here. 7442 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7443 QuestionLoc); 7444 if (LHS.isInvalid() || RHS.isInvalid()) 7445 return QualType(); 7446 if (!compositeType.isNull()) 7447 return compositeType; 7448 7449 7450 // Handle block pointer types. 7451 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7452 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7453 QuestionLoc); 7454 7455 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7456 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7457 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7458 QuestionLoc); 7459 7460 // GCC compatibility: soften pointer/integer mismatch. Note that 7461 // null pointers have been filtered out by this point. 7462 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7463 /*IsIntFirstExpr=*/true)) 7464 return RHSTy; 7465 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7466 /*IsIntFirstExpr=*/false)) 7467 return LHSTy; 7468 7469 // Emit a better diagnostic if one of the expressions is a null pointer 7470 // constant and the other is not a pointer type. In this case, the user most 7471 // likely forgot to take the address of the other expression. 7472 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7473 return QualType(); 7474 7475 // Otherwise, the operands are not compatible. 7476 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7477 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7478 << RHS.get()->getSourceRange(); 7479 return QualType(); 7480 } 7481 7482 /// FindCompositeObjCPointerType - Helper method to find composite type of 7483 /// two objective-c pointer types of the two input expressions. 7484 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7485 SourceLocation QuestionLoc) { 7486 QualType LHSTy = LHS.get()->getType(); 7487 QualType RHSTy = RHS.get()->getType(); 7488 7489 // Handle things like Class and struct objc_class*. Here we case the result 7490 // to the pseudo-builtin, because that will be implicitly cast back to the 7491 // redefinition type if an attempt is made to access its fields. 7492 if (LHSTy->isObjCClassType() && 7493 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7494 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7495 return LHSTy; 7496 } 7497 if (RHSTy->isObjCClassType() && 7498 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7499 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7500 return RHSTy; 7501 } 7502 // And the same for struct objc_object* / id 7503 if (LHSTy->isObjCIdType() && 7504 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7505 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7506 return LHSTy; 7507 } 7508 if (RHSTy->isObjCIdType() && 7509 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7510 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7511 return RHSTy; 7512 } 7513 // And the same for struct objc_selector* / SEL 7514 if (Context.isObjCSelType(LHSTy) && 7515 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7516 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7517 return LHSTy; 7518 } 7519 if (Context.isObjCSelType(RHSTy) && 7520 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7521 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7522 return RHSTy; 7523 } 7524 // Check constraints for Objective-C object pointers types. 7525 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7526 7527 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7528 // Two identical object pointer types are always compatible. 7529 return LHSTy; 7530 } 7531 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7532 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7533 QualType compositeType = LHSTy; 7534 7535 // If both operands are interfaces and either operand can be 7536 // assigned to the other, use that type as the composite 7537 // type. This allows 7538 // xxx ? (A*) a : (B*) b 7539 // where B is a subclass of A. 7540 // 7541 // Additionally, as for assignment, if either type is 'id' 7542 // allow silent coercion. Finally, if the types are 7543 // incompatible then make sure to use 'id' as the composite 7544 // type so the result is acceptable for sending messages to. 7545 7546 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7547 // It could return the composite type. 7548 if (!(compositeType = 7549 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7550 // Nothing more to do. 7551 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7552 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7553 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7554 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7555 } else if ((LHSOPT->isObjCQualifiedIdType() || 7556 RHSOPT->isObjCQualifiedIdType()) && 7557 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7558 true)) { 7559 // Need to handle "id<xx>" explicitly. 7560 // GCC allows qualified id and any Objective-C type to devolve to 7561 // id. Currently localizing to here until clear this should be 7562 // part of ObjCQualifiedIdTypesAreCompatible. 7563 compositeType = Context.getObjCIdType(); 7564 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7565 compositeType = Context.getObjCIdType(); 7566 } else { 7567 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7568 << LHSTy << RHSTy 7569 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7570 QualType incompatTy = Context.getObjCIdType(); 7571 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7572 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7573 return incompatTy; 7574 } 7575 // The object pointer types are compatible. 7576 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7577 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7578 return compositeType; 7579 } 7580 // Check Objective-C object pointer types and 'void *' 7581 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7582 if (getLangOpts().ObjCAutoRefCount) { 7583 // ARC forbids the implicit conversion of object pointers to 'void *', 7584 // so these types are not compatible. 7585 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7586 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7587 LHS = RHS = true; 7588 return QualType(); 7589 } 7590 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7591 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7592 QualType destPointee 7593 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7594 QualType destType = Context.getPointerType(destPointee); 7595 // Add qualifiers if necessary. 7596 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7597 // Promote to void*. 7598 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7599 return destType; 7600 } 7601 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7602 if (getLangOpts().ObjCAutoRefCount) { 7603 // ARC forbids the implicit conversion of object pointers to 'void *', 7604 // so these types are not compatible. 7605 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7606 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7607 LHS = RHS = true; 7608 return QualType(); 7609 } 7610 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7611 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7612 QualType destPointee 7613 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7614 QualType destType = Context.getPointerType(destPointee); 7615 // Add qualifiers if necessary. 7616 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7617 // Promote to void*. 7618 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7619 return destType; 7620 } 7621 return QualType(); 7622 } 7623 7624 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7625 /// ParenRange in parentheses. 7626 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7627 const PartialDiagnostic &Note, 7628 SourceRange ParenRange) { 7629 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7630 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7631 EndLoc.isValid()) { 7632 Self.Diag(Loc, Note) 7633 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7634 << FixItHint::CreateInsertion(EndLoc, ")"); 7635 } else { 7636 // We can't display the parentheses, so just show the bare note. 7637 Self.Diag(Loc, Note) << ParenRange; 7638 } 7639 } 7640 7641 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7642 return BinaryOperator::isAdditiveOp(Opc) || 7643 BinaryOperator::isMultiplicativeOp(Opc) || 7644 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7645 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7646 // not any of the logical operators. Bitwise-xor is commonly used as a 7647 // logical-xor because there is no logical-xor operator. The logical 7648 // operators, including uses of xor, have a high false positive rate for 7649 // precedence warnings. 7650 } 7651 7652 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7653 /// expression, either using a built-in or overloaded operator, 7654 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7655 /// expression. 7656 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7657 Expr **RHSExprs) { 7658 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7659 E = E->IgnoreImpCasts(); 7660 E = E->IgnoreConversionOperator(); 7661 E = E->IgnoreImpCasts(); 7662 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7663 E = MTE->getSubExpr(); 7664 E = E->IgnoreImpCasts(); 7665 } 7666 7667 // Built-in binary operator. 7668 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7669 if (IsArithmeticOp(OP->getOpcode())) { 7670 *Opcode = OP->getOpcode(); 7671 *RHSExprs = OP->getRHS(); 7672 return true; 7673 } 7674 } 7675 7676 // Overloaded operator. 7677 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7678 if (Call->getNumArgs() != 2) 7679 return false; 7680 7681 // Make sure this is really a binary operator that is safe to pass into 7682 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7683 OverloadedOperatorKind OO = Call->getOperator(); 7684 if (OO < OO_Plus || OO > OO_Arrow || 7685 OO == OO_PlusPlus || OO == OO_MinusMinus) 7686 return false; 7687 7688 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7689 if (IsArithmeticOp(OpKind)) { 7690 *Opcode = OpKind; 7691 *RHSExprs = Call->getArg(1); 7692 return true; 7693 } 7694 } 7695 7696 return false; 7697 } 7698 7699 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7700 /// or is a logical expression such as (x==y) which has int type, but is 7701 /// commonly interpreted as boolean. 7702 static bool ExprLooksBoolean(Expr *E) { 7703 E = E->IgnoreParenImpCasts(); 7704 7705 if (E->getType()->isBooleanType()) 7706 return true; 7707 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7708 return OP->isComparisonOp() || OP->isLogicalOp(); 7709 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7710 return OP->getOpcode() == UO_LNot; 7711 if (E->getType()->isPointerType()) 7712 return true; 7713 // FIXME: What about overloaded operator calls returning "unspecified boolean 7714 // type"s (commonly pointer-to-members)? 7715 7716 return false; 7717 } 7718 7719 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7720 /// and binary operator are mixed in a way that suggests the programmer assumed 7721 /// the conditional operator has higher precedence, for example: 7722 /// "int x = a + someBinaryCondition ? 1 : 2". 7723 static void DiagnoseConditionalPrecedence(Sema &Self, 7724 SourceLocation OpLoc, 7725 Expr *Condition, 7726 Expr *LHSExpr, 7727 Expr *RHSExpr) { 7728 BinaryOperatorKind CondOpcode; 7729 Expr *CondRHS; 7730 7731 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7732 return; 7733 if (!ExprLooksBoolean(CondRHS)) 7734 return; 7735 7736 // The condition is an arithmetic binary expression, with a right- 7737 // hand side that looks boolean, so warn. 7738 7739 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7740 ? diag::warn_precedence_bitwise_conditional 7741 : diag::warn_precedence_conditional; 7742 7743 Self.Diag(OpLoc, DiagID) 7744 << Condition->getSourceRange() 7745 << BinaryOperator::getOpcodeStr(CondOpcode); 7746 7747 SuggestParentheses( 7748 Self, OpLoc, 7749 Self.PDiag(diag::note_precedence_silence) 7750 << BinaryOperator::getOpcodeStr(CondOpcode), 7751 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7752 7753 SuggestParentheses(Self, OpLoc, 7754 Self.PDiag(diag::note_precedence_conditional_first), 7755 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7756 } 7757 7758 /// Compute the nullability of a conditional expression. 7759 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7760 QualType LHSTy, QualType RHSTy, 7761 ASTContext &Ctx) { 7762 if (!ResTy->isAnyPointerType()) 7763 return ResTy; 7764 7765 auto GetNullability = [&Ctx](QualType Ty) { 7766 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7767 if (Kind) 7768 return *Kind; 7769 return NullabilityKind::Unspecified; 7770 }; 7771 7772 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7773 NullabilityKind MergedKind; 7774 7775 // Compute nullability of a binary conditional expression. 7776 if (IsBin) { 7777 if (LHSKind == NullabilityKind::NonNull) 7778 MergedKind = NullabilityKind::NonNull; 7779 else 7780 MergedKind = RHSKind; 7781 // Compute nullability of a normal conditional expression. 7782 } else { 7783 if (LHSKind == NullabilityKind::Nullable || 7784 RHSKind == NullabilityKind::Nullable) 7785 MergedKind = NullabilityKind::Nullable; 7786 else if (LHSKind == NullabilityKind::NonNull) 7787 MergedKind = RHSKind; 7788 else if (RHSKind == NullabilityKind::NonNull) 7789 MergedKind = LHSKind; 7790 else 7791 MergedKind = NullabilityKind::Unspecified; 7792 } 7793 7794 // Return if ResTy already has the correct nullability. 7795 if (GetNullability(ResTy) == MergedKind) 7796 return ResTy; 7797 7798 // Strip all nullability from ResTy. 7799 while (ResTy->getNullability(Ctx)) 7800 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7801 7802 // Create a new AttributedType with the new nullability kind. 7803 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7804 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7805 } 7806 7807 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7808 /// in the case of a the GNU conditional expr extension. 7809 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7810 SourceLocation ColonLoc, 7811 Expr *CondExpr, Expr *LHSExpr, 7812 Expr *RHSExpr) { 7813 if (!getLangOpts().CPlusPlus) { 7814 // C cannot handle TypoExpr nodes in the condition because it 7815 // doesn't handle dependent types properly, so make sure any TypoExprs have 7816 // been dealt with before checking the operands. 7817 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7818 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7819 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7820 7821 if (!CondResult.isUsable()) 7822 return ExprError(); 7823 7824 if (LHSExpr) { 7825 if (!LHSResult.isUsable()) 7826 return ExprError(); 7827 } 7828 7829 if (!RHSResult.isUsable()) 7830 return ExprError(); 7831 7832 CondExpr = CondResult.get(); 7833 LHSExpr = LHSResult.get(); 7834 RHSExpr = RHSResult.get(); 7835 } 7836 7837 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7838 // was the condition. 7839 OpaqueValueExpr *opaqueValue = nullptr; 7840 Expr *commonExpr = nullptr; 7841 if (!LHSExpr) { 7842 commonExpr = CondExpr; 7843 // Lower out placeholder types first. This is important so that we don't 7844 // try to capture a placeholder. This happens in few cases in C++; such 7845 // as Objective-C++'s dictionary subscripting syntax. 7846 if (commonExpr->hasPlaceholderType()) { 7847 ExprResult result = CheckPlaceholderExpr(commonExpr); 7848 if (!result.isUsable()) return ExprError(); 7849 commonExpr = result.get(); 7850 } 7851 // We usually want to apply unary conversions *before* saving, except 7852 // in the special case of a C++ l-value conditional. 7853 if (!(getLangOpts().CPlusPlus 7854 && !commonExpr->isTypeDependent() 7855 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7856 && commonExpr->isGLValue() 7857 && commonExpr->isOrdinaryOrBitFieldObject() 7858 && RHSExpr->isOrdinaryOrBitFieldObject() 7859 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7860 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7861 if (commonRes.isInvalid()) 7862 return ExprError(); 7863 commonExpr = commonRes.get(); 7864 } 7865 7866 // If the common expression is a class or array prvalue, materialize it 7867 // so that we can safely refer to it multiple times. 7868 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7869 commonExpr->getType()->isArrayType())) { 7870 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7871 if (MatExpr.isInvalid()) 7872 return ExprError(); 7873 commonExpr = MatExpr.get(); 7874 } 7875 7876 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7877 commonExpr->getType(), 7878 commonExpr->getValueKind(), 7879 commonExpr->getObjectKind(), 7880 commonExpr); 7881 LHSExpr = CondExpr = opaqueValue; 7882 } 7883 7884 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7885 ExprValueKind VK = VK_RValue; 7886 ExprObjectKind OK = OK_Ordinary; 7887 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7888 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7889 VK, OK, QuestionLoc); 7890 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7891 RHS.isInvalid()) 7892 return ExprError(); 7893 7894 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7895 RHS.get()); 7896 7897 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7898 7899 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7900 Context); 7901 7902 if (!commonExpr) 7903 return new (Context) 7904 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7905 RHS.get(), result, VK, OK); 7906 7907 return new (Context) BinaryConditionalOperator( 7908 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7909 ColonLoc, result, VK, OK); 7910 } 7911 7912 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7913 // being closely modeled after the C99 spec:-). The odd characteristic of this 7914 // routine is it effectively iqnores the qualifiers on the top level pointee. 7915 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7916 // FIXME: add a couple examples in this comment. 7917 static Sema::AssignConvertType 7918 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7919 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7920 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7921 7922 // get the "pointed to" type (ignoring qualifiers at the top level) 7923 const Type *lhptee, *rhptee; 7924 Qualifiers lhq, rhq; 7925 std::tie(lhptee, lhq) = 7926 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7927 std::tie(rhptee, rhq) = 7928 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7929 7930 Sema::AssignConvertType ConvTy = Sema::Compatible; 7931 7932 // C99 6.5.16.1p1: This following citation is common to constraints 7933 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7934 // qualifiers of the type *pointed to* by the right; 7935 7936 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7937 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7938 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7939 // Ignore lifetime for further calculation. 7940 lhq.removeObjCLifetime(); 7941 rhq.removeObjCLifetime(); 7942 } 7943 7944 if (!lhq.compatiblyIncludes(rhq)) { 7945 // Treat address-space mismatches as fatal. 7946 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7947 return Sema::IncompatiblePointerDiscardsQualifiers; 7948 7949 // It's okay to add or remove GC or lifetime qualifiers when converting to 7950 // and from void*. 7951 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7952 .compatiblyIncludes( 7953 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7954 && (lhptee->isVoidType() || rhptee->isVoidType())) 7955 ; // keep old 7956 7957 // Treat lifetime mismatches as fatal. 7958 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7959 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7960 7961 // For GCC/MS compatibility, other qualifier mismatches are treated 7962 // as still compatible in C. 7963 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7964 } 7965 7966 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7967 // incomplete type and the other is a pointer to a qualified or unqualified 7968 // version of void... 7969 if (lhptee->isVoidType()) { 7970 if (rhptee->isIncompleteOrObjectType()) 7971 return ConvTy; 7972 7973 // As an extension, we allow cast to/from void* to function pointer. 7974 assert(rhptee->isFunctionType()); 7975 return Sema::FunctionVoidPointer; 7976 } 7977 7978 if (rhptee->isVoidType()) { 7979 if (lhptee->isIncompleteOrObjectType()) 7980 return ConvTy; 7981 7982 // As an extension, we allow cast to/from void* to function pointer. 7983 assert(lhptee->isFunctionType()); 7984 return Sema::FunctionVoidPointer; 7985 } 7986 7987 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7988 // unqualified versions of compatible types, ... 7989 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7990 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7991 // Check if the pointee types are compatible ignoring the sign. 7992 // We explicitly check for char so that we catch "char" vs 7993 // "unsigned char" on systems where "char" is unsigned. 7994 if (lhptee->isCharType()) 7995 ltrans = S.Context.UnsignedCharTy; 7996 else if (lhptee->hasSignedIntegerRepresentation()) 7997 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7998 7999 if (rhptee->isCharType()) 8000 rtrans = S.Context.UnsignedCharTy; 8001 else if (rhptee->hasSignedIntegerRepresentation()) 8002 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8003 8004 if (ltrans == rtrans) { 8005 // Types are compatible ignoring the sign. Qualifier incompatibility 8006 // takes priority over sign incompatibility because the sign 8007 // warning can be disabled. 8008 if (ConvTy != Sema::Compatible) 8009 return ConvTy; 8010 8011 return Sema::IncompatiblePointerSign; 8012 } 8013 8014 // If we are a multi-level pointer, it's possible that our issue is simply 8015 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8016 // the eventual target type is the same and the pointers have the same 8017 // level of indirection, this must be the issue. 8018 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8019 do { 8020 std::tie(lhptee, lhq) = 8021 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8022 std::tie(rhptee, rhq) = 8023 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8024 8025 // Inconsistent address spaces at this point is invalid, even if the 8026 // address spaces would be compatible. 8027 // FIXME: This doesn't catch address space mismatches for pointers of 8028 // different nesting levels, like: 8029 // __local int *** a; 8030 // int ** b = a; 8031 // It's not clear how to actually determine when such pointers are 8032 // invalidly incompatible. 8033 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8034 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8035 8036 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8037 8038 if (lhptee == rhptee) 8039 return Sema::IncompatibleNestedPointerQualifiers; 8040 } 8041 8042 // General pointer incompatibility takes priority over qualifiers. 8043 return Sema::IncompatiblePointer; 8044 } 8045 if (!S.getLangOpts().CPlusPlus && 8046 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8047 return Sema::IncompatiblePointer; 8048 return ConvTy; 8049 } 8050 8051 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8052 /// block pointer types are compatible or whether a block and normal pointer 8053 /// are compatible. It is more restrict than comparing two function pointer 8054 // types. 8055 static Sema::AssignConvertType 8056 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8057 QualType RHSType) { 8058 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8059 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8060 8061 QualType lhptee, rhptee; 8062 8063 // get the "pointed to" type (ignoring qualifiers at the top level) 8064 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8065 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8066 8067 // In C++, the types have to match exactly. 8068 if (S.getLangOpts().CPlusPlus) 8069 return Sema::IncompatibleBlockPointer; 8070 8071 Sema::AssignConvertType ConvTy = Sema::Compatible; 8072 8073 // For blocks we enforce that qualifiers are identical. 8074 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8075 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8076 if (S.getLangOpts().OpenCL) { 8077 LQuals.removeAddressSpace(); 8078 RQuals.removeAddressSpace(); 8079 } 8080 if (LQuals != RQuals) 8081 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8082 8083 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8084 // assignment. 8085 // The current behavior is similar to C++ lambdas. A block might be 8086 // assigned to a variable iff its return type and parameters are compatible 8087 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8088 // an assignment. Presumably it should behave in way that a function pointer 8089 // assignment does in C, so for each parameter and return type: 8090 // * CVR and address space of LHS should be a superset of CVR and address 8091 // space of RHS. 8092 // * unqualified types should be compatible. 8093 if (S.getLangOpts().OpenCL) { 8094 if (!S.Context.typesAreBlockPointerCompatible( 8095 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8096 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8097 return Sema::IncompatibleBlockPointer; 8098 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8099 return Sema::IncompatibleBlockPointer; 8100 8101 return ConvTy; 8102 } 8103 8104 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8105 /// for assignment compatibility. 8106 static Sema::AssignConvertType 8107 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8108 QualType RHSType) { 8109 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8110 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8111 8112 if (LHSType->isObjCBuiltinType()) { 8113 // Class is not compatible with ObjC object pointers. 8114 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8115 !RHSType->isObjCQualifiedClassType()) 8116 return Sema::IncompatiblePointer; 8117 return Sema::Compatible; 8118 } 8119 if (RHSType->isObjCBuiltinType()) { 8120 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8121 !LHSType->isObjCQualifiedClassType()) 8122 return Sema::IncompatiblePointer; 8123 return Sema::Compatible; 8124 } 8125 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8126 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8127 8128 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8129 // make an exception for id<P> 8130 !LHSType->isObjCQualifiedIdType()) 8131 return Sema::CompatiblePointerDiscardsQualifiers; 8132 8133 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8134 return Sema::Compatible; 8135 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8136 return Sema::IncompatibleObjCQualifiedId; 8137 return Sema::IncompatiblePointer; 8138 } 8139 8140 Sema::AssignConvertType 8141 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8142 QualType LHSType, QualType RHSType) { 8143 // Fake up an opaque expression. We don't actually care about what 8144 // cast operations are required, so if CheckAssignmentConstraints 8145 // adds casts to this they'll be wasted, but fortunately that doesn't 8146 // usually happen on valid code. 8147 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8148 ExprResult RHSPtr = &RHSExpr; 8149 CastKind K; 8150 8151 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8152 } 8153 8154 /// This helper function returns true if QT is a vector type that has element 8155 /// type ElementType. 8156 static bool isVector(QualType QT, QualType ElementType) { 8157 if (const VectorType *VT = QT->getAs<VectorType>()) 8158 return VT->getElementType() == ElementType; 8159 return false; 8160 } 8161 8162 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8163 /// has code to accommodate several GCC extensions when type checking 8164 /// pointers. Here are some objectionable examples that GCC considers warnings: 8165 /// 8166 /// int a, *pint; 8167 /// short *pshort; 8168 /// struct foo *pfoo; 8169 /// 8170 /// pint = pshort; // warning: assignment from incompatible pointer type 8171 /// a = pint; // warning: assignment makes integer from pointer without a cast 8172 /// pint = a; // warning: assignment makes pointer from integer without a cast 8173 /// pint = pfoo; // warning: assignment from incompatible pointer type 8174 /// 8175 /// As a result, the code for dealing with pointers is more complex than the 8176 /// C99 spec dictates. 8177 /// 8178 /// Sets 'Kind' for any result kind except Incompatible. 8179 Sema::AssignConvertType 8180 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8181 CastKind &Kind, bool ConvertRHS) { 8182 QualType RHSType = RHS.get()->getType(); 8183 QualType OrigLHSType = LHSType; 8184 8185 // Get canonical types. We're not formatting these types, just comparing 8186 // them. 8187 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8188 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8189 8190 // Common case: no conversion required. 8191 if (LHSType == RHSType) { 8192 Kind = CK_NoOp; 8193 return Compatible; 8194 } 8195 8196 // If we have an atomic type, try a non-atomic assignment, then just add an 8197 // atomic qualification step. 8198 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8199 Sema::AssignConvertType result = 8200 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8201 if (result != Compatible) 8202 return result; 8203 if (Kind != CK_NoOp && ConvertRHS) 8204 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8205 Kind = CK_NonAtomicToAtomic; 8206 return Compatible; 8207 } 8208 8209 // If the left-hand side is a reference type, then we are in a 8210 // (rare!) case where we've allowed the use of references in C, 8211 // e.g., as a parameter type in a built-in function. In this case, 8212 // just make sure that the type referenced is compatible with the 8213 // right-hand side type. The caller is responsible for adjusting 8214 // LHSType so that the resulting expression does not have reference 8215 // type. 8216 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8217 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8218 Kind = CK_LValueBitCast; 8219 return Compatible; 8220 } 8221 return Incompatible; 8222 } 8223 8224 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8225 // to the same ExtVector type. 8226 if (LHSType->isExtVectorType()) { 8227 if (RHSType->isExtVectorType()) 8228 return Incompatible; 8229 if (RHSType->isArithmeticType()) { 8230 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8231 if (ConvertRHS) 8232 RHS = prepareVectorSplat(LHSType, RHS.get()); 8233 Kind = CK_VectorSplat; 8234 return Compatible; 8235 } 8236 } 8237 8238 // Conversions to or from vector type. 8239 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8240 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8241 // Allow assignments of an AltiVec vector type to an equivalent GCC 8242 // vector type and vice versa 8243 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8244 Kind = CK_BitCast; 8245 return Compatible; 8246 } 8247 8248 // If we are allowing lax vector conversions, and LHS and RHS are both 8249 // vectors, the total size only needs to be the same. This is a bitcast; 8250 // no bits are changed but the result type is different. 8251 if (isLaxVectorConversion(RHSType, LHSType)) { 8252 Kind = CK_BitCast; 8253 return IncompatibleVectors; 8254 } 8255 } 8256 8257 // When the RHS comes from another lax conversion (e.g. binops between 8258 // scalars and vectors) the result is canonicalized as a vector. When the 8259 // LHS is also a vector, the lax is allowed by the condition above. Handle 8260 // the case where LHS is a scalar. 8261 if (LHSType->isScalarType()) { 8262 const VectorType *VecType = RHSType->getAs<VectorType>(); 8263 if (VecType && VecType->getNumElements() == 1 && 8264 isLaxVectorConversion(RHSType, LHSType)) { 8265 ExprResult *VecExpr = &RHS; 8266 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8267 Kind = CK_BitCast; 8268 return Compatible; 8269 } 8270 } 8271 8272 return Incompatible; 8273 } 8274 8275 // Diagnose attempts to convert between __float128 and long double where 8276 // such conversions currently can't be handled. 8277 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8278 return Incompatible; 8279 8280 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8281 // discards the imaginary part. 8282 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8283 !LHSType->getAs<ComplexType>()) 8284 return Incompatible; 8285 8286 // Arithmetic conversions. 8287 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8288 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8289 if (ConvertRHS) 8290 Kind = PrepareScalarCast(RHS, LHSType); 8291 return Compatible; 8292 } 8293 8294 // Conversions to normal pointers. 8295 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8296 // U* -> T* 8297 if (isa<PointerType>(RHSType)) { 8298 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8299 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8300 if (AddrSpaceL != AddrSpaceR) 8301 Kind = CK_AddressSpaceConversion; 8302 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8303 Kind = CK_NoOp; 8304 else 8305 Kind = CK_BitCast; 8306 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8307 } 8308 8309 // int -> T* 8310 if (RHSType->isIntegerType()) { 8311 Kind = CK_IntegralToPointer; // FIXME: null? 8312 return IntToPointer; 8313 } 8314 8315 // C pointers are not compatible with ObjC object pointers, 8316 // with two exceptions: 8317 if (isa<ObjCObjectPointerType>(RHSType)) { 8318 // - conversions to void* 8319 if (LHSPointer->getPointeeType()->isVoidType()) { 8320 Kind = CK_BitCast; 8321 return Compatible; 8322 } 8323 8324 // - conversions from 'Class' to the redefinition type 8325 if (RHSType->isObjCClassType() && 8326 Context.hasSameType(LHSType, 8327 Context.getObjCClassRedefinitionType())) { 8328 Kind = CK_BitCast; 8329 return Compatible; 8330 } 8331 8332 Kind = CK_BitCast; 8333 return IncompatiblePointer; 8334 } 8335 8336 // U^ -> void* 8337 if (RHSType->getAs<BlockPointerType>()) { 8338 if (LHSPointer->getPointeeType()->isVoidType()) { 8339 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8340 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8341 ->getPointeeType() 8342 .getAddressSpace(); 8343 Kind = 8344 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8345 return Compatible; 8346 } 8347 } 8348 8349 return Incompatible; 8350 } 8351 8352 // Conversions to block pointers. 8353 if (isa<BlockPointerType>(LHSType)) { 8354 // U^ -> T^ 8355 if (RHSType->isBlockPointerType()) { 8356 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8357 ->getPointeeType() 8358 .getAddressSpace(); 8359 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8360 ->getPointeeType() 8361 .getAddressSpace(); 8362 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8363 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8364 } 8365 8366 // int or null -> T^ 8367 if (RHSType->isIntegerType()) { 8368 Kind = CK_IntegralToPointer; // FIXME: null 8369 return IntToBlockPointer; 8370 } 8371 8372 // id -> T^ 8373 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8374 Kind = CK_AnyPointerToBlockPointerCast; 8375 return Compatible; 8376 } 8377 8378 // void* -> T^ 8379 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8380 if (RHSPT->getPointeeType()->isVoidType()) { 8381 Kind = CK_AnyPointerToBlockPointerCast; 8382 return Compatible; 8383 } 8384 8385 return Incompatible; 8386 } 8387 8388 // Conversions to Objective-C pointers. 8389 if (isa<ObjCObjectPointerType>(LHSType)) { 8390 // A* -> B* 8391 if (RHSType->isObjCObjectPointerType()) { 8392 Kind = CK_BitCast; 8393 Sema::AssignConvertType result = 8394 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8395 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8396 result == Compatible && 8397 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8398 result = IncompatibleObjCWeakRef; 8399 return result; 8400 } 8401 8402 // int or null -> A* 8403 if (RHSType->isIntegerType()) { 8404 Kind = CK_IntegralToPointer; // FIXME: null 8405 return IntToPointer; 8406 } 8407 8408 // In general, C pointers are not compatible with ObjC object pointers, 8409 // with two exceptions: 8410 if (isa<PointerType>(RHSType)) { 8411 Kind = CK_CPointerToObjCPointerCast; 8412 8413 // - conversions from 'void*' 8414 if (RHSType->isVoidPointerType()) { 8415 return Compatible; 8416 } 8417 8418 // - conversions to 'Class' from its redefinition type 8419 if (LHSType->isObjCClassType() && 8420 Context.hasSameType(RHSType, 8421 Context.getObjCClassRedefinitionType())) { 8422 return Compatible; 8423 } 8424 8425 return IncompatiblePointer; 8426 } 8427 8428 // Only under strict condition T^ is compatible with an Objective-C pointer. 8429 if (RHSType->isBlockPointerType() && 8430 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8431 if (ConvertRHS) 8432 maybeExtendBlockObject(RHS); 8433 Kind = CK_BlockPointerToObjCPointerCast; 8434 return Compatible; 8435 } 8436 8437 return Incompatible; 8438 } 8439 8440 // Conversions from pointers that are not covered by the above. 8441 if (isa<PointerType>(RHSType)) { 8442 // T* -> _Bool 8443 if (LHSType == Context.BoolTy) { 8444 Kind = CK_PointerToBoolean; 8445 return Compatible; 8446 } 8447 8448 // T* -> int 8449 if (LHSType->isIntegerType()) { 8450 Kind = CK_PointerToIntegral; 8451 return PointerToInt; 8452 } 8453 8454 return Incompatible; 8455 } 8456 8457 // Conversions from Objective-C pointers that are not covered by the above. 8458 if (isa<ObjCObjectPointerType>(RHSType)) { 8459 // T* -> _Bool 8460 if (LHSType == Context.BoolTy) { 8461 Kind = CK_PointerToBoolean; 8462 return Compatible; 8463 } 8464 8465 // T* -> int 8466 if (LHSType->isIntegerType()) { 8467 Kind = CK_PointerToIntegral; 8468 return PointerToInt; 8469 } 8470 8471 return Incompatible; 8472 } 8473 8474 // struct A -> struct B 8475 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8476 if (Context.typesAreCompatible(LHSType, RHSType)) { 8477 Kind = CK_NoOp; 8478 return Compatible; 8479 } 8480 } 8481 8482 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8483 Kind = CK_IntToOCLSampler; 8484 return Compatible; 8485 } 8486 8487 return Incompatible; 8488 } 8489 8490 /// Constructs a transparent union from an expression that is 8491 /// used to initialize the transparent union. 8492 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8493 ExprResult &EResult, QualType UnionType, 8494 FieldDecl *Field) { 8495 // Build an initializer list that designates the appropriate member 8496 // of the transparent union. 8497 Expr *E = EResult.get(); 8498 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8499 E, SourceLocation()); 8500 Initializer->setType(UnionType); 8501 Initializer->setInitializedFieldInUnion(Field); 8502 8503 // Build a compound literal constructing a value of the transparent 8504 // union type from this initializer list. 8505 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8506 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8507 VK_RValue, Initializer, false); 8508 } 8509 8510 Sema::AssignConvertType 8511 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8512 ExprResult &RHS) { 8513 QualType RHSType = RHS.get()->getType(); 8514 8515 // If the ArgType is a Union type, we want to handle a potential 8516 // transparent_union GCC extension. 8517 const RecordType *UT = ArgType->getAsUnionType(); 8518 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8519 return Incompatible; 8520 8521 // The field to initialize within the transparent union. 8522 RecordDecl *UD = UT->getDecl(); 8523 FieldDecl *InitField = nullptr; 8524 // It's compatible if the expression matches any of the fields. 8525 for (auto *it : UD->fields()) { 8526 if (it->getType()->isPointerType()) { 8527 // If the transparent union contains a pointer type, we allow: 8528 // 1) void pointer 8529 // 2) null pointer constant 8530 if (RHSType->isPointerType()) 8531 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8532 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8533 InitField = it; 8534 break; 8535 } 8536 8537 if (RHS.get()->isNullPointerConstant(Context, 8538 Expr::NPC_ValueDependentIsNull)) { 8539 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8540 CK_NullToPointer); 8541 InitField = it; 8542 break; 8543 } 8544 } 8545 8546 CastKind Kind; 8547 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8548 == Compatible) { 8549 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8550 InitField = it; 8551 break; 8552 } 8553 } 8554 8555 if (!InitField) 8556 return Incompatible; 8557 8558 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8559 return Compatible; 8560 } 8561 8562 Sema::AssignConvertType 8563 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8564 bool Diagnose, 8565 bool DiagnoseCFAudited, 8566 bool ConvertRHS) { 8567 // We need to be able to tell the caller whether we diagnosed a problem, if 8568 // they ask us to issue diagnostics. 8569 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8570 8571 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8572 // we can't avoid *all* modifications at the moment, so we need some somewhere 8573 // to put the updated value. 8574 ExprResult LocalRHS = CallerRHS; 8575 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8576 8577 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8578 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8579 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8580 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8581 Diag(RHS.get()->getExprLoc(), 8582 diag::warn_noderef_to_dereferenceable_pointer) 8583 << RHS.get()->getSourceRange(); 8584 } 8585 } 8586 } 8587 8588 if (getLangOpts().CPlusPlus) { 8589 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8590 // C++ 5.17p3: If the left operand is not of class type, the 8591 // expression is implicitly converted (C++ 4) to the 8592 // cv-unqualified type of the left operand. 8593 QualType RHSType = RHS.get()->getType(); 8594 if (Diagnose) { 8595 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8596 AA_Assigning); 8597 } else { 8598 ImplicitConversionSequence ICS = 8599 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8600 /*SuppressUserConversions=*/false, 8601 /*AllowExplicit=*/false, 8602 /*InOverloadResolution=*/false, 8603 /*CStyle=*/false, 8604 /*AllowObjCWritebackConversion=*/false); 8605 if (ICS.isFailure()) 8606 return Incompatible; 8607 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8608 ICS, AA_Assigning); 8609 } 8610 if (RHS.isInvalid()) 8611 return Incompatible; 8612 Sema::AssignConvertType result = Compatible; 8613 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8614 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8615 result = IncompatibleObjCWeakRef; 8616 return result; 8617 } 8618 8619 // FIXME: Currently, we fall through and treat C++ classes like C 8620 // structures. 8621 // FIXME: We also fall through for atomics; not sure what should 8622 // happen there, though. 8623 } else if (RHS.get()->getType() == Context.OverloadTy) { 8624 // As a set of extensions to C, we support overloading on functions. These 8625 // functions need to be resolved here. 8626 DeclAccessPair DAP; 8627 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8628 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8629 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8630 else 8631 return Incompatible; 8632 } 8633 8634 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8635 // a null pointer constant. 8636 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8637 LHSType->isBlockPointerType()) && 8638 RHS.get()->isNullPointerConstant(Context, 8639 Expr::NPC_ValueDependentIsNull)) { 8640 if (Diagnose || ConvertRHS) { 8641 CastKind Kind; 8642 CXXCastPath Path; 8643 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8644 /*IgnoreBaseAccess=*/false, Diagnose); 8645 if (ConvertRHS) 8646 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8647 } 8648 return Compatible; 8649 } 8650 8651 // OpenCL queue_t type assignment. 8652 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8653 Context, Expr::NPC_ValueDependentIsNull)) { 8654 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8655 return Compatible; 8656 } 8657 8658 // This check seems unnatural, however it is necessary to ensure the proper 8659 // conversion of functions/arrays. If the conversion were done for all 8660 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8661 // expressions that suppress this implicit conversion (&, sizeof). 8662 // 8663 // Suppress this for references: C++ 8.5.3p5. 8664 if (!LHSType->isReferenceType()) { 8665 // FIXME: We potentially allocate here even if ConvertRHS is false. 8666 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8667 if (RHS.isInvalid()) 8668 return Incompatible; 8669 } 8670 CastKind Kind; 8671 Sema::AssignConvertType result = 8672 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8673 8674 // C99 6.5.16.1p2: The value of the right operand is converted to the 8675 // type of the assignment expression. 8676 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8677 // so that we can use references in built-in functions even in C. 8678 // The getNonReferenceType() call makes sure that the resulting expression 8679 // does not have reference type. 8680 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8681 QualType Ty = LHSType.getNonLValueExprType(Context); 8682 Expr *E = RHS.get(); 8683 8684 // Check for various Objective-C errors. If we are not reporting 8685 // diagnostics and just checking for errors, e.g., during overload 8686 // resolution, return Incompatible to indicate the failure. 8687 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8688 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8689 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8690 if (!Diagnose) 8691 return Incompatible; 8692 } 8693 if (getLangOpts().ObjC && 8694 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8695 E->getType(), E, Diagnose) || 8696 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8697 if (!Diagnose) 8698 return Incompatible; 8699 // Replace the expression with a corrected version and continue so we 8700 // can find further errors. 8701 RHS = E; 8702 return Compatible; 8703 } 8704 8705 if (ConvertRHS) 8706 RHS = ImpCastExprToType(E, Ty, Kind); 8707 } 8708 8709 return result; 8710 } 8711 8712 namespace { 8713 /// The original operand to an operator, prior to the application of the usual 8714 /// arithmetic conversions and converting the arguments of a builtin operator 8715 /// candidate. 8716 struct OriginalOperand { 8717 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8718 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8719 Op = MTE->getSubExpr(); 8720 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8721 Op = BTE->getSubExpr(); 8722 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8723 Orig = ICE->getSubExprAsWritten(); 8724 Conversion = ICE->getConversionFunction(); 8725 } 8726 } 8727 8728 QualType getType() const { return Orig->getType(); } 8729 8730 Expr *Orig; 8731 NamedDecl *Conversion; 8732 }; 8733 } 8734 8735 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8736 ExprResult &RHS) { 8737 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8738 8739 Diag(Loc, diag::err_typecheck_invalid_operands) 8740 << OrigLHS.getType() << OrigRHS.getType() 8741 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8742 8743 // If a user-defined conversion was applied to either of the operands prior 8744 // to applying the built-in operator rules, tell the user about it. 8745 if (OrigLHS.Conversion) { 8746 Diag(OrigLHS.Conversion->getLocation(), 8747 diag::note_typecheck_invalid_operands_converted) 8748 << 0 << LHS.get()->getType(); 8749 } 8750 if (OrigRHS.Conversion) { 8751 Diag(OrigRHS.Conversion->getLocation(), 8752 diag::note_typecheck_invalid_operands_converted) 8753 << 1 << RHS.get()->getType(); 8754 } 8755 8756 return QualType(); 8757 } 8758 8759 // Diagnose cases where a scalar was implicitly converted to a vector and 8760 // diagnose the underlying types. Otherwise, diagnose the error 8761 // as invalid vector logical operands for non-C++ cases. 8762 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8763 ExprResult &RHS) { 8764 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8765 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8766 8767 bool LHSNatVec = LHSType->isVectorType(); 8768 bool RHSNatVec = RHSType->isVectorType(); 8769 8770 if (!(LHSNatVec && RHSNatVec)) { 8771 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8772 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8773 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8774 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8775 << Vector->getSourceRange(); 8776 return QualType(); 8777 } 8778 8779 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8780 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8781 << RHS.get()->getSourceRange(); 8782 8783 return QualType(); 8784 } 8785 8786 /// Try to convert a value of non-vector type to a vector type by converting 8787 /// the type to the element type of the vector and then performing a splat. 8788 /// If the language is OpenCL, we only use conversions that promote scalar 8789 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8790 /// for float->int. 8791 /// 8792 /// OpenCL V2.0 6.2.6.p2: 8793 /// An error shall occur if any scalar operand type has greater rank 8794 /// than the type of the vector element. 8795 /// 8796 /// \param scalar - if non-null, actually perform the conversions 8797 /// \return true if the operation fails (but without diagnosing the failure) 8798 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8799 QualType scalarTy, 8800 QualType vectorEltTy, 8801 QualType vectorTy, 8802 unsigned &DiagID) { 8803 // The conversion to apply to the scalar before splatting it, 8804 // if necessary. 8805 CastKind scalarCast = CK_NoOp; 8806 8807 if (vectorEltTy->isIntegralType(S.Context)) { 8808 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8809 (scalarTy->isIntegerType() && 8810 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8811 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8812 return true; 8813 } 8814 if (!scalarTy->isIntegralType(S.Context)) 8815 return true; 8816 scalarCast = CK_IntegralCast; 8817 } else if (vectorEltTy->isRealFloatingType()) { 8818 if (scalarTy->isRealFloatingType()) { 8819 if (S.getLangOpts().OpenCL && 8820 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8821 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8822 return true; 8823 } 8824 scalarCast = CK_FloatingCast; 8825 } 8826 else if (scalarTy->isIntegralType(S.Context)) 8827 scalarCast = CK_IntegralToFloating; 8828 else 8829 return true; 8830 } else { 8831 return true; 8832 } 8833 8834 // Adjust scalar if desired. 8835 if (scalar) { 8836 if (scalarCast != CK_NoOp) 8837 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8838 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8839 } 8840 return false; 8841 } 8842 8843 /// Convert vector E to a vector with the same number of elements but different 8844 /// element type. 8845 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8846 const auto *VecTy = E->getType()->getAs<VectorType>(); 8847 assert(VecTy && "Expression E must be a vector"); 8848 QualType NewVecTy = S.Context.getVectorType(ElementType, 8849 VecTy->getNumElements(), 8850 VecTy->getVectorKind()); 8851 8852 // Look through the implicit cast. Return the subexpression if its type is 8853 // NewVecTy. 8854 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8855 if (ICE->getSubExpr()->getType() == NewVecTy) 8856 return ICE->getSubExpr(); 8857 8858 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8859 return S.ImpCastExprToType(E, NewVecTy, Cast); 8860 } 8861 8862 /// Test if a (constant) integer Int can be casted to another integer type 8863 /// IntTy without losing precision. 8864 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8865 QualType OtherIntTy) { 8866 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8867 8868 // Reject cases where the value of the Int is unknown as that would 8869 // possibly cause truncation, but accept cases where the scalar can be 8870 // demoted without loss of precision. 8871 Expr::EvalResult EVResult; 8872 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8873 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8874 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8875 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8876 8877 if (CstInt) { 8878 // If the scalar is constant and is of a higher order and has more active 8879 // bits that the vector element type, reject it. 8880 llvm::APSInt Result = EVResult.Val.getInt(); 8881 unsigned NumBits = IntSigned 8882 ? (Result.isNegative() ? Result.getMinSignedBits() 8883 : Result.getActiveBits()) 8884 : Result.getActiveBits(); 8885 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8886 return true; 8887 8888 // If the signedness of the scalar type and the vector element type 8889 // differs and the number of bits is greater than that of the vector 8890 // element reject it. 8891 return (IntSigned != OtherIntSigned && 8892 NumBits > S.Context.getIntWidth(OtherIntTy)); 8893 } 8894 8895 // Reject cases where the value of the scalar is not constant and it's 8896 // order is greater than that of the vector element type. 8897 return (Order < 0); 8898 } 8899 8900 /// Test if a (constant) integer Int can be casted to floating point type 8901 /// FloatTy without losing precision. 8902 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8903 QualType FloatTy) { 8904 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8905 8906 // Determine if the integer constant can be expressed as a floating point 8907 // number of the appropriate type. 8908 Expr::EvalResult EVResult; 8909 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8910 8911 uint64_t Bits = 0; 8912 if (CstInt) { 8913 // Reject constants that would be truncated if they were converted to 8914 // the floating point type. Test by simple to/from conversion. 8915 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8916 // could be avoided if there was a convertFromAPInt method 8917 // which could signal back if implicit truncation occurred. 8918 llvm::APSInt Result = EVResult.Val.getInt(); 8919 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8920 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8921 llvm::APFloat::rmTowardZero); 8922 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8923 !IntTy->hasSignedIntegerRepresentation()); 8924 bool Ignored = false; 8925 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8926 &Ignored); 8927 if (Result != ConvertBack) 8928 return true; 8929 } else { 8930 // Reject types that cannot be fully encoded into the mantissa of 8931 // the float. 8932 Bits = S.Context.getTypeSize(IntTy); 8933 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8934 S.Context.getFloatTypeSemantics(FloatTy)); 8935 if (Bits > FloatPrec) 8936 return true; 8937 } 8938 8939 return false; 8940 } 8941 8942 /// Attempt to convert and splat Scalar into a vector whose types matches 8943 /// Vector following GCC conversion rules. The rule is that implicit 8944 /// conversion can occur when Scalar can be casted to match Vector's element 8945 /// type without causing truncation of Scalar. 8946 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8947 ExprResult *Vector) { 8948 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8949 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8950 const VectorType *VT = VectorTy->getAs<VectorType>(); 8951 8952 assert(!isa<ExtVectorType>(VT) && 8953 "ExtVectorTypes should not be handled here!"); 8954 8955 QualType VectorEltTy = VT->getElementType(); 8956 8957 // Reject cases where the vector element type or the scalar element type are 8958 // not integral or floating point types. 8959 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8960 return true; 8961 8962 // The conversion to apply to the scalar before splatting it, 8963 // if necessary. 8964 CastKind ScalarCast = CK_NoOp; 8965 8966 // Accept cases where the vector elements are integers and the scalar is 8967 // an integer. 8968 // FIXME: Notionally if the scalar was a floating point value with a precise 8969 // integral representation, we could cast it to an appropriate integer 8970 // type and then perform the rest of the checks here. GCC will perform 8971 // this conversion in some cases as determined by the input language. 8972 // We should accept it on a language independent basis. 8973 if (VectorEltTy->isIntegralType(S.Context) && 8974 ScalarTy->isIntegralType(S.Context) && 8975 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8976 8977 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8978 return true; 8979 8980 ScalarCast = CK_IntegralCast; 8981 } else if (VectorEltTy->isRealFloatingType()) { 8982 if (ScalarTy->isRealFloatingType()) { 8983 8984 // Reject cases where the scalar type is not a constant and has a higher 8985 // Order than the vector element type. 8986 llvm::APFloat Result(0.0); 8987 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8988 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8989 if (!CstScalar && Order < 0) 8990 return true; 8991 8992 // If the scalar cannot be safely casted to the vector element type, 8993 // reject it. 8994 if (CstScalar) { 8995 bool Truncated = false; 8996 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8997 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8998 if (Truncated) 8999 return true; 9000 } 9001 9002 ScalarCast = CK_FloatingCast; 9003 } else if (ScalarTy->isIntegralType(S.Context)) { 9004 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9005 return true; 9006 9007 ScalarCast = CK_IntegralToFloating; 9008 } else 9009 return true; 9010 } 9011 9012 // Adjust scalar if desired. 9013 if (Scalar) { 9014 if (ScalarCast != CK_NoOp) 9015 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9016 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9017 } 9018 return false; 9019 } 9020 9021 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9022 SourceLocation Loc, bool IsCompAssign, 9023 bool AllowBothBool, 9024 bool AllowBoolConversions) { 9025 if (!IsCompAssign) { 9026 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9027 if (LHS.isInvalid()) 9028 return QualType(); 9029 } 9030 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9031 if (RHS.isInvalid()) 9032 return QualType(); 9033 9034 // For conversion purposes, we ignore any qualifiers. 9035 // For example, "const float" and "float" are equivalent. 9036 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9037 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9038 9039 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9040 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9041 assert(LHSVecType || RHSVecType); 9042 9043 // AltiVec-style "vector bool op vector bool" combinations are allowed 9044 // for some operators but not others. 9045 if (!AllowBothBool && 9046 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9047 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9048 return InvalidOperands(Loc, LHS, RHS); 9049 9050 // If the vector types are identical, return. 9051 if (Context.hasSameType(LHSType, RHSType)) 9052 return LHSType; 9053 9054 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9055 if (LHSVecType && RHSVecType && 9056 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9057 if (isa<ExtVectorType>(LHSVecType)) { 9058 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9059 return LHSType; 9060 } 9061 9062 if (!IsCompAssign) 9063 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9064 return RHSType; 9065 } 9066 9067 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9068 // can be mixed, with the result being the non-bool type. The non-bool 9069 // operand must have integer element type. 9070 if (AllowBoolConversions && LHSVecType && RHSVecType && 9071 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9072 (Context.getTypeSize(LHSVecType->getElementType()) == 9073 Context.getTypeSize(RHSVecType->getElementType()))) { 9074 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9075 LHSVecType->getElementType()->isIntegerType() && 9076 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9077 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9078 return LHSType; 9079 } 9080 if (!IsCompAssign && 9081 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9082 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9083 RHSVecType->getElementType()->isIntegerType()) { 9084 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9085 return RHSType; 9086 } 9087 } 9088 9089 // If there's a vector type and a scalar, try to convert the scalar to 9090 // the vector element type and splat. 9091 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9092 if (!RHSVecType) { 9093 if (isa<ExtVectorType>(LHSVecType)) { 9094 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9095 LHSVecType->getElementType(), LHSType, 9096 DiagID)) 9097 return LHSType; 9098 } else { 9099 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9100 return LHSType; 9101 } 9102 } 9103 if (!LHSVecType) { 9104 if (isa<ExtVectorType>(RHSVecType)) { 9105 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9106 LHSType, RHSVecType->getElementType(), 9107 RHSType, DiagID)) 9108 return RHSType; 9109 } else { 9110 if (LHS.get()->getValueKind() == VK_LValue || 9111 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9112 return RHSType; 9113 } 9114 } 9115 9116 // FIXME: The code below also handles conversion between vectors and 9117 // non-scalars, we should break this down into fine grained specific checks 9118 // and emit proper diagnostics. 9119 QualType VecType = LHSVecType ? LHSType : RHSType; 9120 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9121 QualType OtherType = LHSVecType ? RHSType : LHSType; 9122 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9123 if (isLaxVectorConversion(OtherType, VecType)) { 9124 // If we're allowing lax vector conversions, only the total (data) size 9125 // needs to be the same. For non compound assignment, if one of the types is 9126 // scalar, the result is always the vector type. 9127 if (!IsCompAssign) { 9128 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9129 return VecType; 9130 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9131 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9132 // type. Note that this is already done by non-compound assignments in 9133 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9134 // <1 x T> -> T. The result is also a vector type. 9135 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9136 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9137 ExprResult *RHSExpr = &RHS; 9138 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9139 return VecType; 9140 } 9141 } 9142 9143 // Okay, the expression is invalid. 9144 9145 // If there's a non-vector, non-real operand, diagnose that. 9146 if ((!RHSVecType && !RHSType->isRealType()) || 9147 (!LHSVecType && !LHSType->isRealType())) { 9148 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9149 << LHSType << RHSType 9150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9151 return QualType(); 9152 } 9153 9154 // OpenCL V1.1 6.2.6.p1: 9155 // If the operands are of more than one vector type, then an error shall 9156 // occur. Implicit conversions between vector types are not permitted, per 9157 // section 6.2.1. 9158 if (getLangOpts().OpenCL && 9159 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9160 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9161 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9162 << RHSType; 9163 return QualType(); 9164 } 9165 9166 9167 // If there is a vector type that is not a ExtVector and a scalar, we reach 9168 // this point if scalar could not be converted to the vector's element type 9169 // without truncation. 9170 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9171 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9172 QualType Scalar = LHSVecType ? RHSType : LHSType; 9173 QualType Vector = LHSVecType ? LHSType : RHSType; 9174 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9175 Diag(Loc, 9176 diag::err_typecheck_vector_not_convertable_implict_truncation) 9177 << ScalarOrVector << Scalar << Vector; 9178 9179 return QualType(); 9180 } 9181 9182 // Otherwise, use the generic diagnostic. 9183 Diag(Loc, DiagID) 9184 << LHSType << RHSType 9185 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9186 return QualType(); 9187 } 9188 9189 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9190 // expression. These are mainly cases where the null pointer is used as an 9191 // integer instead of a pointer. 9192 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9193 SourceLocation Loc, bool IsCompare) { 9194 // The canonical way to check for a GNU null is with isNullPointerConstant, 9195 // but we use a bit of a hack here for speed; this is a relatively 9196 // hot path, and isNullPointerConstant is slow. 9197 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9198 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9199 9200 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9201 9202 // Avoid analyzing cases where the result will either be invalid (and 9203 // diagnosed as such) or entirely valid and not something to warn about. 9204 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9205 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9206 return; 9207 9208 // Comparison operations would not make sense with a null pointer no matter 9209 // what the other expression is. 9210 if (!IsCompare) { 9211 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9212 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9213 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9214 return; 9215 } 9216 9217 // The rest of the operations only make sense with a null pointer 9218 // if the other expression is a pointer. 9219 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9220 NonNullType->canDecayToPointerType()) 9221 return; 9222 9223 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9224 << LHSNull /* LHS is NULL */ << NonNullType 9225 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9226 } 9227 9228 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9229 SourceLocation Loc) { 9230 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9231 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9232 if (!LUE || !RUE) 9233 return; 9234 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9235 RUE->getKind() != UETT_SizeOf) 9236 return; 9237 9238 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9239 QualType LHSTy = LHSArg->getType(); 9240 QualType RHSTy; 9241 9242 if (RUE->isArgumentType()) 9243 RHSTy = RUE->getArgumentType(); 9244 else 9245 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9246 9247 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9248 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9249 return; 9250 9251 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9252 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9253 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9254 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9255 << LHSArgDecl; 9256 } 9257 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9258 QualType ArrayElemTy = ArrayTy->getElementType(); 9259 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9260 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9261 ArrayElemTy->isCharType() || 9262 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9263 return; 9264 S.Diag(Loc, diag::warn_division_sizeof_array) 9265 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9266 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9267 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9268 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9269 << LHSArgDecl; 9270 } 9271 9272 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9273 } 9274 } 9275 9276 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9277 ExprResult &RHS, 9278 SourceLocation Loc, bool IsDiv) { 9279 // Check for division/remainder by zero. 9280 Expr::EvalResult RHSValue; 9281 if (!RHS.get()->isValueDependent() && 9282 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9283 RHSValue.Val.getInt() == 0) 9284 S.DiagRuntimeBehavior(Loc, RHS.get(), 9285 S.PDiag(diag::warn_remainder_division_by_zero) 9286 << IsDiv << RHS.get()->getSourceRange()); 9287 } 9288 9289 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9290 SourceLocation Loc, 9291 bool IsCompAssign, bool IsDiv) { 9292 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9293 9294 if (LHS.get()->getType()->isVectorType() || 9295 RHS.get()->getType()->isVectorType()) 9296 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9297 /*AllowBothBool*/getLangOpts().AltiVec, 9298 /*AllowBoolConversions*/false); 9299 9300 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9301 if (LHS.isInvalid() || RHS.isInvalid()) 9302 return QualType(); 9303 9304 9305 if (compType.isNull() || !compType->isArithmeticType()) 9306 return InvalidOperands(Loc, LHS, RHS); 9307 if (IsDiv) { 9308 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9309 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9310 } 9311 return compType; 9312 } 9313 9314 QualType Sema::CheckRemainderOperands( 9315 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9316 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9317 9318 if (LHS.get()->getType()->isVectorType() || 9319 RHS.get()->getType()->isVectorType()) { 9320 if (LHS.get()->getType()->hasIntegerRepresentation() && 9321 RHS.get()->getType()->hasIntegerRepresentation()) 9322 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9323 /*AllowBothBool*/getLangOpts().AltiVec, 9324 /*AllowBoolConversions*/false); 9325 return InvalidOperands(Loc, LHS, RHS); 9326 } 9327 9328 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9329 if (LHS.isInvalid() || RHS.isInvalid()) 9330 return QualType(); 9331 9332 if (compType.isNull() || !compType->isIntegerType()) 9333 return InvalidOperands(Loc, LHS, RHS); 9334 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9335 return compType; 9336 } 9337 9338 /// Diagnose invalid arithmetic on two void pointers. 9339 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9340 Expr *LHSExpr, Expr *RHSExpr) { 9341 S.Diag(Loc, S.getLangOpts().CPlusPlus 9342 ? diag::err_typecheck_pointer_arith_void_type 9343 : diag::ext_gnu_void_ptr) 9344 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9345 << RHSExpr->getSourceRange(); 9346 } 9347 9348 /// Diagnose invalid arithmetic on a void pointer. 9349 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9350 Expr *Pointer) { 9351 S.Diag(Loc, S.getLangOpts().CPlusPlus 9352 ? diag::err_typecheck_pointer_arith_void_type 9353 : diag::ext_gnu_void_ptr) 9354 << 0 /* one pointer */ << Pointer->getSourceRange(); 9355 } 9356 9357 /// Diagnose invalid arithmetic on a null pointer. 9358 /// 9359 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9360 /// idiom, which we recognize as a GNU extension. 9361 /// 9362 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9363 Expr *Pointer, bool IsGNUIdiom) { 9364 if (IsGNUIdiom) 9365 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9366 << Pointer->getSourceRange(); 9367 else 9368 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9369 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9370 } 9371 9372 /// Diagnose invalid arithmetic on two function pointers. 9373 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9374 Expr *LHS, Expr *RHS) { 9375 assert(LHS->getType()->isAnyPointerType()); 9376 assert(RHS->getType()->isAnyPointerType()); 9377 S.Diag(Loc, S.getLangOpts().CPlusPlus 9378 ? diag::err_typecheck_pointer_arith_function_type 9379 : diag::ext_gnu_ptr_func_arith) 9380 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9381 // We only show the second type if it differs from the first. 9382 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9383 RHS->getType()) 9384 << RHS->getType()->getPointeeType() 9385 << LHS->getSourceRange() << RHS->getSourceRange(); 9386 } 9387 9388 /// Diagnose invalid arithmetic on a function pointer. 9389 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9390 Expr *Pointer) { 9391 assert(Pointer->getType()->isAnyPointerType()); 9392 S.Diag(Loc, S.getLangOpts().CPlusPlus 9393 ? diag::err_typecheck_pointer_arith_function_type 9394 : diag::ext_gnu_ptr_func_arith) 9395 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9396 << 0 /* one pointer, so only one type */ 9397 << Pointer->getSourceRange(); 9398 } 9399 9400 /// Emit error if Operand is incomplete pointer type 9401 /// 9402 /// \returns True if pointer has incomplete type 9403 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9404 Expr *Operand) { 9405 QualType ResType = Operand->getType(); 9406 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9407 ResType = ResAtomicType->getValueType(); 9408 9409 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9410 QualType PointeeTy = ResType->getPointeeType(); 9411 return S.RequireCompleteType(Loc, PointeeTy, 9412 diag::err_typecheck_arithmetic_incomplete_type, 9413 PointeeTy, Operand->getSourceRange()); 9414 } 9415 9416 /// Check the validity of an arithmetic pointer operand. 9417 /// 9418 /// If the operand has pointer type, this code will check for pointer types 9419 /// which are invalid in arithmetic operations. These will be diagnosed 9420 /// appropriately, including whether or not the use is supported as an 9421 /// extension. 9422 /// 9423 /// \returns True when the operand is valid to use (even if as an extension). 9424 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9425 Expr *Operand) { 9426 QualType ResType = Operand->getType(); 9427 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9428 ResType = ResAtomicType->getValueType(); 9429 9430 if (!ResType->isAnyPointerType()) return true; 9431 9432 QualType PointeeTy = ResType->getPointeeType(); 9433 if (PointeeTy->isVoidType()) { 9434 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9435 return !S.getLangOpts().CPlusPlus; 9436 } 9437 if (PointeeTy->isFunctionType()) { 9438 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9439 return !S.getLangOpts().CPlusPlus; 9440 } 9441 9442 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9443 9444 return true; 9445 } 9446 9447 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9448 /// operands. 9449 /// 9450 /// This routine will diagnose any invalid arithmetic on pointer operands much 9451 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9452 /// for emitting a single diagnostic even for operations where both LHS and RHS 9453 /// are (potentially problematic) pointers. 9454 /// 9455 /// \returns True when the operand is valid to use (even if as an extension). 9456 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9457 Expr *LHSExpr, Expr *RHSExpr) { 9458 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9459 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9460 if (!isLHSPointer && !isRHSPointer) return true; 9461 9462 QualType LHSPointeeTy, RHSPointeeTy; 9463 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9464 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9465 9466 // if both are pointers check if operation is valid wrt address spaces 9467 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9468 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9469 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9470 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9471 S.Diag(Loc, 9472 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9473 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9474 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9475 return false; 9476 } 9477 } 9478 9479 // Check for arithmetic on pointers to incomplete types. 9480 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9481 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9482 if (isLHSVoidPtr || isRHSVoidPtr) { 9483 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9484 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9485 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9486 9487 return !S.getLangOpts().CPlusPlus; 9488 } 9489 9490 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9491 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9492 if (isLHSFuncPtr || isRHSFuncPtr) { 9493 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9494 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9495 RHSExpr); 9496 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9497 9498 return !S.getLangOpts().CPlusPlus; 9499 } 9500 9501 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9502 return false; 9503 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9504 return false; 9505 9506 return true; 9507 } 9508 9509 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9510 /// literal. 9511 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9512 Expr *LHSExpr, Expr *RHSExpr) { 9513 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9514 Expr* IndexExpr = RHSExpr; 9515 if (!StrExpr) { 9516 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9517 IndexExpr = LHSExpr; 9518 } 9519 9520 bool IsStringPlusInt = StrExpr && 9521 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9522 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9523 return; 9524 9525 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9526 Self.Diag(OpLoc, diag::warn_string_plus_int) 9527 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9528 9529 // Only print a fixit for "str" + int, not for int + "str". 9530 if (IndexExpr == RHSExpr) { 9531 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9532 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9533 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9534 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9535 << FixItHint::CreateInsertion(EndLoc, "]"); 9536 } else 9537 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9538 } 9539 9540 /// Emit a warning when adding a char literal to a string. 9541 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9542 Expr *LHSExpr, Expr *RHSExpr) { 9543 const Expr *StringRefExpr = LHSExpr; 9544 const CharacterLiteral *CharExpr = 9545 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9546 9547 if (!CharExpr) { 9548 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9549 StringRefExpr = RHSExpr; 9550 } 9551 9552 if (!CharExpr || !StringRefExpr) 9553 return; 9554 9555 const QualType StringType = StringRefExpr->getType(); 9556 9557 // Return if not a PointerType. 9558 if (!StringType->isAnyPointerType()) 9559 return; 9560 9561 // Return if not a CharacterType. 9562 if (!StringType->getPointeeType()->isAnyCharacterType()) 9563 return; 9564 9565 ASTContext &Ctx = Self.getASTContext(); 9566 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9567 9568 const QualType CharType = CharExpr->getType(); 9569 if (!CharType->isAnyCharacterType() && 9570 CharType->isIntegerType() && 9571 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9572 Self.Diag(OpLoc, diag::warn_string_plus_char) 9573 << DiagRange << Ctx.CharTy; 9574 } else { 9575 Self.Diag(OpLoc, diag::warn_string_plus_char) 9576 << DiagRange << CharExpr->getType(); 9577 } 9578 9579 // Only print a fixit for str + char, not for char + str. 9580 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9581 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9582 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9583 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9584 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9585 << FixItHint::CreateInsertion(EndLoc, "]"); 9586 } else { 9587 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9588 } 9589 } 9590 9591 /// Emit error when two pointers are incompatible. 9592 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9593 Expr *LHSExpr, Expr *RHSExpr) { 9594 assert(LHSExpr->getType()->isAnyPointerType()); 9595 assert(RHSExpr->getType()->isAnyPointerType()); 9596 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9597 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9598 << RHSExpr->getSourceRange(); 9599 } 9600 9601 // C99 6.5.6 9602 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9603 SourceLocation Loc, BinaryOperatorKind Opc, 9604 QualType* CompLHSTy) { 9605 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9606 9607 if (LHS.get()->getType()->isVectorType() || 9608 RHS.get()->getType()->isVectorType()) { 9609 QualType compType = CheckVectorOperands( 9610 LHS, RHS, Loc, CompLHSTy, 9611 /*AllowBothBool*/getLangOpts().AltiVec, 9612 /*AllowBoolConversions*/getLangOpts().ZVector); 9613 if (CompLHSTy) *CompLHSTy = compType; 9614 return compType; 9615 } 9616 9617 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9618 if (LHS.isInvalid() || RHS.isInvalid()) 9619 return QualType(); 9620 9621 // Diagnose "string literal" '+' int and string '+' "char literal". 9622 if (Opc == BO_Add) { 9623 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9624 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9625 } 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 // Type-checking. Ultimately the pointer's going to be in PExp; 9634 // note that we bias towards the LHS being the pointer. 9635 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9636 9637 bool isObjCPointer; 9638 if (PExp->getType()->isPointerType()) { 9639 isObjCPointer = false; 9640 } else if (PExp->getType()->isObjCObjectPointerType()) { 9641 isObjCPointer = true; 9642 } else { 9643 std::swap(PExp, IExp); 9644 if (PExp->getType()->isPointerType()) { 9645 isObjCPointer = false; 9646 } else if (PExp->getType()->isObjCObjectPointerType()) { 9647 isObjCPointer = true; 9648 } else { 9649 return InvalidOperands(Loc, LHS, RHS); 9650 } 9651 } 9652 assert(PExp->getType()->isAnyPointerType()); 9653 9654 if (!IExp->getType()->isIntegerType()) 9655 return InvalidOperands(Loc, LHS, RHS); 9656 9657 // Adding to a null pointer results in undefined behavior. 9658 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9659 Context, Expr::NPC_ValueDependentIsNotNull)) { 9660 // In C++ adding zero to a null pointer is defined. 9661 Expr::EvalResult KnownVal; 9662 if (!getLangOpts().CPlusPlus || 9663 (!IExp->isValueDependent() && 9664 (!IExp->EvaluateAsInt(KnownVal, Context) || 9665 KnownVal.Val.getInt() != 0))) { 9666 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9667 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9668 Context, BO_Add, PExp, IExp); 9669 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9670 } 9671 } 9672 9673 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9674 return QualType(); 9675 9676 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9677 return QualType(); 9678 9679 // Check array bounds for pointer arithemtic 9680 CheckArrayAccess(PExp, IExp); 9681 9682 if (CompLHSTy) { 9683 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9684 if (LHSTy.isNull()) { 9685 LHSTy = LHS.get()->getType(); 9686 if (LHSTy->isPromotableIntegerType()) 9687 LHSTy = Context.getPromotedIntegerType(LHSTy); 9688 } 9689 *CompLHSTy = LHSTy; 9690 } 9691 9692 return PExp->getType(); 9693 } 9694 9695 // C99 6.5.6 9696 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9697 SourceLocation Loc, 9698 QualType* CompLHSTy) { 9699 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9700 9701 if (LHS.get()->getType()->isVectorType() || 9702 RHS.get()->getType()->isVectorType()) { 9703 QualType compType = CheckVectorOperands( 9704 LHS, RHS, Loc, CompLHSTy, 9705 /*AllowBothBool*/getLangOpts().AltiVec, 9706 /*AllowBoolConversions*/getLangOpts().ZVector); 9707 if (CompLHSTy) *CompLHSTy = compType; 9708 return compType; 9709 } 9710 9711 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9712 if (LHS.isInvalid() || RHS.isInvalid()) 9713 return QualType(); 9714 9715 // Enforce type constraints: C99 6.5.6p3. 9716 9717 // Handle the common case first (both operands are arithmetic). 9718 if (!compType.isNull() && compType->isArithmeticType()) { 9719 if (CompLHSTy) *CompLHSTy = compType; 9720 return compType; 9721 } 9722 9723 // Either ptr - int or ptr - ptr. 9724 if (LHS.get()->getType()->isAnyPointerType()) { 9725 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9726 9727 // Diagnose bad cases where we step over interface counts. 9728 if (LHS.get()->getType()->isObjCObjectPointerType() && 9729 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9730 return QualType(); 9731 9732 // The result type of a pointer-int computation is the pointer type. 9733 if (RHS.get()->getType()->isIntegerType()) { 9734 // Subtracting from a null pointer should produce a warning. 9735 // The last argument to the diagnose call says this doesn't match the 9736 // GNU int-to-pointer idiom. 9737 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9738 Expr::NPC_ValueDependentIsNotNull)) { 9739 // In C++ adding zero to a null pointer is defined. 9740 Expr::EvalResult KnownVal; 9741 if (!getLangOpts().CPlusPlus || 9742 (!RHS.get()->isValueDependent() && 9743 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9744 KnownVal.Val.getInt() != 0))) { 9745 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9746 } 9747 } 9748 9749 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9750 return QualType(); 9751 9752 // Check array bounds for pointer arithemtic 9753 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9754 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9755 9756 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9757 return LHS.get()->getType(); 9758 } 9759 9760 // Handle pointer-pointer subtractions. 9761 if (const PointerType *RHSPTy 9762 = RHS.get()->getType()->getAs<PointerType>()) { 9763 QualType rpointee = RHSPTy->getPointeeType(); 9764 9765 if (getLangOpts().CPlusPlus) { 9766 // Pointee types must be the same: C++ [expr.add] 9767 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9768 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9769 } 9770 } else { 9771 // Pointee types must be compatible C99 6.5.6p3 9772 if (!Context.typesAreCompatible( 9773 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9774 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9775 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9776 return QualType(); 9777 } 9778 } 9779 9780 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9781 LHS.get(), RHS.get())) 9782 return QualType(); 9783 9784 // FIXME: Add warnings for nullptr - ptr. 9785 9786 // The pointee type may have zero size. As an extension, a structure or 9787 // union may have zero size or an array may have zero length. In this 9788 // case subtraction does not make sense. 9789 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9790 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9791 if (ElementSize.isZero()) { 9792 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9793 << rpointee.getUnqualifiedType() 9794 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9795 } 9796 } 9797 9798 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9799 return Context.getPointerDiffType(); 9800 } 9801 } 9802 9803 return InvalidOperands(Loc, LHS, RHS); 9804 } 9805 9806 static bool isScopedEnumerationType(QualType T) { 9807 if (const EnumType *ET = T->getAs<EnumType>()) 9808 return ET->getDecl()->isScoped(); 9809 return false; 9810 } 9811 9812 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9813 SourceLocation Loc, BinaryOperatorKind Opc, 9814 QualType LHSType) { 9815 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9816 // so skip remaining warnings as we don't want to modify values within Sema. 9817 if (S.getLangOpts().OpenCL) 9818 return; 9819 9820 // Check right/shifter operand 9821 Expr::EvalResult RHSResult; 9822 if (RHS.get()->isValueDependent() || 9823 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9824 return; 9825 llvm::APSInt Right = RHSResult.Val.getInt(); 9826 9827 if (Right.isNegative()) { 9828 S.DiagRuntimeBehavior(Loc, RHS.get(), 9829 S.PDiag(diag::warn_shift_negative) 9830 << RHS.get()->getSourceRange()); 9831 return; 9832 } 9833 llvm::APInt LeftBits(Right.getBitWidth(), 9834 S.Context.getTypeSize(LHS.get()->getType())); 9835 if (Right.uge(LeftBits)) { 9836 S.DiagRuntimeBehavior(Loc, RHS.get(), 9837 S.PDiag(diag::warn_shift_gt_typewidth) 9838 << RHS.get()->getSourceRange()); 9839 return; 9840 } 9841 if (Opc != BO_Shl) 9842 return; 9843 9844 // When left shifting an ICE which is signed, we can check for overflow which 9845 // according to C++ standards prior to C++2a has undefined behavior 9846 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9847 // more than the maximum value representable in the result type, so never 9848 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9849 // expression is still probably a bug.) 9850 Expr::EvalResult LHSResult; 9851 if (LHS.get()->isValueDependent() || 9852 LHSType->hasUnsignedIntegerRepresentation() || 9853 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9854 return; 9855 llvm::APSInt Left = LHSResult.Val.getInt(); 9856 9857 // If LHS does not have a signed type and non-negative value 9858 // then, the behavior is undefined before C++2a. Warn about it. 9859 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9860 !S.getLangOpts().CPlusPlus2a) { 9861 S.DiagRuntimeBehavior(Loc, LHS.get(), 9862 S.PDiag(diag::warn_shift_lhs_negative) 9863 << LHS.get()->getSourceRange()); 9864 return; 9865 } 9866 9867 llvm::APInt ResultBits = 9868 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9869 if (LeftBits.uge(ResultBits)) 9870 return; 9871 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9872 Result = Result.shl(Right); 9873 9874 // Print the bit representation of the signed integer as an unsigned 9875 // hexadecimal number. 9876 SmallString<40> HexResult; 9877 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9878 9879 // If we are only missing a sign bit, this is less likely to result in actual 9880 // bugs -- if the result is cast back to an unsigned type, it will have the 9881 // expected value. Thus we place this behind a different warning that can be 9882 // turned off separately if needed. 9883 if (LeftBits == ResultBits - 1) { 9884 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9885 << HexResult << LHSType 9886 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9887 return; 9888 } 9889 9890 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9891 << HexResult.str() << Result.getMinSignedBits() << LHSType 9892 << Left.getBitWidth() << LHS.get()->getSourceRange() 9893 << RHS.get()->getSourceRange(); 9894 } 9895 9896 /// Return the resulting type when a vector is shifted 9897 /// by a scalar or vector shift amount. 9898 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9899 SourceLocation Loc, bool IsCompAssign) { 9900 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9901 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9902 !LHS.get()->getType()->isVectorType()) { 9903 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9904 << RHS.get()->getType() << LHS.get()->getType() 9905 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9906 return QualType(); 9907 } 9908 9909 if (!IsCompAssign) { 9910 LHS = S.UsualUnaryConversions(LHS.get()); 9911 if (LHS.isInvalid()) return QualType(); 9912 } 9913 9914 RHS = S.UsualUnaryConversions(RHS.get()); 9915 if (RHS.isInvalid()) return QualType(); 9916 9917 QualType LHSType = LHS.get()->getType(); 9918 // Note that LHS might be a scalar because the routine calls not only in 9919 // OpenCL case. 9920 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9921 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9922 9923 // Note that RHS might not be a vector. 9924 QualType RHSType = RHS.get()->getType(); 9925 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9926 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9927 9928 // The operands need to be integers. 9929 if (!LHSEleType->isIntegerType()) { 9930 S.Diag(Loc, diag::err_typecheck_expect_int) 9931 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9932 return QualType(); 9933 } 9934 9935 if (!RHSEleType->isIntegerType()) { 9936 S.Diag(Loc, diag::err_typecheck_expect_int) 9937 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9938 return QualType(); 9939 } 9940 9941 if (!LHSVecTy) { 9942 assert(RHSVecTy); 9943 if (IsCompAssign) 9944 return RHSType; 9945 if (LHSEleType != RHSEleType) { 9946 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9947 LHSEleType = RHSEleType; 9948 } 9949 QualType VecTy = 9950 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9951 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9952 LHSType = VecTy; 9953 } else if (RHSVecTy) { 9954 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9955 // are applied component-wise. So if RHS is a vector, then ensure 9956 // that the number of elements is the same as LHS... 9957 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9958 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9959 << LHS.get()->getType() << RHS.get()->getType() 9960 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9961 return QualType(); 9962 } 9963 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9964 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9965 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9966 if (LHSBT != RHSBT && 9967 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9968 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9969 << LHS.get()->getType() << RHS.get()->getType() 9970 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9971 } 9972 } 9973 } else { 9974 // ...else expand RHS to match the number of elements in LHS. 9975 QualType VecTy = 9976 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9977 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9978 } 9979 9980 return LHSType; 9981 } 9982 9983 // C99 6.5.7 9984 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9985 SourceLocation Loc, BinaryOperatorKind Opc, 9986 bool IsCompAssign) { 9987 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9988 9989 // Vector shifts promote their scalar inputs to vector type. 9990 if (LHS.get()->getType()->isVectorType() || 9991 RHS.get()->getType()->isVectorType()) { 9992 if (LangOpts.ZVector) { 9993 // The shift operators for the z vector extensions work basically 9994 // like general shifts, except that neither the LHS nor the RHS is 9995 // allowed to be a "vector bool". 9996 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9997 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9998 return InvalidOperands(Loc, LHS, RHS); 9999 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10000 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10001 return InvalidOperands(Loc, LHS, RHS); 10002 } 10003 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10004 } 10005 10006 // Shifts don't perform usual arithmetic conversions, they just do integer 10007 // promotions on each operand. C99 6.5.7p3 10008 10009 // For the LHS, do usual unary conversions, but then reset them away 10010 // if this is a compound assignment. 10011 ExprResult OldLHS = LHS; 10012 LHS = UsualUnaryConversions(LHS.get()); 10013 if (LHS.isInvalid()) 10014 return QualType(); 10015 QualType LHSType = LHS.get()->getType(); 10016 if (IsCompAssign) LHS = OldLHS; 10017 10018 // The RHS is simpler. 10019 RHS = UsualUnaryConversions(RHS.get()); 10020 if (RHS.isInvalid()) 10021 return QualType(); 10022 QualType RHSType = RHS.get()->getType(); 10023 10024 // C99 6.5.7p2: Each of the operands shall have integer type. 10025 if (!LHSType->hasIntegerRepresentation() || 10026 !RHSType->hasIntegerRepresentation()) 10027 return InvalidOperands(Loc, LHS, RHS); 10028 10029 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10030 // hasIntegerRepresentation() above instead of this. 10031 if (isScopedEnumerationType(LHSType) || 10032 isScopedEnumerationType(RHSType)) { 10033 return InvalidOperands(Loc, LHS, RHS); 10034 } 10035 // Sanity-check shift operands 10036 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10037 10038 // "The type of the result is that of the promoted left operand." 10039 return LHSType; 10040 } 10041 10042 /// If two different enums are compared, raise a warning. 10043 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 10044 Expr *RHS) { 10045 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 10046 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 10047 10048 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 10049 if (!LHSEnumType) 10050 return; 10051 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 10052 if (!RHSEnumType) 10053 return; 10054 10055 // Ignore anonymous enums. 10056 if (!LHSEnumType->getDecl()->getIdentifier() && 10057 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10058 return; 10059 if (!RHSEnumType->getDecl()->getIdentifier() && 10060 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10061 return; 10062 10063 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 10064 return; 10065 10066 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 10067 << LHSStrippedType << RHSStrippedType 10068 << LHS->getSourceRange() << RHS->getSourceRange(); 10069 } 10070 10071 /// Diagnose bad pointer comparisons. 10072 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10073 ExprResult &LHS, ExprResult &RHS, 10074 bool IsError) { 10075 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10076 : diag::ext_typecheck_comparison_of_distinct_pointers) 10077 << LHS.get()->getType() << RHS.get()->getType() 10078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10079 } 10080 10081 /// Returns false if the pointers are converted to a composite type, 10082 /// true otherwise. 10083 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10084 ExprResult &LHS, ExprResult &RHS) { 10085 // C++ [expr.rel]p2: 10086 // [...] Pointer conversions (4.10) and qualification 10087 // conversions (4.4) are performed on pointer operands (or on 10088 // a pointer operand and a null pointer constant) to bring 10089 // them to their composite pointer type. [...] 10090 // 10091 // C++ [expr.eq]p1 uses the same notion for (in)equality 10092 // comparisons of pointers. 10093 10094 QualType LHSType = LHS.get()->getType(); 10095 QualType RHSType = RHS.get()->getType(); 10096 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10097 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10098 10099 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10100 if (T.isNull()) { 10101 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10102 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10103 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10104 else 10105 S.InvalidOperands(Loc, LHS, RHS); 10106 return true; 10107 } 10108 10109 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10110 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10111 return false; 10112 } 10113 10114 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10115 ExprResult &LHS, 10116 ExprResult &RHS, 10117 bool IsError) { 10118 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10119 : diag::ext_typecheck_comparison_of_fptr_to_void) 10120 << LHS.get()->getType() << RHS.get()->getType() 10121 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10122 } 10123 10124 static bool isObjCObjectLiteral(ExprResult &E) { 10125 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10126 case Stmt::ObjCArrayLiteralClass: 10127 case Stmt::ObjCDictionaryLiteralClass: 10128 case Stmt::ObjCStringLiteralClass: 10129 case Stmt::ObjCBoxedExprClass: 10130 return true; 10131 default: 10132 // Note that ObjCBoolLiteral is NOT an object literal! 10133 return false; 10134 } 10135 } 10136 10137 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10138 const ObjCObjectPointerType *Type = 10139 LHS->getType()->getAs<ObjCObjectPointerType>(); 10140 10141 // If this is not actually an Objective-C object, bail out. 10142 if (!Type) 10143 return false; 10144 10145 // Get the LHS object's interface type. 10146 QualType InterfaceType = Type->getPointeeType(); 10147 10148 // If the RHS isn't an Objective-C object, bail out. 10149 if (!RHS->getType()->isObjCObjectPointerType()) 10150 return false; 10151 10152 // Try to find the -isEqual: method. 10153 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10154 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10155 InterfaceType, 10156 /*IsInstance=*/true); 10157 if (!Method) { 10158 if (Type->isObjCIdType()) { 10159 // For 'id', just check the global pool. 10160 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10161 /*receiverId=*/true); 10162 } else { 10163 // Check protocols. 10164 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10165 /*IsInstance=*/true); 10166 } 10167 } 10168 10169 if (!Method) 10170 return false; 10171 10172 QualType T = Method->parameters()[0]->getType(); 10173 if (!T->isObjCObjectPointerType()) 10174 return false; 10175 10176 QualType R = Method->getReturnType(); 10177 if (!R->isScalarType()) 10178 return false; 10179 10180 return true; 10181 } 10182 10183 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10184 FromE = FromE->IgnoreParenImpCasts(); 10185 switch (FromE->getStmtClass()) { 10186 default: 10187 break; 10188 case Stmt::ObjCStringLiteralClass: 10189 // "string literal" 10190 return LK_String; 10191 case Stmt::ObjCArrayLiteralClass: 10192 // "array literal" 10193 return LK_Array; 10194 case Stmt::ObjCDictionaryLiteralClass: 10195 // "dictionary literal" 10196 return LK_Dictionary; 10197 case Stmt::BlockExprClass: 10198 return LK_Block; 10199 case Stmt::ObjCBoxedExprClass: { 10200 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10201 switch (Inner->getStmtClass()) { 10202 case Stmt::IntegerLiteralClass: 10203 case Stmt::FloatingLiteralClass: 10204 case Stmt::CharacterLiteralClass: 10205 case Stmt::ObjCBoolLiteralExprClass: 10206 case Stmt::CXXBoolLiteralExprClass: 10207 // "numeric literal" 10208 return LK_Numeric; 10209 case Stmt::ImplicitCastExprClass: { 10210 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10211 // Boolean literals can be represented by implicit casts. 10212 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10213 return LK_Numeric; 10214 break; 10215 } 10216 default: 10217 break; 10218 } 10219 return LK_Boxed; 10220 } 10221 } 10222 return LK_None; 10223 } 10224 10225 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10226 ExprResult &LHS, ExprResult &RHS, 10227 BinaryOperator::Opcode Opc){ 10228 Expr *Literal; 10229 Expr *Other; 10230 if (isObjCObjectLiteral(LHS)) { 10231 Literal = LHS.get(); 10232 Other = RHS.get(); 10233 } else { 10234 Literal = RHS.get(); 10235 Other = LHS.get(); 10236 } 10237 10238 // Don't warn on comparisons against nil. 10239 Other = Other->IgnoreParenCasts(); 10240 if (Other->isNullPointerConstant(S.getASTContext(), 10241 Expr::NPC_ValueDependentIsNotNull)) 10242 return; 10243 10244 // This should be kept in sync with warn_objc_literal_comparison. 10245 // LK_String should always be after the other literals, since it has its own 10246 // warning flag. 10247 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10248 assert(LiteralKind != Sema::LK_Block); 10249 if (LiteralKind == Sema::LK_None) { 10250 llvm_unreachable("Unknown Objective-C object literal kind"); 10251 } 10252 10253 if (LiteralKind == Sema::LK_String) 10254 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10255 << Literal->getSourceRange(); 10256 else 10257 S.Diag(Loc, diag::warn_objc_literal_comparison) 10258 << LiteralKind << Literal->getSourceRange(); 10259 10260 if (BinaryOperator::isEqualityOp(Opc) && 10261 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10262 SourceLocation Start = LHS.get()->getBeginLoc(); 10263 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10264 CharSourceRange OpRange = 10265 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10266 10267 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10268 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10269 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10270 << FixItHint::CreateInsertion(End, "]"); 10271 } 10272 } 10273 10274 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10275 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10276 ExprResult &RHS, SourceLocation Loc, 10277 BinaryOperatorKind Opc) { 10278 // Check that left hand side is !something. 10279 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10280 if (!UO || UO->getOpcode() != UO_LNot) return; 10281 10282 // Only check if the right hand side is non-bool arithmetic type. 10283 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10284 10285 // Make sure that the something in !something is not bool. 10286 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10287 if (SubExpr->isKnownToHaveBooleanValue()) return; 10288 10289 // Emit warning. 10290 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10291 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10292 << Loc << IsBitwiseOp; 10293 10294 // First note suggest !(x < y) 10295 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10296 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10297 FirstClose = S.getLocForEndOfToken(FirstClose); 10298 if (FirstClose.isInvalid()) 10299 FirstOpen = SourceLocation(); 10300 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10301 << IsBitwiseOp 10302 << FixItHint::CreateInsertion(FirstOpen, "(") 10303 << FixItHint::CreateInsertion(FirstClose, ")"); 10304 10305 // Second note suggests (!x) < y 10306 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10307 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10308 SecondClose = S.getLocForEndOfToken(SecondClose); 10309 if (SecondClose.isInvalid()) 10310 SecondOpen = SourceLocation(); 10311 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10312 << FixItHint::CreateInsertion(SecondOpen, "(") 10313 << FixItHint::CreateInsertion(SecondClose, ")"); 10314 } 10315 10316 // Returns true if E refers to a non-weak array. 10317 static bool checkForArray(const Expr *E) { 10318 const ValueDecl *D = nullptr; 10319 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10320 D = DR->getDecl(); 10321 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10322 if (Mem->isImplicitAccess()) 10323 D = Mem->getMemberDecl(); 10324 } 10325 if (!D) 10326 return false; 10327 return D->getType()->isArrayType() && !D->isWeak(); 10328 } 10329 10330 /// Diagnose some forms of syntactically-obvious tautological comparison. 10331 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10332 Expr *LHS, Expr *RHS, 10333 BinaryOperatorKind Opc) { 10334 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10335 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10336 10337 QualType LHSType = LHS->getType(); 10338 QualType RHSType = RHS->getType(); 10339 if (LHSType->hasFloatingRepresentation() || 10340 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10341 S.inTemplateInstantiation()) 10342 return; 10343 10344 // Comparisons between two array types are ill-formed for operator<=>, so 10345 // we shouldn't emit any additional warnings about it. 10346 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10347 return; 10348 10349 // For non-floating point types, check for self-comparisons of the form 10350 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10351 // often indicate logic errors in the program. 10352 // 10353 // NOTE: Don't warn about comparison expressions resulting from macro 10354 // expansion. Also don't warn about comparisons which are only self 10355 // comparisons within a template instantiation. The warnings should catch 10356 // obvious cases in the definition of the template anyways. The idea is to 10357 // warn when the typed comparison operator will always evaluate to the same 10358 // result. 10359 10360 // Used for indexing into %select in warn_comparison_always 10361 enum { 10362 AlwaysConstant, 10363 AlwaysTrue, 10364 AlwaysFalse, 10365 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10366 }; 10367 10368 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10369 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10370 unsigned Result; 10371 switch (Opc) { 10372 case BO_EQ: 10373 case BO_LE: 10374 case BO_GE: 10375 Result = AlwaysTrue; 10376 break; 10377 case BO_NE: 10378 case BO_LT: 10379 case BO_GT: 10380 Result = AlwaysFalse; 10381 break; 10382 case BO_Cmp: 10383 Result = AlwaysEqual; 10384 break; 10385 default: 10386 Result = AlwaysConstant; 10387 break; 10388 } 10389 S.DiagRuntimeBehavior(Loc, nullptr, 10390 S.PDiag(diag::warn_comparison_always) 10391 << 0 /*self-comparison*/ 10392 << Result); 10393 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10394 // What is it always going to evaluate to? 10395 unsigned Result; 10396 switch (Opc) { 10397 case BO_EQ: // e.g. array1 == array2 10398 Result = AlwaysFalse; 10399 break; 10400 case BO_NE: // e.g. array1 != array2 10401 Result = AlwaysTrue; 10402 break; 10403 default: // e.g. array1 <= array2 10404 // The best we can say is 'a constant' 10405 Result = AlwaysConstant; 10406 break; 10407 } 10408 S.DiagRuntimeBehavior(Loc, nullptr, 10409 S.PDiag(diag::warn_comparison_always) 10410 << 1 /*array comparison*/ 10411 << Result); 10412 } 10413 } 10414 10415 if (isa<CastExpr>(LHSStripped)) 10416 LHSStripped = LHSStripped->IgnoreParenCasts(); 10417 if (isa<CastExpr>(RHSStripped)) 10418 RHSStripped = RHSStripped->IgnoreParenCasts(); 10419 10420 // Warn about comparisons against a string constant (unless the other 10421 // operand is null); the user probably wants string comparison function. 10422 Expr *LiteralString = nullptr; 10423 Expr *LiteralStringStripped = nullptr; 10424 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10425 !RHSStripped->isNullPointerConstant(S.Context, 10426 Expr::NPC_ValueDependentIsNull)) { 10427 LiteralString = LHS; 10428 LiteralStringStripped = LHSStripped; 10429 } else if ((isa<StringLiteral>(RHSStripped) || 10430 isa<ObjCEncodeExpr>(RHSStripped)) && 10431 !LHSStripped->isNullPointerConstant(S.Context, 10432 Expr::NPC_ValueDependentIsNull)) { 10433 LiteralString = RHS; 10434 LiteralStringStripped = RHSStripped; 10435 } 10436 10437 if (LiteralString) { 10438 S.DiagRuntimeBehavior(Loc, nullptr, 10439 S.PDiag(diag::warn_stringcompare) 10440 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10441 << LiteralString->getSourceRange()); 10442 } 10443 } 10444 10445 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10446 switch (CK) { 10447 default: { 10448 #ifndef NDEBUG 10449 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10450 << "\n"; 10451 #endif 10452 llvm_unreachable("unhandled cast kind"); 10453 } 10454 case CK_UserDefinedConversion: 10455 return ICK_Identity; 10456 case CK_LValueToRValue: 10457 return ICK_Lvalue_To_Rvalue; 10458 case CK_ArrayToPointerDecay: 10459 return ICK_Array_To_Pointer; 10460 case CK_FunctionToPointerDecay: 10461 return ICK_Function_To_Pointer; 10462 case CK_IntegralCast: 10463 return ICK_Integral_Conversion; 10464 case CK_FloatingCast: 10465 return ICK_Floating_Conversion; 10466 case CK_IntegralToFloating: 10467 case CK_FloatingToIntegral: 10468 return ICK_Floating_Integral; 10469 case CK_IntegralComplexCast: 10470 case CK_FloatingComplexCast: 10471 case CK_FloatingComplexToIntegralComplex: 10472 case CK_IntegralComplexToFloatingComplex: 10473 return ICK_Complex_Conversion; 10474 case CK_FloatingComplexToReal: 10475 case CK_FloatingRealToComplex: 10476 case CK_IntegralComplexToReal: 10477 case CK_IntegralRealToComplex: 10478 return ICK_Complex_Real; 10479 } 10480 } 10481 10482 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10483 QualType FromType, 10484 SourceLocation Loc) { 10485 // Check for a narrowing implicit conversion. 10486 StandardConversionSequence SCS; 10487 SCS.setAsIdentityConversion(); 10488 SCS.setToType(0, FromType); 10489 SCS.setToType(1, ToType); 10490 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10491 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10492 10493 APValue PreNarrowingValue; 10494 QualType PreNarrowingType; 10495 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10496 PreNarrowingType, 10497 /*IgnoreFloatToIntegralConversion*/ true)) { 10498 case NK_Dependent_Narrowing: 10499 // Implicit conversion to a narrower type, but the expression is 10500 // value-dependent so we can't tell whether it's actually narrowing. 10501 case NK_Not_Narrowing: 10502 return false; 10503 10504 case NK_Constant_Narrowing: 10505 // Implicit conversion to a narrower type, and the value is not a constant 10506 // expression. 10507 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10508 << /*Constant*/ 1 10509 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10510 return true; 10511 10512 case NK_Variable_Narrowing: 10513 // Implicit conversion to a narrower type, and the value is not a constant 10514 // expression. 10515 case NK_Type_Narrowing: 10516 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10517 << /*Constant*/ 0 << FromType << ToType; 10518 // TODO: It's not a constant expression, but what if the user intended it 10519 // to be? Can we produce notes to help them figure out why it isn't? 10520 return true; 10521 } 10522 llvm_unreachable("unhandled case in switch"); 10523 } 10524 10525 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10526 ExprResult &LHS, 10527 ExprResult &RHS, 10528 SourceLocation Loc) { 10529 using CCT = ComparisonCategoryType; 10530 10531 QualType LHSType = LHS.get()->getType(); 10532 QualType RHSType = RHS.get()->getType(); 10533 // Dig out the original argument type and expression before implicit casts 10534 // were applied. These are the types/expressions we need to check the 10535 // [expr.spaceship] requirements against. 10536 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10537 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10538 QualType LHSStrippedType = LHSStripped.get()->getType(); 10539 QualType RHSStrippedType = RHSStripped.get()->getType(); 10540 10541 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10542 // other is not, the program is ill-formed. 10543 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10544 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10545 return QualType(); 10546 } 10547 10548 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10549 RHSStrippedType->isEnumeralType(); 10550 if (NumEnumArgs == 1) { 10551 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10552 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10553 if (OtherTy->hasFloatingRepresentation()) { 10554 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10555 return QualType(); 10556 } 10557 } 10558 if (NumEnumArgs == 2) { 10559 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10560 // type E, the operator yields the result of converting the operands 10561 // to the underlying type of E and applying <=> to the converted operands. 10562 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10563 S.InvalidOperands(Loc, LHS, RHS); 10564 return QualType(); 10565 } 10566 QualType IntType = 10567 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10568 assert(IntType->isArithmeticType()); 10569 10570 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10571 // promote the boolean type, and all other promotable integer types, to 10572 // avoid this. 10573 if (IntType->isPromotableIntegerType()) 10574 IntType = S.Context.getPromotedIntegerType(IntType); 10575 10576 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10577 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10578 LHSType = RHSType = IntType; 10579 } 10580 10581 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10582 // usual arithmetic conversions are applied to the operands. 10583 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10584 if (LHS.isInvalid() || RHS.isInvalid()) 10585 return QualType(); 10586 if (Type.isNull()) 10587 return S.InvalidOperands(Loc, LHS, RHS); 10588 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10589 10590 bool HasNarrowing = checkThreeWayNarrowingConversion( 10591 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10592 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10593 RHS.get()->getBeginLoc()); 10594 if (HasNarrowing) 10595 return QualType(); 10596 10597 assert(!Type.isNull() && "composite type for <=> has not been set"); 10598 10599 auto TypeKind = [&]() { 10600 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10601 if (CT->getElementType()->hasFloatingRepresentation()) 10602 return CCT::WeakEquality; 10603 return CCT::StrongEquality; 10604 } 10605 if (Type->isIntegralOrEnumerationType()) 10606 return CCT::StrongOrdering; 10607 if (Type->hasFloatingRepresentation()) 10608 return CCT::PartialOrdering; 10609 llvm_unreachable("other types are unimplemented"); 10610 }(); 10611 10612 return S.CheckComparisonCategoryType(TypeKind, Loc); 10613 } 10614 10615 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10616 ExprResult &RHS, 10617 SourceLocation Loc, 10618 BinaryOperatorKind Opc) { 10619 if (Opc == BO_Cmp) 10620 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10621 10622 // C99 6.5.8p3 / C99 6.5.9p4 10623 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10624 if (LHS.isInvalid() || RHS.isInvalid()) 10625 return QualType(); 10626 if (Type.isNull()) 10627 return S.InvalidOperands(Loc, LHS, RHS); 10628 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10629 10630 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10631 10632 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10633 return S.InvalidOperands(Loc, LHS, RHS); 10634 10635 // Check for comparisons of floating point operands using != and ==. 10636 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10637 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10638 10639 // The result of comparisons is 'bool' in C++, 'int' in C. 10640 return S.Context.getLogicalOperationType(); 10641 } 10642 10643 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10644 if (!NullE.get()->getType()->isAnyPointerType()) 10645 return; 10646 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10647 if (!E.get()->getType()->isAnyPointerType() && 10648 E.get()->isNullPointerConstant(Context, 10649 Expr::NPC_ValueDependentIsNotNull) == 10650 Expr::NPCK_ZeroExpression) { 10651 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10652 if (CL->getValue() == 0) 10653 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10654 << NullValue 10655 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10656 NullValue ? "NULL" : "(void *)0"); 10657 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10658 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10659 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10660 if (T == Context.CharTy) 10661 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10662 << NullValue 10663 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10664 NullValue ? "NULL" : "(void *)0"); 10665 } 10666 } 10667 } 10668 10669 // C99 6.5.8, C++ [expr.rel] 10670 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10671 SourceLocation Loc, 10672 BinaryOperatorKind Opc) { 10673 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10674 bool IsThreeWay = Opc == BO_Cmp; 10675 auto IsAnyPointerType = [](ExprResult E) { 10676 QualType Ty = E.get()->getType(); 10677 return Ty->isPointerType() || Ty->isMemberPointerType(); 10678 }; 10679 10680 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10681 // type, array-to-pointer, ..., conversions are performed on both operands to 10682 // bring them to their composite type. 10683 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10684 // any type-related checks. 10685 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10686 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10687 if (LHS.isInvalid()) 10688 return QualType(); 10689 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10690 if (RHS.isInvalid()) 10691 return QualType(); 10692 } else { 10693 LHS = DefaultLvalueConversion(LHS.get()); 10694 if (LHS.isInvalid()) 10695 return QualType(); 10696 RHS = DefaultLvalueConversion(RHS.get()); 10697 if (RHS.isInvalid()) 10698 return QualType(); 10699 } 10700 10701 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10702 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10703 CheckPtrComparisonWithNullChar(LHS, RHS); 10704 CheckPtrComparisonWithNullChar(RHS, LHS); 10705 } 10706 10707 // Handle vector comparisons separately. 10708 if (LHS.get()->getType()->isVectorType() || 10709 RHS.get()->getType()->isVectorType()) 10710 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10711 10712 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10713 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10714 10715 QualType LHSType = LHS.get()->getType(); 10716 QualType RHSType = RHS.get()->getType(); 10717 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10718 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10719 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10720 10721 const Expr::NullPointerConstantKind LHSNullKind = 10722 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10723 const Expr::NullPointerConstantKind RHSNullKind = 10724 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10725 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10726 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10727 10728 auto computeResultTy = [&]() { 10729 if (Opc != BO_Cmp) 10730 return Context.getLogicalOperationType(); 10731 assert(getLangOpts().CPlusPlus); 10732 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10733 10734 QualType CompositeTy = LHS.get()->getType(); 10735 assert(!CompositeTy->isReferenceType()); 10736 10737 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10738 return CheckComparisonCategoryType(Kind, Loc); 10739 }; 10740 10741 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10742 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10743 // result is of type std::strong_equality 10744 if (CompositeTy->isFunctionPointerType() || 10745 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10746 // FIXME: consider making the function pointer case produce 10747 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10748 // and direction polls 10749 return buildResultTy(ComparisonCategoryType::StrongEquality); 10750 10751 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10752 // pointer type, p <=> q is of type std::strong_ordering. 10753 if (CompositeTy->isPointerType()) { 10754 // P0946R0: Comparisons between a null pointer constant and an object 10755 // pointer result in std::strong_equality 10756 if (LHSIsNull != RHSIsNull) 10757 return buildResultTy(ComparisonCategoryType::StrongEquality); 10758 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10759 } 10760 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10761 // TODO: Extend support for operator<=> to ObjC types. 10762 return InvalidOperands(Loc, LHS, RHS); 10763 }; 10764 10765 10766 if (!IsRelational && LHSIsNull != RHSIsNull) { 10767 bool IsEquality = Opc == BO_EQ; 10768 if (RHSIsNull) 10769 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10770 RHS.get()->getSourceRange()); 10771 else 10772 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10773 LHS.get()->getSourceRange()); 10774 } 10775 10776 if ((LHSType->isIntegerType() && !LHSIsNull) || 10777 (RHSType->isIntegerType() && !RHSIsNull)) { 10778 // Skip normal pointer conversion checks in this case; we have better 10779 // diagnostics for this below. 10780 } else if (getLangOpts().CPlusPlus) { 10781 // Equality comparison of a function pointer to a void pointer is invalid, 10782 // but we allow it as an extension. 10783 // FIXME: If we really want to allow this, should it be part of composite 10784 // pointer type computation so it works in conditionals too? 10785 if (!IsRelational && 10786 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10787 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10788 // This is a gcc extension compatibility comparison. 10789 // In a SFINAE context, we treat this as a hard error to maintain 10790 // conformance with the C++ standard. 10791 diagnoseFunctionPointerToVoidComparison( 10792 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10793 10794 if (isSFINAEContext()) 10795 return QualType(); 10796 10797 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10798 return computeResultTy(); 10799 } 10800 10801 // C++ [expr.eq]p2: 10802 // If at least one operand is a pointer [...] bring them to their 10803 // composite pointer type. 10804 // C++ [expr.spaceship]p6 10805 // If at least one of the operands is of pointer type, [...] bring them 10806 // to their composite pointer type. 10807 // C++ [expr.rel]p2: 10808 // If both operands are pointers, [...] bring them to their composite 10809 // pointer type. 10810 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10811 (IsRelational ? 2 : 1) && 10812 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10813 RHSType->isObjCObjectPointerType()))) { 10814 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10815 return QualType(); 10816 return computeResultTy(); 10817 } 10818 } else if (LHSType->isPointerType() && 10819 RHSType->isPointerType()) { // C99 6.5.8p2 10820 // All of the following pointer-related warnings are GCC extensions, except 10821 // when handling null pointer constants. 10822 QualType LCanPointeeTy = 10823 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10824 QualType RCanPointeeTy = 10825 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10826 10827 // C99 6.5.9p2 and C99 6.5.8p2 10828 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10829 RCanPointeeTy.getUnqualifiedType())) { 10830 // Valid unless a relational comparison of function pointers 10831 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10832 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10833 << LHSType << RHSType << LHS.get()->getSourceRange() 10834 << RHS.get()->getSourceRange(); 10835 } 10836 } else if (!IsRelational && 10837 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10838 // Valid unless comparison between non-null pointer and function pointer 10839 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10840 && !LHSIsNull && !RHSIsNull) 10841 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10842 /*isError*/false); 10843 } else { 10844 // Invalid 10845 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10846 } 10847 if (LCanPointeeTy != RCanPointeeTy) { 10848 // Treat NULL constant as a special case in OpenCL. 10849 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10850 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10851 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10852 Diag(Loc, 10853 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10854 << LHSType << RHSType << 0 /* comparison */ 10855 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10856 } 10857 } 10858 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10859 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10860 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10861 : CK_BitCast; 10862 if (LHSIsNull && !RHSIsNull) 10863 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10864 else 10865 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10866 } 10867 return computeResultTy(); 10868 } 10869 10870 if (getLangOpts().CPlusPlus) { 10871 // C++ [expr.eq]p4: 10872 // Two operands of type std::nullptr_t or one operand of type 10873 // std::nullptr_t and the other a null pointer constant compare equal. 10874 if (!IsRelational && LHSIsNull && RHSIsNull) { 10875 if (LHSType->isNullPtrType()) { 10876 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10877 return computeResultTy(); 10878 } 10879 if (RHSType->isNullPtrType()) { 10880 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10881 return computeResultTy(); 10882 } 10883 } 10884 10885 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10886 // These aren't covered by the composite pointer type rules. 10887 if (!IsRelational && RHSType->isNullPtrType() && 10888 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10889 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10890 return computeResultTy(); 10891 } 10892 if (!IsRelational && LHSType->isNullPtrType() && 10893 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10894 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10895 return computeResultTy(); 10896 } 10897 10898 if (IsRelational && 10899 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10900 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10901 // HACK: Relational comparison of nullptr_t against a pointer type is 10902 // invalid per DR583, but we allow it within std::less<> and friends, 10903 // since otherwise common uses of it break. 10904 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10905 // friends to have std::nullptr_t overload candidates. 10906 DeclContext *DC = CurContext; 10907 if (isa<FunctionDecl>(DC)) 10908 DC = DC->getParent(); 10909 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10910 if (CTSD->isInStdNamespace() && 10911 llvm::StringSwitch<bool>(CTSD->getName()) 10912 .Cases("less", "less_equal", "greater", "greater_equal", true) 10913 .Default(false)) { 10914 if (RHSType->isNullPtrType()) 10915 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10916 else 10917 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10918 return computeResultTy(); 10919 } 10920 } 10921 } 10922 10923 // C++ [expr.eq]p2: 10924 // If at least one operand is a pointer to member, [...] bring them to 10925 // their composite pointer type. 10926 if (!IsRelational && 10927 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10928 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10929 return QualType(); 10930 else 10931 return computeResultTy(); 10932 } 10933 } 10934 10935 // Handle block pointer types. 10936 if (!IsRelational && LHSType->isBlockPointerType() && 10937 RHSType->isBlockPointerType()) { 10938 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10939 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10940 10941 if (!LHSIsNull && !RHSIsNull && 10942 !Context.typesAreCompatible(lpointee, rpointee)) { 10943 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10944 << LHSType << RHSType << LHS.get()->getSourceRange() 10945 << RHS.get()->getSourceRange(); 10946 } 10947 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10948 return computeResultTy(); 10949 } 10950 10951 // Allow block pointers to be compared with null pointer constants. 10952 if (!IsRelational 10953 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10954 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10955 if (!LHSIsNull && !RHSIsNull) { 10956 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10957 ->getPointeeType()->isVoidType()) 10958 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10959 ->getPointeeType()->isVoidType()))) 10960 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10961 << LHSType << RHSType << LHS.get()->getSourceRange() 10962 << RHS.get()->getSourceRange(); 10963 } 10964 if (LHSIsNull && !RHSIsNull) 10965 LHS = ImpCastExprToType(LHS.get(), RHSType, 10966 RHSType->isPointerType() ? CK_BitCast 10967 : CK_AnyPointerToBlockPointerCast); 10968 else 10969 RHS = ImpCastExprToType(RHS.get(), LHSType, 10970 LHSType->isPointerType() ? CK_BitCast 10971 : CK_AnyPointerToBlockPointerCast); 10972 return computeResultTy(); 10973 } 10974 10975 if (LHSType->isObjCObjectPointerType() || 10976 RHSType->isObjCObjectPointerType()) { 10977 const PointerType *LPT = LHSType->getAs<PointerType>(); 10978 const PointerType *RPT = RHSType->getAs<PointerType>(); 10979 if (LPT || RPT) { 10980 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10981 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10982 10983 if (!LPtrToVoid && !RPtrToVoid && 10984 !Context.typesAreCompatible(LHSType, RHSType)) { 10985 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10986 /*isError*/false); 10987 } 10988 if (LHSIsNull && !RHSIsNull) { 10989 Expr *E = LHS.get(); 10990 if (getLangOpts().ObjCAutoRefCount) 10991 CheckObjCConversion(SourceRange(), RHSType, E, 10992 CCK_ImplicitConversion); 10993 LHS = ImpCastExprToType(E, RHSType, 10994 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10995 } 10996 else { 10997 Expr *E = RHS.get(); 10998 if (getLangOpts().ObjCAutoRefCount) 10999 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11000 /*Diagnose=*/true, 11001 /*DiagnoseCFAudited=*/false, Opc); 11002 RHS = ImpCastExprToType(E, LHSType, 11003 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11004 } 11005 return computeResultTy(); 11006 } 11007 if (LHSType->isObjCObjectPointerType() && 11008 RHSType->isObjCObjectPointerType()) { 11009 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11010 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11011 /*isError*/false); 11012 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11013 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11014 11015 if (LHSIsNull && !RHSIsNull) 11016 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11017 else 11018 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11019 return computeResultTy(); 11020 } 11021 11022 if (!IsRelational && LHSType->isBlockPointerType() && 11023 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11024 LHS = ImpCastExprToType(LHS.get(), RHSType, 11025 CK_BlockPointerToObjCPointerCast); 11026 return computeResultTy(); 11027 } else if (!IsRelational && 11028 LHSType->isBlockCompatibleObjCPointerType(Context) && 11029 RHSType->isBlockPointerType()) { 11030 RHS = ImpCastExprToType(RHS.get(), LHSType, 11031 CK_BlockPointerToObjCPointerCast); 11032 return computeResultTy(); 11033 } 11034 } 11035 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11036 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11037 unsigned DiagID = 0; 11038 bool isError = false; 11039 if (LangOpts.DebuggerSupport) { 11040 // Under a debugger, allow the comparison of pointers to integers, 11041 // since users tend to want to compare addresses. 11042 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11043 (RHSIsNull && RHSType->isIntegerType())) { 11044 if (IsRelational) { 11045 isError = getLangOpts().CPlusPlus; 11046 DiagID = 11047 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11048 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11049 } 11050 } else if (getLangOpts().CPlusPlus) { 11051 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11052 isError = true; 11053 } else if (IsRelational) 11054 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11055 else 11056 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11057 11058 if (DiagID) { 11059 Diag(Loc, DiagID) 11060 << LHSType << RHSType << LHS.get()->getSourceRange() 11061 << RHS.get()->getSourceRange(); 11062 if (isError) 11063 return QualType(); 11064 } 11065 11066 if (LHSType->isIntegerType()) 11067 LHS = ImpCastExprToType(LHS.get(), RHSType, 11068 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11069 else 11070 RHS = ImpCastExprToType(RHS.get(), LHSType, 11071 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11072 return computeResultTy(); 11073 } 11074 11075 // Handle block pointers. 11076 if (!IsRelational && RHSIsNull 11077 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11078 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11079 return computeResultTy(); 11080 } 11081 if (!IsRelational && LHSIsNull 11082 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11083 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11084 return computeResultTy(); 11085 } 11086 11087 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11088 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11089 return computeResultTy(); 11090 } 11091 11092 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11093 return computeResultTy(); 11094 } 11095 11096 if (LHSIsNull && RHSType->isQueueT()) { 11097 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11098 return computeResultTy(); 11099 } 11100 11101 if (LHSType->isQueueT() && RHSIsNull) { 11102 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11103 return computeResultTy(); 11104 } 11105 } 11106 11107 return InvalidOperands(Loc, LHS, RHS); 11108 } 11109 11110 // Return a signed ext_vector_type that is of identical size and number of 11111 // elements. For floating point vectors, return an integer type of identical 11112 // size and number of elements. In the non ext_vector_type case, search from 11113 // the largest type to the smallest type to avoid cases where long long == long, 11114 // where long gets picked over long long. 11115 QualType Sema::GetSignedVectorType(QualType V) { 11116 const VectorType *VTy = V->castAs<VectorType>(); 11117 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11118 11119 if (isa<ExtVectorType>(VTy)) { 11120 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11121 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11122 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11123 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11124 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11125 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11126 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11127 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11128 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11129 "Unhandled vector element size in vector compare"); 11130 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11131 } 11132 11133 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11134 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11135 VectorType::GenericVector); 11136 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11137 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11138 VectorType::GenericVector); 11139 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11140 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11141 VectorType::GenericVector); 11142 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11143 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11144 VectorType::GenericVector); 11145 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11146 "Unhandled vector element size in vector compare"); 11147 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11148 VectorType::GenericVector); 11149 } 11150 11151 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11152 /// operates on extended vector types. Instead of producing an IntTy result, 11153 /// like a scalar comparison, a vector comparison produces a vector of integer 11154 /// types. 11155 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11156 SourceLocation Loc, 11157 BinaryOperatorKind Opc) { 11158 // Check to make sure we're operating on vectors of the same type and width, 11159 // Allowing one side to be a scalar of element type. 11160 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11161 /*AllowBothBool*/true, 11162 /*AllowBoolConversions*/getLangOpts().ZVector); 11163 if (vType.isNull()) 11164 return vType; 11165 11166 QualType LHSType = LHS.get()->getType(); 11167 11168 // If AltiVec, the comparison results in a numeric type, i.e. 11169 // bool for C++, int for C 11170 if (getLangOpts().AltiVec && 11171 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11172 return Context.getLogicalOperationType(); 11173 11174 // For non-floating point types, check for self-comparisons of the form 11175 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11176 // often indicate logic errors in the program. 11177 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11178 11179 // Check for comparisons of floating point operands using != and ==. 11180 if (BinaryOperator::isEqualityOp(Opc) && 11181 LHSType->hasFloatingRepresentation()) { 11182 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11183 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11184 } 11185 11186 // Return a signed type for the vector. 11187 return GetSignedVectorType(vType); 11188 } 11189 11190 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11191 const ExprResult &XorRHS, 11192 const SourceLocation Loc) { 11193 // Do not diagnose macros. 11194 if (Loc.isMacroID()) 11195 return; 11196 11197 bool Negative = false; 11198 bool ExplicitPlus = false; 11199 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11200 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11201 11202 if (!LHSInt) 11203 return; 11204 if (!RHSInt) { 11205 // Check negative literals. 11206 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11207 UnaryOperatorKind Opc = UO->getOpcode(); 11208 if (Opc != UO_Minus && Opc != UO_Plus) 11209 return; 11210 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11211 if (!RHSInt) 11212 return; 11213 Negative = (Opc == UO_Minus); 11214 ExplicitPlus = !Negative; 11215 } else { 11216 return; 11217 } 11218 } 11219 11220 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11221 llvm::APInt RightSideValue = RHSInt->getValue(); 11222 if (LeftSideValue != 2 && LeftSideValue != 10) 11223 return; 11224 11225 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11226 return; 11227 11228 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11229 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11230 llvm::StringRef ExprStr = 11231 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11232 11233 CharSourceRange XorRange = 11234 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11235 llvm::StringRef XorStr = 11236 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11237 // Do not diagnose if xor keyword/macro is used. 11238 if (XorStr == "xor") 11239 return; 11240 11241 std::string LHSStr = Lexer::getSourceText( 11242 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11243 S.getSourceManager(), S.getLangOpts()); 11244 std::string RHSStr = Lexer::getSourceText( 11245 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11246 S.getSourceManager(), S.getLangOpts()); 11247 11248 if (Negative) { 11249 RightSideValue = -RightSideValue; 11250 RHSStr = "-" + RHSStr; 11251 } else if (ExplicitPlus) { 11252 RHSStr = "+" + RHSStr; 11253 } 11254 11255 StringRef LHSStrRef = LHSStr; 11256 StringRef RHSStrRef = RHSStr; 11257 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11258 // literals. 11259 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11260 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11261 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11262 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11263 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11264 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11265 LHSStrRef.find('\'') != StringRef::npos || 11266 RHSStrRef.find('\'') != StringRef::npos) 11267 return; 11268 11269 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11270 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11271 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11272 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11273 std::string SuggestedExpr = "1 << " + RHSStr; 11274 bool Overflow = false; 11275 llvm::APInt One = (LeftSideValue - 1); 11276 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11277 if (Overflow) { 11278 if (RightSideIntValue < 64) 11279 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11280 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11281 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11282 else if (RightSideIntValue == 64) 11283 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11284 else 11285 return; 11286 } else { 11287 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11288 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11289 << PowValue.toString(10, true) 11290 << FixItHint::CreateReplacement( 11291 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11292 } 11293 11294 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11295 } else if (LeftSideValue == 10) { 11296 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11297 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11298 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11299 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11300 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11301 } 11302 } 11303 11304 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11305 SourceLocation Loc) { 11306 // Ensure that either both operands are of the same vector type, or 11307 // one operand is of a vector type and the other is of its element type. 11308 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11309 /*AllowBothBool*/true, 11310 /*AllowBoolConversions*/false); 11311 if (vType.isNull()) 11312 return InvalidOperands(Loc, LHS, RHS); 11313 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11314 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11315 return InvalidOperands(Loc, LHS, RHS); 11316 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11317 // usage of the logical operators && and || with vectors in C. This 11318 // check could be notionally dropped. 11319 if (!getLangOpts().CPlusPlus && 11320 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11321 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11322 11323 return GetSignedVectorType(LHS.get()->getType()); 11324 } 11325 11326 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11327 SourceLocation Loc, 11328 BinaryOperatorKind Opc) { 11329 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11330 11331 bool IsCompAssign = 11332 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11333 11334 if (LHS.get()->getType()->isVectorType() || 11335 RHS.get()->getType()->isVectorType()) { 11336 if (LHS.get()->getType()->hasIntegerRepresentation() && 11337 RHS.get()->getType()->hasIntegerRepresentation()) 11338 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11339 /*AllowBothBool*/true, 11340 /*AllowBoolConversions*/getLangOpts().ZVector); 11341 return InvalidOperands(Loc, LHS, RHS); 11342 } 11343 11344 if (Opc == BO_And) 11345 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11346 11347 ExprResult LHSResult = LHS, RHSResult = RHS; 11348 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11349 IsCompAssign); 11350 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11351 return QualType(); 11352 LHS = LHSResult.get(); 11353 RHS = RHSResult.get(); 11354 11355 if (Opc == BO_Xor) 11356 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11357 11358 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11359 return compType; 11360 return InvalidOperands(Loc, LHS, RHS); 11361 } 11362 11363 // C99 6.5.[13,14] 11364 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11365 SourceLocation Loc, 11366 BinaryOperatorKind Opc) { 11367 // Check vector operands differently. 11368 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11369 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11370 11371 bool EnumConstantInBoolContext = false; 11372 for (const ExprResult &HS : {LHS, RHS}) { 11373 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11374 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11375 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11376 EnumConstantInBoolContext = true; 11377 } 11378 } 11379 11380 if (EnumConstantInBoolContext) 11381 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11382 11383 // Diagnose cases where the user write a logical and/or but probably meant a 11384 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11385 // is a constant. 11386 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11387 !LHS.get()->getType()->isBooleanType() && 11388 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11389 // Don't warn in macros or template instantiations. 11390 !Loc.isMacroID() && !inTemplateInstantiation()) { 11391 // If the RHS can be constant folded, and if it constant folds to something 11392 // that isn't 0 or 1 (which indicate a potential logical operation that 11393 // happened to fold to true/false) then warn. 11394 // Parens on the RHS are ignored. 11395 Expr::EvalResult EVResult; 11396 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11397 llvm::APSInt Result = EVResult.Val.getInt(); 11398 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11399 !RHS.get()->getExprLoc().isMacroID()) || 11400 (Result != 0 && Result != 1)) { 11401 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11402 << RHS.get()->getSourceRange() 11403 << (Opc == BO_LAnd ? "&&" : "||"); 11404 // Suggest replacing the logical operator with the bitwise version 11405 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11406 << (Opc == BO_LAnd ? "&" : "|") 11407 << FixItHint::CreateReplacement(SourceRange( 11408 Loc, getLocForEndOfToken(Loc)), 11409 Opc == BO_LAnd ? "&" : "|"); 11410 if (Opc == BO_LAnd) 11411 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11412 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11413 << FixItHint::CreateRemoval( 11414 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11415 RHS.get()->getEndLoc())); 11416 } 11417 } 11418 } 11419 11420 if (!Context.getLangOpts().CPlusPlus) { 11421 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11422 // not operate on the built-in scalar and vector float types. 11423 if (Context.getLangOpts().OpenCL && 11424 Context.getLangOpts().OpenCLVersion < 120) { 11425 if (LHS.get()->getType()->isFloatingType() || 11426 RHS.get()->getType()->isFloatingType()) 11427 return InvalidOperands(Loc, LHS, RHS); 11428 } 11429 11430 LHS = UsualUnaryConversions(LHS.get()); 11431 if (LHS.isInvalid()) 11432 return QualType(); 11433 11434 RHS = UsualUnaryConversions(RHS.get()); 11435 if (RHS.isInvalid()) 11436 return QualType(); 11437 11438 if (!LHS.get()->getType()->isScalarType() || 11439 !RHS.get()->getType()->isScalarType()) 11440 return InvalidOperands(Loc, LHS, RHS); 11441 11442 return Context.IntTy; 11443 } 11444 11445 // The following is safe because we only use this method for 11446 // non-overloadable operands. 11447 11448 // C++ [expr.log.and]p1 11449 // C++ [expr.log.or]p1 11450 // The operands are both contextually converted to type bool. 11451 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11452 if (LHSRes.isInvalid()) 11453 return InvalidOperands(Loc, LHS, RHS); 11454 LHS = LHSRes; 11455 11456 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11457 if (RHSRes.isInvalid()) 11458 return InvalidOperands(Loc, LHS, RHS); 11459 RHS = RHSRes; 11460 11461 // C++ [expr.log.and]p2 11462 // C++ [expr.log.or]p2 11463 // The result is a bool. 11464 return Context.BoolTy; 11465 } 11466 11467 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11468 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11469 if (!ME) return false; 11470 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11471 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11472 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11473 if (!Base) return false; 11474 return Base->getMethodDecl() != nullptr; 11475 } 11476 11477 /// Is the given expression (which must be 'const') a reference to a 11478 /// variable which was originally non-const, but which has become 11479 /// 'const' due to being captured within a block? 11480 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11481 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11482 assert(E->isLValue() && E->getType().isConstQualified()); 11483 E = E->IgnoreParens(); 11484 11485 // Must be a reference to a declaration from an enclosing scope. 11486 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11487 if (!DRE) return NCCK_None; 11488 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11489 11490 // The declaration must be a variable which is not declared 'const'. 11491 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11492 if (!var) return NCCK_None; 11493 if (var->getType().isConstQualified()) return NCCK_None; 11494 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11495 11496 // Decide whether the first capture was for a block or a lambda. 11497 DeclContext *DC = S.CurContext, *Prev = nullptr; 11498 // Decide whether the first capture was for a block or a lambda. 11499 while (DC) { 11500 // For init-capture, it is possible that the variable belongs to the 11501 // template pattern of the current context. 11502 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11503 if (var->isInitCapture() && 11504 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11505 break; 11506 if (DC == var->getDeclContext()) 11507 break; 11508 Prev = DC; 11509 DC = DC->getParent(); 11510 } 11511 // Unless we have an init-capture, we've gone one step too far. 11512 if (!var->isInitCapture()) 11513 DC = Prev; 11514 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11515 } 11516 11517 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11518 Ty = Ty.getNonReferenceType(); 11519 if (IsDereference && Ty->isPointerType()) 11520 Ty = Ty->getPointeeType(); 11521 return !Ty.isConstQualified(); 11522 } 11523 11524 // Update err_typecheck_assign_const and note_typecheck_assign_const 11525 // when this enum is changed. 11526 enum { 11527 ConstFunction, 11528 ConstVariable, 11529 ConstMember, 11530 ConstMethod, 11531 NestedConstMember, 11532 ConstUnknown, // Keep as last element 11533 }; 11534 11535 /// Emit the "read-only variable not assignable" error and print notes to give 11536 /// more information about why the variable is not assignable, such as pointing 11537 /// to the declaration of a const variable, showing that a method is const, or 11538 /// that the function is returning a const reference. 11539 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11540 SourceLocation Loc) { 11541 SourceRange ExprRange = E->getSourceRange(); 11542 11543 // Only emit one error on the first const found. All other consts will emit 11544 // a note to the error. 11545 bool DiagnosticEmitted = false; 11546 11547 // Track if the current expression is the result of a dereference, and if the 11548 // next checked expression is the result of a dereference. 11549 bool IsDereference = false; 11550 bool NextIsDereference = false; 11551 11552 // Loop to process MemberExpr chains. 11553 while (true) { 11554 IsDereference = NextIsDereference; 11555 11556 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11557 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11558 NextIsDereference = ME->isArrow(); 11559 const ValueDecl *VD = ME->getMemberDecl(); 11560 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11561 // Mutable fields can be modified even if the class is const. 11562 if (Field->isMutable()) { 11563 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11564 break; 11565 } 11566 11567 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11568 if (!DiagnosticEmitted) { 11569 S.Diag(Loc, diag::err_typecheck_assign_const) 11570 << ExprRange << ConstMember << false /*static*/ << Field 11571 << Field->getType(); 11572 DiagnosticEmitted = true; 11573 } 11574 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11575 << ConstMember << false /*static*/ << Field << Field->getType() 11576 << Field->getSourceRange(); 11577 } 11578 E = ME->getBase(); 11579 continue; 11580 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11581 if (VDecl->getType().isConstQualified()) { 11582 if (!DiagnosticEmitted) { 11583 S.Diag(Loc, diag::err_typecheck_assign_const) 11584 << ExprRange << ConstMember << true /*static*/ << VDecl 11585 << VDecl->getType(); 11586 DiagnosticEmitted = true; 11587 } 11588 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11589 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11590 << VDecl->getSourceRange(); 11591 } 11592 // Static fields do not inherit constness from parents. 11593 break; 11594 } 11595 break; // End MemberExpr 11596 } else if (const ArraySubscriptExpr *ASE = 11597 dyn_cast<ArraySubscriptExpr>(E)) { 11598 E = ASE->getBase()->IgnoreParenImpCasts(); 11599 continue; 11600 } else if (const ExtVectorElementExpr *EVE = 11601 dyn_cast<ExtVectorElementExpr>(E)) { 11602 E = EVE->getBase()->IgnoreParenImpCasts(); 11603 continue; 11604 } 11605 break; 11606 } 11607 11608 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11609 // Function calls 11610 const FunctionDecl *FD = CE->getDirectCallee(); 11611 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11612 if (!DiagnosticEmitted) { 11613 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11614 << ConstFunction << FD; 11615 DiagnosticEmitted = true; 11616 } 11617 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11618 diag::note_typecheck_assign_const) 11619 << ConstFunction << FD << FD->getReturnType() 11620 << FD->getReturnTypeSourceRange(); 11621 } 11622 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11623 // Point to variable declaration. 11624 if (const ValueDecl *VD = DRE->getDecl()) { 11625 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11626 if (!DiagnosticEmitted) { 11627 S.Diag(Loc, diag::err_typecheck_assign_const) 11628 << ExprRange << ConstVariable << VD << VD->getType(); 11629 DiagnosticEmitted = true; 11630 } 11631 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11632 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11633 } 11634 } 11635 } else if (isa<CXXThisExpr>(E)) { 11636 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11637 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11638 if (MD->isConst()) { 11639 if (!DiagnosticEmitted) { 11640 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11641 << ConstMethod << MD; 11642 DiagnosticEmitted = true; 11643 } 11644 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11645 << ConstMethod << MD << MD->getSourceRange(); 11646 } 11647 } 11648 } 11649 } 11650 11651 if (DiagnosticEmitted) 11652 return; 11653 11654 // Can't determine a more specific message, so display the generic error. 11655 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11656 } 11657 11658 enum OriginalExprKind { 11659 OEK_Variable, 11660 OEK_Member, 11661 OEK_LValue 11662 }; 11663 11664 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11665 const RecordType *Ty, 11666 SourceLocation Loc, SourceRange Range, 11667 OriginalExprKind OEK, 11668 bool &DiagnosticEmitted) { 11669 std::vector<const RecordType *> RecordTypeList; 11670 RecordTypeList.push_back(Ty); 11671 unsigned NextToCheckIndex = 0; 11672 // We walk the record hierarchy breadth-first to ensure that we print 11673 // diagnostics in field nesting order. 11674 while (RecordTypeList.size() > NextToCheckIndex) { 11675 bool IsNested = NextToCheckIndex > 0; 11676 for (const FieldDecl *Field : 11677 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11678 // First, check every field for constness. 11679 QualType FieldTy = Field->getType(); 11680 if (FieldTy.isConstQualified()) { 11681 if (!DiagnosticEmitted) { 11682 S.Diag(Loc, diag::err_typecheck_assign_const) 11683 << Range << NestedConstMember << OEK << VD 11684 << IsNested << Field; 11685 DiagnosticEmitted = true; 11686 } 11687 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11688 << NestedConstMember << IsNested << Field 11689 << FieldTy << Field->getSourceRange(); 11690 } 11691 11692 // Then we append it to the list to check next in order. 11693 FieldTy = FieldTy.getCanonicalType(); 11694 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11695 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11696 RecordTypeList.push_back(FieldRecTy); 11697 } 11698 } 11699 ++NextToCheckIndex; 11700 } 11701 } 11702 11703 /// Emit an error for the case where a record we are trying to assign to has a 11704 /// const-qualified field somewhere in its hierarchy. 11705 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11706 SourceLocation Loc) { 11707 QualType Ty = E->getType(); 11708 assert(Ty->isRecordType() && "lvalue was not record?"); 11709 SourceRange Range = E->getSourceRange(); 11710 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11711 bool DiagEmitted = false; 11712 11713 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11714 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11715 Range, OEK_Member, DiagEmitted); 11716 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11717 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11718 Range, OEK_Variable, DiagEmitted); 11719 else 11720 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11721 Range, OEK_LValue, DiagEmitted); 11722 if (!DiagEmitted) 11723 DiagnoseConstAssignment(S, E, Loc); 11724 } 11725 11726 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11727 /// emit an error and return true. If so, return false. 11728 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11729 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11730 11731 S.CheckShadowingDeclModification(E, Loc); 11732 11733 SourceLocation OrigLoc = Loc; 11734 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11735 &Loc); 11736 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11737 IsLV = Expr::MLV_InvalidMessageExpression; 11738 if (IsLV == Expr::MLV_Valid) 11739 return false; 11740 11741 unsigned DiagID = 0; 11742 bool NeedType = false; 11743 switch (IsLV) { // C99 6.5.16p2 11744 case Expr::MLV_ConstQualified: 11745 // Use a specialized diagnostic when we're assigning to an object 11746 // from an enclosing function or block. 11747 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11748 if (NCCK == NCCK_Block) 11749 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11750 else 11751 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11752 break; 11753 } 11754 11755 // In ARC, use some specialized diagnostics for occasions where we 11756 // infer 'const'. These are always pseudo-strong variables. 11757 if (S.getLangOpts().ObjCAutoRefCount) { 11758 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11759 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11760 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11761 11762 // Use the normal diagnostic if it's pseudo-__strong but the 11763 // user actually wrote 'const'. 11764 if (var->isARCPseudoStrong() && 11765 (!var->getTypeSourceInfo() || 11766 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11767 // There are three pseudo-strong cases: 11768 // - self 11769 ObjCMethodDecl *method = S.getCurMethodDecl(); 11770 if (method && var == method->getSelfDecl()) { 11771 DiagID = method->isClassMethod() 11772 ? diag::err_typecheck_arc_assign_self_class_method 11773 : diag::err_typecheck_arc_assign_self; 11774 11775 // - Objective-C externally_retained attribute. 11776 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11777 isa<ParmVarDecl>(var)) { 11778 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11779 11780 // - fast enumeration variables 11781 } else { 11782 DiagID = diag::err_typecheck_arr_assign_enumeration; 11783 } 11784 11785 SourceRange Assign; 11786 if (Loc != OrigLoc) 11787 Assign = SourceRange(OrigLoc, OrigLoc); 11788 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11789 // We need to preserve the AST regardless, so migration tool 11790 // can do its job. 11791 return false; 11792 } 11793 } 11794 } 11795 11796 // If none of the special cases above are triggered, then this is a 11797 // simple const assignment. 11798 if (DiagID == 0) { 11799 DiagnoseConstAssignment(S, E, Loc); 11800 return true; 11801 } 11802 11803 break; 11804 case Expr::MLV_ConstAddrSpace: 11805 DiagnoseConstAssignment(S, E, Loc); 11806 return true; 11807 case Expr::MLV_ConstQualifiedField: 11808 DiagnoseRecursiveConstFields(S, E, Loc); 11809 return true; 11810 case Expr::MLV_ArrayType: 11811 case Expr::MLV_ArrayTemporary: 11812 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11813 NeedType = true; 11814 break; 11815 case Expr::MLV_NotObjectType: 11816 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11817 NeedType = true; 11818 break; 11819 case Expr::MLV_LValueCast: 11820 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11821 break; 11822 case Expr::MLV_Valid: 11823 llvm_unreachable("did not take early return for MLV_Valid"); 11824 case Expr::MLV_InvalidExpression: 11825 case Expr::MLV_MemberFunction: 11826 case Expr::MLV_ClassTemporary: 11827 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11828 break; 11829 case Expr::MLV_IncompleteType: 11830 case Expr::MLV_IncompleteVoidType: 11831 return S.RequireCompleteType(Loc, E->getType(), 11832 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11833 case Expr::MLV_DuplicateVectorComponents: 11834 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11835 break; 11836 case Expr::MLV_NoSetterProperty: 11837 llvm_unreachable("readonly properties should be processed differently"); 11838 case Expr::MLV_InvalidMessageExpression: 11839 DiagID = diag::err_readonly_message_assignment; 11840 break; 11841 case Expr::MLV_SubObjCPropertySetting: 11842 DiagID = diag::err_no_subobject_property_setting; 11843 break; 11844 } 11845 11846 SourceRange Assign; 11847 if (Loc != OrigLoc) 11848 Assign = SourceRange(OrigLoc, OrigLoc); 11849 if (NeedType) 11850 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11851 else 11852 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11853 return true; 11854 } 11855 11856 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11857 SourceLocation Loc, 11858 Sema &Sema) { 11859 if (Sema.inTemplateInstantiation()) 11860 return; 11861 if (Sema.isUnevaluatedContext()) 11862 return; 11863 if (Loc.isInvalid() || Loc.isMacroID()) 11864 return; 11865 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11866 return; 11867 11868 // C / C++ fields 11869 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11870 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11871 if (ML && MR) { 11872 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11873 return; 11874 const ValueDecl *LHSDecl = 11875 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11876 const ValueDecl *RHSDecl = 11877 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11878 if (LHSDecl != RHSDecl) 11879 return; 11880 if (LHSDecl->getType().isVolatileQualified()) 11881 return; 11882 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11883 if (RefTy->getPointeeType().isVolatileQualified()) 11884 return; 11885 11886 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11887 } 11888 11889 // Objective-C instance variables 11890 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11891 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11892 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11893 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11894 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11895 if (RL && RR && RL->getDecl() == RR->getDecl()) 11896 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11897 } 11898 } 11899 11900 // C99 6.5.16.1 11901 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11902 SourceLocation Loc, 11903 QualType CompoundType) { 11904 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11905 11906 // Verify that LHS is a modifiable lvalue, and emit error if not. 11907 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11908 return QualType(); 11909 11910 QualType LHSType = LHSExpr->getType(); 11911 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11912 CompoundType; 11913 // OpenCL v1.2 s6.1.1.1 p2: 11914 // The half data type can only be used to declare a pointer to a buffer that 11915 // contains half values 11916 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11917 LHSType->isHalfType()) { 11918 Diag(Loc, diag::err_opencl_half_load_store) << 1 11919 << LHSType.getUnqualifiedType(); 11920 return QualType(); 11921 } 11922 11923 AssignConvertType ConvTy; 11924 if (CompoundType.isNull()) { 11925 Expr *RHSCheck = RHS.get(); 11926 11927 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11928 11929 QualType LHSTy(LHSType); 11930 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11931 if (RHS.isInvalid()) 11932 return QualType(); 11933 // Special case of NSObject attributes on c-style pointer types. 11934 if (ConvTy == IncompatiblePointer && 11935 ((Context.isObjCNSObjectType(LHSType) && 11936 RHSType->isObjCObjectPointerType()) || 11937 (Context.isObjCNSObjectType(RHSType) && 11938 LHSType->isObjCObjectPointerType()))) 11939 ConvTy = Compatible; 11940 11941 if (ConvTy == Compatible && 11942 LHSType->isObjCObjectType()) 11943 Diag(Loc, diag::err_objc_object_assignment) 11944 << LHSType; 11945 11946 // If the RHS is a unary plus or minus, check to see if they = and + are 11947 // right next to each other. If so, the user may have typo'd "x =+ 4" 11948 // instead of "x += 4". 11949 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11950 RHSCheck = ICE->getSubExpr(); 11951 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11952 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11953 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11954 // Only if the two operators are exactly adjacent. 11955 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11956 // And there is a space or other character before the subexpr of the 11957 // unary +/-. We don't want to warn on "x=-1". 11958 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11959 UO->getSubExpr()->getBeginLoc().isFileID()) { 11960 Diag(Loc, diag::warn_not_compound_assign) 11961 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11962 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11963 } 11964 } 11965 11966 if (ConvTy == Compatible) { 11967 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11968 // Warn about retain cycles where a block captures the LHS, but 11969 // not if the LHS is a simple variable into which the block is 11970 // being stored...unless that variable can be captured by reference! 11971 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11972 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11973 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11974 checkRetainCycles(LHSExpr, RHS.get()); 11975 } 11976 11977 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11978 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11979 // It is safe to assign a weak reference into a strong variable. 11980 // Although this code can still have problems: 11981 // id x = self.weakProp; 11982 // id y = self.weakProp; 11983 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11984 // paths through the function. This should be revisited if 11985 // -Wrepeated-use-of-weak is made flow-sensitive. 11986 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11987 // variable, which will be valid for the current autorelease scope. 11988 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11989 RHS.get()->getBeginLoc())) 11990 getCurFunction()->markSafeWeakUse(RHS.get()); 11991 11992 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11993 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11994 } 11995 } 11996 } else { 11997 // Compound assignment "x += y" 11998 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11999 } 12000 12001 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12002 RHS.get(), AA_Assigning)) 12003 return QualType(); 12004 12005 CheckForNullPointerDereference(*this, LHSExpr); 12006 12007 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12008 if (CompoundType.isNull()) { 12009 // C++2a [expr.ass]p5: 12010 // A simple-assignment whose left operand is of a volatile-qualified 12011 // type is deprecated unless the assignment is either a discarded-value 12012 // expression or an unevaluated operand 12013 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12014 } else { 12015 // C++2a [expr.ass]p6: 12016 // [Compound-assignment] expressions are deprecated if E1 has 12017 // volatile-qualified type 12018 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12019 } 12020 } 12021 12022 // C99 6.5.16p3: The type of an assignment expression is the type of the 12023 // left operand unless the left operand has qualified type, in which case 12024 // it is the unqualified version of the type of the left operand. 12025 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12026 // is converted to the type of the assignment expression (above). 12027 // C++ 5.17p1: the type of the assignment expression is that of its left 12028 // operand. 12029 return (getLangOpts().CPlusPlus 12030 ? LHSType : LHSType.getUnqualifiedType()); 12031 } 12032 12033 // Only ignore explicit casts to void. 12034 static bool IgnoreCommaOperand(const Expr *E) { 12035 E = E->IgnoreParens(); 12036 12037 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12038 if (CE->getCastKind() == CK_ToVoid) { 12039 return true; 12040 } 12041 12042 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12043 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12044 CE->getSubExpr()->getType()->isDependentType()) { 12045 return true; 12046 } 12047 } 12048 12049 return false; 12050 } 12051 12052 // Look for instances where it is likely the comma operator is confused with 12053 // another operator. There is a whitelist of acceptable expressions for the 12054 // left hand side of the comma operator, otherwise emit a warning. 12055 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12056 // No warnings in macros 12057 if (Loc.isMacroID()) 12058 return; 12059 12060 // Don't warn in template instantiations. 12061 if (inTemplateInstantiation()) 12062 return; 12063 12064 // Scope isn't fine-grained enough to whitelist the specific cases, so 12065 // instead, skip more than needed, then call back into here with the 12066 // CommaVisitor in SemaStmt.cpp. 12067 // The whitelisted locations are the initialization and increment portions 12068 // of a for loop. The additional checks are on the condition of 12069 // if statements, do/while loops, and for loops. 12070 // Differences in scope flags for C89 mode requires the extra logic. 12071 const unsigned ForIncrementFlags = 12072 getLangOpts().C99 || getLangOpts().CPlusPlus 12073 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12074 : Scope::ContinueScope | Scope::BreakScope; 12075 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12076 const unsigned ScopeFlags = getCurScope()->getFlags(); 12077 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12078 (ScopeFlags & ForInitFlags) == ForInitFlags) 12079 return; 12080 12081 // If there are multiple comma operators used together, get the RHS of the 12082 // of the comma operator as the LHS. 12083 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12084 if (BO->getOpcode() != BO_Comma) 12085 break; 12086 LHS = BO->getRHS(); 12087 } 12088 12089 // Only allow some expressions on LHS to not warn. 12090 if (IgnoreCommaOperand(LHS)) 12091 return; 12092 12093 Diag(Loc, diag::warn_comma_operator); 12094 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12095 << LHS->getSourceRange() 12096 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12097 LangOpts.CPlusPlus ? "static_cast<void>(" 12098 : "(void)(") 12099 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12100 ")"); 12101 } 12102 12103 // C99 6.5.17 12104 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12105 SourceLocation Loc) { 12106 LHS = S.CheckPlaceholderExpr(LHS.get()); 12107 RHS = S.CheckPlaceholderExpr(RHS.get()); 12108 if (LHS.isInvalid() || RHS.isInvalid()) 12109 return QualType(); 12110 12111 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12112 // operands, but not unary promotions. 12113 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12114 12115 // So we treat the LHS as a ignored value, and in C++ we allow the 12116 // containing site to determine what should be done with the RHS. 12117 LHS = S.IgnoredValueConversions(LHS.get()); 12118 if (LHS.isInvalid()) 12119 return QualType(); 12120 12121 S.DiagnoseUnusedExprResult(LHS.get()); 12122 12123 if (!S.getLangOpts().CPlusPlus) { 12124 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12125 if (RHS.isInvalid()) 12126 return QualType(); 12127 if (!RHS.get()->getType()->isVoidType()) 12128 S.RequireCompleteType(Loc, RHS.get()->getType(), 12129 diag::err_incomplete_type); 12130 } 12131 12132 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12133 S.DiagnoseCommaOperator(LHS.get(), Loc); 12134 12135 return RHS.get()->getType(); 12136 } 12137 12138 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12139 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12140 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12141 ExprValueKind &VK, 12142 ExprObjectKind &OK, 12143 SourceLocation OpLoc, 12144 bool IsInc, bool IsPrefix) { 12145 if (Op->isTypeDependent()) 12146 return S.Context.DependentTy; 12147 12148 QualType ResType = Op->getType(); 12149 // Atomic types can be used for increment / decrement where the non-atomic 12150 // versions can, so ignore the _Atomic() specifier for the purpose of 12151 // checking. 12152 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12153 ResType = ResAtomicType->getValueType(); 12154 12155 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12156 12157 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12158 // Decrement of bool is not allowed. 12159 if (!IsInc) { 12160 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12161 return QualType(); 12162 } 12163 // Increment of bool sets it to true, but is deprecated. 12164 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12165 : diag::warn_increment_bool) 12166 << Op->getSourceRange(); 12167 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12168 // Error on enum increments and decrements in C++ mode 12169 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12170 return QualType(); 12171 } else if (ResType->isRealType()) { 12172 // OK! 12173 } else if (ResType->isPointerType()) { 12174 // C99 6.5.2.4p2, 6.5.6p2 12175 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12176 return QualType(); 12177 } else if (ResType->isObjCObjectPointerType()) { 12178 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12179 // Otherwise, we just need a complete type. 12180 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12181 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12182 return QualType(); 12183 } else if (ResType->isAnyComplexType()) { 12184 // C99 does not support ++/-- on complex types, we allow as an extension. 12185 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12186 << ResType << Op->getSourceRange(); 12187 } else if (ResType->isPlaceholderType()) { 12188 ExprResult PR = S.CheckPlaceholderExpr(Op); 12189 if (PR.isInvalid()) return QualType(); 12190 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12191 IsInc, IsPrefix); 12192 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12193 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12194 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12195 (ResType->castAs<VectorType>()->getVectorKind() != 12196 VectorType::AltiVecBool)) { 12197 // The z vector extensions allow ++ and -- for non-bool vectors. 12198 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12199 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12200 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12201 } else { 12202 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12203 << ResType << int(IsInc) << Op->getSourceRange(); 12204 return QualType(); 12205 } 12206 // At this point, we know we have a real, complex or pointer type. 12207 // Now make sure the operand is a modifiable lvalue. 12208 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12209 return QualType(); 12210 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12211 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12212 // An operand with volatile-qualified type is deprecated 12213 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12214 << IsInc << ResType; 12215 } 12216 // In C++, a prefix increment is the same type as the operand. Otherwise 12217 // (in C or with postfix), the increment is the unqualified type of the 12218 // operand. 12219 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12220 VK = VK_LValue; 12221 OK = Op->getObjectKind(); 12222 return ResType; 12223 } else { 12224 VK = VK_RValue; 12225 return ResType.getUnqualifiedType(); 12226 } 12227 } 12228 12229 12230 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12231 /// This routine allows us to typecheck complex/recursive expressions 12232 /// where the declaration is needed for type checking. We only need to 12233 /// handle cases when the expression references a function designator 12234 /// or is an lvalue. Here are some examples: 12235 /// - &(x) => x 12236 /// - &*****f => f for f a function designator. 12237 /// - &s.xx => s 12238 /// - &s.zz[1].yy -> s, if zz is an array 12239 /// - *(x + 1) -> x, if x is an array 12240 /// - &"123"[2] -> 0 12241 /// - & __real__ x -> x 12242 static ValueDecl *getPrimaryDecl(Expr *E) { 12243 switch (E->getStmtClass()) { 12244 case Stmt::DeclRefExprClass: 12245 return cast<DeclRefExpr>(E)->getDecl(); 12246 case Stmt::MemberExprClass: 12247 // If this is an arrow operator, the address is an offset from 12248 // the base's value, so the object the base refers to is 12249 // irrelevant. 12250 if (cast<MemberExpr>(E)->isArrow()) 12251 return nullptr; 12252 // Otherwise, the expression refers to a part of the base 12253 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12254 case Stmt::ArraySubscriptExprClass: { 12255 // FIXME: This code shouldn't be necessary! We should catch the implicit 12256 // promotion of register arrays earlier. 12257 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12258 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12259 if (ICE->getSubExpr()->getType()->isArrayType()) 12260 return getPrimaryDecl(ICE->getSubExpr()); 12261 } 12262 return nullptr; 12263 } 12264 case Stmt::UnaryOperatorClass: { 12265 UnaryOperator *UO = cast<UnaryOperator>(E); 12266 12267 switch(UO->getOpcode()) { 12268 case UO_Real: 12269 case UO_Imag: 12270 case UO_Extension: 12271 return getPrimaryDecl(UO->getSubExpr()); 12272 default: 12273 return nullptr; 12274 } 12275 } 12276 case Stmt::ParenExprClass: 12277 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12278 case Stmt::ImplicitCastExprClass: 12279 // If the result of an implicit cast is an l-value, we care about 12280 // the sub-expression; otherwise, the result here doesn't matter. 12281 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12282 default: 12283 return nullptr; 12284 } 12285 } 12286 12287 namespace { 12288 enum { 12289 AO_Bit_Field = 0, 12290 AO_Vector_Element = 1, 12291 AO_Property_Expansion = 2, 12292 AO_Register_Variable = 3, 12293 AO_No_Error = 4 12294 }; 12295 } 12296 /// Diagnose invalid operand for address of operations. 12297 /// 12298 /// \param Type The type of operand which cannot have its address taken. 12299 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12300 Expr *E, unsigned Type) { 12301 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12302 } 12303 12304 /// CheckAddressOfOperand - The operand of & must be either a function 12305 /// designator or an lvalue designating an object. If it is an lvalue, the 12306 /// object cannot be declared with storage class register or be a bit field. 12307 /// Note: The usual conversions are *not* applied to the operand of the & 12308 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12309 /// In C++, the operand might be an overloaded function name, in which case 12310 /// we allow the '&' but retain the overloaded-function type. 12311 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12312 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12313 if (PTy->getKind() == BuiltinType::Overload) { 12314 Expr *E = OrigOp.get()->IgnoreParens(); 12315 if (!isa<OverloadExpr>(E)) { 12316 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12317 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12318 << OrigOp.get()->getSourceRange(); 12319 return QualType(); 12320 } 12321 12322 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12323 if (isa<UnresolvedMemberExpr>(Ovl)) 12324 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12325 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12326 << OrigOp.get()->getSourceRange(); 12327 return QualType(); 12328 } 12329 12330 return Context.OverloadTy; 12331 } 12332 12333 if (PTy->getKind() == BuiltinType::UnknownAny) 12334 return Context.UnknownAnyTy; 12335 12336 if (PTy->getKind() == BuiltinType::BoundMember) { 12337 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12338 << OrigOp.get()->getSourceRange(); 12339 return QualType(); 12340 } 12341 12342 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12343 if (OrigOp.isInvalid()) return QualType(); 12344 } 12345 12346 if (OrigOp.get()->isTypeDependent()) 12347 return Context.DependentTy; 12348 12349 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12350 12351 // Make sure to ignore parentheses in subsequent checks 12352 Expr *op = OrigOp.get()->IgnoreParens(); 12353 12354 // In OpenCL captures for blocks called as lambda functions 12355 // are located in the private address space. Blocks used in 12356 // enqueue_kernel can be located in a different address space 12357 // depending on a vendor implementation. Thus preventing 12358 // taking an address of the capture to avoid invalid AS casts. 12359 if (LangOpts.OpenCL) { 12360 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12361 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12362 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12363 return QualType(); 12364 } 12365 } 12366 12367 if (getLangOpts().C99) { 12368 // Implement C99-only parts of addressof rules. 12369 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12370 if (uOp->getOpcode() == UO_Deref) 12371 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12372 // (assuming the deref expression is valid). 12373 return uOp->getSubExpr()->getType(); 12374 } 12375 // Technically, there should be a check for array subscript 12376 // expressions here, but the result of one is always an lvalue anyway. 12377 } 12378 ValueDecl *dcl = getPrimaryDecl(op); 12379 12380 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12381 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12382 op->getBeginLoc())) 12383 return QualType(); 12384 12385 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12386 unsigned AddressOfError = AO_No_Error; 12387 12388 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12389 bool sfinae = (bool)isSFINAEContext(); 12390 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12391 : diag::ext_typecheck_addrof_temporary) 12392 << op->getType() << op->getSourceRange(); 12393 if (sfinae) 12394 return QualType(); 12395 // Materialize the temporary as an lvalue so that we can take its address. 12396 OrigOp = op = 12397 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12398 } else if (isa<ObjCSelectorExpr>(op)) { 12399 return Context.getPointerType(op->getType()); 12400 } else if (lval == Expr::LV_MemberFunction) { 12401 // If it's an instance method, make a member pointer. 12402 // The expression must have exactly the form &A::foo. 12403 12404 // If the underlying expression isn't a decl ref, give up. 12405 if (!isa<DeclRefExpr>(op)) { 12406 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12407 << OrigOp.get()->getSourceRange(); 12408 return QualType(); 12409 } 12410 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12411 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12412 12413 // The id-expression was parenthesized. 12414 if (OrigOp.get() != DRE) { 12415 Diag(OpLoc, diag::err_parens_pointer_member_function) 12416 << OrigOp.get()->getSourceRange(); 12417 12418 // The method was named without a qualifier. 12419 } else if (!DRE->getQualifier()) { 12420 if (MD->getParent()->getName().empty()) 12421 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12422 << op->getSourceRange(); 12423 else { 12424 SmallString<32> Str; 12425 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12426 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12427 << op->getSourceRange() 12428 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12429 } 12430 } 12431 12432 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12433 if (isa<CXXDestructorDecl>(MD)) 12434 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12435 12436 QualType MPTy = Context.getMemberPointerType( 12437 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12438 // Under the MS ABI, lock down the inheritance model now. 12439 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12440 (void)isCompleteType(OpLoc, MPTy); 12441 return MPTy; 12442 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12443 // C99 6.5.3.2p1 12444 // The operand must be either an l-value or a function designator 12445 if (!op->getType()->isFunctionType()) { 12446 // Use a special diagnostic for loads from property references. 12447 if (isa<PseudoObjectExpr>(op)) { 12448 AddressOfError = AO_Property_Expansion; 12449 } else { 12450 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12451 << op->getType() << op->getSourceRange(); 12452 return QualType(); 12453 } 12454 } 12455 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12456 // The operand cannot be a bit-field 12457 AddressOfError = AO_Bit_Field; 12458 } else if (op->getObjectKind() == OK_VectorComponent) { 12459 // The operand cannot be an element of a vector 12460 AddressOfError = AO_Vector_Element; 12461 } else if (dcl) { // C99 6.5.3.2p1 12462 // We have an lvalue with a decl. Make sure the decl is not declared 12463 // with the register storage-class specifier. 12464 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12465 // in C++ it is not error to take address of a register 12466 // variable (c++03 7.1.1P3) 12467 if (vd->getStorageClass() == SC_Register && 12468 !getLangOpts().CPlusPlus) { 12469 AddressOfError = AO_Register_Variable; 12470 } 12471 } else if (isa<MSPropertyDecl>(dcl)) { 12472 AddressOfError = AO_Property_Expansion; 12473 } else if (isa<FunctionTemplateDecl>(dcl)) { 12474 return Context.OverloadTy; 12475 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12476 // Okay: we can take the address of a field. 12477 // Could be a pointer to member, though, if there is an explicit 12478 // scope qualifier for the class. 12479 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12480 DeclContext *Ctx = dcl->getDeclContext(); 12481 if (Ctx && Ctx->isRecord()) { 12482 if (dcl->getType()->isReferenceType()) { 12483 Diag(OpLoc, 12484 diag::err_cannot_form_pointer_to_member_of_reference_type) 12485 << dcl->getDeclName() << dcl->getType(); 12486 return QualType(); 12487 } 12488 12489 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12490 Ctx = Ctx->getParent(); 12491 12492 QualType MPTy = Context.getMemberPointerType( 12493 op->getType(), 12494 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12495 // Under the MS ABI, lock down the inheritance model now. 12496 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12497 (void)isCompleteType(OpLoc, MPTy); 12498 return MPTy; 12499 } 12500 } 12501 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12502 !isa<BindingDecl>(dcl)) 12503 llvm_unreachable("Unknown/unexpected decl type"); 12504 } 12505 12506 if (AddressOfError != AO_No_Error) { 12507 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12508 return QualType(); 12509 } 12510 12511 if (lval == Expr::LV_IncompleteVoidType) { 12512 // Taking the address of a void variable is technically illegal, but we 12513 // allow it in cases which are otherwise valid. 12514 // Example: "extern void x; void* y = &x;". 12515 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12516 } 12517 12518 // If the operand has type "type", the result has type "pointer to type". 12519 if (op->getType()->isObjCObjectType()) 12520 return Context.getObjCObjectPointerType(op->getType()); 12521 12522 CheckAddressOfPackedMember(op); 12523 12524 return Context.getPointerType(op->getType()); 12525 } 12526 12527 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12528 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12529 if (!DRE) 12530 return; 12531 const Decl *D = DRE->getDecl(); 12532 if (!D) 12533 return; 12534 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12535 if (!Param) 12536 return; 12537 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12538 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12539 return; 12540 if (FunctionScopeInfo *FD = S.getCurFunction()) 12541 if (!FD->ModifiedNonNullParams.count(Param)) 12542 FD->ModifiedNonNullParams.insert(Param); 12543 } 12544 12545 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12546 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12547 SourceLocation OpLoc) { 12548 if (Op->isTypeDependent()) 12549 return S.Context.DependentTy; 12550 12551 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12552 if (ConvResult.isInvalid()) 12553 return QualType(); 12554 Op = ConvResult.get(); 12555 QualType OpTy = Op->getType(); 12556 QualType Result; 12557 12558 if (isa<CXXReinterpretCastExpr>(Op)) { 12559 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12560 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12561 Op->getSourceRange()); 12562 } 12563 12564 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12565 { 12566 Result = PT->getPointeeType(); 12567 } 12568 else if (const ObjCObjectPointerType *OPT = 12569 OpTy->getAs<ObjCObjectPointerType>()) 12570 Result = OPT->getPointeeType(); 12571 else { 12572 ExprResult PR = S.CheckPlaceholderExpr(Op); 12573 if (PR.isInvalid()) return QualType(); 12574 if (PR.get() != Op) 12575 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12576 } 12577 12578 if (Result.isNull()) { 12579 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12580 << OpTy << Op->getSourceRange(); 12581 return QualType(); 12582 } 12583 12584 // Note that per both C89 and C99, indirection is always legal, even if Result 12585 // is an incomplete type or void. It would be possible to warn about 12586 // dereferencing a void pointer, but it's completely well-defined, and such a 12587 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12588 // for pointers to 'void' but is fine for any other pointer type: 12589 // 12590 // C++ [expr.unary.op]p1: 12591 // [...] the expression to which [the unary * operator] is applied shall 12592 // be a pointer to an object type, or a pointer to a function type 12593 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12594 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12595 << OpTy << Op->getSourceRange(); 12596 12597 // Dereferences are usually l-values... 12598 VK = VK_LValue; 12599 12600 // ...except that certain expressions are never l-values in C. 12601 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12602 VK = VK_RValue; 12603 12604 return Result; 12605 } 12606 12607 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12608 BinaryOperatorKind Opc; 12609 switch (Kind) { 12610 default: llvm_unreachable("Unknown binop!"); 12611 case tok::periodstar: Opc = BO_PtrMemD; break; 12612 case tok::arrowstar: Opc = BO_PtrMemI; break; 12613 case tok::star: Opc = BO_Mul; break; 12614 case tok::slash: Opc = BO_Div; break; 12615 case tok::percent: Opc = BO_Rem; break; 12616 case tok::plus: Opc = BO_Add; break; 12617 case tok::minus: Opc = BO_Sub; break; 12618 case tok::lessless: Opc = BO_Shl; break; 12619 case tok::greatergreater: Opc = BO_Shr; break; 12620 case tok::lessequal: Opc = BO_LE; break; 12621 case tok::less: Opc = BO_LT; break; 12622 case tok::greaterequal: Opc = BO_GE; break; 12623 case tok::greater: Opc = BO_GT; break; 12624 case tok::exclaimequal: Opc = BO_NE; break; 12625 case tok::equalequal: Opc = BO_EQ; break; 12626 case tok::spaceship: Opc = BO_Cmp; break; 12627 case tok::amp: Opc = BO_And; break; 12628 case tok::caret: Opc = BO_Xor; break; 12629 case tok::pipe: Opc = BO_Or; break; 12630 case tok::ampamp: Opc = BO_LAnd; break; 12631 case tok::pipepipe: Opc = BO_LOr; break; 12632 case tok::equal: Opc = BO_Assign; break; 12633 case tok::starequal: Opc = BO_MulAssign; break; 12634 case tok::slashequal: Opc = BO_DivAssign; break; 12635 case tok::percentequal: Opc = BO_RemAssign; break; 12636 case tok::plusequal: Opc = BO_AddAssign; break; 12637 case tok::minusequal: Opc = BO_SubAssign; break; 12638 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12639 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12640 case tok::ampequal: Opc = BO_AndAssign; break; 12641 case tok::caretequal: Opc = BO_XorAssign; break; 12642 case tok::pipeequal: Opc = BO_OrAssign; break; 12643 case tok::comma: Opc = BO_Comma; break; 12644 } 12645 return Opc; 12646 } 12647 12648 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12649 tok::TokenKind Kind) { 12650 UnaryOperatorKind Opc; 12651 switch (Kind) { 12652 default: llvm_unreachable("Unknown unary op!"); 12653 case tok::plusplus: Opc = UO_PreInc; break; 12654 case tok::minusminus: Opc = UO_PreDec; break; 12655 case tok::amp: Opc = UO_AddrOf; break; 12656 case tok::star: Opc = UO_Deref; break; 12657 case tok::plus: Opc = UO_Plus; break; 12658 case tok::minus: Opc = UO_Minus; break; 12659 case tok::tilde: Opc = UO_Not; break; 12660 case tok::exclaim: Opc = UO_LNot; break; 12661 case tok::kw___real: Opc = UO_Real; break; 12662 case tok::kw___imag: Opc = UO_Imag; break; 12663 case tok::kw___extension__: Opc = UO_Extension; break; 12664 } 12665 return Opc; 12666 } 12667 12668 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12669 /// This warning suppressed in the event of macro expansions. 12670 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12671 SourceLocation OpLoc, bool IsBuiltin) { 12672 if (S.inTemplateInstantiation()) 12673 return; 12674 if (S.isUnevaluatedContext()) 12675 return; 12676 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12677 return; 12678 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12679 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12680 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12681 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12682 if (!LHSDeclRef || !RHSDeclRef || 12683 LHSDeclRef->getLocation().isMacroID() || 12684 RHSDeclRef->getLocation().isMacroID()) 12685 return; 12686 const ValueDecl *LHSDecl = 12687 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12688 const ValueDecl *RHSDecl = 12689 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12690 if (LHSDecl != RHSDecl) 12691 return; 12692 if (LHSDecl->getType().isVolatileQualified()) 12693 return; 12694 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12695 if (RefTy->getPointeeType().isVolatileQualified()) 12696 return; 12697 12698 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12699 : diag::warn_self_assignment_overloaded) 12700 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12701 << RHSExpr->getSourceRange(); 12702 } 12703 12704 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12705 /// is usually indicative of introspection within the Objective-C pointer. 12706 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12707 SourceLocation OpLoc) { 12708 if (!S.getLangOpts().ObjC) 12709 return; 12710 12711 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12712 const Expr *LHS = L.get(); 12713 const Expr *RHS = R.get(); 12714 12715 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12716 ObjCPointerExpr = LHS; 12717 OtherExpr = RHS; 12718 } 12719 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12720 ObjCPointerExpr = RHS; 12721 OtherExpr = LHS; 12722 } 12723 12724 // This warning is deliberately made very specific to reduce false 12725 // positives with logic that uses '&' for hashing. This logic mainly 12726 // looks for code trying to introspect into tagged pointers, which 12727 // code should generally never do. 12728 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12729 unsigned Diag = diag::warn_objc_pointer_masking; 12730 // Determine if we are introspecting the result of performSelectorXXX. 12731 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12732 // Special case messages to -performSelector and friends, which 12733 // can return non-pointer values boxed in a pointer value. 12734 // Some clients may wish to silence warnings in this subcase. 12735 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12736 Selector S = ME->getSelector(); 12737 StringRef SelArg0 = S.getNameForSlot(0); 12738 if (SelArg0.startswith("performSelector")) 12739 Diag = diag::warn_objc_pointer_masking_performSelector; 12740 } 12741 12742 S.Diag(OpLoc, Diag) 12743 << ObjCPointerExpr->getSourceRange(); 12744 } 12745 } 12746 12747 static NamedDecl *getDeclFromExpr(Expr *E) { 12748 if (!E) 12749 return nullptr; 12750 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12751 return DRE->getDecl(); 12752 if (auto *ME = dyn_cast<MemberExpr>(E)) 12753 return ME->getMemberDecl(); 12754 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12755 return IRE->getDecl(); 12756 return nullptr; 12757 } 12758 12759 // This helper function promotes a binary operator's operands (which are of a 12760 // half vector type) to a vector of floats and then truncates the result to 12761 // a vector of either half or short. 12762 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12763 BinaryOperatorKind Opc, QualType ResultTy, 12764 ExprValueKind VK, ExprObjectKind OK, 12765 bool IsCompAssign, SourceLocation OpLoc, 12766 FPOptions FPFeatures) { 12767 auto &Context = S.getASTContext(); 12768 assert((isVector(ResultTy, Context.HalfTy) || 12769 isVector(ResultTy, Context.ShortTy)) && 12770 "Result must be a vector of half or short"); 12771 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12772 isVector(RHS.get()->getType(), Context.HalfTy) && 12773 "both operands expected to be a half vector"); 12774 12775 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12776 QualType BinOpResTy = RHS.get()->getType(); 12777 12778 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12779 // change BinOpResTy to a vector of ints. 12780 if (isVector(ResultTy, Context.ShortTy)) 12781 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12782 12783 if (IsCompAssign) 12784 return new (Context) CompoundAssignOperator( 12785 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12786 OpLoc, FPFeatures); 12787 12788 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12789 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12790 VK, OK, OpLoc, FPFeatures); 12791 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12792 } 12793 12794 static std::pair<ExprResult, ExprResult> 12795 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12796 Expr *RHSExpr) { 12797 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12798 if (!S.getLangOpts().CPlusPlus) { 12799 // C cannot handle TypoExpr nodes on either side of a binop because it 12800 // doesn't handle dependent types properly, so make sure any TypoExprs have 12801 // been dealt with before checking the operands. 12802 LHS = S.CorrectDelayedTyposInExpr(LHS); 12803 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12804 if (Opc != BO_Assign) 12805 return ExprResult(E); 12806 // Avoid correcting the RHS to the same Expr as the LHS. 12807 Decl *D = getDeclFromExpr(E); 12808 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12809 }); 12810 } 12811 return std::make_pair(LHS, RHS); 12812 } 12813 12814 /// Returns true if conversion between vectors of halfs and vectors of floats 12815 /// is needed. 12816 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12817 QualType SrcType) { 12818 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12819 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12820 isVector(SrcType, Ctx.HalfTy); 12821 } 12822 12823 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12824 /// operator @p Opc at location @c TokLoc. This routine only supports 12825 /// built-in operations; ActOnBinOp handles overloaded operators. 12826 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12827 BinaryOperatorKind Opc, 12828 Expr *LHSExpr, Expr *RHSExpr) { 12829 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12830 // The syntax only allows initializer lists on the RHS of assignment, 12831 // so we don't need to worry about accepting invalid code for 12832 // non-assignment operators. 12833 // C++11 5.17p9: 12834 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12835 // of x = {} is x = T(). 12836 InitializationKind Kind = InitializationKind::CreateDirectList( 12837 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12838 InitializedEntity Entity = 12839 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12840 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12841 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12842 if (Init.isInvalid()) 12843 return Init; 12844 RHSExpr = Init.get(); 12845 } 12846 12847 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12848 QualType ResultTy; // Result type of the binary operator. 12849 // The following two variables are used for compound assignment operators 12850 QualType CompLHSTy; // Type of LHS after promotions for computation 12851 QualType CompResultTy; // Type of computation result 12852 ExprValueKind VK = VK_RValue; 12853 ExprObjectKind OK = OK_Ordinary; 12854 bool ConvertHalfVec = false; 12855 12856 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12857 if (!LHS.isUsable() || !RHS.isUsable()) 12858 return ExprError(); 12859 12860 if (getLangOpts().OpenCL) { 12861 QualType LHSTy = LHSExpr->getType(); 12862 QualType RHSTy = RHSExpr->getType(); 12863 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12864 // the ATOMIC_VAR_INIT macro. 12865 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12866 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12867 if (BO_Assign == Opc) 12868 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12869 else 12870 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12871 return ExprError(); 12872 } 12873 12874 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12875 // only with a builtin functions and therefore should be disallowed here. 12876 if (LHSTy->isImageType() || RHSTy->isImageType() || 12877 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12878 LHSTy->isPipeType() || RHSTy->isPipeType() || 12879 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12880 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12881 return ExprError(); 12882 } 12883 } 12884 12885 // Diagnose operations on the unsupported types for OpenMP device compilation. 12886 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12887 if (Opc != BO_Assign && Opc != BO_Comma) { 12888 checkOpenMPDeviceExpr(LHSExpr); 12889 checkOpenMPDeviceExpr(RHSExpr); 12890 } 12891 } 12892 12893 switch (Opc) { 12894 case BO_Assign: 12895 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12896 if (getLangOpts().CPlusPlus && 12897 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12898 VK = LHS.get()->getValueKind(); 12899 OK = LHS.get()->getObjectKind(); 12900 } 12901 if (!ResultTy.isNull()) { 12902 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12903 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12904 12905 // Avoid copying a block to the heap if the block is assigned to a local 12906 // auto variable that is declared in the same scope as the block. This 12907 // optimization is unsafe if the local variable is declared in an outer 12908 // scope. For example: 12909 // 12910 // BlockTy b; 12911 // { 12912 // b = ^{...}; 12913 // } 12914 // // It is unsafe to invoke the block here if it wasn't copied to the 12915 // // heap. 12916 // b(); 12917 12918 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12919 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12920 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12921 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12922 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12923 12924 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12925 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12926 NTCUC_Assignment, NTCUK_Copy); 12927 } 12928 RecordModifiableNonNullParam(*this, LHS.get()); 12929 break; 12930 case BO_PtrMemD: 12931 case BO_PtrMemI: 12932 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12933 Opc == BO_PtrMemI); 12934 break; 12935 case BO_Mul: 12936 case BO_Div: 12937 ConvertHalfVec = true; 12938 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12939 Opc == BO_Div); 12940 break; 12941 case BO_Rem: 12942 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12943 break; 12944 case BO_Add: 12945 ConvertHalfVec = true; 12946 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12947 break; 12948 case BO_Sub: 12949 ConvertHalfVec = true; 12950 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12951 break; 12952 case BO_Shl: 12953 case BO_Shr: 12954 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12955 break; 12956 case BO_LE: 12957 case BO_LT: 12958 case BO_GE: 12959 case BO_GT: 12960 ConvertHalfVec = true; 12961 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12962 break; 12963 case BO_EQ: 12964 case BO_NE: 12965 ConvertHalfVec = true; 12966 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12967 break; 12968 case BO_Cmp: 12969 ConvertHalfVec = true; 12970 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12971 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12972 break; 12973 case BO_And: 12974 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12975 LLVM_FALLTHROUGH; 12976 case BO_Xor: 12977 case BO_Or: 12978 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12979 break; 12980 case BO_LAnd: 12981 case BO_LOr: 12982 ConvertHalfVec = true; 12983 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12984 break; 12985 case BO_MulAssign: 12986 case BO_DivAssign: 12987 ConvertHalfVec = true; 12988 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12989 Opc == BO_DivAssign); 12990 CompLHSTy = CompResultTy; 12991 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12992 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12993 break; 12994 case BO_RemAssign: 12995 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12996 CompLHSTy = CompResultTy; 12997 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12998 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12999 break; 13000 case BO_AddAssign: 13001 ConvertHalfVec = true; 13002 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13003 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13004 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13005 break; 13006 case BO_SubAssign: 13007 ConvertHalfVec = true; 13008 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13009 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13010 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13011 break; 13012 case BO_ShlAssign: 13013 case BO_ShrAssign: 13014 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13015 CompLHSTy = CompResultTy; 13016 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13017 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13018 break; 13019 case BO_AndAssign: 13020 case BO_OrAssign: // fallthrough 13021 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13022 LLVM_FALLTHROUGH; 13023 case BO_XorAssign: 13024 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13025 CompLHSTy = CompResultTy; 13026 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13027 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13028 break; 13029 case BO_Comma: 13030 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13031 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13032 VK = RHS.get()->getValueKind(); 13033 OK = RHS.get()->getObjectKind(); 13034 } 13035 break; 13036 } 13037 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13038 return ExprError(); 13039 13040 // Some of the binary operations require promoting operands of half vector to 13041 // float vectors and truncating the result back to half vector. For now, we do 13042 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13043 // arm64). 13044 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13045 isVector(LHS.get()->getType(), Context.HalfTy) && 13046 "both sides are half vectors or neither sides are"); 13047 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13048 LHS.get()->getType()); 13049 13050 // Check for array bounds violations for both sides of the BinaryOperator 13051 CheckArrayAccess(LHS.get()); 13052 CheckArrayAccess(RHS.get()); 13053 13054 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13055 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13056 &Context.Idents.get("object_setClass"), 13057 SourceLocation(), LookupOrdinaryName); 13058 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13059 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13060 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13061 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13062 "object_setClass(") 13063 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13064 ",") 13065 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13066 } 13067 else 13068 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13069 } 13070 else if (const ObjCIvarRefExpr *OIRE = 13071 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13072 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13073 13074 // Opc is not a compound assignment if CompResultTy is null. 13075 if (CompResultTy.isNull()) { 13076 if (ConvertHalfVec) 13077 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13078 OpLoc, FPFeatures); 13079 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13080 OK, OpLoc, FPFeatures); 13081 } 13082 13083 // Handle compound assignments. 13084 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13085 OK_ObjCProperty) { 13086 VK = VK_LValue; 13087 OK = LHS.get()->getObjectKind(); 13088 } 13089 13090 if (ConvertHalfVec) 13091 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13092 OpLoc, FPFeatures); 13093 13094 return new (Context) CompoundAssignOperator( 13095 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13096 OpLoc, FPFeatures); 13097 } 13098 13099 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13100 /// operators are mixed in a way that suggests that the programmer forgot that 13101 /// comparison operators have higher precedence. The most typical example of 13102 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13103 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13104 SourceLocation OpLoc, Expr *LHSExpr, 13105 Expr *RHSExpr) { 13106 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13107 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13108 13109 // Check that one of the sides is a comparison operator and the other isn't. 13110 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13111 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13112 if (isLeftComp == isRightComp) 13113 return; 13114 13115 // Bitwise operations are sometimes used as eager logical ops. 13116 // Don't diagnose this. 13117 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13118 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13119 if (isLeftBitwise || isRightBitwise) 13120 return; 13121 13122 SourceRange DiagRange = isLeftComp 13123 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13124 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13125 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13126 SourceRange ParensRange = 13127 isLeftComp 13128 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13129 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13130 13131 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13132 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13133 SuggestParentheses(Self, OpLoc, 13134 Self.PDiag(diag::note_precedence_silence) << OpStr, 13135 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13136 SuggestParentheses(Self, OpLoc, 13137 Self.PDiag(diag::note_precedence_bitwise_first) 13138 << BinaryOperator::getOpcodeStr(Opc), 13139 ParensRange); 13140 } 13141 13142 /// It accepts a '&&' expr that is inside a '||' one. 13143 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13144 /// in parentheses. 13145 static void 13146 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13147 BinaryOperator *Bop) { 13148 assert(Bop->getOpcode() == BO_LAnd); 13149 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13150 << Bop->getSourceRange() << OpLoc; 13151 SuggestParentheses(Self, Bop->getOperatorLoc(), 13152 Self.PDiag(diag::note_precedence_silence) 13153 << Bop->getOpcodeStr(), 13154 Bop->getSourceRange()); 13155 } 13156 13157 /// Returns true if the given expression can be evaluated as a constant 13158 /// 'true'. 13159 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13160 bool Res; 13161 return !E->isValueDependent() && 13162 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13163 } 13164 13165 /// Returns true if the given expression can be evaluated as a constant 13166 /// 'false'. 13167 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13168 bool Res; 13169 return !E->isValueDependent() && 13170 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13171 } 13172 13173 /// Look for '&&' in the left hand of a '||' expr. 13174 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13175 Expr *LHSExpr, Expr *RHSExpr) { 13176 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13177 if (Bop->getOpcode() == BO_LAnd) { 13178 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13179 if (EvaluatesAsFalse(S, RHSExpr)) 13180 return; 13181 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13182 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13183 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13184 } else if (Bop->getOpcode() == BO_LOr) { 13185 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13186 // If it's "a || b && 1 || c" we didn't warn earlier for 13187 // "a || b && 1", but warn now. 13188 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13189 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13190 } 13191 } 13192 } 13193 } 13194 13195 /// Look for '&&' in the right hand of a '||' expr. 13196 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13197 Expr *LHSExpr, Expr *RHSExpr) { 13198 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13199 if (Bop->getOpcode() == BO_LAnd) { 13200 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13201 if (EvaluatesAsFalse(S, LHSExpr)) 13202 return; 13203 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13204 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13205 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13206 } 13207 } 13208 } 13209 13210 /// Look for bitwise op in the left or right hand of a bitwise op with 13211 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13212 /// the '&' expression in parentheses. 13213 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13214 SourceLocation OpLoc, Expr *SubExpr) { 13215 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13216 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13217 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13218 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13219 << Bop->getSourceRange() << OpLoc; 13220 SuggestParentheses(S, Bop->getOperatorLoc(), 13221 S.PDiag(diag::note_precedence_silence) 13222 << Bop->getOpcodeStr(), 13223 Bop->getSourceRange()); 13224 } 13225 } 13226 } 13227 13228 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13229 Expr *SubExpr, StringRef Shift) { 13230 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13231 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13232 StringRef Op = Bop->getOpcodeStr(); 13233 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13234 << Bop->getSourceRange() << OpLoc << Shift << Op; 13235 SuggestParentheses(S, Bop->getOperatorLoc(), 13236 S.PDiag(diag::note_precedence_silence) << Op, 13237 Bop->getSourceRange()); 13238 } 13239 } 13240 } 13241 13242 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13243 Expr *LHSExpr, Expr *RHSExpr) { 13244 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13245 if (!OCE) 13246 return; 13247 13248 FunctionDecl *FD = OCE->getDirectCallee(); 13249 if (!FD || !FD->isOverloadedOperator()) 13250 return; 13251 13252 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13253 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13254 return; 13255 13256 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13257 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13258 << (Kind == OO_LessLess); 13259 SuggestParentheses(S, OCE->getOperatorLoc(), 13260 S.PDiag(diag::note_precedence_silence) 13261 << (Kind == OO_LessLess ? "<<" : ">>"), 13262 OCE->getSourceRange()); 13263 SuggestParentheses( 13264 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13265 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13266 } 13267 13268 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13269 /// precedence. 13270 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13271 SourceLocation OpLoc, Expr *LHSExpr, 13272 Expr *RHSExpr){ 13273 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13274 if (BinaryOperator::isBitwiseOp(Opc)) 13275 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13276 13277 // Diagnose "arg1 & arg2 | arg3" 13278 if ((Opc == BO_Or || Opc == BO_Xor) && 13279 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13280 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13281 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13282 } 13283 13284 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13285 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13286 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13287 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13288 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13289 } 13290 13291 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13292 || Opc == BO_Shr) { 13293 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13294 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13295 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13296 } 13297 13298 // Warn on overloaded shift operators and comparisons, such as: 13299 // cout << 5 == 4; 13300 if (BinaryOperator::isComparisonOp(Opc)) 13301 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13302 } 13303 13304 // Binary Operators. 'Tok' is the token for the operator. 13305 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13306 tok::TokenKind Kind, 13307 Expr *LHSExpr, Expr *RHSExpr) { 13308 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13309 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13310 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13311 13312 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13313 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13314 13315 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13316 } 13317 13318 /// Build an overloaded binary operator expression in the given scope. 13319 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13320 BinaryOperatorKind Opc, 13321 Expr *LHS, Expr *RHS) { 13322 switch (Opc) { 13323 case BO_Assign: 13324 case BO_DivAssign: 13325 case BO_RemAssign: 13326 case BO_SubAssign: 13327 case BO_AndAssign: 13328 case BO_OrAssign: 13329 case BO_XorAssign: 13330 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13331 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13332 break; 13333 default: 13334 break; 13335 } 13336 13337 // Find all of the overloaded operators visible from this 13338 // point. We perform both an operator-name lookup from the local 13339 // scope and an argument-dependent lookup based on the types of 13340 // the arguments. 13341 UnresolvedSet<16> Functions; 13342 OverloadedOperatorKind OverOp 13343 = BinaryOperator::getOverloadedOperator(Opc); 13344 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13345 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13346 RHS->getType(), Functions); 13347 13348 // In C++20 onwards, we may have a second operator to look up. 13349 if (S.getLangOpts().CPlusPlus2a) { 13350 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13351 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13352 RHS->getType(), Functions); 13353 } 13354 13355 // Build the (potentially-overloaded, potentially-dependent) 13356 // binary operation. 13357 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13358 } 13359 13360 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13361 BinaryOperatorKind Opc, 13362 Expr *LHSExpr, Expr *RHSExpr) { 13363 ExprResult LHS, RHS; 13364 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13365 if (!LHS.isUsable() || !RHS.isUsable()) 13366 return ExprError(); 13367 LHSExpr = LHS.get(); 13368 RHSExpr = RHS.get(); 13369 13370 // We want to end up calling one of checkPseudoObjectAssignment 13371 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13372 // both expressions are overloadable or either is type-dependent), 13373 // or CreateBuiltinBinOp (in any other case). We also want to get 13374 // any placeholder types out of the way. 13375 13376 // Handle pseudo-objects in the LHS. 13377 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13378 // Assignments with a pseudo-object l-value need special analysis. 13379 if (pty->getKind() == BuiltinType::PseudoObject && 13380 BinaryOperator::isAssignmentOp(Opc)) 13381 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13382 13383 // Don't resolve overloads if the other type is overloadable. 13384 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13385 // We can't actually test that if we still have a placeholder, 13386 // though. Fortunately, none of the exceptions we see in that 13387 // code below are valid when the LHS is an overload set. Note 13388 // that an overload set can be dependently-typed, but it never 13389 // instantiates to having an overloadable type. 13390 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13391 if (resolvedRHS.isInvalid()) return ExprError(); 13392 RHSExpr = resolvedRHS.get(); 13393 13394 if (RHSExpr->isTypeDependent() || 13395 RHSExpr->getType()->isOverloadableType()) 13396 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13397 } 13398 13399 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13400 // template, diagnose the missing 'template' keyword instead of diagnosing 13401 // an invalid use of a bound member function. 13402 // 13403 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13404 // to C++1z [over.over]/1.4, but we already checked for that case above. 13405 if (Opc == BO_LT && inTemplateInstantiation() && 13406 (pty->getKind() == BuiltinType::BoundMember || 13407 pty->getKind() == BuiltinType::Overload)) { 13408 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13409 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13410 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13411 return isa<FunctionTemplateDecl>(ND); 13412 })) { 13413 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13414 : OE->getNameLoc(), 13415 diag::err_template_kw_missing) 13416 << OE->getName().getAsString() << ""; 13417 return ExprError(); 13418 } 13419 } 13420 13421 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13422 if (LHS.isInvalid()) return ExprError(); 13423 LHSExpr = LHS.get(); 13424 } 13425 13426 // Handle pseudo-objects in the RHS. 13427 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13428 // An overload in the RHS can potentially be resolved by the type 13429 // being assigned to. 13430 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13431 if (getLangOpts().CPlusPlus && 13432 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13433 LHSExpr->getType()->isOverloadableType())) 13434 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13435 13436 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13437 } 13438 13439 // Don't resolve overloads if the other type is overloadable. 13440 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13441 LHSExpr->getType()->isOverloadableType()) 13442 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13443 13444 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13445 if (!resolvedRHS.isUsable()) return ExprError(); 13446 RHSExpr = resolvedRHS.get(); 13447 } 13448 13449 if (getLangOpts().CPlusPlus) { 13450 // If either expression is type-dependent, always build an 13451 // overloaded op. 13452 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13453 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13454 13455 // Otherwise, build an overloaded op if either expression has an 13456 // overloadable type. 13457 if (LHSExpr->getType()->isOverloadableType() || 13458 RHSExpr->getType()->isOverloadableType()) 13459 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13460 } 13461 13462 // Build a built-in binary operation. 13463 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13464 } 13465 13466 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13467 if (T.isNull() || T->isDependentType()) 13468 return false; 13469 13470 if (!T->isPromotableIntegerType()) 13471 return true; 13472 13473 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13474 } 13475 13476 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13477 UnaryOperatorKind Opc, 13478 Expr *InputExpr) { 13479 ExprResult Input = InputExpr; 13480 ExprValueKind VK = VK_RValue; 13481 ExprObjectKind OK = OK_Ordinary; 13482 QualType resultType; 13483 bool CanOverflow = false; 13484 13485 bool ConvertHalfVec = false; 13486 if (getLangOpts().OpenCL) { 13487 QualType Ty = InputExpr->getType(); 13488 // The only legal unary operation for atomics is '&'. 13489 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13490 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13491 // only with a builtin functions and therefore should be disallowed here. 13492 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13493 || Ty->isBlockPointerType())) { 13494 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13495 << InputExpr->getType() 13496 << Input.get()->getSourceRange()); 13497 } 13498 } 13499 // Diagnose operations on the unsupported types for OpenMP device compilation. 13500 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13501 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13502 UnaryOperator::isArithmeticOp(Opc)) 13503 checkOpenMPDeviceExpr(InputExpr); 13504 } 13505 13506 switch (Opc) { 13507 case UO_PreInc: 13508 case UO_PreDec: 13509 case UO_PostInc: 13510 case UO_PostDec: 13511 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13512 OpLoc, 13513 Opc == UO_PreInc || 13514 Opc == UO_PostInc, 13515 Opc == UO_PreInc || 13516 Opc == UO_PreDec); 13517 CanOverflow = isOverflowingIntegerType(Context, resultType); 13518 break; 13519 case UO_AddrOf: 13520 resultType = CheckAddressOfOperand(Input, OpLoc); 13521 CheckAddressOfNoDeref(InputExpr); 13522 RecordModifiableNonNullParam(*this, InputExpr); 13523 break; 13524 case UO_Deref: { 13525 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13526 if (Input.isInvalid()) return ExprError(); 13527 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13528 break; 13529 } 13530 case UO_Plus: 13531 case UO_Minus: 13532 CanOverflow = Opc == UO_Minus && 13533 isOverflowingIntegerType(Context, Input.get()->getType()); 13534 Input = UsualUnaryConversions(Input.get()); 13535 if (Input.isInvalid()) return ExprError(); 13536 // Unary plus and minus require promoting an operand of half vector to a 13537 // float vector and truncating the result back to a half vector. For now, we 13538 // do this only when HalfArgsAndReturns is set (that is, when the target is 13539 // arm or arm64). 13540 ConvertHalfVec = 13541 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13542 13543 // If the operand is a half vector, promote it to a float vector. 13544 if (ConvertHalfVec) 13545 Input = convertVector(Input.get(), Context.FloatTy, *this); 13546 resultType = Input.get()->getType(); 13547 if (resultType->isDependentType()) 13548 break; 13549 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13550 break; 13551 else if (resultType->isVectorType() && 13552 // The z vector extensions don't allow + or - with bool vectors. 13553 (!Context.getLangOpts().ZVector || 13554 resultType->castAs<VectorType>()->getVectorKind() != 13555 VectorType::AltiVecBool)) 13556 break; 13557 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13558 Opc == UO_Plus && 13559 resultType->isPointerType()) 13560 break; 13561 13562 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13563 << resultType << Input.get()->getSourceRange()); 13564 13565 case UO_Not: // bitwise complement 13566 Input = UsualUnaryConversions(Input.get()); 13567 if (Input.isInvalid()) 13568 return ExprError(); 13569 resultType = Input.get()->getType(); 13570 if (resultType->isDependentType()) 13571 break; 13572 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13573 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13574 // C99 does not support '~' for complex conjugation. 13575 Diag(OpLoc, diag::ext_integer_complement_complex) 13576 << resultType << Input.get()->getSourceRange(); 13577 else if (resultType->hasIntegerRepresentation()) 13578 break; 13579 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13580 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13581 // on vector float types. 13582 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13583 if (!T->isIntegerType()) 13584 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13585 << resultType << Input.get()->getSourceRange()); 13586 } else { 13587 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13588 << resultType << Input.get()->getSourceRange()); 13589 } 13590 break; 13591 13592 case UO_LNot: // logical negation 13593 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13594 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13595 if (Input.isInvalid()) return ExprError(); 13596 resultType = Input.get()->getType(); 13597 13598 // Though we still have to promote half FP to float... 13599 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13600 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13601 resultType = Context.FloatTy; 13602 } 13603 13604 if (resultType->isDependentType()) 13605 break; 13606 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13607 // C99 6.5.3.3p1: ok, fallthrough; 13608 if (Context.getLangOpts().CPlusPlus) { 13609 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13610 // operand contextually converted to bool. 13611 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13612 ScalarTypeToBooleanCastKind(resultType)); 13613 } else if (Context.getLangOpts().OpenCL && 13614 Context.getLangOpts().OpenCLVersion < 120) { 13615 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13616 // operate on scalar float types. 13617 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13618 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13619 << resultType << Input.get()->getSourceRange()); 13620 } 13621 } else if (resultType->isExtVectorType()) { 13622 if (Context.getLangOpts().OpenCL && 13623 Context.getLangOpts().OpenCLVersion < 120 && 13624 !Context.getLangOpts().OpenCLCPlusPlus) { 13625 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13626 // operate on vector float types. 13627 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13628 if (!T->isIntegerType()) 13629 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13630 << resultType << Input.get()->getSourceRange()); 13631 } 13632 // Vector logical not returns the signed variant of the operand type. 13633 resultType = GetSignedVectorType(resultType); 13634 break; 13635 } else { 13636 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13637 // type in C++. We should allow that here too. 13638 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13639 << resultType << Input.get()->getSourceRange()); 13640 } 13641 13642 // LNot always has type int. C99 6.5.3.3p5. 13643 // In C++, it's bool. C++ 5.3.1p8 13644 resultType = Context.getLogicalOperationType(); 13645 break; 13646 case UO_Real: 13647 case UO_Imag: 13648 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13649 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13650 // complex l-values to ordinary l-values and all other values to r-values. 13651 if (Input.isInvalid()) return ExprError(); 13652 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13653 if (Input.get()->getValueKind() != VK_RValue && 13654 Input.get()->getObjectKind() == OK_Ordinary) 13655 VK = Input.get()->getValueKind(); 13656 } else if (!getLangOpts().CPlusPlus) { 13657 // In C, a volatile scalar is read by __imag. In C++, it is not. 13658 Input = DefaultLvalueConversion(Input.get()); 13659 } 13660 break; 13661 case UO_Extension: 13662 resultType = Input.get()->getType(); 13663 VK = Input.get()->getValueKind(); 13664 OK = Input.get()->getObjectKind(); 13665 break; 13666 case UO_Coawait: 13667 // It's unnecessary to represent the pass-through operator co_await in the 13668 // AST; just return the input expression instead. 13669 assert(!Input.get()->getType()->isDependentType() && 13670 "the co_await expression must be non-dependant before " 13671 "building operator co_await"); 13672 return Input; 13673 } 13674 if (resultType.isNull() || Input.isInvalid()) 13675 return ExprError(); 13676 13677 // Check for array bounds violations in the operand of the UnaryOperator, 13678 // except for the '*' and '&' operators that have to be handled specially 13679 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13680 // that are explicitly defined as valid by the standard). 13681 if (Opc != UO_AddrOf && Opc != UO_Deref) 13682 CheckArrayAccess(Input.get()); 13683 13684 auto *UO = new (Context) 13685 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13686 13687 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13688 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13689 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13690 13691 // Convert the result back to a half vector. 13692 if (ConvertHalfVec) 13693 return convertVector(UO, Context.HalfTy, *this); 13694 return UO; 13695 } 13696 13697 /// Determine whether the given expression is a qualified member 13698 /// access expression, of a form that could be turned into a pointer to member 13699 /// with the address-of operator. 13700 bool Sema::isQualifiedMemberAccess(Expr *E) { 13701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13702 if (!DRE->getQualifier()) 13703 return false; 13704 13705 ValueDecl *VD = DRE->getDecl(); 13706 if (!VD->isCXXClassMember()) 13707 return false; 13708 13709 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13710 return true; 13711 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13712 return Method->isInstance(); 13713 13714 return false; 13715 } 13716 13717 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13718 if (!ULE->getQualifier()) 13719 return false; 13720 13721 for (NamedDecl *D : ULE->decls()) { 13722 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13723 if (Method->isInstance()) 13724 return true; 13725 } else { 13726 // Overload set does not contain methods. 13727 break; 13728 } 13729 } 13730 13731 return false; 13732 } 13733 13734 return false; 13735 } 13736 13737 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13738 UnaryOperatorKind Opc, Expr *Input) { 13739 // First things first: handle placeholders so that the 13740 // overloaded-operator check considers the right type. 13741 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13742 // Increment and decrement of pseudo-object references. 13743 if (pty->getKind() == BuiltinType::PseudoObject && 13744 UnaryOperator::isIncrementDecrementOp(Opc)) 13745 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13746 13747 // extension is always a builtin operator. 13748 if (Opc == UO_Extension) 13749 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13750 13751 // & gets special logic for several kinds of placeholder. 13752 // The builtin code knows what to do. 13753 if (Opc == UO_AddrOf && 13754 (pty->getKind() == BuiltinType::Overload || 13755 pty->getKind() == BuiltinType::UnknownAny || 13756 pty->getKind() == BuiltinType::BoundMember)) 13757 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13758 13759 // Anything else needs to be handled now. 13760 ExprResult Result = CheckPlaceholderExpr(Input); 13761 if (Result.isInvalid()) return ExprError(); 13762 Input = Result.get(); 13763 } 13764 13765 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13766 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13767 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13768 // Find all of the overloaded operators visible from this 13769 // point. We perform both an operator-name lookup from the local 13770 // scope and an argument-dependent lookup based on the types of 13771 // the arguments. 13772 UnresolvedSet<16> Functions; 13773 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13774 if (S && OverOp != OO_None) 13775 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13776 Functions); 13777 13778 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13779 } 13780 13781 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13782 } 13783 13784 // Unary Operators. 'Tok' is the token for the operator. 13785 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13786 tok::TokenKind Op, Expr *Input) { 13787 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13788 } 13789 13790 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13791 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13792 LabelDecl *TheDecl) { 13793 TheDecl->markUsed(Context); 13794 // Create the AST node. The address of a label always has type 'void*'. 13795 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13796 Context.getPointerType(Context.VoidTy)); 13797 } 13798 13799 void Sema::ActOnStartStmtExpr() { 13800 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13801 } 13802 13803 void Sema::ActOnStmtExprError() { 13804 // Note that function is also called by TreeTransform when leaving a 13805 // StmtExpr scope without rebuilding anything. 13806 13807 DiscardCleanupsInEvaluationContext(); 13808 PopExpressionEvaluationContext(); 13809 } 13810 13811 ExprResult 13812 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13813 SourceLocation RPLoc) { // "({..})" 13814 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13815 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13816 13817 if (hasAnyUnrecoverableErrorsInThisFunction()) 13818 DiscardCleanupsInEvaluationContext(); 13819 assert(!Cleanup.exprNeedsCleanups() && 13820 "cleanups within StmtExpr not correctly bound!"); 13821 PopExpressionEvaluationContext(); 13822 13823 // FIXME: there are a variety of strange constraints to enforce here, for 13824 // example, it is not possible to goto into a stmt expression apparently. 13825 // More semantic analysis is needed. 13826 13827 // If there are sub-stmts in the compound stmt, take the type of the last one 13828 // as the type of the stmtexpr. 13829 QualType Ty = Context.VoidTy; 13830 bool StmtExprMayBindToTemp = false; 13831 if (!Compound->body_empty()) { 13832 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13833 if (const auto *LastStmt = 13834 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13835 if (const Expr *Value = LastStmt->getExprStmt()) { 13836 StmtExprMayBindToTemp = true; 13837 Ty = Value->getType(); 13838 } 13839 } 13840 } 13841 13842 // FIXME: Check that expression type is complete/non-abstract; statement 13843 // expressions are not lvalues. 13844 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13845 if (StmtExprMayBindToTemp) 13846 return MaybeBindToTemporary(ResStmtExpr); 13847 return ResStmtExpr; 13848 } 13849 13850 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13851 if (ER.isInvalid()) 13852 return ExprError(); 13853 13854 // Do function/array conversion on the last expression, but not 13855 // lvalue-to-rvalue. However, initialize an unqualified type. 13856 ER = DefaultFunctionArrayConversion(ER.get()); 13857 if (ER.isInvalid()) 13858 return ExprError(); 13859 Expr *E = ER.get(); 13860 13861 if (E->isTypeDependent()) 13862 return E; 13863 13864 // In ARC, if the final expression ends in a consume, splice 13865 // the consume out and bind it later. In the alternate case 13866 // (when dealing with a retainable type), the result 13867 // initialization will create a produce. In both cases the 13868 // result will be +1, and we'll need to balance that out with 13869 // a bind. 13870 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13871 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13872 return Cast->getSubExpr(); 13873 13874 // FIXME: Provide a better location for the initialization. 13875 return PerformCopyInitialization( 13876 InitializedEntity::InitializeStmtExprResult( 13877 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13878 SourceLocation(), E); 13879 } 13880 13881 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13882 TypeSourceInfo *TInfo, 13883 ArrayRef<OffsetOfComponent> Components, 13884 SourceLocation RParenLoc) { 13885 QualType ArgTy = TInfo->getType(); 13886 bool Dependent = ArgTy->isDependentType(); 13887 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13888 13889 // We must have at least one component that refers to the type, and the first 13890 // one is known to be a field designator. Verify that the ArgTy represents 13891 // a struct/union/class. 13892 if (!Dependent && !ArgTy->isRecordType()) 13893 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13894 << ArgTy << TypeRange); 13895 13896 // Type must be complete per C99 7.17p3 because a declaring a variable 13897 // with an incomplete type would be ill-formed. 13898 if (!Dependent 13899 && RequireCompleteType(BuiltinLoc, ArgTy, 13900 diag::err_offsetof_incomplete_type, TypeRange)) 13901 return ExprError(); 13902 13903 bool DidWarnAboutNonPOD = false; 13904 QualType CurrentType = ArgTy; 13905 SmallVector<OffsetOfNode, 4> Comps; 13906 SmallVector<Expr*, 4> Exprs; 13907 for (const OffsetOfComponent &OC : Components) { 13908 if (OC.isBrackets) { 13909 // Offset of an array sub-field. TODO: Should we allow vector elements? 13910 if (!CurrentType->isDependentType()) { 13911 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13912 if(!AT) 13913 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13914 << CurrentType); 13915 CurrentType = AT->getElementType(); 13916 } else 13917 CurrentType = Context.DependentTy; 13918 13919 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13920 if (IdxRval.isInvalid()) 13921 return ExprError(); 13922 Expr *Idx = IdxRval.get(); 13923 13924 // The expression must be an integral expression. 13925 // FIXME: An integral constant expression? 13926 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13927 !Idx->getType()->isIntegerType()) 13928 return ExprError( 13929 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13930 << Idx->getSourceRange()); 13931 13932 // Record this array index. 13933 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13934 Exprs.push_back(Idx); 13935 continue; 13936 } 13937 13938 // Offset of a field. 13939 if (CurrentType->isDependentType()) { 13940 // We have the offset of a field, but we can't look into the dependent 13941 // type. Just record the identifier of the field. 13942 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13943 CurrentType = Context.DependentTy; 13944 continue; 13945 } 13946 13947 // We need to have a complete type to look into. 13948 if (RequireCompleteType(OC.LocStart, CurrentType, 13949 diag::err_offsetof_incomplete_type)) 13950 return ExprError(); 13951 13952 // Look for the designated field. 13953 const RecordType *RC = CurrentType->getAs<RecordType>(); 13954 if (!RC) 13955 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13956 << CurrentType); 13957 RecordDecl *RD = RC->getDecl(); 13958 13959 // C++ [lib.support.types]p5: 13960 // The macro offsetof accepts a restricted set of type arguments in this 13961 // International Standard. type shall be a POD structure or a POD union 13962 // (clause 9). 13963 // C++11 [support.types]p4: 13964 // If type is not a standard-layout class (Clause 9), the results are 13965 // undefined. 13966 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13967 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13968 unsigned DiagID = 13969 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13970 : diag::ext_offsetof_non_pod_type; 13971 13972 if (!IsSafe && !DidWarnAboutNonPOD && 13973 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13974 PDiag(DiagID) 13975 << SourceRange(Components[0].LocStart, OC.LocEnd) 13976 << CurrentType)) 13977 DidWarnAboutNonPOD = true; 13978 } 13979 13980 // Look for the field. 13981 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13982 LookupQualifiedName(R, RD); 13983 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13984 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13985 if (!MemberDecl) { 13986 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13987 MemberDecl = IndirectMemberDecl->getAnonField(); 13988 } 13989 13990 if (!MemberDecl) 13991 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13992 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13993 OC.LocEnd)); 13994 13995 // C99 7.17p3: 13996 // (If the specified member is a bit-field, the behavior is undefined.) 13997 // 13998 // We diagnose this as an error. 13999 if (MemberDecl->isBitField()) { 14000 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14001 << MemberDecl->getDeclName() 14002 << SourceRange(BuiltinLoc, RParenLoc); 14003 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14004 return ExprError(); 14005 } 14006 14007 RecordDecl *Parent = MemberDecl->getParent(); 14008 if (IndirectMemberDecl) 14009 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14010 14011 // If the member was found in a base class, introduce OffsetOfNodes for 14012 // the base class indirections. 14013 CXXBasePaths Paths; 14014 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14015 Paths)) { 14016 if (Paths.getDetectedVirtual()) { 14017 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14018 << MemberDecl->getDeclName() 14019 << SourceRange(BuiltinLoc, RParenLoc); 14020 return ExprError(); 14021 } 14022 14023 CXXBasePath &Path = Paths.front(); 14024 for (const CXXBasePathElement &B : Path) 14025 Comps.push_back(OffsetOfNode(B.Base)); 14026 } 14027 14028 if (IndirectMemberDecl) { 14029 for (auto *FI : IndirectMemberDecl->chain()) { 14030 assert(isa<FieldDecl>(FI)); 14031 Comps.push_back(OffsetOfNode(OC.LocStart, 14032 cast<FieldDecl>(FI), OC.LocEnd)); 14033 } 14034 } else 14035 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14036 14037 CurrentType = MemberDecl->getType().getNonReferenceType(); 14038 } 14039 14040 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14041 Comps, Exprs, RParenLoc); 14042 } 14043 14044 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14045 SourceLocation BuiltinLoc, 14046 SourceLocation TypeLoc, 14047 ParsedType ParsedArgTy, 14048 ArrayRef<OffsetOfComponent> Components, 14049 SourceLocation RParenLoc) { 14050 14051 TypeSourceInfo *ArgTInfo; 14052 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14053 if (ArgTy.isNull()) 14054 return ExprError(); 14055 14056 if (!ArgTInfo) 14057 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14058 14059 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14060 } 14061 14062 14063 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14064 Expr *CondExpr, 14065 Expr *LHSExpr, Expr *RHSExpr, 14066 SourceLocation RPLoc) { 14067 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14068 14069 ExprValueKind VK = VK_RValue; 14070 ExprObjectKind OK = OK_Ordinary; 14071 QualType resType; 14072 bool ValueDependent = false; 14073 bool CondIsTrue = false; 14074 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14075 resType = Context.DependentTy; 14076 ValueDependent = true; 14077 } else { 14078 // The conditional expression is required to be a constant expression. 14079 llvm::APSInt condEval(32); 14080 ExprResult CondICE 14081 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14082 diag::err_typecheck_choose_expr_requires_constant, false); 14083 if (CondICE.isInvalid()) 14084 return ExprError(); 14085 CondExpr = CondICE.get(); 14086 CondIsTrue = condEval.getZExtValue(); 14087 14088 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14089 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14090 14091 resType = ActiveExpr->getType(); 14092 ValueDependent = ActiveExpr->isValueDependent(); 14093 VK = ActiveExpr->getValueKind(); 14094 OK = ActiveExpr->getObjectKind(); 14095 } 14096 14097 return new (Context) 14098 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14099 CondIsTrue, resType->isDependentType(), ValueDependent); 14100 } 14101 14102 //===----------------------------------------------------------------------===// 14103 // Clang Extensions. 14104 //===----------------------------------------------------------------------===// 14105 14106 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14107 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14108 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14109 14110 if (LangOpts.CPlusPlus) { 14111 MangleNumberingContext *MCtx; 14112 Decl *ManglingContextDecl; 14113 std::tie(MCtx, ManglingContextDecl) = 14114 getCurrentMangleNumberContext(Block->getDeclContext()); 14115 if (MCtx) { 14116 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14117 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14118 } 14119 } 14120 14121 PushBlockScope(CurScope, Block); 14122 CurContext->addDecl(Block); 14123 if (CurScope) 14124 PushDeclContext(CurScope, Block); 14125 else 14126 CurContext = Block; 14127 14128 getCurBlock()->HasImplicitReturnType = true; 14129 14130 // Enter a new evaluation context to insulate the block from any 14131 // cleanups from the enclosing full-expression. 14132 PushExpressionEvaluationContext( 14133 ExpressionEvaluationContext::PotentiallyEvaluated); 14134 } 14135 14136 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14137 Scope *CurScope) { 14138 assert(ParamInfo.getIdentifier() == nullptr && 14139 "block-id should have no identifier!"); 14140 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14141 BlockScopeInfo *CurBlock = getCurBlock(); 14142 14143 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14144 QualType T = Sig->getType(); 14145 14146 // FIXME: We should allow unexpanded parameter packs here, but that would, 14147 // in turn, make the block expression contain unexpanded parameter packs. 14148 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14149 // Drop the parameters. 14150 FunctionProtoType::ExtProtoInfo EPI; 14151 EPI.HasTrailingReturn = false; 14152 EPI.TypeQuals.addConst(); 14153 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14154 Sig = Context.getTrivialTypeSourceInfo(T); 14155 } 14156 14157 // GetTypeForDeclarator always produces a function type for a block 14158 // literal signature. Furthermore, it is always a FunctionProtoType 14159 // unless the function was written with a typedef. 14160 assert(T->isFunctionType() && 14161 "GetTypeForDeclarator made a non-function block signature"); 14162 14163 // Look for an explicit signature in that function type. 14164 FunctionProtoTypeLoc ExplicitSignature; 14165 14166 if ((ExplicitSignature = Sig->getTypeLoc() 14167 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14168 14169 // Check whether that explicit signature was synthesized by 14170 // GetTypeForDeclarator. If so, don't save that as part of the 14171 // written signature. 14172 if (ExplicitSignature.getLocalRangeBegin() == 14173 ExplicitSignature.getLocalRangeEnd()) { 14174 // This would be much cheaper if we stored TypeLocs instead of 14175 // TypeSourceInfos. 14176 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14177 unsigned Size = Result.getFullDataSize(); 14178 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14179 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14180 14181 ExplicitSignature = FunctionProtoTypeLoc(); 14182 } 14183 } 14184 14185 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14186 CurBlock->FunctionType = T; 14187 14188 const FunctionType *Fn = T->getAs<FunctionType>(); 14189 QualType RetTy = Fn->getReturnType(); 14190 bool isVariadic = 14191 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14192 14193 CurBlock->TheDecl->setIsVariadic(isVariadic); 14194 14195 // Context.DependentTy is used as a placeholder for a missing block 14196 // return type. TODO: what should we do with declarators like: 14197 // ^ * { ... } 14198 // If the answer is "apply template argument deduction".... 14199 if (RetTy != Context.DependentTy) { 14200 CurBlock->ReturnType = RetTy; 14201 CurBlock->TheDecl->setBlockMissingReturnType(false); 14202 CurBlock->HasImplicitReturnType = false; 14203 } 14204 14205 // Push block parameters from the declarator if we had them. 14206 SmallVector<ParmVarDecl*, 8> Params; 14207 if (ExplicitSignature) { 14208 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14209 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14210 if (Param->getIdentifier() == nullptr && 14211 !Param->isImplicit() && 14212 !Param->isInvalidDecl() && 14213 !getLangOpts().CPlusPlus) 14214 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14215 Params.push_back(Param); 14216 } 14217 14218 // Fake up parameter variables if we have a typedef, like 14219 // ^ fntype { ... } 14220 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14221 for (const auto &I : Fn->param_types()) { 14222 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14223 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14224 Params.push_back(Param); 14225 } 14226 } 14227 14228 // Set the parameters on the block decl. 14229 if (!Params.empty()) { 14230 CurBlock->TheDecl->setParams(Params); 14231 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14232 /*CheckParameterNames=*/false); 14233 } 14234 14235 // Finally we can process decl attributes. 14236 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14237 14238 // Put the parameter variables in scope. 14239 for (auto AI : CurBlock->TheDecl->parameters()) { 14240 AI->setOwningFunction(CurBlock->TheDecl); 14241 14242 // If this has an identifier, add it to the scope stack. 14243 if (AI->getIdentifier()) { 14244 CheckShadow(CurBlock->TheScope, AI); 14245 14246 PushOnScopeChains(AI, CurBlock->TheScope); 14247 } 14248 } 14249 } 14250 14251 /// ActOnBlockError - If there is an error parsing a block, this callback 14252 /// is invoked to pop the information about the block from the action impl. 14253 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14254 // Leave the expression-evaluation context. 14255 DiscardCleanupsInEvaluationContext(); 14256 PopExpressionEvaluationContext(); 14257 14258 // Pop off CurBlock, handle nested blocks. 14259 PopDeclContext(); 14260 PopFunctionScopeInfo(); 14261 } 14262 14263 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14264 /// literal was successfully completed. ^(int x){...} 14265 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14266 Stmt *Body, Scope *CurScope) { 14267 // If blocks are disabled, emit an error. 14268 if (!LangOpts.Blocks) 14269 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14270 14271 // Leave the expression-evaluation context. 14272 if (hasAnyUnrecoverableErrorsInThisFunction()) 14273 DiscardCleanupsInEvaluationContext(); 14274 assert(!Cleanup.exprNeedsCleanups() && 14275 "cleanups within block not correctly bound!"); 14276 PopExpressionEvaluationContext(); 14277 14278 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14279 BlockDecl *BD = BSI->TheDecl; 14280 14281 if (BSI->HasImplicitReturnType) 14282 deduceClosureReturnType(*BSI); 14283 14284 QualType RetTy = Context.VoidTy; 14285 if (!BSI->ReturnType.isNull()) 14286 RetTy = BSI->ReturnType; 14287 14288 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14289 QualType BlockTy; 14290 14291 // If the user wrote a function type in some form, try to use that. 14292 if (!BSI->FunctionType.isNull()) { 14293 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14294 14295 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14296 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14297 14298 // Turn protoless block types into nullary block types. 14299 if (isa<FunctionNoProtoType>(FTy)) { 14300 FunctionProtoType::ExtProtoInfo EPI; 14301 EPI.ExtInfo = Ext; 14302 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14303 14304 // Otherwise, if we don't need to change anything about the function type, 14305 // preserve its sugar structure. 14306 } else if (FTy->getReturnType() == RetTy && 14307 (!NoReturn || FTy->getNoReturnAttr())) { 14308 BlockTy = BSI->FunctionType; 14309 14310 // Otherwise, make the minimal modifications to the function type. 14311 } else { 14312 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14313 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14314 EPI.TypeQuals = Qualifiers(); 14315 EPI.ExtInfo = Ext; 14316 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14317 } 14318 14319 // If we don't have a function type, just build one from nothing. 14320 } else { 14321 FunctionProtoType::ExtProtoInfo EPI; 14322 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14323 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14324 } 14325 14326 DiagnoseUnusedParameters(BD->parameters()); 14327 BlockTy = Context.getBlockPointerType(BlockTy); 14328 14329 // If needed, diagnose invalid gotos and switches in the block. 14330 if (getCurFunction()->NeedsScopeChecking() && 14331 !PP.isCodeCompletionEnabled()) 14332 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14333 14334 BD->setBody(cast<CompoundStmt>(Body)); 14335 14336 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14337 DiagnoseUnguardedAvailabilityViolations(BD); 14338 14339 // Try to apply the named return value optimization. We have to check again 14340 // if we can do this, though, because blocks keep return statements around 14341 // to deduce an implicit return type. 14342 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14343 !BD->isDependentContext()) 14344 computeNRVO(Body, BSI); 14345 14346 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14347 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14348 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14349 NTCUK_Destruct|NTCUK_Copy); 14350 14351 PopDeclContext(); 14352 14353 // Pop the block scope now but keep it alive to the end of this function. 14354 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14355 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14356 14357 // Set the captured variables on the block. 14358 SmallVector<BlockDecl::Capture, 4> Captures; 14359 for (Capture &Cap : BSI->Captures) { 14360 if (Cap.isInvalid() || Cap.isThisCapture()) 14361 continue; 14362 14363 VarDecl *Var = Cap.getVariable(); 14364 Expr *CopyExpr = nullptr; 14365 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14366 if (const RecordType *Record = 14367 Cap.getCaptureType()->getAs<RecordType>()) { 14368 // The capture logic needs the destructor, so make sure we mark it. 14369 // Usually this is unnecessary because most local variables have 14370 // their destructors marked at declaration time, but parameters are 14371 // an exception because it's technically only the call site that 14372 // actually requires the destructor. 14373 if (isa<ParmVarDecl>(Var)) 14374 FinalizeVarWithDestructor(Var, Record); 14375 14376 // Enter a separate potentially-evaluated context while building block 14377 // initializers to isolate their cleanups from those of the block 14378 // itself. 14379 // FIXME: Is this appropriate even when the block itself occurs in an 14380 // unevaluated operand? 14381 EnterExpressionEvaluationContext EvalContext( 14382 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14383 14384 SourceLocation Loc = Cap.getLocation(); 14385 14386 ExprResult Result = BuildDeclarationNameExpr( 14387 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14388 14389 // According to the blocks spec, the capture of a variable from 14390 // the stack requires a const copy constructor. This is not true 14391 // of the copy/move done to move a __block variable to the heap. 14392 if (!Result.isInvalid() && 14393 !Result.get()->getType().isConstQualified()) { 14394 Result = ImpCastExprToType(Result.get(), 14395 Result.get()->getType().withConst(), 14396 CK_NoOp, VK_LValue); 14397 } 14398 14399 if (!Result.isInvalid()) { 14400 Result = PerformCopyInitialization( 14401 InitializedEntity::InitializeBlock(Var->getLocation(), 14402 Cap.getCaptureType(), false), 14403 Loc, Result.get()); 14404 } 14405 14406 // Build a full-expression copy expression if initialization 14407 // succeeded and used a non-trivial constructor. Recover from 14408 // errors by pretending that the copy isn't necessary. 14409 if (!Result.isInvalid() && 14410 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14411 ->isTrivial()) { 14412 Result = MaybeCreateExprWithCleanups(Result); 14413 CopyExpr = Result.get(); 14414 } 14415 } 14416 } 14417 14418 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14419 CopyExpr); 14420 Captures.push_back(NewCap); 14421 } 14422 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14423 14424 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14425 14426 // If the block isn't obviously global, i.e. it captures anything at 14427 // all, then we need to do a few things in the surrounding context: 14428 if (Result->getBlockDecl()->hasCaptures()) { 14429 // First, this expression has a new cleanup object. 14430 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14431 Cleanup.setExprNeedsCleanups(true); 14432 14433 // It also gets a branch-protected scope if any of the captured 14434 // variables needs destruction. 14435 for (const auto &CI : Result->getBlockDecl()->captures()) { 14436 const VarDecl *var = CI.getVariable(); 14437 if (var->getType().isDestructedType() != QualType::DK_none) { 14438 setFunctionHasBranchProtectedScope(); 14439 break; 14440 } 14441 } 14442 } 14443 14444 if (getCurFunction()) 14445 getCurFunction()->addBlock(BD); 14446 14447 return Result; 14448 } 14449 14450 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14451 SourceLocation RPLoc) { 14452 TypeSourceInfo *TInfo; 14453 GetTypeFromParser(Ty, &TInfo); 14454 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14455 } 14456 14457 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14458 Expr *E, TypeSourceInfo *TInfo, 14459 SourceLocation RPLoc) { 14460 Expr *OrigExpr = E; 14461 bool IsMS = false; 14462 14463 // CUDA device code does not support varargs. 14464 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14465 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14466 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14467 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14468 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14469 } 14470 } 14471 14472 // NVPTX does not support va_arg expression. 14473 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14474 Context.getTargetInfo().getTriple().isNVPTX()) 14475 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14476 14477 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14478 // as Microsoft ABI on an actual Microsoft platform, where 14479 // __builtin_ms_va_list and __builtin_va_list are the same.) 14480 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14481 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14482 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14483 if (Context.hasSameType(MSVaListType, E->getType())) { 14484 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14485 return ExprError(); 14486 IsMS = true; 14487 } 14488 } 14489 14490 // Get the va_list type 14491 QualType VaListType = Context.getBuiltinVaListType(); 14492 if (!IsMS) { 14493 if (VaListType->isArrayType()) { 14494 // Deal with implicit array decay; for example, on x86-64, 14495 // va_list is an array, but it's supposed to decay to 14496 // a pointer for va_arg. 14497 VaListType = Context.getArrayDecayedType(VaListType); 14498 // Make sure the input expression also decays appropriately. 14499 ExprResult Result = UsualUnaryConversions(E); 14500 if (Result.isInvalid()) 14501 return ExprError(); 14502 E = Result.get(); 14503 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14504 // If va_list is a record type and we are compiling in C++ mode, 14505 // check the argument using reference binding. 14506 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14507 Context, Context.getLValueReferenceType(VaListType), false); 14508 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14509 if (Init.isInvalid()) 14510 return ExprError(); 14511 E = Init.getAs<Expr>(); 14512 } else { 14513 // Otherwise, the va_list argument must be an l-value because 14514 // it is modified by va_arg. 14515 if (!E->isTypeDependent() && 14516 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14517 return ExprError(); 14518 } 14519 } 14520 14521 if (!IsMS && !E->isTypeDependent() && 14522 !Context.hasSameType(VaListType, E->getType())) 14523 return ExprError( 14524 Diag(E->getBeginLoc(), 14525 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14526 << OrigExpr->getType() << E->getSourceRange()); 14527 14528 if (!TInfo->getType()->isDependentType()) { 14529 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14530 diag::err_second_parameter_to_va_arg_incomplete, 14531 TInfo->getTypeLoc())) 14532 return ExprError(); 14533 14534 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14535 TInfo->getType(), 14536 diag::err_second_parameter_to_va_arg_abstract, 14537 TInfo->getTypeLoc())) 14538 return ExprError(); 14539 14540 if (!TInfo->getType().isPODType(Context)) { 14541 Diag(TInfo->getTypeLoc().getBeginLoc(), 14542 TInfo->getType()->isObjCLifetimeType() 14543 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14544 : diag::warn_second_parameter_to_va_arg_not_pod) 14545 << TInfo->getType() 14546 << TInfo->getTypeLoc().getSourceRange(); 14547 } 14548 14549 // Check for va_arg where arguments of the given type will be promoted 14550 // (i.e. this va_arg is guaranteed to have undefined behavior). 14551 QualType PromoteType; 14552 if (TInfo->getType()->isPromotableIntegerType()) { 14553 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14554 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14555 PromoteType = QualType(); 14556 } 14557 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14558 PromoteType = Context.DoubleTy; 14559 if (!PromoteType.isNull()) 14560 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14561 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14562 << TInfo->getType() 14563 << PromoteType 14564 << TInfo->getTypeLoc().getSourceRange()); 14565 } 14566 14567 QualType T = TInfo->getType().getNonLValueExprType(Context); 14568 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14569 } 14570 14571 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14572 // The type of __null will be int or long, depending on the size of 14573 // pointers on the target. 14574 QualType Ty; 14575 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14576 if (pw == Context.getTargetInfo().getIntWidth()) 14577 Ty = Context.IntTy; 14578 else if (pw == Context.getTargetInfo().getLongWidth()) 14579 Ty = Context.LongTy; 14580 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14581 Ty = Context.LongLongTy; 14582 else { 14583 llvm_unreachable("I don't know size of pointer!"); 14584 } 14585 14586 return new (Context) GNUNullExpr(Ty, TokenLoc); 14587 } 14588 14589 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14590 SourceLocation BuiltinLoc, 14591 SourceLocation RPLoc) { 14592 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14593 } 14594 14595 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14596 SourceLocation BuiltinLoc, 14597 SourceLocation RPLoc, 14598 DeclContext *ParentContext) { 14599 return new (Context) 14600 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14601 } 14602 14603 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14604 bool Diagnose) { 14605 if (!getLangOpts().ObjC) 14606 return false; 14607 14608 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14609 if (!PT) 14610 return false; 14611 14612 if (!PT->isObjCIdType()) { 14613 // Check if the destination is the 'NSString' interface. 14614 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14615 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14616 return false; 14617 } 14618 14619 // Ignore any parens, implicit casts (should only be 14620 // array-to-pointer decays), and not-so-opaque values. The last is 14621 // important for making this trigger for property assignments. 14622 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14623 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14624 if (OV->getSourceExpr()) 14625 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14626 14627 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14628 if (!SL || !SL->isAscii()) 14629 return false; 14630 if (Diagnose) { 14631 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14632 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14633 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14634 } 14635 return true; 14636 } 14637 14638 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14639 const Expr *SrcExpr) { 14640 if (!DstType->isFunctionPointerType() || 14641 !SrcExpr->getType()->isFunctionType()) 14642 return false; 14643 14644 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14645 if (!DRE) 14646 return false; 14647 14648 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14649 if (!FD) 14650 return false; 14651 14652 return !S.checkAddressOfFunctionIsAvailable(FD, 14653 /*Complain=*/true, 14654 SrcExpr->getBeginLoc()); 14655 } 14656 14657 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14658 SourceLocation Loc, 14659 QualType DstType, QualType SrcType, 14660 Expr *SrcExpr, AssignmentAction Action, 14661 bool *Complained) { 14662 if (Complained) 14663 *Complained = false; 14664 14665 // Decode the result (notice that AST's are still created for extensions). 14666 bool CheckInferredResultType = false; 14667 bool isInvalid = false; 14668 unsigned DiagKind = 0; 14669 FixItHint Hint; 14670 ConversionFixItGenerator ConvHints; 14671 bool MayHaveConvFixit = false; 14672 bool MayHaveFunctionDiff = false; 14673 const ObjCInterfaceDecl *IFace = nullptr; 14674 const ObjCProtocolDecl *PDecl = nullptr; 14675 14676 switch (ConvTy) { 14677 case Compatible: 14678 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14679 return false; 14680 14681 case PointerToInt: 14682 DiagKind = diag::ext_typecheck_convert_pointer_int; 14683 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14684 MayHaveConvFixit = true; 14685 break; 14686 case IntToPointer: 14687 DiagKind = diag::ext_typecheck_convert_int_pointer; 14688 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14689 MayHaveConvFixit = true; 14690 break; 14691 case IncompatiblePointer: 14692 if (Action == AA_Passing_CFAudited) 14693 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14694 else if (SrcType->isFunctionPointerType() && 14695 DstType->isFunctionPointerType()) 14696 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14697 else 14698 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14699 14700 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14701 SrcType->isObjCObjectPointerType(); 14702 if (Hint.isNull() && !CheckInferredResultType) { 14703 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14704 } 14705 else if (CheckInferredResultType) { 14706 SrcType = SrcType.getUnqualifiedType(); 14707 DstType = DstType.getUnqualifiedType(); 14708 } 14709 MayHaveConvFixit = true; 14710 break; 14711 case IncompatiblePointerSign: 14712 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14713 break; 14714 case FunctionVoidPointer: 14715 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14716 break; 14717 case IncompatiblePointerDiscardsQualifiers: { 14718 // Perform array-to-pointer decay if necessary. 14719 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14720 14721 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14722 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14723 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14724 DiagKind = diag::err_typecheck_incompatible_address_space; 14725 break; 14726 14727 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14728 DiagKind = diag::err_typecheck_incompatible_ownership; 14729 break; 14730 } 14731 14732 llvm_unreachable("unknown error case for discarding qualifiers!"); 14733 // fallthrough 14734 } 14735 case CompatiblePointerDiscardsQualifiers: 14736 // If the qualifiers lost were because we were applying the 14737 // (deprecated) C++ conversion from a string literal to a char* 14738 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14739 // Ideally, this check would be performed in 14740 // checkPointerTypesForAssignment. However, that would require a 14741 // bit of refactoring (so that the second argument is an 14742 // expression, rather than a type), which should be done as part 14743 // of a larger effort to fix checkPointerTypesForAssignment for 14744 // C++ semantics. 14745 if (getLangOpts().CPlusPlus && 14746 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14747 return false; 14748 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14749 break; 14750 case IncompatibleNestedPointerQualifiers: 14751 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14752 break; 14753 case IncompatibleNestedPointerAddressSpaceMismatch: 14754 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14755 break; 14756 case IntToBlockPointer: 14757 DiagKind = diag::err_int_to_block_pointer; 14758 break; 14759 case IncompatibleBlockPointer: 14760 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14761 break; 14762 case IncompatibleObjCQualifiedId: { 14763 if (SrcType->isObjCQualifiedIdType()) { 14764 const ObjCObjectPointerType *srcOPT = 14765 SrcType->castAs<ObjCObjectPointerType>(); 14766 for (auto *srcProto : srcOPT->quals()) { 14767 PDecl = srcProto; 14768 break; 14769 } 14770 if (const ObjCInterfaceType *IFaceT = 14771 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14772 IFace = IFaceT->getDecl(); 14773 } 14774 else if (DstType->isObjCQualifiedIdType()) { 14775 const ObjCObjectPointerType *dstOPT = 14776 DstType->castAs<ObjCObjectPointerType>(); 14777 for (auto *dstProto : dstOPT->quals()) { 14778 PDecl = dstProto; 14779 break; 14780 } 14781 if (const ObjCInterfaceType *IFaceT = 14782 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14783 IFace = IFaceT->getDecl(); 14784 } 14785 DiagKind = diag::warn_incompatible_qualified_id; 14786 break; 14787 } 14788 case IncompatibleVectors: 14789 DiagKind = diag::warn_incompatible_vectors; 14790 break; 14791 case IncompatibleObjCWeakRef: 14792 DiagKind = diag::err_arc_weak_unavailable_assign; 14793 break; 14794 case Incompatible: 14795 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14796 if (Complained) 14797 *Complained = true; 14798 return true; 14799 } 14800 14801 DiagKind = diag::err_typecheck_convert_incompatible; 14802 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14803 MayHaveConvFixit = true; 14804 isInvalid = true; 14805 MayHaveFunctionDiff = true; 14806 break; 14807 } 14808 14809 QualType FirstType, SecondType; 14810 switch (Action) { 14811 case AA_Assigning: 14812 case AA_Initializing: 14813 // The destination type comes first. 14814 FirstType = DstType; 14815 SecondType = SrcType; 14816 break; 14817 14818 case AA_Returning: 14819 case AA_Passing: 14820 case AA_Passing_CFAudited: 14821 case AA_Converting: 14822 case AA_Sending: 14823 case AA_Casting: 14824 // The source type comes first. 14825 FirstType = SrcType; 14826 SecondType = DstType; 14827 break; 14828 } 14829 14830 PartialDiagnostic FDiag = PDiag(DiagKind); 14831 if (Action == AA_Passing_CFAudited) 14832 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14833 else 14834 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14835 14836 // If we can fix the conversion, suggest the FixIts. 14837 assert(ConvHints.isNull() || Hint.isNull()); 14838 if (!ConvHints.isNull()) { 14839 for (FixItHint &H : ConvHints.Hints) 14840 FDiag << H; 14841 } else { 14842 FDiag << Hint; 14843 } 14844 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14845 14846 if (MayHaveFunctionDiff) 14847 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14848 14849 Diag(Loc, FDiag); 14850 if (DiagKind == diag::warn_incompatible_qualified_id && 14851 PDecl && IFace && !IFace->hasDefinition()) 14852 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14853 << IFace << PDecl; 14854 14855 if (SecondType == Context.OverloadTy) 14856 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14857 FirstType, /*TakingAddress=*/true); 14858 14859 if (CheckInferredResultType) 14860 EmitRelatedResultTypeNote(SrcExpr); 14861 14862 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14863 EmitRelatedResultTypeNoteForReturn(DstType); 14864 14865 if (Complained) 14866 *Complained = true; 14867 return isInvalid; 14868 } 14869 14870 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14871 llvm::APSInt *Result) { 14872 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14873 public: 14874 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14875 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14876 } 14877 } Diagnoser; 14878 14879 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14880 } 14881 14882 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14883 llvm::APSInt *Result, 14884 unsigned DiagID, 14885 bool AllowFold) { 14886 class IDDiagnoser : public VerifyICEDiagnoser { 14887 unsigned DiagID; 14888 14889 public: 14890 IDDiagnoser(unsigned DiagID) 14891 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14892 14893 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14894 S.Diag(Loc, DiagID) << SR; 14895 } 14896 } Diagnoser(DiagID); 14897 14898 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14899 } 14900 14901 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14902 SourceRange SR) { 14903 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14904 } 14905 14906 ExprResult 14907 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14908 VerifyICEDiagnoser &Diagnoser, 14909 bool AllowFold) { 14910 SourceLocation DiagLoc = E->getBeginLoc(); 14911 14912 if (getLangOpts().CPlusPlus11) { 14913 // C++11 [expr.const]p5: 14914 // If an expression of literal class type is used in a context where an 14915 // integral constant expression is required, then that class type shall 14916 // have a single non-explicit conversion function to an integral or 14917 // unscoped enumeration type 14918 ExprResult Converted; 14919 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14920 public: 14921 CXX11ConvertDiagnoser(bool Silent) 14922 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14923 Silent, true) {} 14924 14925 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14926 QualType T) override { 14927 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14928 } 14929 14930 SemaDiagnosticBuilder diagnoseIncomplete( 14931 Sema &S, SourceLocation Loc, QualType T) override { 14932 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14933 } 14934 14935 SemaDiagnosticBuilder diagnoseExplicitConv( 14936 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14937 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14938 } 14939 14940 SemaDiagnosticBuilder noteExplicitConv( 14941 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14942 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14943 << ConvTy->isEnumeralType() << ConvTy; 14944 } 14945 14946 SemaDiagnosticBuilder diagnoseAmbiguous( 14947 Sema &S, SourceLocation Loc, QualType T) override { 14948 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14949 } 14950 14951 SemaDiagnosticBuilder noteAmbiguous( 14952 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14953 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14954 << ConvTy->isEnumeralType() << ConvTy; 14955 } 14956 14957 SemaDiagnosticBuilder diagnoseConversion( 14958 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14959 llvm_unreachable("conversion functions are permitted"); 14960 } 14961 } ConvertDiagnoser(Diagnoser.Suppress); 14962 14963 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14964 ConvertDiagnoser); 14965 if (Converted.isInvalid()) 14966 return Converted; 14967 E = Converted.get(); 14968 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14969 return ExprError(); 14970 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14971 // An ICE must be of integral or unscoped enumeration type. 14972 if (!Diagnoser.Suppress) 14973 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14974 return ExprError(); 14975 } 14976 14977 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14978 // in the non-ICE case. 14979 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14980 if (Result) 14981 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14982 if (!isa<ConstantExpr>(E)) 14983 E = ConstantExpr::Create(Context, E); 14984 return E; 14985 } 14986 14987 Expr::EvalResult EvalResult; 14988 SmallVector<PartialDiagnosticAt, 8> Notes; 14989 EvalResult.Diag = &Notes; 14990 14991 // Try to evaluate the expression, and produce diagnostics explaining why it's 14992 // not a constant expression as a side-effect. 14993 bool Folded = 14994 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 14995 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14996 14997 if (!isa<ConstantExpr>(E)) 14998 E = ConstantExpr::Create(Context, E, EvalResult.Val); 14999 15000 // In C++11, we can rely on diagnostics being produced for any expression 15001 // which is not a constant expression. If no diagnostics were produced, then 15002 // this is a constant expression. 15003 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15004 if (Result) 15005 *Result = EvalResult.Val.getInt(); 15006 return E; 15007 } 15008 15009 // If our only note is the usual "invalid subexpression" note, just point 15010 // the caret at its location rather than producing an essentially 15011 // redundant note. 15012 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15013 diag::note_invalid_subexpr_in_const_expr) { 15014 DiagLoc = Notes[0].first; 15015 Notes.clear(); 15016 } 15017 15018 if (!Folded || !AllowFold) { 15019 if (!Diagnoser.Suppress) { 15020 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15021 for (const PartialDiagnosticAt &Note : Notes) 15022 Diag(Note.first, Note.second); 15023 } 15024 15025 return ExprError(); 15026 } 15027 15028 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15029 for (const PartialDiagnosticAt &Note : Notes) 15030 Diag(Note.first, Note.second); 15031 15032 if (Result) 15033 *Result = EvalResult.Val.getInt(); 15034 return E; 15035 } 15036 15037 namespace { 15038 // Handle the case where we conclude a expression which we speculatively 15039 // considered to be unevaluated is actually evaluated. 15040 class TransformToPE : public TreeTransform<TransformToPE> { 15041 typedef TreeTransform<TransformToPE> BaseTransform; 15042 15043 public: 15044 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15045 15046 // Make sure we redo semantic analysis 15047 bool AlwaysRebuild() { return true; } 15048 bool ReplacingOriginal() { return true; } 15049 15050 // We need to special-case DeclRefExprs referring to FieldDecls which 15051 // are not part of a member pointer formation; normal TreeTransforming 15052 // doesn't catch this case because of the way we represent them in the AST. 15053 // FIXME: This is a bit ugly; is it really the best way to handle this 15054 // case? 15055 // 15056 // Error on DeclRefExprs referring to FieldDecls. 15057 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15058 if (isa<FieldDecl>(E->getDecl()) && 15059 !SemaRef.isUnevaluatedContext()) 15060 return SemaRef.Diag(E->getLocation(), 15061 diag::err_invalid_non_static_member_use) 15062 << E->getDecl() << E->getSourceRange(); 15063 15064 return BaseTransform::TransformDeclRefExpr(E); 15065 } 15066 15067 // Exception: filter out member pointer formation 15068 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15069 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15070 return E; 15071 15072 return BaseTransform::TransformUnaryOperator(E); 15073 } 15074 15075 // The body of a lambda-expression is in a separate expression evaluation 15076 // context so never needs to be transformed. 15077 // FIXME: Ideally we wouldn't transform the closure type either, and would 15078 // just recreate the capture expressions and lambda expression. 15079 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15080 return SkipLambdaBody(E, Body); 15081 } 15082 }; 15083 } 15084 15085 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15086 assert(isUnevaluatedContext() && 15087 "Should only transform unevaluated expressions"); 15088 ExprEvalContexts.back().Context = 15089 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15090 if (isUnevaluatedContext()) 15091 return E; 15092 return TransformToPE(*this).TransformExpr(E); 15093 } 15094 15095 void 15096 Sema::PushExpressionEvaluationContext( 15097 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15098 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15099 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15100 LambdaContextDecl, ExprContext); 15101 Cleanup.reset(); 15102 if (!MaybeODRUseExprs.empty()) 15103 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15104 } 15105 15106 void 15107 Sema::PushExpressionEvaluationContext( 15108 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15109 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15110 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15111 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15112 } 15113 15114 namespace { 15115 15116 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15117 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15118 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15119 if (E->getOpcode() == UO_Deref) 15120 return CheckPossibleDeref(S, E->getSubExpr()); 15121 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15122 return CheckPossibleDeref(S, E->getBase()); 15123 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15124 return CheckPossibleDeref(S, E->getBase()); 15125 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15126 QualType Inner; 15127 QualType Ty = E->getType(); 15128 if (const auto *Ptr = Ty->getAs<PointerType>()) 15129 Inner = Ptr->getPointeeType(); 15130 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15131 Inner = Arr->getElementType(); 15132 else 15133 return nullptr; 15134 15135 if (Inner->hasAttr(attr::NoDeref)) 15136 return E; 15137 } 15138 return nullptr; 15139 } 15140 15141 } // namespace 15142 15143 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15144 for (const Expr *E : Rec.PossibleDerefs) { 15145 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15146 if (DeclRef) { 15147 const ValueDecl *Decl = DeclRef->getDecl(); 15148 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15149 << Decl->getName() << E->getSourceRange(); 15150 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15151 } else { 15152 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15153 << E->getSourceRange(); 15154 } 15155 } 15156 Rec.PossibleDerefs.clear(); 15157 } 15158 15159 /// Check whether E, which is either a discarded-value expression or an 15160 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15161 /// and if so, remove it from the list of volatile-qualified assignments that 15162 /// we are going to warn are deprecated. 15163 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15164 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15165 return; 15166 15167 // Note: ignoring parens here is not justified by the standard rules, but 15168 // ignoring parentheses seems like a more reasonable approach, and this only 15169 // drives a deprecation warning so doesn't affect conformance. 15170 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15171 if (BO->getOpcode() == BO_Assign) { 15172 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15173 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15174 LHSs.end()); 15175 } 15176 } 15177 } 15178 15179 void Sema::PopExpressionEvaluationContext() { 15180 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15181 unsigned NumTypos = Rec.NumTypos; 15182 15183 if (!Rec.Lambdas.empty()) { 15184 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15185 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15186 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15187 unsigned D; 15188 if (Rec.isUnevaluated()) { 15189 // C++11 [expr.prim.lambda]p2: 15190 // A lambda-expression shall not appear in an unevaluated operand 15191 // (Clause 5). 15192 D = diag::err_lambda_unevaluated_operand; 15193 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15194 // C++1y [expr.const]p2: 15195 // A conditional-expression e is a core constant expression unless the 15196 // evaluation of e, following the rules of the abstract machine, would 15197 // evaluate [...] a lambda-expression. 15198 D = diag::err_lambda_in_constant_expression; 15199 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15200 // C++17 [expr.prim.lamda]p2: 15201 // A lambda-expression shall not appear [...] in a template-argument. 15202 D = diag::err_lambda_in_invalid_context; 15203 } else 15204 llvm_unreachable("Couldn't infer lambda error message."); 15205 15206 for (const auto *L : Rec.Lambdas) 15207 Diag(L->getBeginLoc(), D); 15208 } 15209 } 15210 15211 WarnOnPendingNoDerefs(Rec); 15212 15213 // Warn on any volatile-qualified simple-assignments that are not discarded- 15214 // value expressions nor unevaluated operands (those cases get removed from 15215 // this list by CheckUnusedVolatileAssignment). 15216 for (auto *BO : Rec.VolatileAssignmentLHSs) 15217 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15218 << BO->getType(); 15219 15220 // When are coming out of an unevaluated context, clear out any 15221 // temporaries that we may have created as part of the evaluation of 15222 // the expression in that context: they aren't relevant because they 15223 // will never be constructed. 15224 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15225 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15226 ExprCleanupObjects.end()); 15227 Cleanup = Rec.ParentCleanup; 15228 CleanupVarDeclMarking(); 15229 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15230 // Otherwise, merge the contexts together. 15231 } else { 15232 Cleanup.mergeFrom(Rec.ParentCleanup); 15233 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15234 Rec.SavedMaybeODRUseExprs.end()); 15235 } 15236 15237 // Pop the current expression evaluation context off the stack. 15238 ExprEvalContexts.pop_back(); 15239 15240 // The global expression evaluation context record is never popped. 15241 ExprEvalContexts.back().NumTypos += NumTypos; 15242 } 15243 15244 void Sema::DiscardCleanupsInEvaluationContext() { 15245 ExprCleanupObjects.erase( 15246 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15247 ExprCleanupObjects.end()); 15248 Cleanup.reset(); 15249 MaybeODRUseExprs.clear(); 15250 } 15251 15252 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15253 ExprResult Result = CheckPlaceholderExpr(E); 15254 if (Result.isInvalid()) 15255 return ExprError(); 15256 E = Result.get(); 15257 if (!E->getType()->isVariablyModifiedType()) 15258 return E; 15259 return TransformToPotentiallyEvaluated(E); 15260 } 15261 15262 /// Are we in a context that is potentially constant evaluated per C++20 15263 /// [expr.const]p12? 15264 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15265 /// C++2a [expr.const]p12: 15266 // An expression or conversion is potentially constant evaluated if it is 15267 switch (SemaRef.ExprEvalContexts.back().Context) { 15268 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15269 // -- a manifestly constant-evaluated expression, 15270 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15271 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15272 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15273 // -- a potentially-evaluated expression, 15274 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15275 // -- an immediate subexpression of a braced-init-list, 15276 15277 // -- [FIXME] an expression of the form & cast-expression that occurs 15278 // within a templated entity 15279 // -- a subexpression of one of the above that is not a subexpression of 15280 // a nested unevaluated operand. 15281 return true; 15282 15283 case Sema::ExpressionEvaluationContext::Unevaluated: 15284 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15285 // Expressions in this context are never evaluated. 15286 return false; 15287 } 15288 llvm_unreachable("Invalid context"); 15289 } 15290 15291 /// Return true if this function has a calling convention that requires mangling 15292 /// in the size of the parameter pack. 15293 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15294 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15295 // we don't need parameter type sizes. 15296 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15297 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15298 TT.getArch() != llvm::Triple::x86_64)) 15299 return false; 15300 15301 // If this is C++ and this isn't an extern "C" function, parameters do not 15302 // need to be complete. In this case, C++ mangling will apply, which doesn't 15303 // use the size of the parameters. 15304 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15305 return false; 15306 15307 // Stdcall, fastcall, and vectorcall need this special treatment. 15308 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15309 switch (CC) { 15310 case CC_X86StdCall: 15311 case CC_X86FastCall: 15312 case CC_X86VectorCall: 15313 return true; 15314 default: 15315 break; 15316 } 15317 return false; 15318 } 15319 15320 /// Require that all of the parameter types of function be complete. Normally, 15321 /// parameter types are only required to be complete when a function is called 15322 /// or defined, but to mangle functions with certain calling conventions, the 15323 /// mangler needs to know the size of the parameter list. In this situation, 15324 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15325 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15326 /// result in a linker error. Clang doesn't implement this behavior, and instead 15327 /// attempts to error at compile time. 15328 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15329 SourceLocation Loc) { 15330 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15331 FunctionDecl *FD; 15332 ParmVarDecl *Param; 15333 15334 public: 15335 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15336 : FD(FD), Param(Param) {} 15337 15338 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15339 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15340 StringRef CCName; 15341 switch (CC) { 15342 case CC_X86StdCall: 15343 CCName = "stdcall"; 15344 break; 15345 case CC_X86FastCall: 15346 CCName = "fastcall"; 15347 break; 15348 case CC_X86VectorCall: 15349 CCName = "vectorcall"; 15350 break; 15351 default: 15352 llvm_unreachable("CC does not need mangling"); 15353 } 15354 15355 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15356 << Param->getDeclName() << FD->getDeclName() << CCName; 15357 } 15358 }; 15359 15360 for (ParmVarDecl *Param : FD->parameters()) { 15361 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15362 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15363 } 15364 } 15365 15366 namespace { 15367 enum class OdrUseContext { 15368 /// Declarations in this context are not odr-used. 15369 None, 15370 /// Declarations in this context are formally odr-used, but this is a 15371 /// dependent context. 15372 Dependent, 15373 /// Declarations in this context are odr-used but not actually used (yet). 15374 FormallyOdrUsed, 15375 /// Declarations in this context are used. 15376 Used 15377 }; 15378 } 15379 15380 /// Are we within a context in which references to resolved functions or to 15381 /// variables result in odr-use? 15382 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15383 OdrUseContext Result; 15384 15385 switch (SemaRef.ExprEvalContexts.back().Context) { 15386 case Sema::ExpressionEvaluationContext::Unevaluated: 15387 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15388 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15389 return OdrUseContext::None; 15390 15391 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15392 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15393 Result = OdrUseContext::Used; 15394 break; 15395 15396 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15397 Result = OdrUseContext::FormallyOdrUsed; 15398 break; 15399 15400 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15401 // A default argument formally results in odr-use, but doesn't actually 15402 // result in a use in any real sense until it itself is used. 15403 Result = OdrUseContext::FormallyOdrUsed; 15404 break; 15405 } 15406 15407 if (SemaRef.CurContext->isDependentContext()) 15408 return OdrUseContext::Dependent; 15409 15410 return Result; 15411 } 15412 15413 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15414 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 15415 return Func->isConstexpr() && 15416 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 15417 } 15418 15419 /// Mark a function referenced, and check whether it is odr-used 15420 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15421 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15422 bool MightBeOdrUse) { 15423 assert(Func && "No function?"); 15424 15425 Func->setReferenced(); 15426 15427 // Recursive functions aren't really used until they're used from some other 15428 // context. 15429 bool IsRecursiveCall = CurContext == Func; 15430 15431 // C++11 [basic.def.odr]p3: 15432 // A function whose name appears as a potentially-evaluated expression is 15433 // odr-used if it is the unique lookup result or the selected member of a 15434 // set of overloaded functions [...]. 15435 // 15436 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15437 // can just check that here. 15438 OdrUseContext OdrUse = 15439 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15440 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15441 OdrUse = OdrUseContext::FormallyOdrUsed; 15442 15443 // Trivial default constructors and destructors are never actually used. 15444 // FIXME: What about other special members? 15445 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15446 OdrUse == OdrUseContext::Used) { 15447 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15448 if (Constructor->isDefaultConstructor()) 15449 OdrUse = OdrUseContext::FormallyOdrUsed; 15450 if (isa<CXXDestructorDecl>(Func)) 15451 OdrUse = OdrUseContext::FormallyOdrUsed; 15452 } 15453 15454 // C++20 [expr.const]p12: 15455 // A function [...] is needed for constant evaluation if it is [...] a 15456 // constexpr function that is named by an expression that is potentially 15457 // constant evaluated 15458 bool NeededForConstantEvaluation = 15459 isPotentiallyConstantEvaluatedContext(*this) && 15460 isImplicitlyDefinableConstexprFunction(Func); 15461 15462 // Determine whether we require a function definition to exist, per 15463 // C++11 [temp.inst]p3: 15464 // Unless a function template specialization has been explicitly 15465 // instantiated or explicitly specialized, the function template 15466 // specialization is implicitly instantiated when the specialization is 15467 // referenced in a context that requires a function definition to exist. 15468 // C++20 [temp.inst]p7: 15469 // The existence of a definition of a [...] function is considered to 15470 // affect the semantics of the program if the [...] function is needed for 15471 // constant evaluation by an expression 15472 // C++20 [basic.def.odr]p10: 15473 // Every program shall contain exactly one definition of every non-inline 15474 // function or variable that is odr-used in that program outside of a 15475 // discarded statement 15476 // C++20 [special]p1: 15477 // The implementation will implicitly define [defaulted special members] 15478 // if they are odr-used or needed for constant evaluation. 15479 // 15480 // Note that we skip the implicit instantiation of templates that are only 15481 // used in unused default arguments or by recursive calls to themselves. 15482 // This is formally non-conforming, but seems reasonable in practice. 15483 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15484 NeededForConstantEvaluation); 15485 15486 // C++14 [temp.expl.spec]p6: 15487 // If a template [...] is explicitly specialized then that specialization 15488 // shall be declared before the first use of that specialization that would 15489 // cause an implicit instantiation to take place, in every translation unit 15490 // in which such a use occurs 15491 if (NeedDefinition && 15492 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15493 Func->getMemberSpecializationInfo())) 15494 checkSpecializationVisibility(Loc, Func); 15495 15496 // C++14 [except.spec]p17: 15497 // An exception-specification is considered to be needed when: 15498 // - the function is odr-used or, if it appears in an unevaluated operand, 15499 // would be odr-used if the expression were potentially-evaluated; 15500 // 15501 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15502 // function is a pure virtual function we're calling, and in that case the 15503 // function was selected by overload resolution and we need to resolve its 15504 // exception specification for a different reason. 15505 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15506 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15507 ResolveExceptionSpec(Loc, FPT); 15508 15509 if (getLangOpts().CUDA) 15510 CheckCUDACall(Loc, Func); 15511 15512 // If we need a definition, try to create one. 15513 if (NeedDefinition && !Func->getBody()) { 15514 runWithSufficientStackSpace(Loc, [&] { 15515 if (CXXConstructorDecl *Constructor = 15516 dyn_cast<CXXConstructorDecl>(Func)) { 15517 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15518 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15519 if (Constructor->isDefaultConstructor()) { 15520 if (Constructor->isTrivial() && 15521 !Constructor->hasAttr<DLLExportAttr>()) 15522 return; 15523 DefineImplicitDefaultConstructor(Loc, Constructor); 15524 } else if (Constructor->isCopyConstructor()) { 15525 DefineImplicitCopyConstructor(Loc, Constructor); 15526 } else if (Constructor->isMoveConstructor()) { 15527 DefineImplicitMoveConstructor(Loc, Constructor); 15528 } 15529 } else if (Constructor->getInheritedConstructor()) { 15530 DefineInheritingConstructor(Loc, Constructor); 15531 } 15532 } else if (CXXDestructorDecl *Destructor = 15533 dyn_cast<CXXDestructorDecl>(Func)) { 15534 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15535 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15536 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15537 return; 15538 DefineImplicitDestructor(Loc, Destructor); 15539 } 15540 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15541 MarkVTableUsed(Loc, Destructor->getParent()); 15542 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15543 if (MethodDecl->isOverloadedOperator() && 15544 MethodDecl->getOverloadedOperator() == OO_Equal) { 15545 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15546 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15547 if (MethodDecl->isCopyAssignmentOperator()) 15548 DefineImplicitCopyAssignment(Loc, MethodDecl); 15549 else if (MethodDecl->isMoveAssignmentOperator()) 15550 DefineImplicitMoveAssignment(Loc, MethodDecl); 15551 } 15552 } else if (isa<CXXConversionDecl>(MethodDecl) && 15553 MethodDecl->getParent()->isLambda()) { 15554 CXXConversionDecl *Conversion = 15555 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15556 if (Conversion->isLambdaToBlockPointerConversion()) 15557 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15558 else 15559 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15560 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15561 MarkVTableUsed(Loc, MethodDecl->getParent()); 15562 } 15563 15564 // Implicit instantiation of function templates and member functions of 15565 // class templates. 15566 if (Func->isImplicitlyInstantiable()) { 15567 TemplateSpecializationKind TSK = 15568 Func->getTemplateSpecializationKindForInstantiation(); 15569 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15570 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15571 if (FirstInstantiation) { 15572 PointOfInstantiation = Loc; 15573 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15574 } else if (TSK != TSK_ImplicitInstantiation) { 15575 // Use the point of use as the point of instantiation, instead of the 15576 // point of explicit instantiation (which we track as the actual point 15577 // of instantiation). This gives better backtraces in diagnostics. 15578 PointOfInstantiation = Loc; 15579 } 15580 15581 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15582 Func->isConstexpr()) { 15583 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15584 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15585 CodeSynthesisContexts.size()) 15586 PendingLocalImplicitInstantiations.push_back( 15587 std::make_pair(Func, PointOfInstantiation)); 15588 else if (Func->isConstexpr()) 15589 // Do not defer instantiations of constexpr functions, to avoid the 15590 // expression evaluator needing to call back into Sema if it sees a 15591 // call to such a function. 15592 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15593 else { 15594 Func->setInstantiationIsPending(true); 15595 PendingInstantiations.push_back( 15596 std::make_pair(Func, PointOfInstantiation)); 15597 // Notify the consumer that a function was implicitly instantiated. 15598 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15599 } 15600 } 15601 } else { 15602 // Walk redefinitions, as some of them may be instantiable. 15603 for (auto i : Func->redecls()) { 15604 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15605 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15606 } 15607 } 15608 }); 15609 } 15610 15611 // If this is the first "real" use, act on that. 15612 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15613 // Keep track of used but undefined functions. 15614 if (!Func->isDefined()) { 15615 if (mightHaveNonExternalLinkage(Func)) 15616 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15617 else if (Func->getMostRecentDecl()->isInlined() && 15618 !LangOpts.GNUInline && 15619 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15620 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15621 else if (isExternalWithNoLinkageType(Func)) 15622 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15623 } 15624 15625 // Some x86 Windows calling conventions mangle the size of the parameter 15626 // pack into the name. Computing the size of the parameters requires the 15627 // parameter types to be complete. Check that now. 15628 if (funcHasParameterSizeMangling(*this, Func)) 15629 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15630 15631 Func->markUsed(Context); 15632 } 15633 15634 if (LangOpts.OpenMP) { 15635 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15636 if (LangOpts.OpenMPIsDevice) 15637 checkOpenMPDeviceFunction(Loc, Func); 15638 else 15639 checkOpenMPHostFunction(Loc, Func); 15640 } 15641 } 15642 15643 /// Directly mark a variable odr-used. Given a choice, prefer to use 15644 /// MarkVariableReferenced since it does additional checks and then 15645 /// calls MarkVarDeclODRUsed. 15646 /// If the variable must be captured: 15647 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15648 /// - else capture it in the DeclContext that maps to the 15649 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15650 static void 15651 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15652 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15653 // Keep track of used but undefined variables. 15654 // FIXME: We shouldn't suppress this warning for static data members. 15655 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15656 (!Var->isExternallyVisible() || Var->isInline() || 15657 SemaRef.isExternalWithNoLinkageType(Var)) && 15658 !(Var->isStaticDataMember() && Var->hasInit())) { 15659 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15660 if (old.isInvalid()) 15661 old = Loc; 15662 } 15663 QualType CaptureType, DeclRefType; 15664 if (SemaRef.LangOpts.OpenMP) 15665 SemaRef.tryCaptureOpenMPLambdas(Var); 15666 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15667 /*EllipsisLoc*/ SourceLocation(), 15668 /*BuildAndDiagnose*/ true, 15669 CaptureType, DeclRefType, 15670 FunctionScopeIndexToStopAt); 15671 15672 Var->markUsed(SemaRef.Context); 15673 } 15674 15675 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15676 SourceLocation Loc, 15677 unsigned CapturingScopeIndex) { 15678 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15679 } 15680 15681 static void 15682 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15683 ValueDecl *var, DeclContext *DC) { 15684 DeclContext *VarDC = var->getDeclContext(); 15685 15686 // If the parameter still belongs to the translation unit, then 15687 // we're actually just using one parameter in the declaration of 15688 // the next. 15689 if (isa<ParmVarDecl>(var) && 15690 isa<TranslationUnitDecl>(VarDC)) 15691 return; 15692 15693 // For C code, don't diagnose about capture if we're not actually in code 15694 // right now; it's impossible to write a non-constant expression outside of 15695 // function context, so we'll get other (more useful) diagnostics later. 15696 // 15697 // For C++, things get a bit more nasty... it would be nice to suppress this 15698 // diagnostic for certain cases like using a local variable in an array bound 15699 // for a member of a local class, but the correct predicate is not obvious. 15700 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15701 return; 15702 15703 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15704 unsigned ContextKind = 3; // unknown 15705 if (isa<CXXMethodDecl>(VarDC) && 15706 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15707 ContextKind = 2; 15708 } else if (isa<FunctionDecl>(VarDC)) { 15709 ContextKind = 0; 15710 } else if (isa<BlockDecl>(VarDC)) { 15711 ContextKind = 1; 15712 } 15713 15714 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15715 << var << ValueKind << ContextKind << VarDC; 15716 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15717 << var; 15718 15719 // FIXME: Add additional diagnostic info about class etc. which prevents 15720 // capture. 15721 } 15722 15723 15724 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15725 bool &SubCapturesAreNested, 15726 QualType &CaptureType, 15727 QualType &DeclRefType) { 15728 // Check whether we've already captured it. 15729 if (CSI->CaptureMap.count(Var)) { 15730 // If we found a capture, any subcaptures are nested. 15731 SubCapturesAreNested = true; 15732 15733 // Retrieve the capture type for this variable. 15734 CaptureType = CSI->getCapture(Var).getCaptureType(); 15735 15736 // Compute the type of an expression that refers to this variable. 15737 DeclRefType = CaptureType.getNonReferenceType(); 15738 15739 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15740 // are mutable in the sense that user can change their value - they are 15741 // private instances of the captured declarations. 15742 const Capture &Cap = CSI->getCapture(Var); 15743 if (Cap.isCopyCapture() && 15744 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15745 !(isa<CapturedRegionScopeInfo>(CSI) && 15746 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15747 DeclRefType.addConst(); 15748 return true; 15749 } 15750 return false; 15751 } 15752 15753 // Only block literals, captured statements, and lambda expressions can 15754 // capture; other scopes don't work. 15755 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15756 SourceLocation Loc, 15757 const bool Diagnose, Sema &S) { 15758 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15759 return getLambdaAwareParentOfDeclContext(DC); 15760 else if (Var->hasLocalStorage()) { 15761 if (Diagnose) 15762 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15763 } 15764 return nullptr; 15765 } 15766 15767 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15768 // certain types of variables (unnamed, variably modified types etc.) 15769 // so check for eligibility. 15770 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15771 SourceLocation Loc, 15772 const bool Diagnose, Sema &S) { 15773 15774 bool IsBlock = isa<BlockScopeInfo>(CSI); 15775 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15776 15777 // Lambdas are not allowed to capture unnamed variables 15778 // (e.g. anonymous unions). 15779 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15780 // assuming that's the intent. 15781 if (IsLambda && !Var->getDeclName()) { 15782 if (Diagnose) { 15783 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15784 S.Diag(Var->getLocation(), diag::note_declared_at); 15785 } 15786 return false; 15787 } 15788 15789 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15790 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15791 if (Diagnose) { 15792 S.Diag(Loc, diag::err_ref_vm_type); 15793 S.Diag(Var->getLocation(), diag::note_previous_decl) 15794 << Var->getDeclName(); 15795 } 15796 return false; 15797 } 15798 // Prohibit structs with flexible array members too. 15799 // We cannot capture what is in the tail end of the struct. 15800 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15801 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15802 if (Diagnose) { 15803 if (IsBlock) 15804 S.Diag(Loc, diag::err_ref_flexarray_type); 15805 else 15806 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15807 << Var->getDeclName(); 15808 S.Diag(Var->getLocation(), diag::note_previous_decl) 15809 << Var->getDeclName(); 15810 } 15811 return false; 15812 } 15813 } 15814 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15815 // Lambdas and captured statements are not allowed to capture __block 15816 // variables; they don't support the expected semantics. 15817 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15818 if (Diagnose) { 15819 S.Diag(Loc, diag::err_capture_block_variable) 15820 << Var->getDeclName() << !IsLambda; 15821 S.Diag(Var->getLocation(), diag::note_previous_decl) 15822 << Var->getDeclName(); 15823 } 15824 return false; 15825 } 15826 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15827 if (S.getLangOpts().OpenCL && IsBlock && 15828 Var->getType()->isBlockPointerType()) { 15829 if (Diagnose) 15830 S.Diag(Loc, diag::err_opencl_block_ref_block); 15831 return false; 15832 } 15833 15834 return true; 15835 } 15836 15837 // Returns true if the capture by block was successful. 15838 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15839 SourceLocation Loc, 15840 const bool BuildAndDiagnose, 15841 QualType &CaptureType, 15842 QualType &DeclRefType, 15843 const bool Nested, 15844 Sema &S, bool Invalid) { 15845 bool ByRef = false; 15846 15847 // Blocks are not allowed to capture arrays, excepting OpenCL. 15848 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15849 // (decayed to pointers). 15850 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15851 if (BuildAndDiagnose) { 15852 S.Diag(Loc, diag::err_ref_array_type); 15853 S.Diag(Var->getLocation(), diag::note_previous_decl) 15854 << Var->getDeclName(); 15855 Invalid = true; 15856 } else { 15857 return false; 15858 } 15859 } 15860 15861 // Forbid the block-capture of autoreleasing variables. 15862 if (!Invalid && 15863 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15864 if (BuildAndDiagnose) { 15865 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15866 << /*block*/ 0; 15867 S.Diag(Var->getLocation(), diag::note_previous_decl) 15868 << Var->getDeclName(); 15869 Invalid = true; 15870 } else { 15871 return false; 15872 } 15873 } 15874 15875 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15876 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15877 QualType PointeeTy = PT->getPointeeType(); 15878 15879 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15880 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15881 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15882 if (BuildAndDiagnose) { 15883 SourceLocation VarLoc = Var->getLocation(); 15884 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15885 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15886 } 15887 } 15888 } 15889 15890 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15891 if (HasBlocksAttr || CaptureType->isReferenceType() || 15892 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15893 // Block capture by reference does not change the capture or 15894 // declaration reference types. 15895 ByRef = true; 15896 } else { 15897 // Block capture by copy introduces 'const'. 15898 CaptureType = CaptureType.getNonReferenceType().withConst(); 15899 DeclRefType = CaptureType; 15900 } 15901 15902 // Actually capture the variable. 15903 if (BuildAndDiagnose) 15904 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15905 CaptureType, Invalid); 15906 15907 return !Invalid; 15908 } 15909 15910 15911 /// Capture the given variable in the captured region. 15912 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15913 VarDecl *Var, 15914 SourceLocation Loc, 15915 const bool BuildAndDiagnose, 15916 QualType &CaptureType, 15917 QualType &DeclRefType, 15918 const bool RefersToCapturedVariable, 15919 Sema &S, bool Invalid) { 15920 // By default, capture variables by reference. 15921 bool ByRef = true; 15922 // Using an LValue reference type is consistent with Lambdas (see below). 15923 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15924 if (S.isOpenMPCapturedDecl(Var)) { 15925 bool HasConst = DeclRefType.isConstQualified(); 15926 DeclRefType = DeclRefType.getUnqualifiedType(); 15927 // Don't lose diagnostics about assignments to const. 15928 if (HasConst) 15929 DeclRefType.addConst(); 15930 } 15931 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15932 RSI->OpenMPCaptureLevel); 15933 } 15934 15935 if (ByRef) 15936 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15937 else 15938 CaptureType = DeclRefType; 15939 15940 // Actually capture the variable. 15941 if (BuildAndDiagnose) 15942 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15943 Loc, SourceLocation(), CaptureType, Invalid); 15944 15945 return !Invalid; 15946 } 15947 15948 /// Capture the given variable in the lambda. 15949 static bool captureInLambda(LambdaScopeInfo *LSI, 15950 VarDecl *Var, 15951 SourceLocation Loc, 15952 const bool BuildAndDiagnose, 15953 QualType &CaptureType, 15954 QualType &DeclRefType, 15955 const bool RefersToCapturedVariable, 15956 const Sema::TryCaptureKind Kind, 15957 SourceLocation EllipsisLoc, 15958 const bool IsTopScope, 15959 Sema &S, bool Invalid) { 15960 // Determine whether we are capturing by reference or by value. 15961 bool ByRef = false; 15962 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15963 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15964 } else { 15965 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15966 } 15967 15968 // Compute the type of the field that will capture this variable. 15969 if (ByRef) { 15970 // C++11 [expr.prim.lambda]p15: 15971 // An entity is captured by reference if it is implicitly or 15972 // explicitly captured but not captured by copy. It is 15973 // unspecified whether additional unnamed non-static data 15974 // members are declared in the closure type for entities 15975 // captured by reference. 15976 // 15977 // FIXME: It is not clear whether we want to build an lvalue reference 15978 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15979 // to do the former, while EDG does the latter. Core issue 1249 will 15980 // clarify, but for now we follow GCC because it's a more permissive and 15981 // easily defensible position. 15982 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15983 } else { 15984 // C++11 [expr.prim.lambda]p14: 15985 // For each entity captured by copy, an unnamed non-static 15986 // data member is declared in the closure type. The 15987 // declaration order of these members is unspecified. The type 15988 // of such a data member is the type of the corresponding 15989 // captured entity if the entity is not a reference to an 15990 // object, or the referenced type otherwise. [Note: If the 15991 // captured entity is a reference to a function, the 15992 // corresponding data member is also a reference to a 15993 // function. - end note ] 15994 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15995 if (!RefType->getPointeeType()->isFunctionType()) 15996 CaptureType = RefType->getPointeeType(); 15997 } 15998 15999 // Forbid the lambda copy-capture of autoreleasing variables. 16000 if (!Invalid && 16001 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16002 if (BuildAndDiagnose) { 16003 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16004 S.Diag(Var->getLocation(), diag::note_previous_decl) 16005 << Var->getDeclName(); 16006 Invalid = true; 16007 } else { 16008 return false; 16009 } 16010 } 16011 16012 // Make sure that by-copy captures are of a complete and non-abstract type. 16013 if (!Invalid && BuildAndDiagnose) { 16014 if (!CaptureType->isDependentType() && 16015 S.RequireCompleteType(Loc, CaptureType, 16016 diag::err_capture_of_incomplete_type, 16017 Var->getDeclName())) 16018 Invalid = true; 16019 else if (S.RequireNonAbstractType(Loc, CaptureType, 16020 diag::err_capture_of_abstract_type)) 16021 Invalid = true; 16022 } 16023 } 16024 16025 // Compute the type of a reference to this captured variable. 16026 if (ByRef) 16027 DeclRefType = CaptureType.getNonReferenceType(); 16028 else { 16029 // C++ [expr.prim.lambda]p5: 16030 // The closure type for a lambda-expression has a public inline 16031 // function call operator [...]. This function call operator is 16032 // declared const (9.3.1) if and only if the lambda-expression's 16033 // parameter-declaration-clause is not followed by mutable. 16034 DeclRefType = CaptureType.getNonReferenceType(); 16035 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16036 DeclRefType.addConst(); 16037 } 16038 16039 // Add the capture. 16040 if (BuildAndDiagnose) 16041 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16042 Loc, EllipsisLoc, CaptureType, Invalid); 16043 16044 return !Invalid; 16045 } 16046 16047 bool Sema::tryCaptureVariable( 16048 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16049 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16050 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16051 // An init-capture is notionally from the context surrounding its 16052 // declaration, but its parent DC is the lambda class. 16053 DeclContext *VarDC = Var->getDeclContext(); 16054 if (Var->isInitCapture()) 16055 VarDC = VarDC->getParent(); 16056 16057 DeclContext *DC = CurContext; 16058 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16059 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16060 // We need to sync up the Declaration Context with the 16061 // FunctionScopeIndexToStopAt 16062 if (FunctionScopeIndexToStopAt) { 16063 unsigned FSIndex = FunctionScopes.size() - 1; 16064 while (FSIndex != MaxFunctionScopesIndex) { 16065 DC = getLambdaAwareParentOfDeclContext(DC); 16066 --FSIndex; 16067 } 16068 } 16069 16070 16071 // If the variable is declared in the current context, there is no need to 16072 // capture it. 16073 if (VarDC == DC) return true; 16074 16075 // Capture global variables if it is required to use private copy of this 16076 // variable. 16077 bool IsGlobal = !Var->hasLocalStorage(); 16078 if (IsGlobal && 16079 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16080 MaxFunctionScopesIndex))) 16081 return true; 16082 Var = Var->getCanonicalDecl(); 16083 16084 // Walk up the stack to determine whether we can capture the variable, 16085 // performing the "simple" checks that don't depend on type. We stop when 16086 // we've either hit the declared scope of the variable or find an existing 16087 // capture of that variable. We start from the innermost capturing-entity 16088 // (the DC) and ensure that all intervening capturing-entities 16089 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16090 // declcontext can either capture the variable or have already captured 16091 // the variable. 16092 CaptureType = Var->getType(); 16093 DeclRefType = CaptureType.getNonReferenceType(); 16094 bool Nested = false; 16095 bool Explicit = (Kind != TryCapture_Implicit); 16096 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16097 do { 16098 // Only block literals, captured statements, and lambda expressions can 16099 // capture; other scopes don't work. 16100 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16101 ExprLoc, 16102 BuildAndDiagnose, 16103 *this); 16104 // We need to check for the parent *first* because, if we *have* 16105 // private-captured a global variable, we need to recursively capture it in 16106 // intermediate blocks, lambdas, etc. 16107 if (!ParentDC) { 16108 if (IsGlobal) { 16109 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16110 break; 16111 } 16112 return true; 16113 } 16114 16115 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16116 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16117 16118 16119 // Check whether we've already captured it. 16120 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16121 DeclRefType)) { 16122 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16123 break; 16124 } 16125 // If we are instantiating a generic lambda call operator body, 16126 // we do not want to capture new variables. What was captured 16127 // during either a lambdas transformation or initial parsing 16128 // should be used. 16129 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16130 if (BuildAndDiagnose) { 16131 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16132 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16133 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16134 Diag(Var->getLocation(), diag::note_previous_decl) 16135 << Var->getDeclName(); 16136 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16137 } else 16138 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16139 } 16140 return true; 16141 } 16142 16143 // Try to capture variable-length arrays types. 16144 if (Var->getType()->isVariablyModifiedType()) { 16145 // We're going to walk down into the type and look for VLA 16146 // expressions. 16147 QualType QTy = Var->getType(); 16148 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16149 QTy = PVD->getOriginalType(); 16150 captureVariablyModifiedType(Context, QTy, CSI); 16151 } 16152 16153 if (getLangOpts().OpenMP) { 16154 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16155 // OpenMP private variables should not be captured in outer scope, so 16156 // just break here. Similarly, global variables that are captured in a 16157 // target region should not be captured outside the scope of the region. 16158 if (RSI->CapRegionKind == CR_OpenMP) { 16159 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16160 // If the variable is private (i.e. not captured) and has variably 16161 // modified type, we still need to capture the type for correct 16162 // codegen in all regions, associated with the construct. Currently, 16163 // it is captured in the innermost captured region only. 16164 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16165 QualType QTy = Var->getType(); 16166 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16167 QTy = PVD->getOriginalType(); 16168 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16169 I < E; ++I) { 16170 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16171 FunctionScopes[FunctionScopesIndex - I]); 16172 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16173 "Wrong number of captured regions associated with the " 16174 "OpenMP construct."); 16175 captureVariablyModifiedType(Context, QTy, OuterRSI); 16176 } 16177 } 16178 bool IsTargetCap = !IsOpenMPPrivateDecl && 16179 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16180 // When we detect target captures we are looking from inside the 16181 // target region, therefore we need to propagate the capture from the 16182 // enclosing region. Therefore, the capture is not initially nested. 16183 if (IsTargetCap) 16184 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16185 16186 if (IsTargetCap || IsOpenMPPrivateDecl) { 16187 Nested = !IsTargetCap; 16188 DeclRefType = DeclRefType.getUnqualifiedType(); 16189 CaptureType = Context.getLValueReferenceType(DeclRefType); 16190 break; 16191 } 16192 } 16193 } 16194 } 16195 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16196 // No capture-default, and this is not an explicit capture 16197 // so cannot capture this variable. 16198 if (BuildAndDiagnose) { 16199 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16200 Diag(Var->getLocation(), diag::note_previous_decl) 16201 << Var->getDeclName(); 16202 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16203 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16204 diag::note_lambda_decl); 16205 // FIXME: If we error out because an outer lambda can not implicitly 16206 // capture a variable that an inner lambda explicitly captures, we 16207 // should have the inner lambda do the explicit capture - because 16208 // it makes for cleaner diagnostics later. This would purely be done 16209 // so that the diagnostic does not misleadingly claim that a variable 16210 // can not be captured by a lambda implicitly even though it is captured 16211 // explicitly. Suggestion: 16212 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16213 // at the function head 16214 // - cache the StartingDeclContext - this must be a lambda 16215 // - captureInLambda in the innermost lambda the variable. 16216 } 16217 return true; 16218 } 16219 16220 FunctionScopesIndex--; 16221 DC = ParentDC; 16222 Explicit = false; 16223 } while (!VarDC->Equals(DC)); 16224 16225 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16226 // computing the type of the capture at each step, checking type-specific 16227 // requirements, and adding captures if requested. 16228 // If the variable had already been captured previously, we start capturing 16229 // at the lambda nested within that one. 16230 bool Invalid = false; 16231 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16232 ++I) { 16233 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16234 16235 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16236 // certain types of variables (unnamed, variably modified types etc.) 16237 // so check for eligibility. 16238 if (!Invalid) 16239 Invalid = 16240 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16241 16242 // After encountering an error, if we're actually supposed to capture, keep 16243 // capturing in nested contexts to suppress any follow-on diagnostics. 16244 if (Invalid && !BuildAndDiagnose) 16245 return true; 16246 16247 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16248 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16249 DeclRefType, Nested, *this, Invalid); 16250 Nested = true; 16251 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16252 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16253 CaptureType, DeclRefType, Nested, 16254 *this, Invalid); 16255 Nested = true; 16256 } else { 16257 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16258 Invalid = 16259 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16260 DeclRefType, Nested, Kind, EllipsisLoc, 16261 /*IsTopScope*/ I == N - 1, *this, Invalid); 16262 Nested = true; 16263 } 16264 16265 if (Invalid && !BuildAndDiagnose) 16266 return true; 16267 } 16268 return Invalid; 16269 } 16270 16271 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16272 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16273 QualType CaptureType; 16274 QualType DeclRefType; 16275 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16276 /*BuildAndDiagnose=*/true, CaptureType, 16277 DeclRefType, nullptr); 16278 } 16279 16280 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16281 QualType CaptureType; 16282 QualType DeclRefType; 16283 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16284 /*BuildAndDiagnose=*/false, CaptureType, 16285 DeclRefType, nullptr); 16286 } 16287 16288 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16289 QualType CaptureType; 16290 QualType DeclRefType; 16291 16292 // Determine whether we can capture this variable. 16293 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16294 /*BuildAndDiagnose=*/false, CaptureType, 16295 DeclRefType, nullptr)) 16296 return QualType(); 16297 16298 return DeclRefType; 16299 } 16300 16301 namespace { 16302 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16303 // The produced TemplateArgumentListInfo* points to data stored within this 16304 // object, so should only be used in contexts where the pointer will not be 16305 // used after the CopiedTemplateArgs object is destroyed. 16306 class CopiedTemplateArgs { 16307 bool HasArgs; 16308 TemplateArgumentListInfo TemplateArgStorage; 16309 public: 16310 template<typename RefExpr> 16311 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16312 if (HasArgs) 16313 E->copyTemplateArgumentsInto(TemplateArgStorage); 16314 } 16315 operator TemplateArgumentListInfo*() 16316 #ifdef __has_cpp_attribute 16317 #if __has_cpp_attribute(clang::lifetimebound) 16318 [[clang::lifetimebound]] 16319 #endif 16320 #endif 16321 { 16322 return HasArgs ? &TemplateArgStorage : nullptr; 16323 } 16324 }; 16325 } 16326 16327 /// Walk the set of potential results of an expression and mark them all as 16328 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16329 /// 16330 /// \return A new expression if we found any potential results, ExprEmpty() if 16331 /// not, and ExprError() if we diagnosed an error. 16332 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16333 NonOdrUseReason NOUR) { 16334 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16335 // an object that satisfies the requirements for appearing in a 16336 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16337 // is immediately applied." This function handles the lvalue-to-rvalue 16338 // conversion part. 16339 // 16340 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16341 // transform it into the relevant kind of non-odr-use node and rebuild the 16342 // tree of nodes leading to it. 16343 // 16344 // This is a mini-TreeTransform that only transforms a restricted subset of 16345 // nodes (and only certain operands of them). 16346 16347 // Rebuild a subexpression. 16348 auto Rebuild = [&](Expr *Sub) { 16349 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16350 }; 16351 16352 // Check whether a potential result satisfies the requirements of NOUR. 16353 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16354 // Any entity other than a VarDecl is always odr-used whenever it's named 16355 // in a potentially-evaluated expression. 16356 auto *VD = dyn_cast<VarDecl>(D); 16357 if (!VD) 16358 return true; 16359 16360 // C++2a [basic.def.odr]p4: 16361 // A variable x whose name appears as a potentially-evalauted expression 16362 // e is odr-used by e unless 16363 // -- x is a reference that is usable in constant expressions, or 16364 // -- x is a variable of non-reference type that is usable in constant 16365 // expressions and has no mutable subobjects, and e is an element of 16366 // the set of potential results of an expression of 16367 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16368 // conversion is applied, or 16369 // -- x is a variable of non-reference type, and e is an element of the 16370 // set of potential results of a discarded-value expression to which 16371 // the lvalue-to-rvalue conversion is not applied 16372 // 16373 // We check the first bullet and the "potentially-evaluated" condition in 16374 // BuildDeclRefExpr. We check the type requirements in the second bullet 16375 // in CheckLValueToRValueConversionOperand below. 16376 switch (NOUR) { 16377 case NOUR_None: 16378 case NOUR_Unevaluated: 16379 llvm_unreachable("unexpected non-odr-use-reason"); 16380 16381 case NOUR_Constant: 16382 // Constant references were handled when they were built. 16383 if (VD->getType()->isReferenceType()) 16384 return true; 16385 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16386 if (RD->hasMutableFields()) 16387 return true; 16388 if (!VD->isUsableInConstantExpressions(S.Context)) 16389 return true; 16390 break; 16391 16392 case NOUR_Discarded: 16393 if (VD->getType()->isReferenceType()) 16394 return true; 16395 break; 16396 } 16397 return false; 16398 }; 16399 16400 // Mark that this expression does not constitute an odr-use. 16401 auto MarkNotOdrUsed = [&] { 16402 S.MaybeODRUseExprs.erase(E); 16403 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16404 LSI->markVariableExprAsNonODRUsed(E); 16405 }; 16406 16407 // C++2a [basic.def.odr]p2: 16408 // The set of potential results of an expression e is defined as follows: 16409 switch (E->getStmtClass()) { 16410 // -- If e is an id-expression, ... 16411 case Expr::DeclRefExprClass: { 16412 auto *DRE = cast<DeclRefExpr>(E); 16413 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16414 break; 16415 16416 // Rebuild as a non-odr-use DeclRefExpr. 16417 MarkNotOdrUsed(); 16418 return DeclRefExpr::Create( 16419 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16420 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16421 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16422 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16423 } 16424 16425 case Expr::FunctionParmPackExprClass: { 16426 auto *FPPE = cast<FunctionParmPackExpr>(E); 16427 // If any of the declarations in the pack is odr-used, then the expression 16428 // as a whole constitutes an odr-use. 16429 for (VarDecl *D : *FPPE) 16430 if (IsPotentialResultOdrUsed(D)) 16431 return ExprEmpty(); 16432 16433 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16434 // nothing cares about whether we marked this as an odr-use, but it might 16435 // be useful for non-compiler tools. 16436 MarkNotOdrUsed(); 16437 break; 16438 } 16439 16440 // -- If e is a subscripting operation with an array operand... 16441 case Expr::ArraySubscriptExprClass: { 16442 auto *ASE = cast<ArraySubscriptExpr>(E); 16443 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16444 if (!OldBase->getType()->isArrayType()) 16445 break; 16446 ExprResult Base = Rebuild(OldBase); 16447 if (!Base.isUsable()) 16448 return Base; 16449 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16450 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16451 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16452 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16453 ASE->getRBracketLoc()); 16454 } 16455 16456 case Expr::MemberExprClass: { 16457 auto *ME = cast<MemberExpr>(E); 16458 // -- If e is a class member access expression [...] naming a non-static 16459 // data member... 16460 if (isa<FieldDecl>(ME->getMemberDecl())) { 16461 ExprResult Base = Rebuild(ME->getBase()); 16462 if (!Base.isUsable()) 16463 return Base; 16464 return MemberExpr::Create( 16465 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16466 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16467 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16468 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16469 ME->getObjectKind(), ME->isNonOdrUse()); 16470 } 16471 16472 if (ME->getMemberDecl()->isCXXInstanceMember()) 16473 break; 16474 16475 // -- If e is a class member access expression naming a static data member, 16476 // ... 16477 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16478 break; 16479 16480 // Rebuild as a non-odr-use MemberExpr. 16481 MarkNotOdrUsed(); 16482 return MemberExpr::Create( 16483 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16484 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16485 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16486 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16487 return ExprEmpty(); 16488 } 16489 16490 case Expr::BinaryOperatorClass: { 16491 auto *BO = cast<BinaryOperator>(E); 16492 Expr *LHS = BO->getLHS(); 16493 Expr *RHS = BO->getRHS(); 16494 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16495 if (BO->getOpcode() == BO_PtrMemD) { 16496 ExprResult Sub = Rebuild(LHS); 16497 if (!Sub.isUsable()) 16498 return Sub; 16499 LHS = Sub.get(); 16500 // -- If e is a comma expression, ... 16501 } else if (BO->getOpcode() == BO_Comma) { 16502 ExprResult Sub = Rebuild(RHS); 16503 if (!Sub.isUsable()) 16504 return Sub; 16505 RHS = Sub.get(); 16506 } else { 16507 break; 16508 } 16509 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16510 LHS, RHS); 16511 } 16512 16513 // -- If e has the form (e1)... 16514 case Expr::ParenExprClass: { 16515 auto *PE = cast<ParenExpr>(E); 16516 ExprResult Sub = Rebuild(PE->getSubExpr()); 16517 if (!Sub.isUsable()) 16518 return Sub; 16519 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16520 } 16521 16522 // -- If e is a glvalue conditional expression, ... 16523 // We don't apply this to a binary conditional operator. FIXME: Should we? 16524 case Expr::ConditionalOperatorClass: { 16525 auto *CO = cast<ConditionalOperator>(E); 16526 ExprResult LHS = Rebuild(CO->getLHS()); 16527 if (LHS.isInvalid()) 16528 return ExprError(); 16529 ExprResult RHS = Rebuild(CO->getRHS()); 16530 if (RHS.isInvalid()) 16531 return ExprError(); 16532 if (!LHS.isUsable() && !RHS.isUsable()) 16533 return ExprEmpty(); 16534 if (!LHS.isUsable()) 16535 LHS = CO->getLHS(); 16536 if (!RHS.isUsable()) 16537 RHS = CO->getRHS(); 16538 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16539 CO->getCond(), LHS.get(), RHS.get()); 16540 } 16541 16542 // [Clang extension] 16543 // -- If e has the form __extension__ e1... 16544 case Expr::UnaryOperatorClass: { 16545 auto *UO = cast<UnaryOperator>(E); 16546 if (UO->getOpcode() != UO_Extension) 16547 break; 16548 ExprResult Sub = Rebuild(UO->getSubExpr()); 16549 if (!Sub.isUsable()) 16550 return Sub; 16551 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16552 Sub.get()); 16553 } 16554 16555 // [Clang extension] 16556 // -- If e has the form _Generic(...), the set of potential results is the 16557 // union of the sets of potential results of the associated expressions. 16558 case Expr::GenericSelectionExprClass: { 16559 auto *GSE = cast<GenericSelectionExpr>(E); 16560 16561 SmallVector<Expr *, 4> AssocExprs; 16562 bool AnyChanged = false; 16563 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16564 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16565 if (AssocExpr.isInvalid()) 16566 return ExprError(); 16567 if (AssocExpr.isUsable()) { 16568 AssocExprs.push_back(AssocExpr.get()); 16569 AnyChanged = true; 16570 } else { 16571 AssocExprs.push_back(OrigAssocExpr); 16572 } 16573 } 16574 16575 return AnyChanged ? S.CreateGenericSelectionExpr( 16576 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16577 GSE->getRParenLoc(), GSE->getControllingExpr(), 16578 GSE->getAssocTypeSourceInfos(), AssocExprs) 16579 : ExprEmpty(); 16580 } 16581 16582 // [Clang extension] 16583 // -- If e has the form __builtin_choose_expr(...), the set of potential 16584 // results is the union of the sets of potential results of the 16585 // second and third subexpressions. 16586 case Expr::ChooseExprClass: { 16587 auto *CE = cast<ChooseExpr>(E); 16588 16589 ExprResult LHS = Rebuild(CE->getLHS()); 16590 if (LHS.isInvalid()) 16591 return ExprError(); 16592 16593 ExprResult RHS = Rebuild(CE->getLHS()); 16594 if (RHS.isInvalid()) 16595 return ExprError(); 16596 16597 if (!LHS.get() && !RHS.get()) 16598 return ExprEmpty(); 16599 if (!LHS.isUsable()) 16600 LHS = CE->getLHS(); 16601 if (!RHS.isUsable()) 16602 RHS = CE->getRHS(); 16603 16604 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16605 RHS.get(), CE->getRParenLoc()); 16606 } 16607 16608 // Step through non-syntactic nodes. 16609 case Expr::ConstantExprClass: { 16610 auto *CE = cast<ConstantExpr>(E); 16611 ExprResult Sub = Rebuild(CE->getSubExpr()); 16612 if (!Sub.isUsable()) 16613 return Sub; 16614 return ConstantExpr::Create(S.Context, Sub.get()); 16615 } 16616 16617 // We could mostly rely on the recursive rebuilding to rebuild implicit 16618 // casts, but not at the top level, so rebuild them here. 16619 case Expr::ImplicitCastExprClass: { 16620 auto *ICE = cast<ImplicitCastExpr>(E); 16621 // Only step through the narrow set of cast kinds we expect to encounter. 16622 // Anything else suggests we've left the region in which potential results 16623 // can be found. 16624 switch (ICE->getCastKind()) { 16625 case CK_NoOp: 16626 case CK_DerivedToBase: 16627 case CK_UncheckedDerivedToBase: { 16628 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16629 if (!Sub.isUsable()) 16630 return Sub; 16631 CXXCastPath Path(ICE->path()); 16632 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16633 ICE->getValueKind(), &Path); 16634 } 16635 16636 default: 16637 break; 16638 } 16639 break; 16640 } 16641 16642 default: 16643 break; 16644 } 16645 16646 // Can't traverse through this node. Nothing to do. 16647 return ExprEmpty(); 16648 } 16649 16650 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16651 // Check whether the operand is or contains an object of non-trivial C union 16652 // type. 16653 if (E->getType().isVolatileQualified() && 16654 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16655 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16656 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16657 Sema::NTCUC_LValueToRValueVolatile, 16658 NTCUK_Destruct|NTCUK_Copy); 16659 16660 // C++2a [basic.def.odr]p4: 16661 // [...] an expression of non-volatile-qualified non-class type to which 16662 // the lvalue-to-rvalue conversion is applied [...] 16663 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16664 return E; 16665 16666 ExprResult Result = 16667 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16668 if (Result.isInvalid()) 16669 return ExprError(); 16670 return Result.get() ? Result : E; 16671 } 16672 16673 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16674 Res = CorrectDelayedTyposInExpr(Res); 16675 16676 if (!Res.isUsable()) 16677 return Res; 16678 16679 // If a constant-expression is a reference to a variable where we delay 16680 // deciding whether it is an odr-use, just assume we will apply the 16681 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16682 // (a non-type template argument), we have special handling anyway. 16683 return CheckLValueToRValueConversionOperand(Res.get()); 16684 } 16685 16686 void Sema::CleanupVarDeclMarking() { 16687 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16688 // call. 16689 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16690 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16691 16692 for (Expr *E : LocalMaybeODRUseExprs) { 16693 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16694 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16695 DRE->getLocation(), *this); 16696 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16697 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16698 *this); 16699 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16700 for (VarDecl *VD : *FP) 16701 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16702 } else { 16703 llvm_unreachable("Unexpected expression"); 16704 } 16705 } 16706 16707 assert(MaybeODRUseExprs.empty() && 16708 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16709 } 16710 16711 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16712 VarDecl *Var, Expr *E) { 16713 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16714 isa<FunctionParmPackExpr>(E)) && 16715 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16716 Var->setReferenced(); 16717 16718 if (Var->isInvalidDecl()) 16719 return; 16720 16721 auto *MSI = Var->getMemberSpecializationInfo(); 16722 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16723 : Var->getTemplateSpecializationKind(); 16724 16725 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16726 bool UsableInConstantExpr = 16727 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16728 16729 // C++20 [expr.const]p12: 16730 // A variable [...] is needed for constant evaluation if it is [...] a 16731 // variable whose name appears as a potentially constant evaluated 16732 // expression that is either a contexpr variable or is of non-volatile 16733 // const-qualified integral type or of reference type 16734 bool NeededForConstantEvaluation = 16735 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16736 16737 bool NeedDefinition = 16738 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16739 16740 VarTemplateSpecializationDecl *VarSpec = 16741 dyn_cast<VarTemplateSpecializationDecl>(Var); 16742 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16743 "Can't instantiate a partial template specialization."); 16744 16745 // If this might be a member specialization of a static data member, check 16746 // the specialization is visible. We already did the checks for variable 16747 // template specializations when we created them. 16748 if (NeedDefinition && TSK != TSK_Undeclared && 16749 !isa<VarTemplateSpecializationDecl>(Var)) 16750 SemaRef.checkSpecializationVisibility(Loc, Var); 16751 16752 // Perform implicit instantiation of static data members, static data member 16753 // templates of class templates, and variable template specializations. Delay 16754 // instantiations of variable templates, except for those that could be used 16755 // in a constant expression. 16756 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16757 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16758 // instantiation declaration if a variable is usable in a constant 16759 // expression (among other cases). 16760 bool TryInstantiating = 16761 TSK == TSK_ImplicitInstantiation || 16762 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16763 16764 if (TryInstantiating) { 16765 SourceLocation PointOfInstantiation = 16766 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16767 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16768 if (FirstInstantiation) { 16769 PointOfInstantiation = Loc; 16770 if (MSI) 16771 MSI->setPointOfInstantiation(PointOfInstantiation); 16772 else 16773 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16774 } 16775 16776 bool InstantiationDependent = false; 16777 bool IsNonDependent = 16778 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16779 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16780 : true; 16781 16782 // Do not instantiate specializations that are still type-dependent. 16783 if (IsNonDependent) { 16784 if (UsableInConstantExpr) { 16785 // Do not defer instantiations of variables that could be used in a 16786 // constant expression. 16787 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16788 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16789 }); 16790 } else if (FirstInstantiation || 16791 isa<VarTemplateSpecializationDecl>(Var)) { 16792 // FIXME: For a specialization of a variable template, we don't 16793 // distinguish between "declaration and type implicitly instantiated" 16794 // and "implicit instantiation of definition requested", so we have 16795 // no direct way to avoid enqueueing the pending instantiation 16796 // multiple times. 16797 SemaRef.PendingInstantiations 16798 .push_back(std::make_pair(Var, PointOfInstantiation)); 16799 } 16800 } 16801 } 16802 } 16803 16804 // C++2a [basic.def.odr]p4: 16805 // A variable x whose name appears as a potentially-evaluated expression e 16806 // is odr-used by e unless 16807 // -- x is a reference that is usable in constant expressions 16808 // -- x is a variable of non-reference type that is usable in constant 16809 // expressions and has no mutable subobjects [FIXME], and e is an 16810 // element of the set of potential results of an expression of 16811 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16812 // conversion is applied 16813 // -- x is a variable of non-reference type, and e is an element of the set 16814 // of potential results of a discarded-value expression to which the 16815 // lvalue-to-rvalue conversion is not applied [FIXME] 16816 // 16817 // We check the first part of the second bullet here, and 16818 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16819 // FIXME: To get the third bullet right, we need to delay this even for 16820 // variables that are not usable in constant expressions. 16821 16822 // If we already know this isn't an odr-use, there's nothing more to do. 16823 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16824 if (DRE->isNonOdrUse()) 16825 return; 16826 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16827 if (ME->isNonOdrUse()) 16828 return; 16829 16830 switch (OdrUse) { 16831 case OdrUseContext::None: 16832 assert((!E || isa<FunctionParmPackExpr>(E)) && 16833 "missing non-odr-use marking for unevaluated decl ref"); 16834 break; 16835 16836 case OdrUseContext::FormallyOdrUsed: 16837 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16838 // behavior. 16839 break; 16840 16841 case OdrUseContext::Used: 16842 // If we might later find that this expression isn't actually an odr-use, 16843 // delay the marking. 16844 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16845 SemaRef.MaybeODRUseExprs.insert(E); 16846 else 16847 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16848 break; 16849 16850 case OdrUseContext::Dependent: 16851 // If this is a dependent context, we don't need to mark variables as 16852 // odr-used, but we may still need to track them for lambda capture. 16853 // FIXME: Do we also need to do this inside dependent typeid expressions 16854 // (which are modeled as unevaluated at this point)? 16855 const bool RefersToEnclosingScope = 16856 (SemaRef.CurContext != Var->getDeclContext() && 16857 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16858 if (RefersToEnclosingScope) { 16859 LambdaScopeInfo *const LSI = 16860 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16861 if (LSI && (!LSI->CallOperator || 16862 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16863 // If a variable could potentially be odr-used, defer marking it so 16864 // until we finish analyzing the full expression for any 16865 // lvalue-to-rvalue 16866 // or discarded value conversions that would obviate odr-use. 16867 // Add it to the list of potential captures that will be analyzed 16868 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16869 // unless the variable is a reference that was initialized by a constant 16870 // expression (this will never need to be captured or odr-used). 16871 // 16872 // FIXME: We can simplify this a lot after implementing P0588R1. 16873 assert(E && "Capture variable should be used in an expression."); 16874 if (!Var->getType()->isReferenceType() || 16875 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16876 LSI->addPotentialCapture(E->IgnoreParens()); 16877 } 16878 } 16879 break; 16880 } 16881 } 16882 16883 /// Mark a variable referenced, and check whether it is odr-used 16884 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16885 /// used directly for normal expressions referring to VarDecl. 16886 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16887 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16888 } 16889 16890 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16891 Decl *D, Expr *E, bool MightBeOdrUse) { 16892 if (SemaRef.isInOpenMPDeclareTargetContext()) 16893 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16894 16895 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16896 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16897 return; 16898 } 16899 16900 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16901 16902 // If this is a call to a method via a cast, also mark the method in the 16903 // derived class used in case codegen can devirtualize the call. 16904 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16905 if (!ME) 16906 return; 16907 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16908 if (!MD) 16909 return; 16910 // Only attempt to devirtualize if this is truly a virtual call. 16911 bool IsVirtualCall = MD->isVirtual() && 16912 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16913 if (!IsVirtualCall) 16914 return; 16915 16916 // If it's possible to devirtualize the call, mark the called function 16917 // referenced. 16918 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16919 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16920 if (DM) 16921 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16922 } 16923 16924 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16925 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16926 // TODO: update this with DR# once a defect report is filed. 16927 // C++11 defect. The address of a pure member should not be an ODR use, even 16928 // if it's a qualified reference. 16929 bool OdrUse = true; 16930 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16931 if (Method->isVirtual() && 16932 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16933 OdrUse = false; 16934 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16935 } 16936 16937 /// Perform reference-marking and odr-use handling for a MemberExpr. 16938 void Sema::MarkMemberReferenced(MemberExpr *E) { 16939 // C++11 [basic.def.odr]p2: 16940 // A non-overloaded function whose name appears as a potentially-evaluated 16941 // expression or a member of a set of candidate functions, if selected by 16942 // overload resolution when referred to from a potentially-evaluated 16943 // expression, is odr-used, unless it is a pure virtual function and its 16944 // name is not explicitly qualified. 16945 bool MightBeOdrUse = true; 16946 if (E->performsVirtualDispatch(getLangOpts())) { 16947 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16948 if (Method->isPure()) 16949 MightBeOdrUse = false; 16950 } 16951 SourceLocation Loc = 16952 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16953 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16954 } 16955 16956 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16957 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16958 for (VarDecl *VD : *E) 16959 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16960 } 16961 16962 /// Perform marking for a reference to an arbitrary declaration. It 16963 /// marks the declaration referenced, and performs odr-use checking for 16964 /// functions and variables. This method should not be used when building a 16965 /// normal expression which refers to a variable. 16966 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16967 bool MightBeOdrUse) { 16968 if (MightBeOdrUse) { 16969 if (auto *VD = dyn_cast<VarDecl>(D)) { 16970 MarkVariableReferenced(Loc, VD); 16971 return; 16972 } 16973 } 16974 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16975 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16976 return; 16977 } 16978 D->setReferenced(); 16979 } 16980 16981 namespace { 16982 // Mark all of the declarations used by a type as referenced. 16983 // FIXME: Not fully implemented yet! We need to have a better understanding 16984 // of when we're entering a context we should not recurse into. 16985 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16986 // TreeTransforms rebuilding the type in a new context. Rather than 16987 // duplicating the TreeTransform logic, we should consider reusing it here. 16988 // Currently that causes problems when rebuilding LambdaExprs. 16989 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 16990 Sema &S; 16991 SourceLocation Loc; 16992 16993 public: 16994 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 16995 16996 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 16997 16998 bool TraverseTemplateArgument(const TemplateArgument &Arg); 16999 }; 17000 } 17001 17002 bool MarkReferencedDecls::TraverseTemplateArgument( 17003 const TemplateArgument &Arg) { 17004 { 17005 // A non-type template argument is a constant-evaluated context. 17006 EnterExpressionEvaluationContext Evaluated( 17007 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17008 if (Arg.getKind() == TemplateArgument::Declaration) { 17009 if (Decl *D = Arg.getAsDecl()) 17010 S.MarkAnyDeclReferenced(Loc, D, true); 17011 } else if (Arg.getKind() == TemplateArgument::Expression) { 17012 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17013 } 17014 } 17015 17016 return Inherited::TraverseTemplateArgument(Arg); 17017 } 17018 17019 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17020 MarkReferencedDecls Marker(*this, Loc); 17021 Marker.TraverseType(T); 17022 } 17023 17024 namespace { 17025 /// Helper class that marks all of the declarations referenced by 17026 /// potentially-evaluated subexpressions as "referenced". 17027 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17028 Sema &S; 17029 bool SkipLocalVariables; 17030 17031 public: 17032 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17033 17034 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17035 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17036 17037 void VisitDeclRefExpr(DeclRefExpr *E) { 17038 // If we were asked not to visit local variables, don't. 17039 if (SkipLocalVariables) { 17040 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17041 if (VD->hasLocalStorage()) 17042 return; 17043 } 17044 17045 S.MarkDeclRefReferenced(E); 17046 } 17047 17048 void VisitMemberExpr(MemberExpr *E) { 17049 S.MarkMemberReferenced(E); 17050 Inherited::VisitMemberExpr(E); 17051 } 17052 17053 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17054 S.MarkFunctionReferenced( 17055 E->getBeginLoc(), 17056 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17057 Visit(E->getSubExpr()); 17058 } 17059 17060 void VisitCXXNewExpr(CXXNewExpr *E) { 17061 if (E->getOperatorNew()) 17062 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17063 if (E->getOperatorDelete()) 17064 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17065 Inherited::VisitCXXNewExpr(E); 17066 } 17067 17068 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17069 if (E->getOperatorDelete()) 17070 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17071 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17072 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17073 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17074 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17075 } 17076 17077 Inherited::VisitCXXDeleteExpr(E); 17078 } 17079 17080 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17081 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17082 Inherited::VisitCXXConstructExpr(E); 17083 } 17084 17085 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17086 Visit(E->getExpr()); 17087 } 17088 }; 17089 } 17090 17091 /// Mark any declarations that appear within this expression or any 17092 /// potentially-evaluated subexpressions as "referenced". 17093 /// 17094 /// \param SkipLocalVariables If true, don't mark local variables as 17095 /// 'referenced'. 17096 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17097 bool SkipLocalVariables) { 17098 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17099 } 17100 17101 /// Emit a diagnostic that describes an effect on the run-time behavior 17102 /// of the program being compiled. 17103 /// 17104 /// This routine emits the given diagnostic when the code currently being 17105 /// type-checked is "potentially evaluated", meaning that there is a 17106 /// possibility that the code will actually be executable. Code in sizeof() 17107 /// expressions, code used only during overload resolution, etc., are not 17108 /// potentially evaluated. This routine will suppress such diagnostics or, 17109 /// in the absolutely nutty case of potentially potentially evaluated 17110 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17111 /// later. 17112 /// 17113 /// This routine should be used for all diagnostics that describe the run-time 17114 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17115 /// Failure to do so will likely result in spurious diagnostics or failures 17116 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17117 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17118 const PartialDiagnostic &PD) { 17119 switch (ExprEvalContexts.back().Context) { 17120 case ExpressionEvaluationContext::Unevaluated: 17121 case ExpressionEvaluationContext::UnevaluatedList: 17122 case ExpressionEvaluationContext::UnevaluatedAbstract: 17123 case ExpressionEvaluationContext::DiscardedStatement: 17124 // The argument will never be evaluated, so don't complain. 17125 break; 17126 17127 case ExpressionEvaluationContext::ConstantEvaluated: 17128 // Relevant diagnostics should be produced by constant evaluation. 17129 break; 17130 17131 case ExpressionEvaluationContext::PotentiallyEvaluated: 17132 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17133 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17134 FunctionScopes.back()->PossiblyUnreachableDiags. 17135 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17136 return true; 17137 } 17138 17139 // The initializer of a constexpr variable or of the first declaration of a 17140 // static data member is not syntactically a constant evaluated constant, 17141 // but nonetheless is always required to be a constant expression, so we 17142 // can skip diagnosing. 17143 // FIXME: Using the mangling context here is a hack. 17144 if (auto *VD = dyn_cast_or_null<VarDecl>( 17145 ExprEvalContexts.back().ManglingContextDecl)) { 17146 if (VD->isConstexpr() || 17147 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17148 break; 17149 // FIXME: For any other kind of variable, we should build a CFG for its 17150 // initializer and check whether the context in question is reachable. 17151 } 17152 17153 Diag(Loc, PD); 17154 return true; 17155 } 17156 17157 return false; 17158 } 17159 17160 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17161 const PartialDiagnostic &PD) { 17162 return DiagRuntimeBehavior( 17163 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17164 } 17165 17166 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17167 CallExpr *CE, FunctionDecl *FD) { 17168 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17169 return false; 17170 17171 // If we're inside a decltype's expression, don't check for a valid return 17172 // type or construct temporaries until we know whether this is the last call. 17173 if (ExprEvalContexts.back().ExprContext == 17174 ExpressionEvaluationContextRecord::EK_Decltype) { 17175 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17176 return false; 17177 } 17178 17179 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17180 FunctionDecl *FD; 17181 CallExpr *CE; 17182 17183 public: 17184 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17185 : FD(FD), CE(CE) { } 17186 17187 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17188 if (!FD) { 17189 S.Diag(Loc, diag::err_call_incomplete_return) 17190 << T << CE->getSourceRange(); 17191 return; 17192 } 17193 17194 S.Diag(Loc, diag::err_call_function_incomplete_return) 17195 << CE->getSourceRange() << FD->getDeclName() << T; 17196 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17197 << FD->getDeclName(); 17198 } 17199 } Diagnoser(FD, CE); 17200 17201 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17202 return true; 17203 17204 return false; 17205 } 17206 17207 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17208 // will prevent this condition from triggering, which is what we want. 17209 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17210 SourceLocation Loc; 17211 17212 unsigned diagnostic = diag::warn_condition_is_assignment; 17213 bool IsOrAssign = false; 17214 17215 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17216 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17217 return; 17218 17219 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17220 17221 // Greylist some idioms by putting them into a warning subcategory. 17222 if (ObjCMessageExpr *ME 17223 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17224 Selector Sel = ME->getSelector(); 17225 17226 // self = [<foo> init...] 17227 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17228 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17229 17230 // <foo> = [<bar> nextObject] 17231 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17232 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17233 } 17234 17235 Loc = Op->getOperatorLoc(); 17236 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17237 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17238 return; 17239 17240 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17241 Loc = Op->getOperatorLoc(); 17242 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17243 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17244 else { 17245 // Not an assignment. 17246 return; 17247 } 17248 17249 Diag(Loc, diagnostic) << E->getSourceRange(); 17250 17251 SourceLocation Open = E->getBeginLoc(); 17252 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17253 Diag(Loc, diag::note_condition_assign_silence) 17254 << FixItHint::CreateInsertion(Open, "(") 17255 << FixItHint::CreateInsertion(Close, ")"); 17256 17257 if (IsOrAssign) 17258 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17259 << FixItHint::CreateReplacement(Loc, "!="); 17260 else 17261 Diag(Loc, diag::note_condition_assign_to_comparison) 17262 << FixItHint::CreateReplacement(Loc, "=="); 17263 } 17264 17265 /// Redundant parentheses over an equality comparison can indicate 17266 /// that the user intended an assignment used as condition. 17267 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17268 // Don't warn if the parens came from a macro. 17269 SourceLocation parenLoc = ParenE->getBeginLoc(); 17270 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17271 return; 17272 // Don't warn for dependent expressions. 17273 if (ParenE->isTypeDependent()) 17274 return; 17275 17276 Expr *E = ParenE->IgnoreParens(); 17277 17278 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17279 if (opE->getOpcode() == BO_EQ && 17280 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17281 == Expr::MLV_Valid) { 17282 SourceLocation Loc = opE->getOperatorLoc(); 17283 17284 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17285 SourceRange ParenERange = ParenE->getSourceRange(); 17286 Diag(Loc, diag::note_equality_comparison_silence) 17287 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17288 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17289 Diag(Loc, diag::note_equality_comparison_to_assign) 17290 << FixItHint::CreateReplacement(Loc, "="); 17291 } 17292 } 17293 17294 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17295 bool IsConstexpr) { 17296 DiagnoseAssignmentAsCondition(E); 17297 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17298 DiagnoseEqualityWithExtraParens(parenE); 17299 17300 ExprResult result = CheckPlaceholderExpr(E); 17301 if (result.isInvalid()) return ExprError(); 17302 E = result.get(); 17303 17304 if (!E->isTypeDependent()) { 17305 if (getLangOpts().CPlusPlus) 17306 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17307 17308 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17309 if (ERes.isInvalid()) 17310 return ExprError(); 17311 E = ERes.get(); 17312 17313 QualType T = E->getType(); 17314 if (!T->isScalarType()) { // C99 6.8.4.1p1 17315 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17316 << T << E->getSourceRange(); 17317 return ExprError(); 17318 } 17319 CheckBoolLikeConversion(E, Loc); 17320 } 17321 17322 return E; 17323 } 17324 17325 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17326 Expr *SubExpr, ConditionKind CK) { 17327 // Empty conditions are valid in for-statements. 17328 if (!SubExpr) 17329 return ConditionResult(); 17330 17331 ExprResult Cond; 17332 switch (CK) { 17333 case ConditionKind::Boolean: 17334 Cond = CheckBooleanCondition(Loc, SubExpr); 17335 break; 17336 17337 case ConditionKind::ConstexprIf: 17338 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17339 break; 17340 17341 case ConditionKind::Switch: 17342 Cond = CheckSwitchCondition(Loc, SubExpr); 17343 break; 17344 } 17345 if (Cond.isInvalid()) 17346 return ConditionError(); 17347 17348 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17349 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17350 if (!FullExpr.get()) 17351 return ConditionError(); 17352 17353 return ConditionResult(*this, nullptr, FullExpr, 17354 CK == ConditionKind::ConstexprIf); 17355 } 17356 17357 namespace { 17358 /// A visitor for rebuilding a call to an __unknown_any expression 17359 /// to have an appropriate type. 17360 struct RebuildUnknownAnyFunction 17361 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17362 17363 Sema &S; 17364 17365 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17366 17367 ExprResult VisitStmt(Stmt *S) { 17368 llvm_unreachable("unexpected statement!"); 17369 } 17370 17371 ExprResult VisitExpr(Expr *E) { 17372 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17373 << E->getSourceRange(); 17374 return ExprError(); 17375 } 17376 17377 /// Rebuild an expression which simply semantically wraps another 17378 /// expression which it shares the type and value kind of. 17379 template <class T> ExprResult rebuildSugarExpr(T *E) { 17380 ExprResult SubResult = Visit(E->getSubExpr()); 17381 if (SubResult.isInvalid()) return ExprError(); 17382 17383 Expr *SubExpr = SubResult.get(); 17384 E->setSubExpr(SubExpr); 17385 E->setType(SubExpr->getType()); 17386 E->setValueKind(SubExpr->getValueKind()); 17387 assert(E->getObjectKind() == OK_Ordinary); 17388 return E; 17389 } 17390 17391 ExprResult VisitParenExpr(ParenExpr *E) { 17392 return rebuildSugarExpr(E); 17393 } 17394 17395 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17396 return rebuildSugarExpr(E); 17397 } 17398 17399 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17400 ExprResult SubResult = Visit(E->getSubExpr()); 17401 if (SubResult.isInvalid()) return ExprError(); 17402 17403 Expr *SubExpr = SubResult.get(); 17404 E->setSubExpr(SubExpr); 17405 E->setType(S.Context.getPointerType(SubExpr->getType())); 17406 assert(E->getValueKind() == VK_RValue); 17407 assert(E->getObjectKind() == OK_Ordinary); 17408 return E; 17409 } 17410 17411 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17412 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17413 17414 E->setType(VD->getType()); 17415 17416 assert(E->getValueKind() == VK_RValue); 17417 if (S.getLangOpts().CPlusPlus && 17418 !(isa<CXXMethodDecl>(VD) && 17419 cast<CXXMethodDecl>(VD)->isInstance())) 17420 E->setValueKind(VK_LValue); 17421 17422 return E; 17423 } 17424 17425 ExprResult VisitMemberExpr(MemberExpr *E) { 17426 return resolveDecl(E, E->getMemberDecl()); 17427 } 17428 17429 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17430 return resolveDecl(E, E->getDecl()); 17431 } 17432 }; 17433 } 17434 17435 /// Given a function expression of unknown-any type, try to rebuild it 17436 /// to have a function type. 17437 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17438 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17439 if (Result.isInvalid()) return ExprError(); 17440 return S.DefaultFunctionArrayConversion(Result.get()); 17441 } 17442 17443 namespace { 17444 /// A visitor for rebuilding an expression of type __unknown_anytype 17445 /// into one which resolves the type directly on the referring 17446 /// expression. Strict preservation of the original source 17447 /// structure is not a goal. 17448 struct RebuildUnknownAnyExpr 17449 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17450 17451 Sema &S; 17452 17453 /// The current destination type. 17454 QualType DestType; 17455 17456 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17457 : S(S), DestType(CastType) {} 17458 17459 ExprResult VisitStmt(Stmt *S) { 17460 llvm_unreachable("unexpected statement!"); 17461 } 17462 17463 ExprResult VisitExpr(Expr *E) { 17464 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17465 << E->getSourceRange(); 17466 return ExprError(); 17467 } 17468 17469 ExprResult VisitCallExpr(CallExpr *E); 17470 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17471 17472 /// Rebuild an expression which simply semantically wraps another 17473 /// expression which it shares the type and value kind of. 17474 template <class T> ExprResult rebuildSugarExpr(T *E) { 17475 ExprResult SubResult = Visit(E->getSubExpr()); 17476 if (SubResult.isInvalid()) return ExprError(); 17477 Expr *SubExpr = SubResult.get(); 17478 E->setSubExpr(SubExpr); 17479 E->setType(SubExpr->getType()); 17480 E->setValueKind(SubExpr->getValueKind()); 17481 assert(E->getObjectKind() == OK_Ordinary); 17482 return E; 17483 } 17484 17485 ExprResult VisitParenExpr(ParenExpr *E) { 17486 return rebuildSugarExpr(E); 17487 } 17488 17489 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17490 return rebuildSugarExpr(E); 17491 } 17492 17493 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17494 const PointerType *Ptr = DestType->getAs<PointerType>(); 17495 if (!Ptr) { 17496 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17497 << E->getSourceRange(); 17498 return ExprError(); 17499 } 17500 17501 if (isa<CallExpr>(E->getSubExpr())) { 17502 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17503 << E->getSourceRange(); 17504 return ExprError(); 17505 } 17506 17507 assert(E->getValueKind() == VK_RValue); 17508 assert(E->getObjectKind() == OK_Ordinary); 17509 E->setType(DestType); 17510 17511 // Build the sub-expression as if it were an object of the pointee type. 17512 DestType = Ptr->getPointeeType(); 17513 ExprResult SubResult = Visit(E->getSubExpr()); 17514 if (SubResult.isInvalid()) return ExprError(); 17515 E->setSubExpr(SubResult.get()); 17516 return E; 17517 } 17518 17519 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17520 17521 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17522 17523 ExprResult VisitMemberExpr(MemberExpr *E) { 17524 return resolveDecl(E, E->getMemberDecl()); 17525 } 17526 17527 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17528 return resolveDecl(E, E->getDecl()); 17529 } 17530 }; 17531 } 17532 17533 /// Rebuilds a call expression which yielded __unknown_anytype. 17534 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17535 Expr *CalleeExpr = E->getCallee(); 17536 17537 enum FnKind { 17538 FK_MemberFunction, 17539 FK_FunctionPointer, 17540 FK_BlockPointer 17541 }; 17542 17543 FnKind Kind; 17544 QualType CalleeType = CalleeExpr->getType(); 17545 if (CalleeType == S.Context.BoundMemberTy) { 17546 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17547 Kind = FK_MemberFunction; 17548 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17549 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17550 CalleeType = Ptr->getPointeeType(); 17551 Kind = FK_FunctionPointer; 17552 } else { 17553 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17554 Kind = FK_BlockPointer; 17555 } 17556 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17557 17558 // Verify that this is a legal result type of a function. 17559 if (DestType->isArrayType() || DestType->isFunctionType()) { 17560 unsigned diagID = diag::err_func_returning_array_function; 17561 if (Kind == FK_BlockPointer) 17562 diagID = diag::err_block_returning_array_function; 17563 17564 S.Diag(E->getExprLoc(), diagID) 17565 << DestType->isFunctionType() << DestType; 17566 return ExprError(); 17567 } 17568 17569 // Otherwise, go ahead and set DestType as the call's result. 17570 E->setType(DestType.getNonLValueExprType(S.Context)); 17571 E->setValueKind(Expr::getValueKindForType(DestType)); 17572 assert(E->getObjectKind() == OK_Ordinary); 17573 17574 // Rebuild the function type, replacing the result type with DestType. 17575 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17576 if (Proto) { 17577 // __unknown_anytype(...) is a special case used by the debugger when 17578 // it has no idea what a function's signature is. 17579 // 17580 // We want to build this call essentially under the K&R 17581 // unprototyped rules, but making a FunctionNoProtoType in C++ 17582 // would foul up all sorts of assumptions. However, we cannot 17583 // simply pass all arguments as variadic arguments, nor can we 17584 // portably just call the function under a non-variadic type; see 17585 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17586 // However, it turns out that in practice it is generally safe to 17587 // call a function declared as "A foo(B,C,D);" under the prototype 17588 // "A foo(B,C,D,...);". The only known exception is with the 17589 // Windows ABI, where any variadic function is implicitly cdecl 17590 // regardless of its normal CC. Therefore we change the parameter 17591 // types to match the types of the arguments. 17592 // 17593 // This is a hack, but it is far superior to moving the 17594 // corresponding target-specific code from IR-gen to Sema/AST. 17595 17596 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17597 SmallVector<QualType, 8> ArgTypes; 17598 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17599 ArgTypes.reserve(E->getNumArgs()); 17600 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17601 Expr *Arg = E->getArg(i); 17602 QualType ArgType = Arg->getType(); 17603 if (E->isLValue()) { 17604 ArgType = S.Context.getLValueReferenceType(ArgType); 17605 } else if (E->isXValue()) { 17606 ArgType = S.Context.getRValueReferenceType(ArgType); 17607 } 17608 ArgTypes.push_back(ArgType); 17609 } 17610 ParamTypes = ArgTypes; 17611 } 17612 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17613 Proto->getExtProtoInfo()); 17614 } else { 17615 DestType = S.Context.getFunctionNoProtoType(DestType, 17616 FnType->getExtInfo()); 17617 } 17618 17619 // Rebuild the appropriate pointer-to-function type. 17620 switch (Kind) { 17621 case FK_MemberFunction: 17622 // Nothing to do. 17623 break; 17624 17625 case FK_FunctionPointer: 17626 DestType = S.Context.getPointerType(DestType); 17627 break; 17628 17629 case FK_BlockPointer: 17630 DestType = S.Context.getBlockPointerType(DestType); 17631 break; 17632 } 17633 17634 // Finally, we can recurse. 17635 ExprResult CalleeResult = Visit(CalleeExpr); 17636 if (!CalleeResult.isUsable()) return ExprError(); 17637 E->setCallee(CalleeResult.get()); 17638 17639 // Bind a temporary if necessary. 17640 return S.MaybeBindToTemporary(E); 17641 } 17642 17643 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17644 // Verify that this is a legal result type of a call. 17645 if (DestType->isArrayType() || DestType->isFunctionType()) { 17646 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17647 << DestType->isFunctionType() << DestType; 17648 return ExprError(); 17649 } 17650 17651 // Rewrite the method result type if available. 17652 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17653 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17654 Method->setReturnType(DestType); 17655 } 17656 17657 // Change the type of the message. 17658 E->setType(DestType.getNonReferenceType()); 17659 E->setValueKind(Expr::getValueKindForType(DestType)); 17660 17661 return S.MaybeBindToTemporary(E); 17662 } 17663 17664 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17665 // The only case we should ever see here is a function-to-pointer decay. 17666 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17667 assert(E->getValueKind() == VK_RValue); 17668 assert(E->getObjectKind() == OK_Ordinary); 17669 17670 E->setType(DestType); 17671 17672 // Rebuild the sub-expression as the pointee (function) type. 17673 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17674 17675 ExprResult Result = Visit(E->getSubExpr()); 17676 if (!Result.isUsable()) return ExprError(); 17677 17678 E->setSubExpr(Result.get()); 17679 return E; 17680 } else if (E->getCastKind() == CK_LValueToRValue) { 17681 assert(E->getValueKind() == VK_RValue); 17682 assert(E->getObjectKind() == OK_Ordinary); 17683 17684 assert(isa<BlockPointerType>(E->getType())); 17685 17686 E->setType(DestType); 17687 17688 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17689 DestType = S.Context.getLValueReferenceType(DestType); 17690 17691 ExprResult Result = Visit(E->getSubExpr()); 17692 if (!Result.isUsable()) return ExprError(); 17693 17694 E->setSubExpr(Result.get()); 17695 return E; 17696 } else { 17697 llvm_unreachable("Unhandled cast type!"); 17698 } 17699 } 17700 17701 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17702 ExprValueKind ValueKind = VK_LValue; 17703 QualType Type = DestType; 17704 17705 // We know how to make this work for certain kinds of decls: 17706 17707 // - functions 17708 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17709 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17710 DestType = Ptr->getPointeeType(); 17711 ExprResult Result = resolveDecl(E, VD); 17712 if (Result.isInvalid()) return ExprError(); 17713 return S.ImpCastExprToType(Result.get(), Type, 17714 CK_FunctionToPointerDecay, VK_RValue); 17715 } 17716 17717 if (!Type->isFunctionType()) { 17718 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17719 << VD << E->getSourceRange(); 17720 return ExprError(); 17721 } 17722 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17723 // We must match the FunctionDecl's type to the hack introduced in 17724 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17725 // type. See the lengthy commentary in that routine. 17726 QualType FDT = FD->getType(); 17727 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17728 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17729 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17730 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17731 SourceLocation Loc = FD->getLocation(); 17732 FunctionDecl *NewFD = FunctionDecl::Create( 17733 S.Context, FD->getDeclContext(), Loc, Loc, 17734 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17735 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17736 /*ConstexprKind*/ CSK_unspecified); 17737 17738 if (FD->getQualifier()) 17739 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17740 17741 SmallVector<ParmVarDecl*, 16> Params; 17742 for (const auto &AI : FT->param_types()) { 17743 ParmVarDecl *Param = 17744 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17745 Param->setScopeInfo(0, Params.size()); 17746 Params.push_back(Param); 17747 } 17748 NewFD->setParams(Params); 17749 DRE->setDecl(NewFD); 17750 VD = DRE->getDecl(); 17751 } 17752 } 17753 17754 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17755 if (MD->isInstance()) { 17756 ValueKind = VK_RValue; 17757 Type = S.Context.BoundMemberTy; 17758 } 17759 17760 // Function references aren't l-values in C. 17761 if (!S.getLangOpts().CPlusPlus) 17762 ValueKind = VK_RValue; 17763 17764 // - variables 17765 } else if (isa<VarDecl>(VD)) { 17766 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17767 Type = RefTy->getPointeeType(); 17768 } else if (Type->isFunctionType()) { 17769 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17770 << VD << E->getSourceRange(); 17771 return ExprError(); 17772 } 17773 17774 // - nothing else 17775 } else { 17776 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17777 << VD << E->getSourceRange(); 17778 return ExprError(); 17779 } 17780 17781 // Modifying the declaration like this is friendly to IR-gen but 17782 // also really dangerous. 17783 VD->setType(DestType); 17784 E->setType(Type); 17785 E->setValueKind(ValueKind); 17786 return E; 17787 } 17788 17789 /// Check a cast of an unknown-any type. We intentionally only 17790 /// trigger this for C-style casts. 17791 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17792 Expr *CastExpr, CastKind &CastKind, 17793 ExprValueKind &VK, CXXCastPath &Path) { 17794 // The type we're casting to must be either void or complete. 17795 if (!CastType->isVoidType() && 17796 RequireCompleteType(TypeRange.getBegin(), CastType, 17797 diag::err_typecheck_cast_to_incomplete)) 17798 return ExprError(); 17799 17800 // Rewrite the casted expression from scratch. 17801 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17802 if (!result.isUsable()) return ExprError(); 17803 17804 CastExpr = result.get(); 17805 VK = CastExpr->getValueKind(); 17806 CastKind = CK_NoOp; 17807 17808 return CastExpr; 17809 } 17810 17811 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17812 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17813 } 17814 17815 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17816 Expr *arg, QualType ¶mType) { 17817 // If the syntactic form of the argument is not an explicit cast of 17818 // any sort, just do default argument promotion. 17819 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17820 if (!castArg) { 17821 ExprResult result = DefaultArgumentPromotion(arg); 17822 if (result.isInvalid()) return ExprError(); 17823 paramType = result.get()->getType(); 17824 return result; 17825 } 17826 17827 // Otherwise, use the type that was written in the explicit cast. 17828 assert(!arg->hasPlaceholderType()); 17829 paramType = castArg->getTypeAsWritten(); 17830 17831 // Copy-initialize a parameter of that type. 17832 InitializedEntity entity = 17833 InitializedEntity::InitializeParameter(Context, paramType, 17834 /*consumed*/ false); 17835 return PerformCopyInitialization(entity, callLoc, arg); 17836 } 17837 17838 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17839 Expr *orig = E; 17840 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17841 while (true) { 17842 E = E->IgnoreParenImpCasts(); 17843 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17844 E = call->getCallee(); 17845 diagID = diag::err_uncasted_call_of_unknown_any; 17846 } else { 17847 break; 17848 } 17849 } 17850 17851 SourceLocation loc; 17852 NamedDecl *d; 17853 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17854 loc = ref->getLocation(); 17855 d = ref->getDecl(); 17856 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17857 loc = mem->getMemberLoc(); 17858 d = mem->getMemberDecl(); 17859 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17860 diagID = diag::err_uncasted_call_of_unknown_any; 17861 loc = msg->getSelectorStartLoc(); 17862 d = msg->getMethodDecl(); 17863 if (!d) { 17864 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17865 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17866 << orig->getSourceRange(); 17867 return ExprError(); 17868 } 17869 } else { 17870 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17871 << E->getSourceRange(); 17872 return ExprError(); 17873 } 17874 17875 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17876 17877 // Never recoverable. 17878 return ExprError(); 17879 } 17880 17881 /// Check for operands with placeholder types and complain if found. 17882 /// Returns ExprError() if there was an error and no recovery was possible. 17883 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17884 if (!getLangOpts().CPlusPlus) { 17885 // C cannot handle TypoExpr nodes on either side of a binop because it 17886 // doesn't handle dependent types properly, so make sure any TypoExprs have 17887 // been dealt with before checking the operands. 17888 ExprResult Result = CorrectDelayedTyposInExpr(E); 17889 if (!Result.isUsable()) return ExprError(); 17890 E = Result.get(); 17891 } 17892 17893 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17894 if (!placeholderType) return E; 17895 17896 switch (placeholderType->getKind()) { 17897 17898 // Overloaded expressions. 17899 case BuiltinType::Overload: { 17900 // Try to resolve a single function template specialization. 17901 // This is obligatory. 17902 ExprResult Result = E; 17903 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17904 return Result; 17905 17906 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17907 // leaves Result unchanged on failure. 17908 Result = E; 17909 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17910 return Result; 17911 17912 // If that failed, try to recover with a call. 17913 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17914 /*complain*/ true); 17915 return Result; 17916 } 17917 17918 // Bound member functions. 17919 case BuiltinType::BoundMember: { 17920 ExprResult result = E; 17921 const Expr *BME = E->IgnoreParens(); 17922 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17923 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17924 if (isa<CXXPseudoDestructorExpr>(BME)) { 17925 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17926 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17927 if (ME->getMemberNameInfo().getName().getNameKind() == 17928 DeclarationName::CXXDestructorName) 17929 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17930 } 17931 tryToRecoverWithCall(result, PD, 17932 /*complain*/ true); 17933 return result; 17934 } 17935 17936 // ARC unbridged casts. 17937 case BuiltinType::ARCUnbridgedCast: { 17938 Expr *realCast = stripARCUnbridgedCast(E); 17939 diagnoseARCUnbridgedCast(realCast); 17940 return realCast; 17941 } 17942 17943 // Expressions of unknown type. 17944 case BuiltinType::UnknownAny: 17945 return diagnoseUnknownAnyExpr(*this, E); 17946 17947 // Pseudo-objects. 17948 case BuiltinType::PseudoObject: 17949 return checkPseudoObjectRValue(E); 17950 17951 case BuiltinType::BuiltinFn: { 17952 // Accept __noop without parens by implicitly converting it to a call expr. 17953 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17954 if (DRE) { 17955 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17956 if (FD->getBuiltinID() == Builtin::BI__noop) { 17957 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17958 CK_BuiltinFnToFnPtr) 17959 .get(); 17960 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17961 VK_RValue, SourceLocation()); 17962 } 17963 } 17964 17965 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17966 return ExprError(); 17967 } 17968 17969 // Expressions of unknown type. 17970 case BuiltinType::OMPArraySection: 17971 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17972 return ExprError(); 17973 17974 // Everything else should be impossible. 17975 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17976 case BuiltinType::Id: 17977 #include "clang/Basic/OpenCLImageTypes.def" 17978 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17979 case BuiltinType::Id: 17980 #include "clang/Basic/OpenCLExtensionTypes.def" 17981 #define SVE_TYPE(Name, Id, SingletonId) \ 17982 case BuiltinType::Id: 17983 #include "clang/Basic/AArch64SVEACLETypes.def" 17984 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17985 #define PLACEHOLDER_TYPE(Id, SingletonId) 17986 #include "clang/AST/BuiltinTypes.def" 17987 break; 17988 } 17989 17990 llvm_unreachable("invalid placeholder type!"); 17991 } 17992 17993 bool Sema::CheckCaseExpression(Expr *E) { 17994 if (E->isTypeDependent()) 17995 return true; 17996 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 17997 return E->getType()->isIntegralOrEnumerationType(); 17998 return false; 17999 } 18000 18001 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18002 ExprResult 18003 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18004 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18005 "Unknown Objective-C Boolean value!"); 18006 QualType BoolT = Context.ObjCBuiltinBoolTy; 18007 if (!Context.getBOOLDecl()) { 18008 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18009 Sema::LookupOrdinaryName); 18010 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18011 NamedDecl *ND = Result.getFoundDecl(); 18012 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18013 Context.setBOOLDecl(TD); 18014 } 18015 } 18016 if (Context.getBOOLDecl()) 18017 BoolT = Context.getBOOLType(); 18018 return new (Context) 18019 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18020 } 18021 18022 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18023 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18024 SourceLocation RParen) { 18025 18026 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18027 18028 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18029 return Spec.getPlatform() == Platform; 18030 }); 18031 18032 VersionTuple Version; 18033 if (Spec != AvailSpecs.end()) 18034 Version = Spec->getVersion(); 18035 18036 // The use of `@available` in the enclosing function should be analyzed to 18037 // warn when it's used inappropriately (i.e. not if(@available)). 18038 if (getCurFunctionOrMethodDecl()) 18039 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18040 else if (getCurBlock() || getCurLambda()) 18041 getCurFunction()->HasPotentialAvailabilityViolations = true; 18042 18043 return new (Context) 18044 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18045 } 18046