1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/FixedPoint.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/Overload.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/Support/ConvertUTF.h" 48 using namespace clang; 49 using namespace sema; 50 51 /// Determine whether the use of this declaration is valid, without 52 /// emitting diagnostics. 53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 54 // See if this is an auto-typed variable whose initializer we are parsing. 55 if (ParsingInitForAutoVars.count(D)) 56 return false; 57 58 // See if this is a deleted function. 59 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 60 if (FD->isDeleted()) 61 return false; 62 63 // If the function has a deduced return type, and we can't deduce it, 64 // then we can't use it either. 65 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 66 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 67 return false; 68 69 // See if this is an aligned allocation/deallocation function that is 70 // unavailable. 71 if (TreatUnavailableAsInvalid && 72 isUnavailableAlignedAllocationFunction(*FD)) 73 return false; 74 } 75 76 // See if this function is unavailable. 77 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 78 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 79 return false; 80 81 return true; 82 } 83 84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 85 // Warn if this is used but marked unused. 86 if (const auto *A = D->getAttr<UnusedAttr>()) { 87 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 88 // should diagnose them. 89 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 90 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 91 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 92 if (DC && !DC->hasAttr<UnusedAttr>()) 93 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 94 } 95 } 96 } 97 98 /// Emit a note explaining that this function is deleted. 99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 100 assert(Decl->isDeleted()); 101 102 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 103 104 if (Method && Method->isDeleted() && Method->isDefaulted()) { 105 // If the method was explicitly defaulted, point at that declaration. 106 if (!Method->isImplicit()) 107 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 108 109 // Try to diagnose why this special member function was implicitly 110 // deleted. This might fail, if that reason no longer applies. 111 CXXSpecialMember CSM = getSpecialMember(Method); 112 if (CSM != CXXInvalid) 113 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 114 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 // See if this is a deleted function. 253 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // If the function has a deduced return type, and we can't deduce it, 267 // then we can't use it either. 268 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 269 DeduceReturnType(FD, Loc)) 270 return true; 271 272 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 273 return true; 274 } 275 276 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 277 // Lambdas are only default-constructible or assignable in C++2a onwards. 278 if (MD->getParent()->isLambda() && 279 ((isa<CXXConstructorDecl>(MD) && 280 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 281 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 282 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 283 << !isa<CXXConstructorDecl>(MD); 284 } 285 } 286 287 auto getReferencedObjCProp = [](const NamedDecl *D) -> 288 const ObjCPropertyDecl * { 289 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 290 return MD->findPropertyDecl(); 291 return nullptr; 292 }; 293 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 294 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 295 return true; 296 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 297 return true; 298 } 299 300 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 301 // Only the variables omp_in and omp_out are allowed in the combiner. 302 // Only the variables omp_priv and omp_orig are allowed in the 303 // initializer-clause. 304 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 305 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 306 isa<VarDecl>(D)) { 307 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 308 << getCurFunction()->HasOMPDeclareReductionCombiner; 309 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 310 return true; 311 } 312 313 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 314 // List-items in map clauses on this construct may only refer to the declared 315 // variable var and entities that could be referenced by a procedure defined 316 // at the same location 317 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 318 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 319 isa<VarDecl>(D)) { 320 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 321 << DMD->getVarName().getAsString(); 322 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 323 return true; 324 } 325 326 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 327 AvoidPartialAvailabilityChecks, ClassReceiver); 328 329 DiagnoseUnusedOfDecl(*this, D, Loc); 330 331 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 332 333 return false; 334 } 335 336 /// DiagnoseSentinelCalls - This routine checks whether a call or 337 /// message-send is to a declaration with the sentinel attribute, and 338 /// if so, it checks that the requirements of the sentinel are 339 /// satisfied. 340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 341 ArrayRef<Expr *> Args) { 342 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 343 if (!attr) 344 return; 345 346 // The number of formal parameters of the declaration. 347 unsigned numFormalParams; 348 349 // The kind of declaration. This is also an index into a %select in 350 // the diagnostic. 351 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 352 353 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 354 numFormalParams = MD->param_size(); 355 calleeType = CT_Method; 356 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 357 numFormalParams = FD->param_size(); 358 calleeType = CT_Function; 359 } else if (isa<VarDecl>(D)) { 360 QualType type = cast<ValueDecl>(D)->getType(); 361 const FunctionType *fn = nullptr; 362 if (const PointerType *ptr = type->getAs<PointerType>()) { 363 fn = ptr->getPointeeType()->getAs<FunctionType>(); 364 if (!fn) return; 365 calleeType = CT_Function; 366 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 367 fn = ptr->getPointeeType()->castAs<FunctionType>(); 368 calleeType = CT_Block; 369 } else { 370 return; 371 } 372 373 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 374 numFormalParams = proto->getNumParams(); 375 } else { 376 numFormalParams = 0; 377 } 378 } else { 379 return; 380 } 381 382 // "nullPos" is the number of formal parameters at the end which 383 // effectively count as part of the variadic arguments. This is 384 // useful if you would prefer to not have *any* formal parameters, 385 // but the language forces you to have at least one. 386 unsigned nullPos = attr->getNullPos(); 387 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 388 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 389 390 // The number of arguments which should follow the sentinel. 391 unsigned numArgsAfterSentinel = attr->getSentinel(); 392 393 // If there aren't enough arguments for all the formal parameters, 394 // the sentinel, and the args after the sentinel, complain. 395 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 396 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 397 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 398 return; 399 } 400 401 // Otherwise, find the sentinel expression. 402 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 403 if (!sentinelExpr) return; 404 if (sentinelExpr->isValueDependent()) return; 405 if (Context.isSentinelNullExpr(sentinelExpr)) return; 406 407 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 408 // or 'NULL' if those are actually defined in the context. Only use 409 // 'nil' for ObjC methods, where it's much more likely that the 410 // variadic arguments form a list of object pointers. 411 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 412 std::string NullValue; 413 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 414 NullValue = "nil"; 415 else if (getLangOpts().CPlusPlus11) 416 NullValue = "nullptr"; 417 else if (PP.isMacroDefined("NULL")) 418 NullValue = "NULL"; 419 else 420 NullValue = "(void*) 0"; 421 422 if (MissingNilLoc.isInvalid()) 423 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 424 else 425 Diag(MissingNilLoc, diag::warn_missing_sentinel) 426 << int(calleeType) 427 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 429 } 430 431 SourceRange Sema::getExprRange(Expr *E) const { 432 return E ? E->getSourceRange() : SourceRange(); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // Standard Promotions and Conversions 437 //===----------------------------------------------------------------------===// 438 439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 441 // Handle any placeholder expressions which made it here. 442 if (E->getType()->isPlaceholderType()) { 443 ExprResult result = CheckPlaceholderExpr(E); 444 if (result.isInvalid()) return ExprError(); 445 E = result.get(); 446 } 447 448 QualType Ty = E->getType(); 449 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 450 451 if (Ty->isFunctionType()) { 452 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 453 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 454 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 455 return ExprError(); 456 457 E = ImpCastExprToType(E, Context.getPointerType(Ty), 458 CK_FunctionToPointerDecay).get(); 459 } else if (Ty->isArrayType()) { 460 // In C90 mode, arrays only promote to pointers if the array expression is 461 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 462 // type 'array of type' is converted to an expression that has type 'pointer 463 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 464 // that has type 'array of type' ...". The relevant change is "an lvalue" 465 // (C90) to "an expression" (C99). 466 // 467 // C++ 4.2p1: 468 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 469 // T" can be converted to an rvalue of type "pointer to T". 470 // 471 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 472 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 473 CK_ArrayToPointerDecay).get(); 474 } 475 return E; 476 } 477 478 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 479 // Check to see if we are dereferencing a null pointer. If so, 480 // and if not volatile-qualified, this is undefined behavior that the 481 // optimizer will delete, so warn about it. People sometimes try to use this 482 // to get a deterministic trap and are surprised by clang's behavior. This 483 // only handles the pattern "*null", which is a very syntactic check. 484 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 485 if (UO && UO->getOpcode() == UO_Deref && 486 UO->getSubExpr()->getType()->isPointerType()) { 487 const LangAS AS = 488 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 489 if ((!isTargetAddressSpace(AS) || 490 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 491 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 492 S.Context, Expr::NPC_ValueDependentIsNotNull) && 493 !UO->getType().isVolatileQualified()) { 494 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 495 S.PDiag(diag::warn_indirection_through_null) 496 << UO->getSubExpr()->getSourceRange()); 497 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 498 S.PDiag(diag::note_indirection_through_null)); 499 } 500 } 501 } 502 503 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 504 SourceLocation AssignLoc, 505 const Expr* RHS) { 506 const ObjCIvarDecl *IV = OIRE->getDecl(); 507 if (!IV) 508 return; 509 510 DeclarationName MemberName = IV->getDeclName(); 511 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 512 if (!Member || !Member->isStr("isa")) 513 return; 514 515 const Expr *Base = OIRE->getBase(); 516 QualType BaseType = Base->getType(); 517 if (OIRE->isArrow()) 518 BaseType = BaseType->getPointeeType(); 519 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 520 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 521 ObjCInterfaceDecl *ClassDeclared = nullptr; 522 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 523 if (!ClassDeclared->getSuperClass() 524 && (*ClassDeclared->ivar_begin()) == IV) { 525 if (RHS) { 526 NamedDecl *ObjectSetClass = 527 S.LookupSingleName(S.TUScope, 528 &S.Context.Idents.get("object_setClass"), 529 SourceLocation(), S.LookupOrdinaryName); 530 if (ObjectSetClass) { 531 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 532 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 533 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 534 "object_setClass(") 535 << FixItHint::CreateReplacement( 536 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 537 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 538 } 539 else 540 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 541 } else { 542 NamedDecl *ObjectGetClass = 543 S.LookupSingleName(S.TUScope, 544 &S.Context.Idents.get("object_getClass"), 545 SourceLocation(), S.LookupOrdinaryName); 546 if (ObjectGetClass) 547 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 548 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 549 "object_getClass(") 550 << FixItHint::CreateReplacement( 551 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 552 else 553 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 554 } 555 S.Diag(IV->getLocation(), diag::note_ivar_decl); 556 } 557 } 558 } 559 560 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 561 // Handle any placeholder expressions which made it here. 562 if (E->getType()->isPlaceholderType()) { 563 ExprResult result = CheckPlaceholderExpr(E); 564 if (result.isInvalid()) return ExprError(); 565 E = result.get(); 566 } 567 568 // C++ [conv.lval]p1: 569 // A glvalue of a non-function, non-array type T can be 570 // converted to a prvalue. 571 if (!E->isGLValue()) return E; 572 573 QualType T = E->getType(); 574 assert(!T.isNull() && "r-value conversion on typeless expression?"); 575 576 // We don't want to throw lvalue-to-rvalue casts on top of 577 // expressions of certain types in C++. 578 if (getLangOpts().CPlusPlus && 579 (E->getType() == Context.OverloadTy || 580 T->isDependentType() || 581 T->isRecordType())) 582 return E; 583 584 // The C standard is actually really unclear on this point, and 585 // DR106 tells us what the result should be but not why. It's 586 // generally best to say that void types just doesn't undergo 587 // lvalue-to-rvalue at all. Note that expressions of unqualified 588 // 'void' type are never l-values, but qualified void can be. 589 if (T->isVoidType()) 590 return E; 591 592 // OpenCL usually rejects direct accesses to values of 'half' type. 593 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 594 T->isHalfType()) { 595 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 596 << 0 << T; 597 return ExprError(); 598 } 599 600 CheckForNullPointerDereference(*this, E); 601 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 602 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 603 &Context.Idents.get("object_getClass"), 604 SourceLocation(), LookupOrdinaryName); 605 if (ObjectGetClass) 606 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 607 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 608 << FixItHint::CreateReplacement( 609 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 610 else 611 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 612 } 613 else if (const ObjCIvarRefExpr *OIRE = 614 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 615 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 616 617 // C++ [conv.lval]p1: 618 // [...] If T is a non-class type, the type of the prvalue is the 619 // cv-unqualified version of T. Otherwise, the type of the 620 // rvalue is T. 621 // 622 // C99 6.3.2.1p2: 623 // If the lvalue has qualified type, the value has the unqualified 624 // version of the type of the lvalue; otherwise, the value has the 625 // type of the lvalue. 626 if (T.hasQualifiers()) 627 T = T.getUnqualifiedType(); 628 629 // Under the MS ABI, lock down the inheritance model now. 630 if (T->isMemberPointerType() && 631 Context.getTargetInfo().getCXXABI().isMicrosoft()) 632 (void)isCompleteType(E->getExprLoc(), T); 633 634 ExprResult Res = CheckLValueToRValueConversionOperand(E); 635 if (Res.isInvalid()) 636 return Res; 637 E = Res.get(); 638 639 // Loading a __weak object implicitly retains the value, so we need a cleanup to 640 // balance that. 641 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 642 Cleanup.setExprNeedsCleanups(true); 643 644 // C++ [conv.lval]p3: 645 // If T is cv std::nullptr_t, the result is a null pointer constant. 646 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 647 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 648 649 // C11 6.3.2.1p2: 650 // ... if the lvalue has atomic type, the value has the non-atomic version 651 // of the type of the lvalue ... 652 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 653 T = Atomic->getValueType().getUnqualifiedType(); 654 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 655 nullptr, VK_RValue); 656 } 657 658 return Res; 659 } 660 661 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 662 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 663 if (Res.isInvalid()) 664 return ExprError(); 665 Res = DefaultLvalueConversion(Res.get()); 666 if (Res.isInvalid()) 667 return ExprError(); 668 return Res; 669 } 670 671 /// CallExprUnaryConversions - a special case of an unary conversion 672 /// performed on a function designator of a call expression. 673 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 674 QualType Ty = E->getType(); 675 ExprResult Res = E; 676 // Only do implicit cast for a function type, but not for a pointer 677 // to function type. 678 if (Ty->isFunctionType()) { 679 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 680 CK_FunctionToPointerDecay).get(); 681 if (Res.isInvalid()) 682 return ExprError(); 683 } 684 Res = DefaultLvalueConversion(Res.get()); 685 if (Res.isInvalid()) 686 return ExprError(); 687 return Res.get(); 688 } 689 690 /// UsualUnaryConversions - Performs various conversions that are common to most 691 /// operators (C99 6.3). The conversions of array and function types are 692 /// sometimes suppressed. For example, the array->pointer conversion doesn't 693 /// apply if the array is an argument to the sizeof or address (&) operators. 694 /// In these instances, this routine should *not* be called. 695 ExprResult Sema::UsualUnaryConversions(Expr *E) { 696 // First, convert to an r-value. 697 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 698 if (Res.isInvalid()) 699 return ExprError(); 700 E = Res.get(); 701 702 QualType Ty = E->getType(); 703 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 704 705 // Half FP have to be promoted to float unless it is natively supported 706 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 707 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 708 709 // Try to perform integral promotions if the object has a theoretically 710 // promotable type. 711 if (Ty->isIntegralOrUnscopedEnumerationType()) { 712 // C99 6.3.1.1p2: 713 // 714 // The following may be used in an expression wherever an int or 715 // unsigned int may be used: 716 // - an object or expression with an integer type whose integer 717 // conversion rank is less than or equal to the rank of int 718 // and unsigned int. 719 // - A bit-field of type _Bool, int, signed int, or unsigned int. 720 // 721 // If an int can represent all values of the original type, the 722 // value is converted to an int; otherwise, it is converted to an 723 // unsigned int. These are called the integer promotions. All 724 // other types are unchanged by the integer promotions. 725 726 QualType PTy = Context.isPromotableBitField(E); 727 if (!PTy.isNull()) { 728 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 729 return E; 730 } 731 if (Ty->isPromotableIntegerType()) { 732 QualType PT = Context.getPromotedIntegerType(Ty); 733 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 734 return E; 735 } 736 } 737 return E; 738 } 739 740 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 741 /// do not have a prototype. Arguments that have type float or __fp16 742 /// are promoted to double. All other argument types are converted by 743 /// UsualUnaryConversions(). 744 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 745 QualType Ty = E->getType(); 746 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 747 748 ExprResult Res = UsualUnaryConversions(E); 749 if (Res.isInvalid()) 750 return ExprError(); 751 E = Res.get(); 752 753 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 754 // promote to double. 755 // Note that default argument promotion applies only to float (and 756 // half/fp16); it does not apply to _Float16. 757 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 758 if (BTy && (BTy->getKind() == BuiltinType::Half || 759 BTy->getKind() == BuiltinType::Float)) { 760 if (getLangOpts().OpenCL && 761 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 762 if (BTy->getKind() == BuiltinType::Half) { 763 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 764 } 765 } else { 766 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 767 } 768 } 769 770 // C++ performs lvalue-to-rvalue conversion as a default argument 771 // promotion, even on class types, but note: 772 // C++11 [conv.lval]p2: 773 // When an lvalue-to-rvalue conversion occurs in an unevaluated 774 // operand or a subexpression thereof the value contained in the 775 // referenced object is not accessed. Otherwise, if the glvalue 776 // has a class type, the conversion copy-initializes a temporary 777 // of type T from the glvalue and the result of the conversion 778 // is a prvalue for the temporary. 779 // FIXME: add some way to gate this entire thing for correctness in 780 // potentially potentially evaluated contexts. 781 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 782 ExprResult Temp = PerformCopyInitialization( 783 InitializedEntity::InitializeTemporary(E->getType()), 784 E->getExprLoc(), E); 785 if (Temp.isInvalid()) 786 return ExprError(); 787 E = Temp.get(); 788 } 789 790 return E; 791 } 792 793 /// Determine the degree of POD-ness for an expression. 794 /// Incomplete types are considered POD, since this check can be performed 795 /// when we're in an unevaluated context. 796 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 797 if (Ty->isIncompleteType()) { 798 // C++11 [expr.call]p7: 799 // After these conversions, if the argument does not have arithmetic, 800 // enumeration, pointer, pointer to member, or class type, the program 801 // is ill-formed. 802 // 803 // Since we've already performed array-to-pointer and function-to-pointer 804 // decay, the only such type in C++ is cv void. This also handles 805 // initializer lists as variadic arguments. 806 if (Ty->isVoidType()) 807 return VAK_Invalid; 808 809 if (Ty->isObjCObjectType()) 810 return VAK_Invalid; 811 return VAK_Valid; 812 } 813 814 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 815 return VAK_Invalid; 816 817 if (Ty.isCXX98PODType(Context)) 818 return VAK_Valid; 819 820 // C++11 [expr.call]p7: 821 // Passing a potentially-evaluated argument of class type (Clause 9) 822 // having a non-trivial copy constructor, a non-trivial move constructor, 823 // or a non-trivial destructor, with no corresponding parameter, 824 // is conditionally-supported with implementation-defined semantics. 825 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 826 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 827 if (!Record->hasNonTrivialCopyConstructor() && 828 !Record->hasNonTrivialMoveConstructor() && 829 !Record->hasNonTrivialDestructor()) 830 return VAK_ValidInCXX11; 831 832 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 833 return VAK_Valid; 834 835 if (Ty->isObjCObjectType()) 836 return VAK_Invalid; 837 838 if (getLangOpts().MSVCCompat) 839 return VAK_MSVCUndefined; 840 841 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 842 // permitted to reject them. We should consider doing so. 843 return VAK_Undefined; 844 } 845 846 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 847 // Don't allow one to pass an Objective-C interface to a vararg. 848 const QualType &Ty = E->getType(); 849 VarArgKind VAK = isValidVarArgType(Ty); 850 851 // Complain about passing non-POD types through varargs. 852 switch (VAK) { 853 case VAK_ValidInCXX11: 854 DiagRuntimeBehavior( 855 E->getBeginLoc(), nullptr, 856 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 857 LLVM_FALLTHROUGH; 858 case VAK_Valid: 859 if (Ty->isRecordType()) { 860 // This is unlikely to be what the user intended. If the class has a 861 // 'c_str' member function, the user probably meant to call that. 862 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 863 PDiag(diag::warn_pass_class_arg_to_vararg) 864 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 865 } 866 break; 867 868 case VAK_Undefined: 869 case VAK_MSVCUndefined: 870 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 871 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 872 << getLangOpts().CPlusPlus11 << Ty << CT); 873 break; 874 875 case VAK_Invalid: 876 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 877 Diag(E->getBeginLoc(), 878 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 879 << Ty << CT; 880 else if (Ty->isObjCObjectType()) 881 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 882 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 883 << Ty << CT); 884 else 885 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 886 << isa<InitListExpr>(E) << Ty << CT; 887 break; 888 } 889 } 890 891 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 892 /// will create a trap if the resulting type is not a POD type. 893 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 894 FunctionDecl *FDecl) { 895 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 896 // Strip the unbridged-cast placeholder expression off, if applicable. 897 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 898 (CT == VariadicMethod || 899 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 900 E = stripARCUnbridgedCast(E); 901 902 // Otherwise, do normal placeholder checking. 903 } else { 904 ExprResult ExprRes = CheckPlaceholderExpr(E); 905 if (ExprRes.isInvalid()) 906 return ExprError(); 907 E = ExprRes.get(); 908 } 909 } 910 911 ExprResult ExprRes = DefaultArgumentPromotion(E); 912 if (ExprRes.isInvalid()) 913 return ExprError(); 914 E = ExprRes.get(); 915 916 // Diagnostics regarding non-POD argument types are 917 // emitted along with format string checking in Sema::CheckFunctionCall(). 918 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 919 // Turn this into a trap. 920 CXXScopeSpec SS; 921 SourceLocation TemplateKWLoc; 922 UnqualifiedId Name; 923 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 924 E->getBeginLoc()); 925 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 926 /*HasTrailingLParen=*/true, 927 /*IsAddressOfOperand=*/false); 928 if (TrapFn.isInvalid()) 929 return ExprError(); 930 931 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 932 None, E->getEndLoc()); 933 if (Call.isInvalid()) 934 return ExprError(); 935 936 ExprResult Comma = 937 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 938 if (Comma.isInvalid()) 939 return ExprError(); 940 return Comma.get(); 941 } 942 943 if (!getLangOpts().CPlusPlus && 944 RequireCompleteType(E->getExprLoc(), E->getType(), 945 diag::err_call_incomplete_argument)) 946 return ExprError(); 947 948 return E; 949 } 950 951 /// Converts an integer to complex float type. Helper function of 952 /// UsualArithmeticConversions() 953 /// 954 /// \return false if the integer expression is an integer type and is 955 /// successfully converted to the complex type. 956 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 957 ExprResult &ComplexExpr, 958 QualType IntTy, 959 QualType ComplexTy, 960 bool SkipCast) { 961 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 962 if (SkipCast) return false; 963 if (IntTy->isIntegerType()) { 964 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 965 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 966 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 967 CK_FloatingRealToComplex); 968 } else { 969 assert(IntTy->isComplexIntegerType()); 970 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 971 CK_IntegralComplexToFloatingComplex); 972 } 973 return false; 974 } 975 976 /// Handle arithmetic conversion with complex types. Helper function of 977 /// UsualArithmeticConversions() 978 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 979 ExprResult &RHS, QualType LHSType, 980 QualType RHSType, 981 bool IsCompAssign) { 982 // if we have an integer operand, the result is the complex type. 983 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 984 /*skipCast*/false)) 985 return LHSType; 986 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 987 /*skipCast*/IsCompAssign)) 988 return RHSType; 989 990 // This handles complex/complex, complex/float, or float/complex. 991 // When both operands are complex, the shorter operand is converted to the 992 // type of the longer, and that is the type of the result. This corresponds 993 // to what is done when combining two real floating-point operands. 994 // The fun begins when size promotion occur across type domains. 995 // From H&S 6.3.4: When one operand is complex and the other is a real 996 // floating-point type, the less precise type is converted, within it's 997 // real or complex domain, to the precision of the other type. For example, 998 // when combining a "long double" with a "double _Complex", the 999 // "double _Complex" is promoted to "long double _Complex". 1000 1001 // Compute the rank of the two types, regardless of whether they are complex. 1002 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1003 1004 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1005 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1006 QualType LHSElementType = 1007 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1008 QualType RHSElementType = 1009 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1010 1011 QualType ResultType = S.Context.getComplexType(LHSElementType); 1012 if (Order < 0) { 1013 // Promote the precision of the LHS if not an assignment. 1014 ResultType = S.Context.getComplexType(RHSElementType); 1015 if (!IsCompAssign) { 1016 if (LHSComplexType) 1017 LHS = 1018 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1019 else 1020 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1021 } 1022 } else if (Order > 0) { 1023 // Promote the precision of the RHS. 1024 if (RHSComplexType) 1025 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1026 else 1027 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1028 } 1029 return ResultType; 1030 } 1031 1032 /// Handle arithmetic conversion from integer to float. Helper function 1033 /// of UsualArithmeticConversions() 1034 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1035 ExprResult &IntExpr, 1036 QualType FloatTy, QualType IntTy, 1037 bool ConvertFloat, bool ConvertInt) { 1038 if (IntTy->isIntegerType()) { 1039 if (ConvertInt) 1040 // Convert intExpr to the lhs floating point type. 1041 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1042 CK_IntegralToFloating); 1043 return FloatTy; 1044 } 1045 1046 // Convert both sides to the appropriate complex float. 1047 assert(IntTy->isComplexIntegerType()); 1048 QualType result = S.Context.getComplexType(FloatTy); 1049 1050 // _Complex int -> _Complex float 1051 if (ConvertInt) 1052 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1053 CK_IntegralComplexToFloatingComplex); 1054 1055 // float -> _Complex float 1056 if (ConvertFloat) 1057 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1058 CK_FloatingRealToComplex); 1059 1060 return result; 1061 } 1062 1063 /// Handle arithmethic conversion with floating point types. Helper 1064 /// function of UsualArithmeticConversions() 1065 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1066 ExprResult &RHS, QualType LHSType, 1067 QualType RHSType, bool IsCompAssign) { 1068 bool LHSFloat = LHSType->isRealFloatingType(); 1069 bool RHSFloat = RHSType->isRealFloatingType(); 1070 1071 // If we have two real floating types, convert the smaller operand 1072 // to the bigger result. 1073 if (LHSFloat && RHSFloat) { 1074 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1075 if (order > 0) { 1076 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1077 return LHSType; 1078 } 1079 1080 assert(order < 0 && "illegal float comparison"); 1081 if (!IsCompAssign) 1082 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1083 return RHSType; 1084 } 1085 1086 if (LHSFloat) { 1087 // Half FP has to be promoted to float unless it is natively supported 1088 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1089 LHSType = S.Context.FloatTy; 1090 1091 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1092 /*ConvertFloat=*/!IsCompAssign, 1093 /*ConvertInt=*/ true); 1094 } 1095 assert(RHSFloat); 1096 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1097 /*convertInt=*/ true, 1098 /*convertFloat=*/!IsCompAssign); 1099 } 1100 1101 /// Diagnose attempts to convert between __float128 and long double if 1102 /// there is no support for such conversion. Helper function of 1103 /// UsualArithmeticConversions(). 1104 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1105 QualType RHSType) { 1106 /* No issue converting if at least one of the types is not a floating point 1107 type or the two types have the same rank. 1108 */ 1109 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1110 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1111 return false; 1112 1113 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1114 "The remaining types must be floating point types."); 1115 1116 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1117 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1118 1119 QualType LHSElemType = LHSComplex ? 1120 LHSComplex->getElementType() : LHSType; 1121 QualType RHSElemType = RHSComplex ? 1122 RHSComplex->getElementType() : RHSType; 1123 1124 // No issue if the two types have the same representation 1125 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1126 &S.Context.getFloatTypeSemantics(RHSElemType)) 1127 return false; 1128 1129 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1130 RHSElemType == S.Context.LongDoubleTy); 1131 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1132 RHSElemType == S.Context.Float128Ty); 1133 1134 // We've handled the situation where __float128 and long double have the same 1135 // representation. We allow all conversions for all possible long double types 1136 // except PPC's double double. 1137 return Float128AndLongDouble && 1138 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1139 &llvm::APFloat::PPCDoubleDouble()); 1140 } 1141 1142 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1143 1144 namespace { 1145 /// These helper callbacks are placed in an anonymous namespace to 1146 /// permit their use as function template parameters. 1147 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1148 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1149 } 1150 1151 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1152 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1153 CK_IntegralComplexCast); 1154 } 1155 } 1156 1157 /// Handle integer arithmetic conversions. Helper function of 1158 /// UsualArithmeticConversions() 1159 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1160 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1161 ExprResult &RHS, QualType LHSType, 1162 QualType RHSType, bool IsCompAssign) { 1163 // The rules for this case are in C99 6.3.1.8 1164 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1165 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1166 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1167 if (LHSSigned == RHSSigned) { 1168 // Same signedness; use the higher-ranked type 1169 if (order >= 0) { 1170 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1171 return LHSType; 1172 } else if (!IsCompAssign) 1173 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1174 return RHSType; 1175 } else if (order != (LHSSigned ? 1 : -1)) { 1176 // The unsigned type has greater than or equal rank to the 1177 // signed type, so use the unsigned type 1178 if (RHSSigned) { 1179 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1180 return LHSType; 1181 } else if (!IsCompAssign) 1182 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1183 return RHSType; 1184 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1185 // The two types are different widths; if we are here, that 1186 // means the signed type is larger than the unsigned type, so 1187 // use the signed type. 1188 if (LHSSigned) { 1189 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1190 return LHSType; 1191 } else if (!IsCompAssign) 1192 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1193 return RHSType; 1194 } else { 1195 // The signed type is higher-ranked than the unsigned type, 1196 // but isn't actually any bigger (like unsigned int and long 1197 // on most 32-bit systems). Use the unsigned type corresponding 1198 // to the signed type. 1199 QualType result = 1200 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1201 RHS = (*doRHSCast)(S, RHS.get(), result); 1202 if (!IsCompAssign) 1203 LHS = (*doLHSCast)(S, LHS.get(), result); 1204 return result; 1205 } 1206 } 1207 1208 /// Handle conversions with GCC complex int extension. Helper function 1209 /// of UsualArithmeticConversions() 1210 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1211 ExprResult &RHS, QualType LHSType, 1212 QualType RHSType, 1213 bool IsCompAssign) { 1214 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1215 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1216 1217 if (LHSComplexInt && RHSComplexInt) { 1218 QualType LHSEltType = LHSComplexInt->getElementType(); 1219 QualType RHSEltType = RHSComplexInt->getElementType(); 1220 QualType ScalarType = 1221 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1222 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1223 1224 return S.Context.getComplexType(ScalarType); 1225 } 1226 1227 if (LHSComplexInt) { 1228 QualType LHSEltType = LHSComplexInt->getElementType(); 1229 QualType ScalarType = 1230 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1231 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1232 QualType ComplexType = S.Context.getComplexType(ScalarType); 1233 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1234 CK_IntegralRealToComplex); 1235 1236 return ComplexType; 1237 } 1238 1239 assert(RHSComplexInt); 1240 1241 QualType RHSEltType = RHSComplexInt->getElementType(); 1242 QualType ScalarType = 1243 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1244 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1245 QualType ComplexType = S.Context.getComplexType(ScalarType); 1246 1247 if (!IsCompAssign) 1248 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1249 CK_IntegralRealToComplex); 1250 return ComplexType; 1251 } 1252 1253 /// Return the rank of a given fixed point or integer type. The value itself 1254 /// doesn't matter, but the values must be increasing with proper increasing 1255 /// rank as described in N1169 4.1.1. 1256 static unsigned GetFixedPointRank(QualType Ty) { 1257 const auto *BTy = Ty->getAs<BuiltinType>(); 1258 assert(BTy && "Expected a builtin type."); 1259 1260 switch (BTy->getKind()) { 1261 case BuiltinType::ShortFract: 1262 case BuiltinType::UShortFract: 1263 case BuiltinType::SatShortFract: 1264 case BuiltinType::SatUShortFract: 1265 return 1; 1266 case BuiltinType::Fract: 1267 case BuiltinType::UFract: 1268 case BuiltinType::SatFract: 1269 case BuiltinType::SatUFract: 1270 return 2; 1271 case BuiltinType::LongFract: 1272 case BuiltinType::ULongFract: 1273 case BuiltinType::SatLongFract: 1274 case BuiltinType::SatULongFract: 1275 return 3; 1276 case BuiltinType::ShortAccum: 1277 case BuiltinType::UShortAccum: 1278 case BuiltinType::SatShortAccum: 1279 case BuiltinType::SatUShortAccum: 1280 return 4; 1281 case BuiltinType::Accum: 1282 case BuiltinType::UAccum: 1283 case BuiltinType::SatAccum: 1284 case BuiltinType::SatUAccum: 1285 return 5; 1286 case BuiltinType::LongAccum: 1287 case BuiltinType::ULongAccum: 1288 case BuiltinType::SatLongAccum: 1289 case BuiltinType::SatULongAccum: 1290 return 6; 1291 default: 1292 if (BTy->isInteger()) 1293 return 0; 1294 llvm_unreachable("Unexpected fixed point or integer type"); 1295 } 1296 } 1297 1298 /// handleFixedPointConversion - Fixed point operations between fixed 1299 /// point types and integers or other fixed point types do not fall under 1300 /// usual arithmetic conversion since these conversions could result in loss 1301 /// of precsision (N1169 4.1.4). These operations should be calculated with 1302 /// the full precision of their result type (N1169 4.1.6.2.1). 1303 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1304 QualType RHSTy) { 1305 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1306 "Expected at least one of the operands to be a fixed point type"); 1307 assert((LHSTy->isFixedPointOrIntegerType() || 1308 RHSTy->isFixedPointOrIntegerType()) && 1309 "Special fixed point arithmetic operation conversions are only " 1310 "applied to ints or other fixed point types"); 1311 1312 // If one operand has signed fixed-point type and the other operand has 1313 // unsigned fixed-point type, then the unsigned fixed-point operand is 1314 // converted to its corresponding signed fixed-point type and the resulting 1315 // type is the type of the converted operand. 1316 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1317 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1318 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1319 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1320 1321 // The result type is the type with the highest rank, whereby a fixed-point 1322 // conversion rank is always greater than an integer conversion rank; if the 1323 // type of either of the operands is a saturating fixedpoint type, the result 1324 // type shall be the saturating fixed-point type corresponding to the type 1325 // with the highest rank; the resulting value is converted (taking into 1326 // account rounding and overflow) to the precision of the resulting type. 1327 // Same ranks between signed and unsigned types are resolved earlier, so both 1328 // types are either signed or both unsigned at this point. 1329 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1330 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1331 1332 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1333 1334 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1335 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1336 1337 return ResultTy; 1338 } 1339 1340 /// UsualArithmeticConversions - Performs various conversions that are common to 1341 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1342 /// routine returns the first non-arithmetic type found. The client is 1343 /// responsible for emitting appropriate error diagnostics. 1344 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1345 bool IsCompAssign) { 1346 if (!IsCompAssign) { 1347 LHS = UsualUnaryConversions(LHS.get()); 1348 if (LHS.isInvalid()) 1349 return QualType(); 1350 } 1351 1352 RHS = UsualUnaryConversions(RHS.get()); 1353 if (RHS.isInvalid()) 1354 return QualType(); 1355 1356 // For conversion purposes, we ignore any qualifiers. 1357 // For example, "const float" and "float" are equivalent. 1358 QualType LHSType = 1359 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1360 QualType RHSType = 1361 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1362 1363 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1364 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1365 LHSType = AtomicLHS->getValueType(); 1366 1367 // If both types are identical, no conversion is needed. 1368 if (LHSType == RHSType) 1369 return LHSType; 1370 1371 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1372 // The caller can deal with this (e.g. pointer + int). 1373 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1374 return QualType(); 1375 1376 // Apply unary and bitfield promotions to the LHS's type. 1377 QualType LHSUnpromotedType = LHSType; 1378 if (LHSType->isPromotableIntegerType()) 1379 LHSType = Context.getPromotedIntegerType(LHSType); 1380 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1381 if (!LHSBitfieldPromoteTy.isNull()) 1382 LHSType = LHSBitfieldPromoteTy; 1383 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1384 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1385 1386 // If both types are identical, no conversion is needed. 1387 if (LHSType == RHSType) 1388 return LHSType; 1389 1390 // At this point, we have two different arithmetic types. 1391 1392 // Diagnose attempts to convert between __float128 and long double where 1393 // such conversions currently can't be handled. 1394 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1395 return QualType(); 1396 1397 // Handle complex types first (C99 6.3.1.8p1). 1398 if (LHSType->isComplexType() || RHSType->isComplexType()) 1399 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1400 IsCompAssign); 1401 1402 // Now handle "real" floating types (i.e. float, double, long double). 1403 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1404 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1405 IsCompAssign); 1406 1407 // Handle GCC complex int extension. 1408 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1409 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1410 IsCompAssign); 1411 1412 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1413 return handleFixedPointConversion(*this, LHSType, RHSType); 1414 1415 // Finally, we have two differing integer types. 1416 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1417 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1418 } 1419 1420 //===----------------------------------------------------------------------===// 1421 // Semantic Analysis for various Expression Types 1422 //===----------------------------------------------------------------------===// 1423 1424 1425 ExprResult 1426 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1427 SourceLocation DefaultLoc, 1428 SourceLocation RParenLoc, 1429 Expr *ControllingExpr, 1430 ArrayRef<ParsedType> ArgTypes, 1431 ArrayRef<Expr *> ArgExprs) { 1432 unsigned NumAssocs = ArgTypes.size(); 1433 assert(NumAssocs == ArgExprs.size()); 1434 1435 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1436 for (unsigned i = 0; i < NumAssocs; ++i) { 1437 if (ArgTypes[i]) 1438 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1439 else 1440 Types[i] = nullptr; 1441 } 1442 1443 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1444 ControllingExpr, 1445 llvm::makeArrayRef(Types, NumAssocs), 1446 ArgExprs); 1447 delete [] Types; 1448 return ER; 1449 } 1450 1451 ExprResult 1452 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1453 SourceLocation DefaultLoc, 1454 SourceLocation RParenLoc, 1455 Expr *ControllingExpr, 1456 ArrayRef<TypeSourceInfo *> Types, 1457 ArrayRef<Expr *> Exprs) { 1458 unsigned NumAssocs = Types.size(); 1459 assert(NumAssocs == Exprs.size()); 1460 1461 // Decay and strip qualifiers for the controlling expression type, and handle 1462 // placeholder type replacement. See committee discussion from WG14 DR423. 1463 { 1464 EnterExpressionEvaluationContext Unevaluated( 1465 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1466 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1467 if (R.isInvalid()) 1468 return ExprError(); 1469 ControllingExpr = R.get(); 1470 } 1471 1472 // The controlling expression is an unevaluated operand, so side effects are 1473 // likely unintended. 1474 if (!inTemplateInstantiation() && 1475 ControllingExpr->HasSideEffects(Context, false)) 1476 Diag(ControllingExpr->getExprLoc(), 1477 diag::warn_side_effects_unevaluated_context); 1478 1479 bool TypeErrorFound = false, 1480 IsResultDependent = ControllingExpr->isTypeDependent(), 1481 ContainsUnexpandedParameterPack 1482 = ControllingExpr->containsUnexpandedParameterPack(); 1483 1484 for (unsigned i = 0; i < NumAssocs; ++i) { 1485 if (Exprs[i]->containsUnexpandedParameterPack()) 1486 ContainsUnexpandedParameterPack = true; 1487 1488 if (Types[i]) { 1489 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1490 ContainsUnexpandedParameterPack = true; 1491 1492 if (Types[i]->getType()->isDependentType()) { 1493 IsResultDependent = true; 1494 } else { 1495 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1496 // complete object type other than a variably modified type." 1497 unsigned D = 0; 1498 if (Types[i]->getType()->isIncompleteType()) 1499 D = diag::err_assoc_type_incomplete; 1500 else if (!Types[i]->getType()->isObjectType()) 1501 D = diag::err_assoc_type_nonobject; 1502 else if (Types[i]->getType()->isVariablyModifiedType()) 1503 D = diag::err_assoc_type_variably_modified; 1504 1505 if (D != 0) { 1506 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1507 << Types[i]->getTypeLoc().getSourceRange() 1508 << Types[i]->getType(); 1509 TypeErrorFound = true; 1510 } 1511 1512 // C11 6.5.1.1p2 "No two generic associations in the same generic 1513 // selection shall specify compatible types." 1514 for (unsigned j = i+1; j < NumAssocs; ++j) 1515 if (Types[j] && !Types[j]->getType()->isDependentType() && 1516 Context.typesAreCompatible(Types[i]->getType(), 1517 Types[j]->getType())) { 1518 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1519 diag::err_assoc_compatible_types) 1520 << Types[j]->getTypeLoc().getSourceRange() 1521 << Types[j]->getType() 1522 << Types[i]->getType(); 1523 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1524 diag::note_compat_assoc) 1525 << Types[i]->getTypeLoc().getSourceRange() 1526 << Types[i]->getType(); 1527 TypeErrorFound = true; 1528 } 1529 } 1530 } 1531 } 1532 if (TypeErrorFound) 1533 return ExprError(); 1534 1535 // If we determined that the generic selection is result-dependent, don't 1536 // try to compute the result expression. 1537 if (IsResultDependent) 1538 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1539 Exprs, DefaultLoc, RParenLoc, 1540 ContainsUnexpandedParameterPack); 1541 1542 SmallVector<unsigned, 1> CompatIndices; 1543 unsigned DefaultIndex = -1U; 1544 for (unsigned i = 0; i < NumAssocs; ++i) { 1545 if (!Types[i]) 1546 DefaultIndex = i; 1547 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1548 Types[i]->getType())) 1549 CompatIndices.push_back(i); 1550 } 1551 1552 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1553 // type compatible with at most one of the types named in its generic 1554 // association list." 1555 if (CompatIndices.size() > 1) { 1556 // We strip parens here because the controlling expression is typically 1557 // parenthesized in macro definitions. 1558 ControllingExpr = ControllingExpr->IgnoreParens(); 1559 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1560 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1561 << (unsigned)CompatIndices.size(); 1562 for (unsigned I : CompatIndices) { 1563 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1564 diag::note_compat_assoc) 1565 << Types[I]->getTypeLoc().getSourceRange() 1566 << Types[I]->getType(); 1567 } 1568 return ExprError(); 1569 } 1570 1571 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1572 // its controlling expression shall have type compatible with exactly one of 1573 // the types named in its generic association list." 1574 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1575 // We strip parens here because the controlling expression is typically 1576 // parenthesized in macro definitions. 1577 ControllingExpr = ControllingExpr->IgnoreParens(); 1578 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1579 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1580 return ExprError(); 1581 } 1582 1583 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1584 // type name that is compatible with the type of the controlling expression, 1585 // then the result expression of the generic selection is the expression 1586 // in that generic association. Otherwise, the result expression of the 1587 // generic selection is the expression in the default generic association." 1588 unsigned ResultIndex = 1589 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1590 1591 return GenericSelectionExpr::Create( 1592 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1593 ContainsUnexpandedParameterPack, ResultIndex); 1594 } 1595 1596 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1597 /// location of the token and the offset of the ud-suffix within it. 1598 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1599 unsigned Offset) { 1600 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1601 S.getLangOpts()); 1602 } 1603 1604 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1605 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1606 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1607 IdentifierInfo *UDSuffix, 1608 SourceLocation UDSuffixLoc, 1609 ArrayRef<Expr*> Args, 1610 SourceLocation LitEndLoc) { 1611 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1612 1613 QualType ArgTy[2]; 1614 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1615 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1616 if (ArgTy[ArgIdx]->isArrayType()) 1617 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1618 } 1619 1620 DeclarationName OpName = 1621 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1622 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1623 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1624 1625 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1626 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1627 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1628 /*AllowStringTemplate*/ false, 1629 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1630 return ExprError(); 1631 1632 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1633 } 1634 1635 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1636 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1637 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1638 /// multiple tokens. However, the common case is that StringToks points to one 1639 /// string. 1640 /// 1641 ExprResult 1642 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1643 assert(!StringToks.empty() && "Must have at least one string!"); 1644 1645 StringLiteralParser Literal(StringToks, PP); 1646 if (Literal.hadError) 1647 return ExprError(); 1648 1649 SmallVector<SourceLocation, 4> StringTokLocs; 1650 for (const Token &Tok : StringToks) 1651 StringTokLocs.push_back(Tok.getLocation()); 1652 1653 QualType CharTy = Context.CharTy; 1654 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1655 if (Literal.isWide()) { 1656 CharTy = Context.getWideCharType(); 1657 Kind = StringLiteral::Wide; 1658 } else if (Literal.isUTF8()) { 1659 if (getLangOpts().Char8) 1660 CharTy = Context.Char8Ty; 1661 Kind = StringLiteral::UTF8; 1662 } else if (Literal.isUTF16()) { 1663 CharTy = Context.Char16Ty; 1664 Kind = StringLiteral::UTF16; 1665 } else if (Literal.isUTF32()) { 1666 CharTy = Context.Char32Ty; 1667 Kind = StringLiteral::UTF32; 1668 } else if (Literal.isPascal()) { 1669 CharTy = Context.UnsignedCharTy; 1670 } 1671 1672 // Warn on initializing an array of char from a u8 string literal; this 1673 // becomes ill-formed in C++2a. 1674 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1675 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1676 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1677 1678 // Create removals for all 'u8' prefixes in the string literal(s). This 1679 // ensures C++2a compatibility (but may change the program behavior when 1680 // built by non-Clang compilers for which the execution character set is 1681 // not always UTF-8). 1682 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1683 SourceLocation RemovalDiagLoc; 1684 for (const Token &Tok : StringToks) { 1685 if (Tok.getKind() == tok::utf8_string_literal) { 1686 if (RemovalDiagLoc.isInvalid()) 1687 RemovalDiagLoc = Tok.getLocation(); 1688 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1689 Tok.getLocation(), 1690 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1691 getSourceManager(), getLangOpts()))); 1692 } 1693 } 1694 Diag(RemovalDiagLoc, RemovalDiag); 1695 } 1696 1697 QualType StrTy = 1698 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1699 1700 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1701 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1702 Kind, Literal.Pascal, StrTy, 1703 &StringTokLocs[0], 1704 StringTokLocs.size()); 1705 if (Literal.getUDSuffix().empty()) 1706 return Lit; 1707 1708 // We're building a user-defined literal. 1709 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1710 SourceLocation UDSuffixLoc = 1711 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1712 Literal.getUDSuffixOffset()); 1713 1714 // Make sure we're allowed user-defined literals here. 1715 if (!UDLScope) 1716 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1717 1718 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1719 // operator "" X (str, len) 1720 QualType SizeType = Context.getSizeType(); 1721 1722 DeclarationName OpName = 1723 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1724 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1725 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1726 1727 QualType ArgTy[] = { 1728 Context.getArrayDecayedType(StrTy), SizeType 1729 }; 1730 1731 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1732 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1733 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1734 /*AllowStringTemplate*/ true, 1735 /*DiagnoseMissing*/ true)) { 1736 1737 case LOLR_Cooked: { 1738 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1739 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1740 StringTokLocs[0]); 1741 Expr *Args[] = { Lit, LenArg }; 1742 1743 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1744 } 1745 1746 case LOLR_StringTemplate: { 1747 TemplateArgumentListInfo ExplicitArgs; 1748 1749 unsigned CharBits = Context.getIntWidth(CharTy); 1750 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1751 llvm::APSInt Value(CharBits, CharIsUnsigned); 1752 1753 TemplateArgument TypeArg(CharTy); 1754 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1755 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1756 1757 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1758 Value = Lit->getCodeUnit(I); 1759 TemplateArgument Arg(Context, Value, CharTy); 1760 TemplateArgumentLocInfo ArgInfo; 1761 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1762 } 1763 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1764 &ExplicitArgs); 1765 } 1766 case LOLR_Raw: 1767 case LOLR_Template: 1768 case LOLR_ErrorNoDiagnostic: 1769 llvm_unreachable("unexpected literal operator lookup result"); 1770 case LOLR_Error: 1771 return ExprError(); 1772 } 1773 llvm_unreachable("unexpected literal operator lookup result"); 1774 } 1775 1776 DeclRefExpr * 1777 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1778 SourceLocation Loc, 1779 const CXXScopeSpec *SS) { 1780 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1781 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1782 } 1783 1784 DeclRefExpr * 1785 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1786 const DeclarationNameInfo &NameInfo, 1787 const CXXScopeSpec *SS, NamedDecl *FoundD, 1788 SourceLocation TemplateKWLoc, 1789 const TemplateArgumentListInfo *TemplateArgs) { 1790 NestedNameSpecifierLoc NNS = 1791 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1792 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1793 TemplateArgs); 1794 } 1795 1796 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1797 // A declaration named in an unevaluated operand never constitutes an odr-use. 1798 if (isUnevaluatedContext()) 1799 return NOUR_Unevaluated; 1800 1801 // C++2a [basic.def.odr]p4: 1802 // A variable x whose name appears as a potentially-evaluated expression e 1803 // is odr-used by e unless [...] x is a reference that is usable in 1804 // constant expressions. 1805 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1806 if (VD->getType()->isReferenceType() && 1807 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1808 VD->isUsableInConstantExpressions(Context)) 1809 return NOUR_Constant; 1810 } 1811 1812 // All remaining non-variable cases constitute an odr-use. For variables, we 1813 // need to wait and see how the expression is used. 1814 return NOUR_None; 1815 } 1816 1817 /// BuildDeclRefExpr - Build an expression that references a 1818 /// declaration that does not require a closure capture. 1819 DeclRefExpr * 1820 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1821 const DeclarationNameInfo &NameInfo, 1822 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1823 SourceLocation TemplateKWLoc, 1824 const TemplateArgumentListInfo *TemplateArgs) { 1825 bool RefersToCapturedVariable = 1826 isa<VarDecl>(D) && 1827 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1828 1829 DeclRefExpr *E = DeclRefExpr::Create( 1830 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1831 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1832 MarkDeclRefReferenced(E); 1833 1834 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1835 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1836 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1837 getCurFunction()->recordUseOfWeak(E); 1838 1839 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1840 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1841 FD = IFD->getAnonField(); 1842 if (FD) { 1843 UnusedPrivateFields.remove(FD); 1844 // Just in case we're building an illegal pointer-to-member. 1845 if (FD->isBitField()) 1846 E->setObjectKind(OK_BitField); 1847 } 1848 1849 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1850 // designates a bit-field. 1851 if (auto *BD = dyn_cast<BindingDecl>(D)) 1852 if (auto *BE = BD->getBinding()) 1853 E->setObjectKind(BE->getObjectKind()); 1854 1855 return E; 1856 } 1857 1858 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1859 /// possibly a list of template arguments. 1860 /// 1861 /// If this produces template arguments, it is permitted to call 1862 /// DecomposeTemplateName. 1863 /// 1864 /// This actually loses a lot of source location information for 1865 /// non-standard name kinds; we should consider preserving that in 1866 /// some way. 1867 void 1868 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1869 TemplateArgumentListInfo &Buffer, 1870 DeclarationNameInfo &NameInfo, 1871 const TemplateArgumentListInfo *&TemplateArgs) { 1872 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1873 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1874 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1875 1876 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1877 Id.TemplateId->NumArgs); 1878 translateTemplateArguments(TemplateArgsPtr, Buffer); 1879 1880 TemplateName TName = Id.TemplateId->Template.get(); 1881 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1882 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1883 TemplateArgs = &Buffer; 1884 } else { 1885 NameInfo = GetNameFromUnqualifiedId(Id); 1886 TemplateArgs = nullptr; 1887 } 1888 } 1889 1890 static void emitEmptyLookupTypoDiagnostic( 1891 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1892 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1893 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1894 DeclContext *Ctx = 1895 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1896 if (!TC) { 1897 // Emit a special diagnostic for failed member lookups. 1898 // FIXME: computing the declaration context might fail here (?) 1899 if (Ctx) 1900 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1901 << SS.getRange(); 1902 else 1903 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1904 return; 1905 } 1906 1907 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1908 bool DroppedSpecifier = 1909 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1910 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1911 ? diag::note_implicit_param_decl 1912 : diag::note_previous_decl; 1913 if (!Ctx) 1914 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1915 SemaRef.PDiag(NoteID)); 1916 else 1917 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1918 << Typo << Ctx << DroppedSpecifier 1919 << SS.getRange(), 1920 SemaRef.PDiag(NoteID)); 1921 } 1922 1923 /// Diagnose an empty lookup. 1924 /// 1925 /// \return false if new lookup candidates were found 1926 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1927 CorrectionCandidateCallback &CCC, 1928 TemplateArgumentListInfo *ExplicitTemplateArgs, 1929 ArrayRef<Expr *> Args, TypoExpr **Out) { 1930 DeclarationName Name = R.getLookupName(); 1931 1932 unsigned diagnostic = diag::err_undeclared_var_use; 1933 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1934 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1935 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1936 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1937 diagnostic = diag::err_undeclared_use; 1938 diagnostic_suggest = diag::err_undeclared_use_suggest; 1939 } 1940 1941 // If the original lookup was an unqualified lookup, fake an 1942 // unqualified lookup. This is useful when (for example) the 1943 // original lookup would not have found something because it was a 1944 // dependent name. 1945 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1946 while (DC) { 1947 if (isa<CXXRecordDecl>(DC)) { 1948 LookupQualifiedName(R, DC); 1949 1950 if (!R.empty()) { 1951 // Don't give errors about ambiguities in this lookup. 1952 R.suppressDiagnostics(); 1953 1954 // During a default argument instantiation the CurContext points 1955 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1956 // function parameter list, hence add an explicit check. 1957 bool isDefaultArgument = 1958 !CodeSynthesisContexts.empty() && 1959 CodeSynthesisContexts.back().Kind == 1960 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1961 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1962 bool isInstance = CurMethod && 1963 CurMethod->isInstance() && 1964 DC == CurMethod->getParent() && !isDefaultArgument; 1965 1966 // Give a code modification hint to insert 'this->'. 1967 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1968 // Actually quite difficult! 1969 if (getLangOpts().MSVCCompat) 1970 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1971 if (isInstance) { 1972 Diag(R.getNameLoc(), diagnostic) << Name 1973 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1974 CheckCXXThisCapture(R.getNameLoc()); 1975 } else { 1976 Diag(R.getNameLoc(), diagnostic) << Name; 1977 } 1978 1979 // Do we really want to note all of these? 1980 for (NamedDecl *D : R) 1981 Diag(D->getLocation(), diag::note_dependent_var_use); 1982 1983 // Return true if we are inside a default argument instantiation 1984 // and the found name refers to an instance member function, otherwise 1985 // the function calling DiagnoseEmptyLookup will try to create an 1986 // implicit member call and this is wrong for default argument. 1987 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1988 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1989 return true; 1990 } 1991 1992 // Tell the callee to try to recover. 1993 return false; 1994 } 1995 1996 R.clear(); 1997 } 1998 1999 DC = DC->getLookupParent(); 2000 } 2001 2002 // We didn't find anything, so try to correct for a typo. 2003 TypoCorrection Corrected; 2004 if (S && Out) { 2005 SourceLocation TypoLoc = R.getNameLoc(); 2006 assert(!ExplicitTemplateArgs && 2007 "Diagnosing an empty lookup with explicit template args!"); 2008 *Out = CorrectTypoDelayed( 2009 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2010 [=](const TypoCorrection &TC) { 2011 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2012 diagnostic, diagnostic_suggest); 2013 }, 2014 nullptr, CTK_ErrorRecovery); 2015 if (*Out) 2016 return true; 2017 } else if (S && 2018 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2019 S, &SS, CCC, CTK_ErrorRecovery))) { 2020 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2021 bool DroppedSpecifier = 2022 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2023 R.setLookupName(Corrected.getCorrection()); 2024 2025 bool AcceptableWithRecovery = false; 2026 bool AcceptableWithoutRecovery = false; 2027 NamedDecl *ND = Corrected.getFoundDecl(); 2028 if (ND) { 2029 if (Corrected.isOverloaded()) { 2030 OverloadCandidateSet OCS(R.getNameLoc(), 2031 OverloadCandidateSet::CSK_Normal); 2032 OverloadCandidateSet::iterator Best; 2033 for (NamedDecl *CD : Corrected) { 2034 if (FunctionTemplateDecl *FTD = 2035 dyn_cast<FunctionTemplateDecl>(CD)) 2036 AddTemplateOverloadCandidate( 2037 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2038 Args, OCS); 2039 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2040 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2041 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2042 Args, OCS); 2043 } 2044 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2045 case OR_Success: 2046 ND = Best->FoundDecl; 2047 Corrected.setCorrectionDecl(ND); 2048 break; 2049 default: 2050 // FIXME: Arbitrarily pick the first declaration for the note. 2051 Corrected.setCorrectionDecl(ND); 2052 break; 2053 } 2054 } 2055 R.addDecl(ND); 2056 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2057 CXXRecordDecl *Record = nullptr; 2058 if (Corrected.getCorrectionSpecifier()) { 2059 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2060 Record = Ty->getAsCXXRecordDecl(); 2061 } 2062 if (!Record) 2063 Record = cast<CXXRecordDecl>( 2064 ND->getDeclContext()->getRedeclContext()); 2065 R.setNamingClass(Record); 2066 } 2067 2068 auto *UnderlyingND = ND->getUnderlyingDecl(); 2069 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2070 isa<FunctionTemplateDecl>(UnderlyingND); 2071 // FIXME: If we ended up with a typo for a type name or 2072 // Objective-C class name, we're in trouble because the parser 2073 // is in the wrong place to recover. Suggest the typo 2074 // correction, but don't make it a fix-it since we're not going 2075 // to recover well anyway. 2076 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2077 getAsTypeTemplateDecl(UnderlyingND) || 2078 isa<ObjCInterfaceDecl>(UnderlyingND); 2079 } else { 2080 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2081 // because we aren't able to recover. 2082 AcceptableWithoutRecovery = true; 2083 } 2084 2085 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2086 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2087 ? diag::note_implicit_param_decl 2088 : diag::note_previous_decl; 2089 if (SS.isEmpty()) 2090 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2091 PDiag(NoteID), AcceptableWithRecovery); 2092 else 2093 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2094 << Name << computeDeclContext(SS, false) 2095 << DroppedSpecifier << SS.getRange(), 2096 PDiag(NoteID), AcceptableWithRecovery); 2097 2098 // Tell the callee whether to try to recover. 2099 return !AcceptableWithRecovery; 2100 } 2101 } 2102 R.clear(); 2103 2104 // Emit a special diagnostic for failed member lookups. 2105 // FIXME: computing the declaration context might fail here (?) 2106 if (!SS.isEmpty()) { 2107 Diag(R.getNameLoc(), diag::err_no_member) 2108 << Name << computeDeclContext(SS, false) 2109 << SS.getRange(); 2110 return true; 2111 } 2112 2113 // Give up, we can't recover. 2114 Diag(R.getNameLoc(), diagnostic) << Name; 2115 return true; 2116 } 2117 2118 /// In Microsoft mode, if we are inside a template class whose parent class has 2119 /// dependent base classes, and we can't resolve an unqualified identifier, then 2120 /// assume the identifier is a member of a dependent base class. We can only 2121 /// recover successfully in static methods, instance methods, and other contexts 2122 /// where 'this' is available. This doesn't precisely match MSVC's 2123 /// instantiation model, but it's close enough. 2124 static Expr * 2125 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2126 DeclarationNameInfo &NameInfo, 2127 SourceLocation TemplateKWLoc, 2128 const TemplateArgumentListInfo *TemplateArgs) { 2129 // Only try to recover from lookup into dependent bases in static methods or 2130 // contexts where 'this' is available. 2131 QualType ThisType = S.getCurrentThisType(); 2132 const CXXRecordDecl *RD = nullptr; 2133 if (!ThisType.isNull()) 2134 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2135 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2136 RD = MD->getParent(); 2137 if (!RD || !RD->hasAnyDependentBases()) 2138 return nullptr; 2139 2140 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2141 // is available, suggest inserting 'this->' as a fixit. 2142 SourceLocation Loc = NameInfo.getLoc(); 2143 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2144 DB << NameInfo.getName() << RD; 2145 2146 if (!ThisType.isNull()) { 2147 DB << FixItHint::CreateInsertion(Loc, "this->"); 2148 return CXXDependentScopeMemberExpr::Create( 2149 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2150 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2151 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2152 } 2153 2154 // Synthesize a fake NNS that points to the derived class. This will 2155 // perform name lookup during template instantiation. 2156 CXXScopeSpec SS; 2157 auto *NNS = 2158 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2159 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2160 return DependentScopeDeclRefExpr::Create( 2161 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2162 TemplateArgs); 2163 } 2164 2165 ExprResult 2166 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2167 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2168 bool HasTrailingLParen, bool IsAddressOfOperand, 2169 CorrectionCandidateCallback *CCC, 2170 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2171 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2172 "cannot be direct & operand and have a trailing lparen"); 2173 if (SS.isInvalid()) 2174 return ExprError(); 2175 2176 TemplateArgumentListInfo TemplateArgsBuffer; 2177 2178 // Decompose the UnqualifiedId into the following data. 2179 DeclarationNameInfo NameInfo; 2180 const TemplateArgumentListInfo *TemplateArgs; 2181 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2182 2183 DeclarationName Name = NameInfo.getName(); 2184 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2185 SourceLocation NameLoc = NameInfo.getLoc(); 2186 2187 if (II && II->isEditorPlaceholder()) { 2188 // FIXME: When typed placeholders are supported we can create a typed 2189 // placeholder expression node. 2190 return ExprError(); 2191 } 2192 2193 // C++ [temp.dep.expr]p3: 2194 // An id-expression is type-dependent if it contains: 2195 // -- an identifier that was declared with a dependent type, 2196 // (note: handled after lookup) 2197 // -- a template-id that is dependent, 2198 // (note: handled in BuildTemplateIdExpr) 2199 // -- a conversion-function-id that specifies a dependent type, 2200 // -- a nested-name-specifier that contains a class-name that 2201 // names a dependent type. 2202 // Determine whether this is a member of an unknown specialization; 2203 // we need to handle these differently. 2204 bool DependentID = false; 2205 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2206 Name.getCXXNameType()->isDependentType()) { 2207 DependentID = true; 2208 } else if (SS.isSet()) { 2209 if (DeclContext *DC = computeDeclContext(SS, false)) { 2210 if (RequireCompleteDeclContext(SS, DC)) 2211 return ExprError(); 2212 } else { 2213 DependentID = true; 2214 } 2215 } 2216 2217 if (DependentID) 2218 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2219 IsAddressOfOperand, TemplateArgs); 2220 2221 // Perform the required lookup. 2222 LookupResult R(*this, NameInfo, 2223 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2224 ? LookupObjCImplicitSelfParam 2225 : LookupOrdinaryName); 2226 if (TemplateKWLoc.isValid() || TemplateArgs) { 2227 // Lookup the template name again to correctly establish the context in 2228 // which it was found. This is really unfortunate as we already did the 2229 // lookup to determine that it was a template name in the first place. If 2230 // this becomes a performance hit, we can work harder to preserve those 2231 // results until we get here but it's likely not worth it. 2232 bool MemberOfUnknownSpecialization; 2233 AssumedTemplateKind AssumedTemplate; 2234 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2235 MemberOfUnknownSpecialization, TemplateKWLoc, 2236 &AssumedTemplate)) 2237 return ExprError(); 2238 2239 if (MemberOfUnknownSpecialization || 2240 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2241 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2242 IsAddressOfOperand, TemplateArgs); 2243 } else { 2244 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2245 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2246 2247 // If the result might be in a dependent base class, this is a dependent 2248 // id-expression. 2249 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2250 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2251 IsAddressOfOperand, TemplateArgs); 2252 2253 // If this reference is in an Objective-C method, then we need to do 2254 // some special Objective-C lookup, too. 2255 if (IvarLookupFollowUp) { 2256 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2257 if (E.isInvalid()) 2258 return ExprError(); 2259 2260 if (Expr *Ex = E.getAs<Expr>()) 2261 return Ex; 2262 } 2263 } 2264 2265 if (R.isAmbiguous()) 2266 return ExprError(); 2267 2268 // This could be an implicitly declared function reference (legal in C90, 2269 // extension in C99, forbidden in C++). 2270 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2271 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2272 if (D) R.addDecl(D); 2273 } 2274 2275 // Determine whether this name might be a candidate for 2276 // argument-dependent lookup. 2277 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2278 2279 if (R.empty() && !ADL) { 2280 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2281 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2282 TemplateKWLoc, TemplateArgs)) 2283 return E; 2284 } 2285 2286 // Don't diagnose an empty lookup for inline assembly. 2287 if (IsInlineAsmIdentifier) 2288 return ExprError(); 2289 2290 // If this name wasn't predeclared and if this is not a function 2291 // call, diagnose the problem. 2292 TypoExpr *TE = nullptr; 2293 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2294 : nullptr); 2295 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2296 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2297 "Typo correction callback misconfigured"); 2298 if (CCC) { 2299 // Make sure the callback knows what the typo being diagnosed is. 2300 CCC->setTypoName(II); 2301 if (SS.isValid()) 2302 CCC->setTypoNNS(SS.getScopeRep()); 2303 } 2304 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2305 // a template name, but we happen to have always already looked up the name 2306 // before we get here if it must be a template name. 2307 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2308 None, &TE)) { 2309 if (TE && KeywordReplacement) { 2310 auto &State = getTypoExprState(TE); 2311 auto BestTC = State.Consumer->getNextCorrection(); 2312 if (BestTC.isKeyword()) { 2313 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2314 if (State.DiagHandler) 2315 State.DiagHandler(BestTC); 2316 KeywordReplacement->startToken(); 2317 KeywordReplacement->setKind(II->getTokenID()); 2318 KeywordReplacement->setIdentifierInfo(II); 2319 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2320 // Clean up the state associated with the TypoExpr, since it has 2321 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2322 clearDelayedTypo(TE); 2323 // Signal that a correction to a keyword was performed by returning a 2324 // valid-but-null ExprResult. 2325 return (Expr*)nullptr; 2326 } 2327 State.Consumer->resetCorrectionStream(); 2328 } 2329 return TE ? TE : ExprError(); 2330 } 2331 2332 assert(!R.empty() && 2333 "DiagnoseEmptyLookup returned false but added no results"); 2334 2335 // If we found an Objective-C instance variable, let 2336 // LookupInObjCMethod build the appropriate expression to 2337 // reference the ivar. 2338 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2339 R.clear(); 2340 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2341 // In a hopelessly buggy code, Objective-C instance variable 2342 // lookup fails and no expression will be built to reference it. 2343 if (!E.isInvalid() && !E.get()) 2344 return ExprError(); 2345 return E; 2346 } 2347 } 2348 2349 // This is guaranteed from this point on. 2350 assert(!R.empty() || ADL); 2351 2352 // Check whether this might be a C++ implicit instance member access. 2353 // C++ [class.mfct.non-static]p3: 2354 // When an id-expression that is not part of a class member access 2355 // syntax and not used to form a pointer to member is used in the 2356 // body of a non-static member function of class X, if name lookup 2357 // resolves the name in the id-expression to a non-static non-type 2358 // member of some class C, the id-expression is transformed into a 2359 // class member access expression using (*this) as the 2360 // postfix-expression to the left of the . operator. 2361 // 2362 // But we don't actually need to do this for '&' operands if R 2363 // resolved to a function or overloaded function set, because the 2364 // expression is ill-formed if it actually works out to be a 2365 // non-static member function: 2366 // 2367 // C++ [expr.ref]p4: 2368 // Otherwise, if E1.E2 refers to a non-static member function. . . 2369 // [t]he expression can be used only as the left-hand operand of a 2370 // member function call. 2371 // 2372 // There are other safeguards against such uses, but it's important 2373 // to get this right here so that we don't end up making a 2374 // spuriously dependent expression if we're inside a dependent 2375 // instance method. 2376 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2377 bool MightBeImplicitMember; 2378 if (!IsAddressOfOperand) 2379 MightBeImplicitMember = true; 2380 else if (!SS.isEmpty()) 2381 MightBeImplicitMember = false; 2382 else if (R.isOverloadedResult()) 2383 MightBeImplicitMember = false; 2384 else if (R.isUnresolvableResult()) 2385 MightBeImplicitMember = true; 2386 else 2387 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2388 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2389 isa<MSPropertyDecl>(R.getFoundDecl()); 2390 2391 if (MightBeImplicitMember) 2392 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2393 R, TemplateArgs, S); 2394 } 2395 2396 if (TemplateArgs || TemplateKWLoc.isValid()) { 2397 2398 // In C++1y, if this is a variable template id, then check it 2399 // in BuildTemplateIdExpr(). 2400 // The single lookup result must be a variable template declaration. 2401 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2402 Id.TemplateId->Kind == TNK_Var_template) { 2403 assert(R.getAsSingle<VarTemplateDecl>() && 2404 "There should only be one declaration found."); 2405 } 2406 2407 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2408 } 2409 2410 return BuildDeclarationNameExpr(SS, R, ADL); 2411 } 2412 2413 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2414 /// declaration name, generally during template instantiation. 2415 /// There's a large number of things which don't need to be done along 2416 /// this path. 2417 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2418 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2419 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2420 DeclContext *DC = computeDeclContext(SS, false); 2421 if (!DC) 2422 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2423 NameInfo, /*TemplateArgs=*/nullptr); 2424 2425 if (RequireCompleteDeclContext(SS, DC)) 2426 return ExprError(); 2427 2428 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2429 LookupQualifiedName(R, DC); 2430 2431 if (R.isAmbiguous()) 2432 return ExprError(); 2433 2434 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2435 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2436 NameInfo, /*TemplateArgs=*/nullptr); 2437 2438 if (R.empty()) { 2439 Diag(NameInfo.getLoc(), diag::err_no_member) 2440 << NameInfo.getName() << DC << SS.getRange(); 2441 return ExprError(); 2442 } 2443 2444 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2445 // Diagnose a missing typename if this resolved unambiguously to a type in 2446 // a dependent context. If we can recover with a type, downgrade this to 2447 // a warning in Microsoft compatibility mode. 2448 unsigned DiagID = diag::err_typename_missing; 2449 if (RecoveryTSI && getLangOpts().MSVCCompat) 2450 DiagID = diag::ext_typename_missing; 2451 SourceLocation Loc = SS.getBeginLoc(); 2452 auto D = Diag(Loc, DiagID); 2453 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2454 << SourceRange(Loc, NameInfo.getEndLoc()); 2455 2456 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2457 // context. 2458 if (!RecoveryTSI) 2459 return ExprError(); 2460 2461 // Only issue the fixit if we're prepared to recover. 2462 D << FixItHint::CreateInsertion(Loc, "typename "); 2463 2464 // Recover by pretending this was an elaborated type. 2465 QualType Ty = Context.getTypeDeclType(TD); 2466 TypeLocBuilder TLB; 2467 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2468 2469 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2470 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2471 QTL.setElaboratedKeywordLoc(SourceLocation()); 2472 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2473 2474 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2475 2476 return ExprEmpty(); 2477 } 2478 2479 // Defend against this resolving to an implicit member access. We usually 2480 // won't get here if this might be a legitimate a class member (we end up in 2481 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2482 // a pointer-to-member or in an unevaluated context in C++11. 2483 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2484 return BuildPossibleImplicitMemberExpr(SS, 2485 /*TemplateKWLoc=*/SourceLocation(), 2486 R, /*TemplateArgs=*/nullptr, S); 2487 2488 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2489 } 2490 2491 /// The parser has read a name in, and Sema has detected that we're currently 2492 /// inside an ObjC method. Perform some additional checks and determine if we 2493 /// should form a reference to an ivar. 2494 /// 2495 /// Ideally, most of this would be done by lookup, but there's 2496 /// actually quite a lot of extra work involved. 2497 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2498 IdentifierInfo *II) { 2499 SourceLocation Loc = Lookup.getNameLoc(); 2500 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2501 2502 // Check for error condition which is already reported. 2503 if (!CurMethod) 2504 return DeclResult(true); 2505 2506 // There are two cases to handle here. 1) scoped lookup could have failed, 2507 // in which case we should look for an ivar. 2) scoped lookup could have 2508 // found a decl, but that decl is outside the current instance method (i.e. 2509 // a global variable). In these two cases, we do a lookup for an ivar with 2510 // this name, if the lookup sucedes, we replace it our current decl. 2511 2512 // If we're in a class method, we don't normally want to look for 2513 // ivars. But if we don't find anything else, and there's an 2514 // ivar, that's an error. 2515 bool IsClassMethod = CurMethod->isClassMethod(); 2516 2517 bool LookForIvars; 2518 if (Lookup.empty()) 2519 LookForIvars = true; 2520 else if (IsClassMethod) 2521 LookForIvars = false; 2522 else 2523 LookForIvars = (Lookup.isSingleResult() && 2524 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2525 ObjCInterfaceDecl *IFace = nullptr; 2526 if (LookForIvars) { 2527 IFace = CurMethod->getClassInterface(); 2528 ObjCInterfaceDecl *ClassDeclared; 2529 ObjCIvarDecl *IV = nullptr; 2530 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2531 // Diagnose using an ivar in a class method. 2532 if (IsClassMethod) { 2533 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2534 return DeclResult(true); 2535 } 2536 2537 // Diagnose the use of an ivar outside of the declaring class. 2538 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2539 !declaresSameEntity(ClassDeclared, IFace) && 2540 !getLangOpts().DebuggerSupport) 2541 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2542 2543 // Success. 2544 return IV; 2545 } 2546 } else if (CurMethod->isInstanceMethod()) { 2547 // We should warn if a local variable hides an ivar. 2548 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2549 ObjCInterfaceDecl *ClassDeclared; 2550 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2551 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2552 declaresSameEntity(IFace, ClassDeclared)) 2553 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2554 } 2555 } 2556 } else if (Lookup.isSingleResult() && 2557 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2558 // If accessing a stand-alone ivar in a class method, this is an error. 2559 if (const ObjCIvarDecl *IV = 2560 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2561 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2562 return DeclResult(true); 2563 } 2564 } 2565 2566 // Didn't encounter an error, didn't find an ivar. 2567 return DeclResult(false); 2568 } 2569 2570 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2571 ObjCIvarDecl *IV) { 2572 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2573 assert(CurMethod && CurMethod->isInstanceMethod() && 2574 "should not reference ivar from this context"); 2575 2576 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2577 assert(IFace && "should not reference ivar from this context"); 2578 2579 // If we're referencing an invalid decl, just return this as a silent 2580 // error node. The error diagnostic was already emitted on the decl. 2581 if (IV->isInvalidDecl()) 2582 return ExprError(); 2583 2584 // Check if referencing a field with __attribute__((deprecated)). 2585 if (DiagnoseUseOfDecl(IV, Loc)) 2586 return ExprError(); 2587 2588 // FIXME: This should use a new expr for a direct reference, don't 2589 // turn this into Self->ivar, just return a BareIVarExpr or something. 2590 IdentifierInfo &II = Context.Idents.get("self"); 2591 UnqualifiedId SelfName; 2592 SelfName.setIdentifier(&II, SourceLocation()); 2593 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2594 CXXScopeSpec SelfScopeSpec; 2595 SourceLocation TemplateKWLoc; 2596 ExprResult SelfExpr = 2597 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2598 /*HasTrailingLParen=*/false, 2599 /*IsAddressOfOperand=*/false); 2600 if (SelfExpr.isInvalid()) 2601 return ExprError(); 2602 2603 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2604 if (SelfExpr.isInvalid()) 2605 return ExprError(); 2606 2607 MarkAnyDeclReferenced(Loc, IV, true); 2608 2609 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2610 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2611 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2612 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2613 2614 ObjCIvarRefExpr *Result = new (Context) 2615 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2616 IV->getLocation(), SelfExpr.get(), true, true); 2617 2618 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2619 if (!isUnevaluatedContext() && 2620 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2621 getCurFunction()->recordUseOfWeak(Result); 2622 } 2623 if (getLangOpts().ObjCAutoRefCount) 2624 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2625 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2626 2627 return Result; 2628 } 2629 2630 /// The parser has read a name in, and Sema has detected that we're currently 2631 /// inside an ObjC method. Perform some additional checks and determine if we 2632 /// should form a reference to an ivar. If so, build an expression referencing 2633 /// that ivar. 2634 ExprResult 2635 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2636 IdentifierInfo *II, bool AllowBuiltinCreation) { 2637 // FIXME: Integrate this lookup step into LookupParsedName. 2638 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2639 if (Ivar.isInvalid()) 2640 return ExprError(); 2641 if (Ivar.isUsable()) 2642 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2643 cast<ObjCIvarDecl>(Ivar.get())); 2644 2645 if (Lookup.empty() && II && AllowBuiltinCreation) 2646 LookupBuiltin(Lookup); 2647 2648 // Sentinel value saying that we didn't do anything special. 2649 return ExprResult(false); 2650 } 2651 2652 /// Cast a base object to a member's actual type. 2653 /// 2654 /// Logically this happens in three phases: 2655 /// 2656 /// * First we cast from the base type to the naming class. 2657 /// The naming class is the class into which we were looking 2658 /// when we found the member; it's the qualifier type if a 2659 /// qualifier was provided, and otherwise it's the base type. 2660 /// 2661 /// * Next we cast from the naming class to the declaring class. 2662 /// If the member we found was brought into a class's scope by 2663 /// a using declaration, this is that class; otherwise it's 2664 /// the class declaring the member. 2665 /// 2666 /// * Finally we cast from the declaring class to the "true" 2667 /// declaring class of the member. This conversion does not 2668 /// obey access control. 2669 ExprResult 2670 Sema::PerformObjectMemberConversion(Expr *From, 2671 NestedNameSpecifier *Qualifier, 2672 NamedDecl *FoundDecl, 2673 NamedDecl *Member) { 2674 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2675 if (!RD) 2676 return From; 2677 2678 QualType DestRecordType; 2679 QualType DestType; 2680 QualType FromRecordType; 2681 QualType FromType = From->getType(); 2682 bool PointerConversions = false; 2683 if (isa<FieldDecl>(Member)) { 2684 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2685 auto FromPtrType = FromType->getAs<PointerType>(); 2686 DestRecordType = Context.getAddrSpaceQualType( 2687 DestRecordType, FromPtrType 2688 ? FromType->getPointeeType().getAddressSpace() 2689 : FromType.getAddressSpace()); 2690 2691 if (FromPtrType) { 2692 DestType = Context.getPointerType(DestRecordType); 2693 FromRecordType = FromPtrType->getPointeeType(); 2694 PointerConversions = true; 2695 } else { 2696 DestType = DestRecordType; 2697 FromRecordType = FromType; 2698 } 2699 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2700 if (Method->isStatic()) 2701 return From; 2702 2703 DestType = Method->getThisType(); 2704 DestRecordType = DestType->getPointeeType(); 2705 2706 if (FromType->getAs<PointerType>()) { 2707 FromRecordType = FromType->getPointeeType(); 2708 PointerConversions = true; 2709 } else { 2710 FromRecordType = FromType; 2711 DestType = DestRecordType; 2712 } 2713 } else { 2714 // No conversion necessary. 2715 return From; 2716 } 2717 2718 if (DestType->isDependentType() || FromType->isDependentType()) 2719 return From; 2720 2721 // If the unqualified types are the same, no conversion is necessary. 2722 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2723 return From; 2724 2725 SourceRange FromRange = From->getSourceRange(); 2726 SourceLocation FromLoc = FromRange.getBegin(); 2727 2728 ExprValueKind VK = From->getValueKind(); 2729 2730 // C++ [class.member.lookup]p8: 2731 // [...] Ambiguities can often be resolved by qualifying a name with its 2732 // class name. 2733 // 2734 // If the member was a qualified name and the qualified referred to a 2735 // specific base subobject type, we'll cast to that intermediate type 2736 // first and then to the object in which the member is declared. That allows 2737 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2738 // 2739 // class Base { public: int x; }; 2740 // class Derived1 : public Base { }; 2741 // class Derived2 : public Base { }; 2742 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2743 // 2744 // void VeryDerived::f() { 2745 // x = 17; // error: ambiguous base subobjects 2746 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2747 // } 2748 if (Qualifier && Qualifier->getAsType()) { 2749 QualType QType = QualType(Qualifier->getAsType(), 0); 2750 assert(QType->isRecordType() && "lookup done with non-record type"); 2751 2752 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2753 2754 // In C++98, the qualifier type doesn't actually have to be a base 2755 // type of the object type, in which case we just ignore it. 2756 // Otherwise build the appropriate casts. 2757 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2758 CXXCastPath BasePath; 2759 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2760 FromLoc, FromRange, &BasePath)) 2761 return ExprError(); 2762 2763 if (PointerConversions) 2764 QType = Context.getPointerType(QType); 2765 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2766 VK, &BasePath).get(); 2767 2768 FromType = QType; 2769 FromRecordType = QRecordType; 2770 2771 // If the qualifier type was the same as the destination type, 2772 // we're done. 2773 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2774 return From; 2775 } 2776 } 2777 2778 bool IgnoreAccess = false; 2779 2780 // If we actually found the member through a using declaration, cast 2781 // down to the using declaration's type. 2782 // 2783 // Pointer equality is fine here because only one declaration of a 2784 // class ever has member declarations. 2785 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2786 assert(isa<UsingShadowDecl>(FoundDecl)); 2787 QualType URecordType = Context.getTypeDeclType( 2788 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2789 2790 // We only need to do this if the naming-class to declaring-class 2791 // conversion is non-trivial. 2792 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2793 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2794 CXXCastPath BasePath; 2795 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2796 FromLoc, FromRange, &BasePath)) 2797 return ExprError(); 2798 2799 QualType UType = URecordType; 2800 if (PointerConversions) 2801 UType = Context.getPointerType(UType); 2802 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2803 VK, &BasePath).get(); 2804 FromType = UType; 2805 FromRecordType = URecordType; 2806 } 2807 2808 // We don't do access control for the conversion from the 2809 // declaring class to the true declaring class. 2810 IgnoreAccess = true; 2811 } 2812 2813 CXXCastPath BasePath; 2814 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2815 FromLoc, FromRange, &BasePath, 2816 IgnoreAccess)) 2817 return ExprError(); 2818 2819 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2820 VK, &BasePath); 2821 } 2822 2823 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2824 const LookupResult &R, 2825 bool HasTrailingLParen) { 2826 // Only when used directly as the postfix-expression of a call. 2827 if (!HasTrailingLParen) 2828 return false; 2829 2830 // Never if a scope specifier was provided. 2831 if (SS.isSet()) 2832 return false; 2833 2834 // Only in C++ or ObjC++. 2835 if (!getLangOpts().CPlusPlus) 2836 return false; 2837 2838 // Turn off ADL when we find certain kinds of declarations during 2839 // normal lookup: 2840 for (NamedDecl *D : R) { 2841 // C++0x [basic.lookup.argdep]p3: 2842 // -- a declaration of a class member 2843 // Since using decls preserve this property, we check this on the 2844 // original decl. 2845 if (D->isCXXClassMember()) 2846 return false; 2847 2848 // C++0x [basic.lookup.argdep]p3: 2849 // -- a block-scope function declaration that is not a 2850 // using-declaration 2851 // NOTE: we also trigger this for function templates (in fact, we 2852 // don't check the decl type at all, since all other decl types 2853 // turn off ADL anyway). 2854 if (isa<UsingShadowDecl>(D)) 2855 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2856 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2857 return false; 2858 2859 // C++0x [basic.lookup.argdep]p3: 2860 // -- a declaration that is neither a function or a function 2861 // template 2862 // And also for builtin functions. 2863 if (isa<FunctionDecl>(D)) { 2864 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2865 2866 // But also builtin functions. 2867 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2868 return false; 2869 } else if (!isa<FunctionTemplateDecl>(D)) 2870 return false; 2871 } 2872 2873 return true; 2874 } 2875 2876 2877 /// Diagnoses obvious problems with the use of the given declaration 2878 /// as an expression. This is only actually called for lookups that 2879 /// were not overloaded, and it doesn't promise that the declaration 2880 /// will in fact be used. 2881 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2882 if (D->isInvalidDecl()) 2883 return true; 2884 2885 if (isa<TypedefNameDecl>(D)) { 2886 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2887 return true; 2888 } 2889 2890 if (isa<ObjCInterfaceDecl>(D)) { 2891 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2892 return true; 2893 } 2894 2895 if (isa<NamespaceDecl>(D)) { 2896 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2897 return true; 2898 } 2899 2900 return false; 2901 } 2902 2903 // Certain multiversion types should be treated as overloaded even when there is 2904 // only one result. 2905 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2906 assert(R.isSingleResult() && "Expected only a single result"); 2907 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2908 return FD && 2909 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2910 } 2911 2912 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2913 LookupResult &R, bool NeedsADL, 2914 bool AcceptInvalidDecl) { 2915 // If this is a single, fully-resolved result and we don't need ADL, 2916 // just build an ordinary singleton decl ref. 2917 if (!NeedsADL && R.isSingleResult() && 2918 !R.getAsSingle<FunctionTemplateDecl>() && 2919 !ShouldLookupResultBeMultiVersionOverload(R)) 2920 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2921 R.getRepresentativeDecl(), nullptr, 2922 AcceptInvalidDecl); 2923 2924 // We only need to check the declaration if there's exactly one 2925 // result, because in the overloaded case the results can only be 2926 // functions and function templates. 2927 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2928 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2929 return ExprError(); 2930 2931 // Otherwise, just build an unresolved lookup expression. Suppress 2932 // any lookup-related diagnostics; we'll hash these out later, when 2933 // we've picked a target. 2934 R.suppressDiagnostics(); 2935 2936 UnresolvedLookupExpr *ULE 2937 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2938 SS.getWithLocInContext(Context), 2939 R.getLookupNameInfo(), 2940 NeedsADL, R.isOverloadedResult(), 2941 R.begin(), R.end()); 2942 2943 return ULE; 2944 } 2945 2946 static void 2947 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2948 ValueDecl *var, DeclContext *DC); 2949 2950 /// Complete semantic analysis for a reference to the given declaration. 2951 ExprResult Sema::BuildDeclarationNameExpr( 2952 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2953 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2954 bool AcceptInvalidDecl) { 2955 assert(D && "Cannot refer to a NULL declaration"); 2956 assert(!isa<FunctionTemplateDecl>(D) && 2957 "Cannot refer unambiguously to a function template"); 2958 2959 SourceLocation Loc = NameInfo.getLoc(); 2960 if (CheckDeclInExpr(*this, Loc, D)) 2961 return ExprError(); 2962 2963 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2964 // Specifically diagnose references to class templates that are missing 2965 // a template argument list. 2966 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2967 return ExprError(); 2968 } 2969 2970 // Make sure that we're referring to a value. 2971 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2972 if (!VD) { 2973 Diag(Loc, diag::err_ref_non_value) 2974 << D << SS.getRange(); 2975 Diag(D->getLocation(), diag::note_declared_at); 2976 return ExprError(); 2977 } 2978 2979 // Check whether this declaration can be used. Note that we suppress 2980 // this check when we're going to perform argument-dependent lookup 2981 // on this function name, because this might not be the function 2982 // that overload resolution actually selects. 2983 if (DiagnoseUseOfDecl(VD, Loc)) 2984 return ExprError(); 2985 2986 // Only create DeclRefExpr's for valid Decl's. 2987 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2988 return ExprError(); 2989 2990 // Handle members of anonymous structs and unions. If we got here, 2991 // and the reference is to a class member indirect field, then this 2992 // must be the subject of a pointer-to-member expression. 2993 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2994 if (!indirectField->isCXXClassMember()) 2995 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2996 indirectField); 2997 2998 { 2999 QualType type = VD->getType(); 3000 if (type.isNull()) 3001 return ExprError(); 3002 if (auto *FPT = type->getAs<FunctionProtoType>()) { 3003 // C++ [except.spec]p17: 3004 // An exception-specification is considered to be needed when: 3005 // - in an expression, the function is the unique lookup result or 3006 // the selected member of a set of overloaded functions. 3007 ResolveExceptionSpec(Loc, FPT); 3008 type = VD->getType(); 3009 } 3010 ExprValueKind valueKind = VK_RValue; 3011 3012 switch (D->getKind()) { 3013 // Ignore all the non-ValueDecl kinds. 3014 #define ABSTRACT_DECL(kind) 3015 #define VALUE(type, base) 3016 #define DECL(type, base) \ 3017 case Decl::type: 3018 #include "clang/AST/DeclNodes.inc" 3019 llvm_unreachable("invalid value decl kind"); 3020 3021 // These shouldn't make it here. 3022 case Decl::ObjCAtDefsField: 3023 llvm_unreachable("forming non-member reference to ivar?"); 3024 3025 // Enum constants are always r-values and never references. 3026 // Unresolved using declarations are dependent. 3027 case Decl::EnumConstant: 3028 case Decl::UnresolvedUsingValue: 3029 case Decl::OMPDeclareReduction: 3030 case Decl::OMPDeclareMapper: 3031 valueKind = VK_RValue; 3032 break; 3033 3034 // Fields and indirect fields that got here must be for 3035 // pointer-to-member expressions; we just call them l-values for 3036 // internal consistency, because this subexpression doesn't really 3037 // exist in the high-level semantics. 3038 case Decl::Field: 3039 case Decl::IndirectField: 3040 case Decl::ObjCIvar: 3041 assert(getLangOpts().CPlusPlus && 3042 "building reference to field in C?"); 3043 3044 // These can't have reference type in well-formed programs, but 3045 // for internal consistency we do this anyway. 3046 type = type.getNonReferenceType(); 3047 valueKind = VK_LValue; 3048 break; 3049 3050 // Non-type template parameters are either l-values or r-values 3051 // depending on the type. 3052 case Decl::NonTypeTemplateParm: { 3053 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3054 type = reftype->getPointeeType(); 3055 valueKind = VK_LValue; // even if the parameter is an r-value reference 3056 break; 3057 } 3058 3059 // For non-references, we need to strip qualifiers just in case 3060 // the template parameter was declared as 'const int' or whatever. 3061 valueKind = VK_RValue; 3062 type = type.getUnqualifiedType(); 3063 break; 3064 } 3065 3066 case Decl::Var: 3067 case Decl::VarTemplateSpecialization: 3068 case Decl::VarTemplatePartialSpecialization: 3069 case Decl::Decomposition: 3070 case Decl::OMPCapturedExpr: 3071 // In C, "extern void blah;" is valid and is an r-value. 3072 if (!getLangOpts().CPlusPlus && 3073 !type.hasQualifiers() && 3074 type->isVoidType()) { 3075 valueKind = VK_RValue; 3076 break; 3077 } 3078 LLVM_FALLTHROUGH; 3079 3080 case Decl::ImplicitParam: 3081 case Decl::ParmVar: { 3082 // These are always l-values. 3083 valueKind = VK_LValue; 3084 type = type.getNonReferenceType(); 3085 3086 // FIXME: Does the addition of const really only apply in 3087 // potentially-evaluated contexts? Since the variable isn't actually 3088 // captured in an unevaluated context, it seems that the answer is no. 3089 if (!isUnevaluatedContext()) { 3090 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3091 if (!CapturedType.isNull()) 3092 type = CapturedType; 3093 } 3094 3095 break; 3096 } 3097 3098 case Decl::Binding: { 3099 // These are always lvalues. 3100 valueKind = VK_LValue; 3101 type = type.getNonReferenceType(); 3102 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3103 // decides how that's supposed to work. 3104 auto *BD = cast<BindingDecl>(VD); 3105 if (BD->getDeclContext() != CurContext) { 3106 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3107 if (DD && DD->hasLocalStorage()) 3108 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3109 } 3110 break; 3111 } 3112 3113 case Decl::Function: { 3114 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3115 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3116 type = Context.BuiltinFnTy; 3117 valueKind = VK_RValue; 3118 break; 3119 } 3120 } 3121 3122 const FunctionType *fty = type->castAs<FunctionType>(); 3123 3124 // If we're referring to a function with an __unknown_anytype 3125 // result type, make the entire expression __unknown_anytype. 3126 if (fty->getReturnType() == Context.UnknownAnyTy) { 3127 type = Context.UnknownAnyTy; 3128 valueKind = VK_RValue; 3129 break; 3130 } 3131 3132 // Functions are l-values in C++. 3133 if (getLangOpts().CPlusPlus) { 3134 valueKind = VK_LValue; 3135 break; 3136 } 3137 3138 // C99 DR 316 says that, if a function type comes from a 3139 // function definition (without a prototype), that type is only 3140 // used for checking compatibility. Therefore, when referencing 3141 // the function, we pretend that we don't have the full function 3142 // type. 3143 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3144 isa<FunctionProtoType>(fty)) 3145 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3146 fty->getExtInfo()); 3147 3148 // Functions are r-values in C. 3149 valueKind = VK_RValue; 3150 break; 3151 } 3152 3153 case Decl::CXXDeductionGuide: 3154 llvm_unreachable("building reference to deduction guide"); 3155 3156 case Decl::MSProperty: 3157 valueKind = VK_LValue; 3158 break; 3159 3160 case Decl::CXXMethod: 3161 // If we're referring to a method with an __unknown_anytype 3162 // result type, make the entire expression __unknown_anytype. 3163 // This should only be possible with a type written directly. 3164 if (const FunctionProtoType *proto 3165 = dyn_cast<FunctionProtoType>(VD->getType())) 3166 if (proto->getReturnType() == Context.UnknownAnyTy) { 3167 type = Context.UnknownAnyTy; 3168 valueKind = VK_RValue; 3169 break; 3170 } 3171 3172 // C++ methods are l-values if static, r-values if non-static. 3173 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3174 valueKind = VK_LValue; 3175 break; 3176 } 3177 LLVM_FALLTHROUGH; 3178 3179 case Decl::CXXConversion: 3180 case Decl::CXXDestructor: 3181 case Decl::CXXConstructor: 3182 valueKind = VK_RValue; 3183 break; 3184 } 3185 3186 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3187 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3188 TemplateArgs); 3189 } 3190 } 3191 3192 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3193 SmallString<32> &Target) { 3194 Target.resize(CharByteWidth * (Source.size() + 1)); 3195 char *ResultPtr = &Target[0]; 3196 const llvm::UTF8 *ErrorPtr; 3197 bool success = 3198 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3199 (void)success; 3200 assert(success); 3201 Target.resize(ResultPtr - &Target[0]); 3202 } 3203 3204 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3205 PredefinedExpr::IdentKind IK) { 3206 // Pick the current block, lambda, captured statement or function. 3207 Decl *currentDecl = nullptr; 3208 if (const BlockScopeInfo *BSI = getCurBlock()) 3209 currentDecl = BSI->TheDecl; 3210 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3211 currentDecl = LSI->CallOperator; 3212 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3213 currentDecl = CSI->TheCapturedDecl; 3214 else 3215 currentDecl = getCurFunctionOrMethodDecl(); 3216 3217 if (!currentDecl) { 3218 Diag(Loc, diag::ext_predef_outside_function); 3219 currentDecl = Context.getTranslationUnitDecl(); 3220 } 3221 3222 QualType ResTy; 3223 StringLiteral *SL = nullptr; 3224 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3225 ResTy = Context.DependentTy; 3226 else { 3227 // Pre-defined identifiers are of type char[x], where x is the length of 3228 // the string. 3229 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3230 unsigned Length = Str.length(); 3231 3232 llvm::APInt LengthI(32, Length + 1); 3233 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3234 ResTy = 3235 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3236 SmallString<32> RawChars; 3237 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3238 Str, RawChars); 3239 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3240 ArrayType::Normal, 3241 /*IndexTypeQuals*/ 0); 3242 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3243 /*Pascal*/ false, ResTy, Loc); 3244 } else { 3245 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3246 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3247 ArrayType::Normal, 3248 /*IndexTypeQuals*/ 0); 3249 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3250 /*Pascal*/ false, ResTy, Loc); 3251 } 3252 } 3253 3254 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3255 } 3256 3257 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3258 PredefinedExpr::IdentKind IK; 3259 3260 switch (Kind) { 3261 default: llvm_unreachable("Unknown simple primary expr!"); 3262 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3263 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3264 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3265 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3266 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3267 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3268 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3269 } 3270 3271 return BuildPredefinedExpr(Loc, IK); 3272 } 3273 3274 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3275 SmallString<16> CharBuffer; 3276 bool Invalid = false; 3277 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3278 if (Invalid) 3279 return ExprError(); 3280 3281 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3282 PP, Tok.getKind()); 3283 if (Literal.hadError()) 3284 return ExprError(); 3285 3286 QualType Ty; 3287 if (Literal.isWide()) 3288 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3289 else if (Literal.isUTF8() && getLangOpts().Char8) 3290 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3291 else if (Literal.isUTF16()) 3292 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3293 else if (Literal.isUTF32()) 3294 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3295 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3296 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3297 else 3298 Ty = Context.CharTy; // 'x' -> char in C++ 3299 3300 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3301 if (Literal.isWide()) 3302 Kind = CharacterLiteral::Wide; 3303 else if (Literal.isUTF16()) 3304 Kind = CharacterLiteral::UTF16; 3305 else if (Literal.isUTF32()) 3306 Kind = CharacterLiteral::UTF32; 3307 else if (Literal.isUTF8()) 3308 Kind = CharacterLiteral::UTF8; 3309 3310 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3311 Tok.getLocation()); 3312 3313 if (Literal.getUDSuffix().empty()) 3314 return Lit; 3315 3316 // We're building a user-defined literal. 3317 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3318 SourceLocation UDSuffixLoc = 3319 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3320 3321 // Make sure we're allowed user-defined literals here. 3322 if (!UDLScope) 3323 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3324 3325 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3326 // operator "" X (ch) 3327 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3328 Lit, Tok.getLocation()); 3329 } 3330 3331 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3332 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3333 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3334 Context.IntTy, Loc); 3335 } 3336 3337 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3338 QualType Ty, SourceLocation Loc) { 3339 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3340 3341 using llvm::APFloat; 3342 APFloat Val(Format); 3343 3344 APFloat::opStatus result = Literal.GetFloatValue(Val); 3345 3346 // Overflow is always an error, but underflow is only an error if 3347 // we underflowed to zero (APFloat reports denormals as underflow). 3348 if ((result & APFloat::opOverflow) || 3349 ((result & APFloat::opUnderflow) && Val.isZero())) { 3350 unsigned diagnostic; 3351 SmallString<20> buffer; 3352 if (result & APFloat::opOverflow) { 3353 diagnostic = diag::warn_float_overflow; 3354 APFloat::getLargest(Format).toString(buffer); 3355 } else { 3356 diagnostic = diag::warn_float_underflow; 3357 APFloat::getSmallest(Format).toString(buffer); 3358 } 3359 3360 S.Diag(Loc, diagnostic) 3361 << Ty 3362 << StringRef(buffer.data(), buffer.size()); 3363 } 3364 3365 bool isExact = (result == APFloat::opOK); 3366 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3367 } 3368 3369 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3370 assert(E && "Invalid expression"); 3371 3372 if (E->isValueDependent()) 3373 return false; 3374 3375 QualType QT = E->getType(); 3376 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3377 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3378 return true; 3379 } 3380 3381 llvm::APSInt ValueAPS; 3382 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3383 3384 if (R.isInvalid()) 3385 return true; 3386 3387 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3388 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3389 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3390 << ValueAPS.toString(10) << ValueIsPositive; 3391 return true; 3392 } 3393 3394 return false; 3395 } 3396 3397 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3398 // Fast path for a single digit (which is quite common). A single digit 3399 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3400 if (Tok.getLength() == 1) { 3401 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3402 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3403 } 3404 3405 SmallString<128> SpellingBuffer; 3406 // NumericLiteralParser wants to overread by one character. Add padding to 3407 // the buffer in case the token is copied to the buffer. If getSpelling() 3408 // returns a StringRef to the memory buffer, it should have a null char at 3409 // the EOF, so it is also safe. 3410 SpellingBuffer.resize(Tok.getLength() + 1); 3411 3412 // Get the spelling of the token, which eliminates trigraphs, etc. 3413 bool Invalid = false; 3414 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3415 if (Invalid) 3416 return ExprError(); 3417 3418 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3419 if (Literal.hadError) 3420 return ExprError(); 3421 3422 if (Literal.hasUDSuffix()) { 3423 // We're building a user-defined literal. 3424 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3425 SourceLocation UDSuffixLoc = 3426 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3427 3428 // Make sure we're allowed user-defined literals here. 3429 if (!UDLScope) 3430 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3431 3432 QualType CookedTy; 3433 if (Literal.isFloatingLiteral()) { 3434 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3435 // long double, the literal is treated as a call of the form 3436 // operator "" X (f L) 3437 CookedTy = Context.LongDoubleTy; 3438 } else { 3439 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3440 // unsigned long long, the literal is treated as a call of the form 3441 // operator "" X (n ULL) 3442 CookedTy = Context.UnsignedLongLongTy; 3443 } 3444 3445 DeclarationName OpName = 3446 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3447 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3448 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3449 3450 SourceLocation TokLoc = Tok.getLocation(); 3451 3452 // Perform literal operator lookup to determine if we're building a raw 3453 // literal or a cooked one. 3454 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3455 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3456 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3457 /*AllowStringTemplate*/ false, 3458 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3459 case LOLR_ErrorNoDiagnostic: 3460 // Lookup failure for imaginary constants isn't fatal, there's still the 3461 // GNU extension producing _Complex types. 3462 break; 3463 case LOLR_Error: 3464 return ExprError(); 3465 case LOLR_Cooked: { 3466 Expr *Lit; 3467 if (Literal.isFloatingLiteral()) { 3468 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3469 } else { 3470 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3471 if (Literal.GetIntegerValue(ResultVal)) 3472 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3473 << /* Unsigned */ 1; 3474 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3475 Tok.getLocation()); 3476 } 3477 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3478 } 3479 3480 case LOLR_Raw: { 3481 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3482 // literal is treated as a call of the form 3483 // operator "" X ("n") 3484 unsigned Length = Literal.getUDSuffixOffset(); 3485 QualType StrTy = Context.getConstantArrayType( 3486 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3487 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3488 Expr *Lit = StringLiteral::Create( 3489 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3490 /*Pascal*/false, StrTy, &TokLoc, 1); 3491 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3492 } 3493 3494 case LOLR_Template: { 3495 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3496 // template), L is treated as a call fo the form 3497 // operator "" X <'c1', 'c2', ... 'ck'>() 3498 // where n is the source character sequence c1 c2 ... ck. 3499 TemplateArgumentListInfo ExplicitArgs; 3500 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3501 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3502 llvm::APSInt Value(CharBits, CharIsUnsigned); 3503 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3504 Value = TokSpelling[I]; 3505 TemplateArgument Arg(Context, Value, Context.CharTy); 3506 TemplateArgumentLocInfo ArgInfo; 3507 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3508 } 3509 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3510 &ExplicitArgs); 3511 } 3512 case LOLR_StringTemplate: 3513 llvm_unreachable("unexpected literal operator lookup result"); 3514 } 3515 } 3516 3517 Expr *Res; 3518 3519 if (Literal.isFixedPointLiteral()) { 3520 QualType Ty; 3521 3522 if (Literal.isAccum) { 3523 if (Literal.isHalf) { 3524 Ty = Context.ShortAccumTy; 3525 } else if (Literal.isLong) { 3526 Ty = Context.LongAccumTy; 3527 } else { 3528 Ty = Context.AccumTy; 3529 } 3530 } else if (Literal.isFract) { 3531 if (Literal.isHalf) { 3532 Ty = Context.ShortFractTy; 3533 } else if (Literal.isLong) { 3534 Ty = Context.LongFractTy; 3535 } else { 3536 Ty = Context.FractTy; 3537 } 3538 } 3539 3540 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3541 3542 bool isSigned = !Literal.isUnsigned; 3543 unsigned scale = Context.getFixedPointScale(Ty); 3544 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3545 3546 llvm::APInt Val(bit_width, 0, isSigned); 3547 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3548 bool ValIsZero = Val.isNullValue() && !Overflowed; 3549 3550 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3551 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3552 // Clause 6.4.4 - The value of a constant shall be in the range of 3553 // representable values for its type, with exception for constants of a 3554 // fract type with a value of exactly 1; such a constant shall denote 3555 // the maximal value for the type. 3556 --Val; 3557 else if (Val.ugt(MaxVal) || Overflowed) 3558 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3559 3560 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3561 Tok.getLocation(), scale); 3562 } else if (Literal.isFloatingLiteral()) { 3563 QualType Ty; 3564 if (Literal.isHalf){ 3565 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3566 Ty = Context.HalfTy; 3567 else { 3568 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3569 return ExprError(); 3570 } 3571 } else if (Literal.isFloat) 3572 Ty = Context.FloatTy; 3573 else if (Literal.isLong) 3574 Ty = Context.LongDoubleTy; 3575 else if (Literal.isFloat16) 3576 Ty = Context.Float16Ty; 3577 else if (Literal.isFloat128) 3578 Ty = Context.Float128Ty; 3579 else 3580 Ty = Context.DoubleTy; 3581 3582 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3583 3584 if (Ty == Context.DoubleTy) { 3585 if (getLangOpts().SinglePrecisionConstants) { 3586 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3587 if (BTy->getKind() != BuiltinType::Float) { 3588 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3589 } 3590 } else if (getLangOpts().OpenCL && 3591 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3592 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3593 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3594 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3595 } 3596 } 3597 } else if (!Literal.isIntegerLiteral()) { 3598 return ExprError(); 3599 } else { 3600 QualType Ty; 3601 3602 // 'long long' is a C99 or C++11 feature. 3603 if (!getLangOpts().C99 && Literal.isLongLong) { 3604 if (getLangOpts().CPlusPlus) 3605 Diag(Tok.getLocation(), 3606 getLangOpts().CPlusPlus11 ? 3607 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3608 else 3609 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3610 } 3611 3612 // Get the value in the widest-possible width. 3613 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3614 llvm::APInt ResultVal(MaxWidth, 0); 3615 3616 if (Literal.GetIntegerValue(ResultVal)) { 3617 // If this value didn't fit into uintmax_t, error and force to ull. 3618 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3619 << /* Unsigned */ 1; 3620 Ty = Context.UnsignedLongLongTy; 3621 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3622 "long long is not intmax_t?"); 3623 } else { 3624 // If this value fits into a ULL, try to figure out what else it fits into 3625 // according to the rules of C99 6.4.4.1p5. 3626 3627 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3628 // be an unsigned int. 3629 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3630 3631 // Check from smallest to largest, picking the smallest type we can. 3632 unsigned Width = 0; 3633 3634 // Microsoft specific integer suffixes are explicitly sized. 3635 if (Literal.MicrosoftInteger) { 3636 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3637 Width = 8; 3638 Ty = Context.CharTy; 3639 } else { 3640 Width = Literal.MicrosoftInteger; 3641 Ty = Context.getIntTypeForBitwidth(Width, 3642 /*Signed=*/!Literal.isUnsigned); 3643 } 3644 } 3645 3646 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3647 // Are int/unsigned possibilities? 3648 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3649 3650 // Does it fit in a unsigned int? 3651 if (ResultVal.isIntN(IntSize)) { 3652 // Does it fit in a signed int? 3653 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3654 Ty = Context.IntTy; 3655 else if (AllowUnsigned) 3656 Ty = Context.UnsignedIntTy; 3657 Width = IntSize; 3658 } 3659 } 3660 3661 // Are long/unsigned long possibilities? 3662 if (Ty.isNull() && !Literal.isLongLong) { 3663 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3664 3665 // Does it fit in a unsigned long? 3666 if (ResultVal.isIntN(LongSize)) { 3667 // Does it fit in a signed long? 3668 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3669 Ty = Context.LongTy; 3670 else if (AllowUnsigned) 3671 Ty = Context.UnsignedLongTy; 3672 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3673 // is compatible. 3674 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3675 const unsigned LongLongSize = 3676 Context.getTargetInfo().getLongLongWidth(); 3677 Diag(Tok.getLocation(), 3678 getLangOpts().CPlusPlus 3679 ? Literal.isLong 3680 ? diag::warn_old_implicitly_unsigned_long_cxx 3681 : /*C++98 UB*/ diag:: 3682 ext_old_implicitly_unsigned_long_cxx 3683 : diag::warn_old_implicitly_unsigned_long) 3684 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3685 : /*will be ill-formed*/ 1); 3686 Ty = Context.UnsignedLongTy; 3687 } 3688 Width = LongSize; 3689 } 3690 } 3691 3692 // Check long long if needed. 3693 if (Ty.isNull()) { 3694 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3695 3696 // Does it fit in a unsigned long long? 3697 if (ResultVal.isIntN(LongLongSize)) { 3698 // Does it fit in a signed long long? 3699 // To be compatible with MSVC, hex integer literals ending with the 3700 // LL or i64 suffix are always signed in Microsoft mode. 3701 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3702 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3703 Ty = Context.LongLongTy; 3704 else if (AllowUnsigned) 3705 Ty = Context.UnsignedLongLongTy; 3706 Width = LongLongSize; 3707 } 3708 } 3709 3710 // If we still couldn't decide a type, we probably have something that 3711 // does not fit in a signed long long, but has no U suffix. 3712 if (Ty.isNull()) { 3713 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3714 Ty = Context.UnsignedLongLongTy; 3715 Width = Context.getTargetInfo().getLongLongWidth(); 3716 } 3717 3718 if (ResultVal.getBitWidth() != Width) 3719 ResultVal = ResultVal.trunc(Width); 3720 } 3721 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3722 } 3723 3724 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3725 if (Literal.isImaginary) { 3726 Res = new (Context) ImaginaryLiteral(Res, 3727 Context.getComplexType(Res->getType())); 3728 3729 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3730 } 3731 return Res; 3732 } 3733 3734 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3735 assert(E && "ActOnParenExpr() missing expr"); 3736 return new (Context) ParenExpr(L, R, E); 3737 } 3738 3739 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3740 SourceLocation Loc, 3741 SourceRange ArgRange) { 3742 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3743 // scalar or vector data type argument..." 3744 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3745 // type (C99 6.2.5p18) or void. 3746 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3747 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3748 << T << ArgRange; 3749 return true; 3750 } 3751 3752 assert((T->isVoidType() || !T->isIncompleteType()) && 3753 "Scalar types should always be complete"); 3754 return false; 3755 } 3756 3757 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3758 SourceLocation Loc, 3759 SourceRange ArgRange, 3760 UnaryExprOrTypeTrait TraitKind) { 3761 // Invalid types must be hard errors for SFINAE in C++. 3762 if (S.LangOpts.CPlusPlus) 3763 return true; 3764 3765 // C99 6.5.3.4p1: 3766 if (T->isFunctionType() && 3767 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3768 TraitKind == UETT_PreferredAlignOf)) { 3769 // sizeof(function)/alignof(function) is allowed as an extension. 3770 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3771 << TraitKind << ArgRange; 3772 return false; 3773 } 3774 3775 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3776 // this is an error (OpenCL v1.1 s6.3.k) 3777 if (T->isVoidType()) { 3778 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3779 : diag::ext_sizeof_alignof_void_type; 3780 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3781 return false; 3782 } 3783 3784 return true; 3785 } 3786 3787 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3788 SourceLocation Loc, 3789 SourceRange ArgRange, 3790 UnaryExprOrTypeTrait TraitKind) { 3791 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3792 // runtime doesn't allow it. 3793 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3794 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3795 << T << (TraitKind == UETT_SizeOf) 3796 << ArgRange; 3797 return true; 3798 } 3799 3800 return false; 3801 } 3802 3803 /// Check whether E is a pointer from a decayed array type (the decayed 3804 /// pointer type is equal to T) and emit a warning if it is. 3805 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3806 Expr *E) { 3807 // Don't warn if the operation changed the type. 3808 if (T != E->getType()) 3809 return; 3810 3811 // Now look for array decays. 3812 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3813 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3814 return; 3815 3816 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3817 << ICE->getType() 3818 << ICE->getSubExpr()->getType(); 3819 } 3820 3821 /// Check the constraints on expression operands to unary type expression 3822 /// and type traits. 3823 /// 3824 /// Completes any types necessary and validates the constraints on the operand 3825 /// expression. The logic mostly mirrors the type-based overload, but may modify 3826 /// the expression as it completes the type for that expression through template 3827 /// instantiation, etc. 3828 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3829 UnaryExprOrTypeTrait ExprKind) { 3830 QualType ExprTy = E->getType(); 3831 assert(!ExprTy->isReferenceType()); 3832 3833 bool IsUnevaluatedOperand = 3834 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3835 ExprKind == UETT_PreferredAlignOf); 3836 if (IsUnevaluatedOperand) { 3837 ExprResult Result = CheckUnevaluatedOperand(E); 3838 if (Result.isInvalid()) 3839 return true; 3840 E = Result.get(); 3841 } 3842 3843 if (ExprKind == UETT_VecStep) 3844 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3845 E->getSourceRange()); 3846 3847 // Whitelist some types as extensions 3848 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3849 E->getSourceRange(), ExprKind)) 3850 return false; 3851 3852 // 'alignof' applied to an expression only requires the base element type of 3853 // the expression to be complete. 'sizeof' requires the expression's type to 3854 // be complete (and will attempt to complete it if it's an array of unknown 3855 // bound). 3856 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3857 if (RequireCompleteType(E->getExprLoc(), 3858 Context.getBaseElementType(E->getType()), 3859 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3860 E->getSourceRange())) 3861 return true; 3862 } else { 3863 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3864 ExprKind, E->getSourceRange())) 3865 return true; 3866 } 3867 3868 // Completing the expression's type may have changed it. 3869 ExprTy = E->getType(); 3870 assert(!ExprTy->isReferenceType()); 3871 3872 if (ExprTy->isFunctionType()) { 3873 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3874 << ExprKind << E->getSourceRange(); 3875 return true; 3876 } 3877 3878 // The operand for sizeof and alignof is in an unevaluated expression context, 3879 // so side effects could result in unintended consequences. 3880 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3881 E->HasSideEffects(Context, false)) 3882 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3883 3884 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3885 E->getSourceRange(), ExprKind)) 3886 return true; 3887 3888 if (ExprKind == UETT_SizeOf) { 3889 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3890 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3891 QualType OType = PVD->getOriginalType(); 3892 QualType Type = PVD->getType(); 3893 if (Type->isPointerType() && OType->isArrayType()) { 3894 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3895 << Type << OType; 3896 Diag(PVD->getLocation(), diag::note_declared_at); 3897 } 3898 } 3899 } 3900 3901 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3902 // decays into a pointer and returns an unintended result. This is most 3903 // likely a typo for "sizeof(array) op x". 3904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3905 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3906 BO->getLHS()); 3907 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3908 BO->getRHS()); 3909 } 3910 } 3911 3912 return false; 3913 } 3914 3915 /// Check the constraints on operands to unary expression and type 3916 /// traits. 3917 /// 3918 /// This will complete any types necessary, and validate the various constraints 3919 /// on those operands. 3920 /// 3921 /// The UsualUnaryConversions() function is *not* called by this routine. 3922 /// C99 6.3.2.1p[2-4] all state: 3923 /// Except when it is the operand of the sizeof operator ... 3924 /// 3925 /// C++ [expr.sizeof]p4 3926 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3927 /// standard conversions are not applied to the operand of sizeof. 3928 /// 3929 /// This policy is followed for all of the unary trait expressions. 3930 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3931 SourceLocation OpLoc, 3932 SourceRange ExprRange, 3933 UnaryExprOrTypeTrait ExprKind) { 3934 if (ExprType->isDependentType()) 3935 return false; 3936 3937 // C++ [expr.sizeof]p2: 3938 // When applied to a reference or a reference type, the result 3939 // is the size of the referenced type. 3940 // C++11 [expr.alignof]p3: 3941 // When alignof is applied to a reference type, the result 3942 // shall be the alignment of the referenced type. 3943 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3944 ExprType = Ref->getPointeeType(); 3945 3946 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3947 // When alignof or _Alignof is applied to an array type, the result 3948 // is the alignment of the element type. 3949 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3950 ExprKind == UETT_OpenMPRequiredSimdAlign) 3951 ExprType = Context.getBaseElementType(ExprType); 3952 3953 if (ExprKind == UETT_VecStep) 3954 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3955 3956 // Whitelist some types as extensions 3957 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3958 ExprKind)) 3959 return false; 3960 3961 if (RequireCompleteType(OpLoc, ExprType, 3962 diag::err_sizeof_alignof_incomplete_type, 3963 ExprKind, ExprRange)) 3964 return true; 3965 3966 if (ExprType->isFunctionType()) { 3967 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3968 << ExprKind << ExprRange; 3969 return true; 3970 } 3971 3972 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3973 ExprKind)) 3974 return true; 3975 3976 return false; 3977 } 3978 3979 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3980 // Cannot know anything else if the expression is dependent. 3981 if (E->isTypeDependent()) 3982 return false; 3983 3984 if (E->getObjectKind() == OK_BitField) { 3985 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3986 << 1 << E->getSourceRange(); 3987 return true; 3988 } 3989 3990 ValueDecl *D = nullptr; 3991 Expr *Inner = E->IgnoreParens(); 3992 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 3993 D = DRE->getDecl(); 3994 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 3995 D = ME->getMemberDecl(); 3996 } 3997 3998 // If it's a field, require the containing struct to have a 3999 // complete definition so that we can compute the layout. 4000 // 4001 // This can happen in C++11 onwards, either by naming the member 4002 // in a way that is not transformed into a member access expression 4003 // (in an unevaluated operand, for instance), or by naming the member 4004 // in a trailing-return-type. 4005 // 4006 // For the record, since __alignof__ on expressions is a GCC 4007 // extension, GCC seems to permit this but always gives the 4008 // nonsensical answer 0. 4009 // 4010 // We don't really need the layout here --- we could instead just 4011 // directly check for all the appropriate alignment-lowing 4012 // attributes --- but that would require duplicating a lot of 4013 // logic that just isn't worth duplicating for such a marginal 4014 // use-case. 4015 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4016 // Fast path this check, since we at least know the record has a 4017 // definition if we can find a member of it. 4018 if (!FD->getParent()->isCompleteDefinition()) { 4019 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4020 << E->getSourceRange(); 4021 return true; 4022 } 4023 4024 // Otherwise, if it's a field, and the field doesn't have 4025 // reference type, then it must have a complete type (or be a 4026 // flexible array member, which we explicitly want to 4027 // white-list anyway), which makes the following checks trivial. 4028 if (!FD->getType()->isReferenceType()) 4029 return false; 4030 } 4031 4032 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4033 } 4034 4035 bool Sema::CheckVecStepExpr(Expr *E) { 4036 E = E->IgnoreParens(); 4037 4038 // Cannot know anything else if the expression is dependent. 4039 if (E->isTypeDependent()) 4040 return false; 4041 4042 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4043 } 4044 4045 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4046 CapturingScopeInfo *CSI) { 4047 assert(T->isVariablyModifiedType()); 4048 assert(CSI != nullptr); 4049 4050 // We're going to walk down into the type and look for VLA expressions. 4051 do { 4052 const Type *Ty = T.getTypePtr(); 4053 switch (Ty->getTypeClass()) { 4054 #define TYPE(Class, Base) 4055 #define ABSTRACT_TYPE(Class, Base) 4056 #define NON_CANONICAL_TYPE(Class, Base) 4057 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4058 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4059 #include "clang/AST/TypeNodes.inc" 4060 T = QualType(); 4061 break; 4062 // These types are never variably-modified. 4063 case Type::Builtin: 4064 case Type::Complex: 4065 case Type::Vector: 4066 case Type::ExtVector: 4067 case Type::Record: 4068 case Type::Enum: 4069 case Type::Elaborated: 4070 case Type::TemplateSpecialization: 4071 case Type::ObjCObject: 4072 case Type::ObjCInterface: 4073 case Type::ObjCObjectPointer: 4074 case Type::ObjCTypeParam: 4075 case Type::Pipe: 4076 llvm_unreachable("type class is never variably-modified!"); 4077 case Type::Adjusted: 4078 T = cast<AdjustedType>(Ty)->getOriginalType(); 4079 break; 4080 case Type::Decayed: 4081 T = cast<DecayedType>(Ty)->getPointeeType(); 4082 break; 4083 case Type::Pointer: 4084 T = cast<PointerType>(Ty)->getPointeeType(); 4085 break; 4086 case Type::BlockPointer: 4087 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4088 break; 4089 case Type::LValueReference: 4090 case Type::RValueReference: 4091 T = cast<ReferenceType>(Ty)->getPointeeType(); 4092 break; 4093 case Type::MemberPointer: 4094 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4095 break; 4096 case Type::ConstantArray: 4097 case Type::IncompleteArray: 4098 // Losing element qualification here is fine. 4099 T = cast<ArrayType>(Ty)->getElementType(); 4100 break; 4101 case Type::VariableArray: { 4102 // Losing element qualification here is fine. 4103 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4104 4105 // Unknown size indication requires no size computation. 4106 // Otherwise, evaluate and record it. 4107 auto Size = VAT->getSizeExpr(); 4108 if (Size && !CSI->isVLATypeCaptured(VAT) && 4109 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4110 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4111 4112 T = VAT->getElementType(); 4113 break; 4114 } 4115 case Type::FunctionProto: 4116 case Type::FunctionNoProto: 4117 T = cast<FunctionType>(Ty)->getReturnType(); 4118 break; 4119 case Type::Paren: 4120 case Type::TypeOf: 4121 case Type::UnaryTransform: 4122 case Type::Attributed: 4123 case Type::SubstTemplateTypeParm: 4124 case Type::PackExpansion: 4125 case Type::MacroQualified: 4126 // Keep walking after single level desugaring. 4127 T = T.getSingleStepDesugaredType(Context); 4128 break; 4129 case Type::Typedef: 4130 T = cast<TypedefType>(Ty)->desugar(); 4131 break; 4132 case Type::Decltype: 4133 T = cast<DecltypeType>(Ty)->desugar(); 4134 break; 4135 case Type::Auto: 4136 case Type::DeducedTemplateSpecialization: 4137 T = cast<DeducedType>(Ty)->getDeducedType(); 4138 break; 4139 case Type::TypeOfExpr: 4140 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4141 break; 4142 case Type::Atomic: 4143 T = cast<AtomicType>(Ty)->getValueType(); 4144 break; 4145 } 4146 } while (!T.isNull() && T->isVariablyModifiedType()); 4147 } 4148 4149 /// Build a sizeof or alignof expression given a type operand. 4150 ExprResult 4151 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4152 SourceLocation OpLoc, 4153 UnaryExprOrTypeTrait ExprKind, 4154 SourceRange R) { 4155 if (!TInfo) 4156 return ExprError(); 4157 4158 QualType T = TInfo->getType(); 4159 4160 if (!T->isDependentType() && 4161 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4162 return ExprError(); 4163 4164 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4165 if (auto *TT = T->getAs<TypedefType>()) { 4166 for (auto I = FunctionScopes.rbegin(), 4167 E = std::prev(FunctionScopes.rend()); 4168 I != E; ++I) { 4169 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4170 if (CSI == nullptr) 4171 break; 4172 DeclContext *DC = nullptr; 4173 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4174 DC = LSI->CallOperator; 4175 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4176 DC = CRSI->TheCapturedDecl; 4177 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4178 DC = BSI->TheDecl; 4179 if (DC) { 4180 if (DC->containsDecl(TT->getDecl())) 4181 break; 4182 captureVariablyModifiedType(Context, T, CSI); 4183 } 4184 } 4185 } 4186 } 4187 4188 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4189 return new (Context) UnaryExprOrTypeTraitExpr( 4190 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4191 } 4192 4193 /// Build a sizeof or alignof expression given an expression 4194 /// operand. 4195 ExprResult 4196 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4197 UnaryExprOrTypeTrait ExprKind) { 4198 ExprResult PE = CheckPlaceholderExpr(E); 4199 if (PE.isInvalid()) 4200 return ExprError(); 4201 4202 E = PE.get(); 4203 4204 // Verify that the operand is valid. 4205 bool isInvalid = false; 4206 if (E->isTypeDependent()) { 4207 // Delay type-checking for type-dependent expressions. 4208 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4209 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4210 } else if (ExprKind == UETT_VecStep) { 4211 isInvalid = CheckVecStepExpr(E); 4212 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4213 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4214 isInvalid = true; 4215 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4216 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4217 isInvalid = true; 4218 } else { 4219 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4220 } 4221 4222 if (isInvalid) 4223 return ExprError(); 4224 4225 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4226 PE = TransformToPotentiallyEvaluated(E); 4227 if (PE.isInvalid()) return ExprError(); 4228 E = PE.get(); 4229 } 4230 4231 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4232 return new (Context) UnaryExprOrTypeTraitExpr( 4233 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4234 } 4235 4236 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4237 /// expr and the same for @c alignof and @c __alignof 4238 /// Note that the ArgRange is invalid if isType is false. 4239 ExprResult 4240 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4241 UnaryExprOrTypeTrait ExprKind, bool IsType, 4242 void *TyOrEx, SourceRange ArgRange) { 4243 // If error parsing type, ignore. 4244 if (!TyOrEx) return ExprError(); 4245 4246 if (IsType) { 4247 TypeSourceInfo *TInfo; 4248 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4249 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4250 } 4251 4252 Expr *ArgEx = (Expr *)TyOrEx; 4253 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4254 return Result; 4255 } 4256 4257 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4258 bool IsReal) { 4259 if (V.get()->isTypeDependent()) 4260 return S.Context.DependentTy; 4261 4262 // _Real and _Imag are only l-values for normal l-values. 4263 if (V.get()->getObjectKind() != OK_Ordinary) { 4264 V = S.DefaultLvalueConversion(V.get()); 4265 if (V.isInvalid()) 4266 return QualType(); 4267 } 4268 4269 // These operators return the element type of a complex type. 4270 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4271 return CT->getElementType(); 4272 4273 // Otherwise they pass through real integer and floating point types here. 4274 if (V.get()->getType()->isArithmeticType()) 4275 return V.get()->getType(); 4276 4277 // Test for placeholders. 4278 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4279 if (PR.isInvalid()) return QualType(); 4280 if (PR.get() != V.get()) { 4281 V = PR; 4282 return CheckRealImagOperand(S, V, Loc, IsReal); 4283 } 4284 4285 // Reject anything else. 4286 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4287 << (IsReal ? "__real" : "__imag"); 4288 return QualType(); 4289 } 4290 4291 4292 4293 ExprResult 4294 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4295 tok::TokenKind Kind, Expr *Input) { 4296 UnaryOperatorKind Opc; 4297 switch (Kind) { 4298 default: llvm_unreachable("Unknown unary op!"); 4299 case tok::plusplus: Opc = UO_PostInc; break; 4300 case tok::minusminus: Opc = UO_PostDec; break; 4301 } 4302 4303 // Since this might is a postfix expression, get rid of ParenListExprs. 4304 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4305 if (Result.isInvalid()) return ExprError(); 4306 Input = Result.get(); 4307 4308 return BuildUnaryOp(S, OpLoc, Opc, Input); 4309 } 4310 4311 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4312 /// 4313 /// \return true on error 4314 static bool checkArithmeticOnObjCPointer(Sema &S, 4315 SourceLocation opLoc, 4316 Expr *op) { 4317 assert(op->getType()->isObjCObjectPointerType()); 4318 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4319 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4320 return false; 4321 4322 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4323 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4324 << op->getSourceRange(); 4325 return true; 4326 } 4327 4328 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4329 auto *BaseNoParens = Base->IgnoreParens(); 4330 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4331 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4332 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4333 } 4334 4335 ExprResult 4336 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4337 Expr *idx, SourceLocation rbLoc) { 4338 if (base && !base->getType().isNull() && 4339 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4340 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4341 /*Length=*/nullptr, rbLoc); 4342 4343 // Since this might be a postfix expression, get rid of ParenListExprs. 4344 if (isa<ParenListExpr>(base)) { 4345 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4346 if (result.isInvalid()) return ExprError(); 4347 base = result.get(); 4348 } 4349 4350 // A comma-expression as the index is deprecated in C++2a onwards. 4351 if (getLangOpts().CPlusPlus2a && 4352 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4353 (isa<CXXOperatorCallExpr>(idx) && 4354 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4355 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4356 << SourceRange(base->getBeginLoc(), rbLoc); 4357 } 4358 4359 // Handle any non-overload placeholder types in the base and index 4360 // expressions. We can't handle overloads here because the other 4361 // operand might be an overloadable type, in which case the overload 4362 // resolution for the operator overload should get the first crack 4363 // at the overload. 4364 bool IsMSPropertySubscript = false; 4365 if (base->getType()->isNonOverloadPlaceholderType()) { 4366 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4367 if (!IsMSPropertySubscript) { 4368 ExprResult result = CheckPlaceholderExpr(base); 4369 if (result.isInvalid()) 4370 return ExprError(); 4371 base = result.get(); 4372 } 4373 } 4374 if (idx->getType()->isNonOverloadPlaceholderType()) { 4375 ExprResult result = CheckPlaceholderExpr(idx); 4376 if (result.isInvalid()) return ExprError(); 4377 idx = result.get(); 4378 } 4379 4380 // Build an unanalyzed expression if either operand is type-dependent. 4381 if (getLangOpts().CPlusPlus && 4382 (base->isTypeDependent() || idx->isTypeDependent())) { 4383 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4384 VK_LValue, OK_Ordinary, rbLoc); 4385 } 4386 4387 // MSDN, property (C++) 4388 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4389 // This attribute can also be used in the declaration of an empty array in a 4390 // class or structure definition. For example: 4391 // __declspec(property(get=GetX, put=PutX)) int x[]; 4392 // The above statement indicates that x[] can be used with one or more array 4393 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4394 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4395 if (IsMSPropertySubscript) { 4396 // Build MS property subscript expression if base is MS property reference 4397 // or MS property subscript. 4398 return new (Context) MSPropertySubscriptExpr( 4399 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4400 } 4401 4402 // Use C++ overloaded-operator rules if either operand has record 4403 // type. The spec says to do this if either type is *overloadable*, 4404 // but enum types can't declare subscript operators or conversion 4405 // operators, so there's nothing interesting for overload resolution 4406 // to do if there aren't any record types involved. 4407 // 4408 // ObjC pointers have their own subscripting logic that is not tied 4409 // to overload resolution and so should not take this path. 4410 if (getLangOpts().CPlusPlus && 4411 (base->getType()->isRecordType() || 4412 (!base->getType()->isObjCObjectPointerType() && 4413 idx->getType()->isRecordType()))) { 4414 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4415 } 4416 4417 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4418 4419 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4420 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4421 4422 return Res; 4423 } 4424 4425 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4426 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4427 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4428 4429 // For expressions like `&(*s).b`, the base is recorded and what should be 4430 // checked. 4431 const MemberExpr *Member = nullptr; 4432 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4433 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4434 4435 LastRecord.PossibleDerefs.erase(StrippedExpr); 4436 } 4437 4438 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4439 QualType ResultTy = E->getType(); 4440 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4441 4442 // Bail if the element is an array since it is not memory access. 4443 if (isa<ArrayType>(ResultTy)) 4444 return; 4445 4446 if (ResultTy->hasAttr(attr::NoDeref)) { 4447 LastRecord.PossibleDerefs.insert(E); 4448 return; 4449 } 4450 4451 // Check if the base type is a pointer to a member access of a struct 4452 // marked with noderef. 4453 const Expr *Base = E->getBase(); 4454 QualType BaseTy = Base->getType(); 4455 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4456 // Not a pointer access 4457 return; 4458 4459 const MemberExpr *Member = nullptr; 4460 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4461 Member->isArrow()) 4462 Base = Member->getBase(); 4463 4464 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4465 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4466 LastRecord.PossibleDerefs.insert(E); 4467 } 4468 } 4469 4470 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4471 Expr *LowerBound, 4472 SourceLocation ColonLoc, Expr *Length, 4473 SourceLocation RBLoc) { 4474 if (Base->getType()->isPlaceholderType() && 4475 !Base->getType()->isSpecificPlaceholderType( 4476 BuiltinType::OMPArraySection)) { 4477 ExprResult Result = CheckPlaceholderExpr(Base); 4478 if (Result.isInvalid()) 4479 return ExprError(); 4480 Base = Result.get(); 4481 } 4482 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4483 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4484 if (Result.isInvalid()) 4485 return ExprError(); 4486 Result = DefaultLvalueConversion(Result.get()); 4487 if (Result.isInvalid()) 4488 return ExprError(); 4489 LowerBound = Result.get(); 4490 } 4491 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4492 ExprResult Result = CheckPlaceholderExpr(Length); 4493 if (Result.isInvalid()) 4494 return ExprError(); 4495 Result = DefaultLvalueConversion(Result.get()); 4496 if (Result.isInvalid()) 4497 return ExprError(); 4498 Length = Result.get(); 4499 } 4500 4501 // Build an unanalyzed expression if either operand is type-dependent. 4502 if (Base->isTypeDependent() || 4503 (LowerBound && 4504 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4505 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4506 return new (Context) 4507 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4508 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4509 } 4510 4511 // Perform default conversions. 4512 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4513 QualType ResultTy; 4514 if (OriginalTy->isAnyPointerType()) { 4515 ResultTy = OriginalTy->getPointeeType(); 4516 } else if (OriginalTy->isArrayType()) { 4517 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4518 } else { 4519 return ExprError( 4520 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4521 << Base->getSourceRange()); 4522 } 4523 // C99 6.5.2.1p1 4524 if (LowerBound) { 4525 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4526 LowerBound); 4527 if (Res.isInvalid()) 4528 return ExprError(Diag(LowerBound->getExprLoc(), 4529 diag::err_omp_typecheck_section_not_integer) 4530 << 0 << LowerBound->getSourceRange()); 4531 LowerBound = Res.get(); 4532 4533 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4534 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4535 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4536 << 0 << LowerBound->getSourceRange(); 4537 } 4538 if (Length) { 4539 auto Res = 4540 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4541 if (Res.isInvalid()) 4542 return ExprError(Diag(Length->getExprLoc(), 4543 diag::err_omp_typecheck_section_not_integer) 4544 << 1 << Length->getSourceRange()); 4545 Length = Res.get(); 4546 4547 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4548 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4549 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4550 << 1 << Length->getSourceRange(); 4551 } 4552 4553 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4554 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4555 // type. Note that functions are not objects, and that (in C99 parlance) 4556 // incomplete types are not object types. 4557 if (ResultTy->isFunctionType()) { 4558 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4559 << ResultTy << Base->getSourceRange(); 4560 return ExprError(); 4561 } 4562 4563 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4564 diag::err_omp_section_incomplete_type, Base)) 4565 return ExprError(); 4566 4567 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4568 Expr::EvalResult Result; 4569 if (LowerBound->EvaluateAsInt(Result, Context)) { 4570 // OpenMP 4.5, [2.4 Array Sections] 4571 // The array section must be a subset of the original array. 4572 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4573 if (LowerBoundValue.isNegative()) { 4574 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4575 << LowerBound->getSourceRange(); 4576 return ExprError(); 4577 } 4578 } 4579 } 4580 4581 if (Length) { 4582 Expr::EvalResult Result; 4583 if (Length->EvaluateAsInt(Result, Context)) { 4584 // OpenMP 4.5, [2.4 Array Sections] 4585 // The length must evaluate to non-negative integers. 4586 llvm::APSInt LengthValue = Result.Val.getInt(); 4587 if (LengthValue.isNegative()) { 4588 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4589 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4590 << Length->getSourceRange(); 4591 return ExprError(); 4592 } 4593 } 4594 } else if (ColonLoc.isValid() && 4595 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4596 !OriginalTy->isVariableArrayType()))) { 4597 // OpenMP 4.5, [2.4 Array Sections] 4598 // When the size of the array dimension is not known, the length must be 4599 // specified explicitly. 4600 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4601 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4602 return ExprError(); 4603 } 4604 4605 if (!Base->getType()->isSpecificPlaceholderType( 4606 BuiltinType::OMPArraySection)) { 4607 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4608 if (Result.isInvalid()) 4609 return ExprError(); 4610 Base = Result.get(); 4611 } 4612 return new (Context) 4613 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4614 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4615 } 4616 4617 ExprResult 4618 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4619 Expr *Idx, SourceLocation RLoc) { 4620 Expr *LHSExp = Base; 4621 Expr *RHSExp = Idx; 4622 4623 ExprValueKind VK = VK_LValue; 4624 ExprObjectKind OK = OK_Ordinary; 4625 4626 // Per C++ core issue 1213, the result is an xvalue if either operand is 4627 // a non-lvalue array, and an lvalue otherwise. 4628 if (getLangOpts().CPlusPlus11) { 4629 for (auto *Op : {LHSExp, RHSExp}) { 4630 Op = Op->IgnoreImplicit(); 4631 if (Op->getType()->isArrayType() && !Op->isLValue()) 4632 VK = VK_XValue; 4633 } 4634 } 4635 4636 // Perform default conversions. 4637 if (!LHSExp->getType()->getAs<VectorType>()) { 4638 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4639 if (Result.isInvalid()) 4640 return ExprError(); 4641 LHSExp = Result.get(); 4642 } 4643 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4644 if (Result.isInvalid()) 4645 return ExprError(); 4646 RHSExp = Result.get(); 4647 4648 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4649 4650 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4651 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4652 // in the subscript position. As a result, we need to derive the array base 4653 // and index from the expression types. 4654 Expr *BaseExpr, *IndexExpr; 4655 QualType ResultType; 4656 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4657 BaseExpr = LHSExp; 4658 IndexExpr = RHSExp; 4659 ResultType = Context.DependentTy; 4660 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4661 BaseExpr = LHSExp; 4662 IndexExpr = RHSExp; 4663 ResultType = PTy->getPointeeType(); 4664 } else if (const ObjCObjectPointerType *PTy = 4665 LHSTy->getAs<ObjCObjectPointerType>()) { 4666 BaseExpr = LHSExp; 4667 IndexExpr = RHSExp; 4668 4669 // Use custom logic if this should be the pseudo-object subscript 4670 // expression. 4671 if (!LangOpts.isSubscriptPointerArithmetic()) 4672 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4673 nullptr); 4674 4675 ResultType = PTy->getPointeeType(); 4676 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4677 // Handle the uncommon case of "123[Ptr]". 4678 BaseExpr = RHSExp; 4679 IndexExpr = LHSExp; 4680 ResultType = PTy->getPointeeType(); 4681 } else if (const ObjCObjectPointerType *PTy = 4682 RHSTy->getAs<ObjCObjectPointerType>()) { 4683 // Handle the uncommon case of "123[Ptr]". 4684 BaseExpr = RHSExp; 4685 IndexExpr = LHSExp; 4686 ResultType = PTy->getPointeeType(); 4687 if (!LangOpts.isSubscriptPointerArithmetic()) { 4688 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4689 << ResultType << BaseExpr->getSourceRange(); 4690 return ExprError(); 4691 } 4692 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4693 BaseExpr = LHSExp; // vectors: V[123] 4694 IndexExpr = RHSExp; 4695 // We apply C++ DR1213 to vector subscripting too. 4696 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4697 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4698 if (Materialized.isInvalid()) 4699 return ExprError(); 4700 LHSExp = Materialized.get(); 4701 } 4702 VK = LHSExp->getValueKind(); 4703 if (VK != VK_RValue) 4704 OK = OK_VectorComponent; 4705 4706 ResultType = VTy->getElementType(); 4707 QualType BaseType = BaseExpr->getType(); 4708 Qualifiers BaseQuals = BaseType.getQualifiers(); 4709 Qualifiers MemberQuals = ResultType.getQualifiers(); 4710 Qualifiers Combined = BaseQuals + MemberQuals; 4711 if (Combined != MemberQuals) 4712 ResultType = Context.getQualifiedType(ResultType, Combined); 4713 } else if (LHSTy->isArrayType()) { 4714 // If we see an array that wasn't promoted by 4715 // DefaultFunctionArrayLvalueConversion, it must be an array that 4716 // wasn't promoted because of the C90 rule that doesn't 4717 // allow promoting non-lvalue arrays. Warn, then 4718 // force the promotion here. 4719 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4720 << LHSExp->getSourceRange(); 4721 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4722 CK_ArrayToPointerDecay).get(); 4723 LHSTy = LHSExp->getType(); 4724 4725 BaseExpr = LHSExp; 4726 IndexExpr = RHSExp; 4727 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4728 } else if (RHSTy->isArrayType()) { 4729 // Same as previous, except for 123[f().a] case 4730 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4731 << RHSExp->getSourceRange(); 4732 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4733 CK_ArrayToPointerDecay).get(); 4734 RHSTy = RHSExp->getType(); 4735 4736 BaseExpr = RHSExp; 4737 IndexExpr = LHSExp; 4738 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4739 } else { 4740 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4741 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4742 } 4743 // C99 6.5.2.1p1 4744 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4745 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4746 << IndexExpr->getSourceRange()); 4747 4748 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4749 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4750 && !IndexExpr->isTypeDependent()) 4751 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4752 4753 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4754 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4755 // type. Note that Functions are not objects, and that (in C99 parlance) 4756 // incomplete types are not object types. 4757 if (ResultType->isFunctionType()) { 4758 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4759 << ResultType << BaseExpr->getSourceRange(); 4760 return ExprError(); 4761 } 4762 4763 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4764 // GNU extension: subscripting on pointer to void 4765 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4766 << BaseExpr->getSourceRange(); 4767 4768 // C forbids expressions of unqualified void type from being l-values. 4769 // See IsCForbiddenLValueType. 4770 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4771 } else if (!ResultType->isDependentType() && 4772 RequireCompleteType(LLoc, ResultType, 4773 diag::err_subscript_incomplete_type, BaseExpr)) 4774 return ExprError(); 4775 4776 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4777 !ResultType.isCForbiddenLValueType()); 4778 4779 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4780 FunctionScopes.size() > 1) { 4781 if (auto *TT = 4782 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4783 for (auto I = FunctionScopes.rbegin(), 4784 E = std::prev(FunctionScopes.rend()); 4785 I != E; ++I) { 4786 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4787 if (CSI == nullptr) 4788 break; 4789 DeclContext *DC = nullptr; 4790 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4791 DC = LSI->CallOperator; 4792 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4793 DC = CRSI->TheCapturedDecl; 4794 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4795 DC = BSI->TheDecl; 4796 if (DC) { 4797 if (DC->containsDecl(TT->getDecl())) 4798 break; 4799 captureVariablyModifiedType( 4800 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4801 } 4802 } 4803 } 4804 } 4805 4806 return new (Context) 4807 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4808 } 4809 4810 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4811 ParmVarDecl *Param) { 4812 if (Param->hasUnparsedDefaultArg()) { 4813 Diag(CallLoc, 4814 diag::err_use_of_default_argument_to_function_declared_later) << 4815 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4816 Diag(UnparsedDefaultArgLocs[Param], 4817 diag::note_default_argument_declared_here); 4818 return true; 4819 } 4820 4821 if (Param->hasUninstantiatedDefaultArg()) { 4822 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4823 4824 EnterExpressionEvaluationContext EvalContext( 4825 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4826 4827 // Instantiate the expression. 4828 // 4829 // FIXME: Pass in a correct Pattern argument, otherwise 4830 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4831 // 4832 // template<typename T> 4833 // struct A { 4834 // static int FooImpl(); 4835 // 4836 // template<typename Tp> 4837 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4838 // // template argument list [[T], [Tp]], should be [[Tp]]. 4839 // friend A<Tp> Foo(int a); 4840 // }; 4841 // 4842 // template<typename T> 4843 // A<T> Foo(int a = A<T>::FooImpl()); 4844 MultiLevelTemplateArgumentList MutiLevelArgList 4845 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4846 4847 InstantiatingTemplate Inst(*this, CallLoc, Param, 4848 MutiLevelArgList.getInnermost()); 4849 if (Inst.isInvalid()) 4850 return true; 4851 if (Inst.isAlreadyInstantiating()) { 4852 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4853 Param->setInvalidDecl(); 4854 return true; 4855 } 4856 4857 ExprResult Result; 4858 { 4859 // C++ [dcl.fct.default]p5: 4860 // The names in the [default argument] expression are bound, and 4861 // the semantic constraints are checked, at the point where the 4862 // default argument expression appears. 4863 ContextRAII SavedContext(*this, FD); 4864 LocalInstantiationScope Local(*this); 4865 runWithSufficientStackSpace(CallLoc, [&] { 4866 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4867 /*DirectInit*/false); 4868 }); 4869 } 4870 if (Result.isInvalid()) 4871 return true; 4872 4873 // Check the expression as an initializer for the parameter. 4874 InitializedEntity Entity 4875 = InitializedEntity::InitializeParameter(Context, Param); 4876 InitializationKind Kind = InitializationKind::CreateCopy( 4877 Param->getLocation(), 4878 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4879 Expr *ResultE = Result.getAs<Expr>(); 4880 4881 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4882 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4883 if (Result.isInvalid()) 4884 return true; 4885 4886 Result = 4887 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4888 /*DiscardedValue*/ false); 4889 if (Result.isInvalid()) 4890 return true; 4891 4892 // Remember the instantiated default argument. 4893 Param->setDefaultArg(Result.getAs<Expr>()); 4894 if (ASTMutationListener *L = getASTMutationListener()) { 4895 L->DefaultArgumentInstantiated(Param); 4896 } 4897 } 4898 4899 // If the default argument expression is not set yet, we are building it now. 4900 if (!Param->hasInit()) { 4901 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4902 Param->setInvalidDecl(); 4903 return true; 4904 } 4905 4906 // If the default expression creates temporaries, we need to 4907 // push them to the current stack of expression temporaries so they'll 4908 // be properly destroyed. 4909 // FIXME: We should really be rebuilding the default argument with new 4910 // bound temporaries; see the comment in PR5810. 4911 // We don't need to do that with block decls, though, because 4912 // blocks in default argument expression can never capture anything. 4913 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4914 // Set the "needs cleanups" bit regardless of whether there are 4915 // any explicit objects. 4916 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4917 4918 // Append all the objects to the cleanup list. Right now, this 4919 // should always be a no-op, because blocks in default argument 4920 // expressions should never be able to capture anything. 4921 assert(!Init->getNumObjects() && 4922 "default argument expression has capturing blocks?"); 4923 } 4924 4925 // We already type-checked the argument, so we know it works. 4926 // Just mark all of the declarations in this potentially-evaluated expression 4927 // as being "referenced". 4928 EnterExpressionEvaluationContext EvalContext( 4929 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4930 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4931 /*SkipLocalVariables=*/true); 4932 return false; 4933 } 4934 4935 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4936 FunctionDecl *FD, ParmVarDecl *Param) { 4937 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4938 return ExprError(); 4939 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 4940 } 4941 4942 Sema::VariadicCallType 4943 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4944 Expr *Fn) { 4945 if (Proto && Proto->isVariadic()) { 4946 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4947 return VariadicConstructor; 4948 else if (Fn && Fn->getType()->isBlockPointerType()) 4949 return VariadicBlock; 4950 else if (FDecl) { 4951 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4952 if (Method->isInstance()) 4953 return VariadicMethod; 4954 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4955 return VariadicMethod; 4956 return VariadicFunction; 4957 } 4958 return VariadicDoesNotApply; 4959 } 4960 4961 namespace { 4962 class FunctionCallCCC final : public FunctionCallFilterCCC { 4963 public: 4964 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4965 unsigned NumArgs, MemberExpr *ME) 4966 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4967 FunctionName(FuncName) {} 4968 4969 bool ValidateCandidate(const TypoCorrection &candidate) override { 4970 if (!candidate.getCorrectionSpecifier() || 4971 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4972 return false; 4973 } 4974 4975 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4976 } 4977 4978 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4979 return std::make_unique<FunctionCallCCC>(*this); 4980 } 4981 4982 private: 4983 const IdentifierInfo *const FunctionName; 4984 }; 4985 } 4986 4987 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4988 FunctionDecl *FDecl, 4989 ArrayRef<Expr *> Args) { 4990 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4991 DeclarationName FuncName = FDecl->getDeclName(); 4992 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4993 4994 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4995 if (TypoCorrection Corrected = S.CorrectTypo( 4996 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4997 S.getScopeForContext(S.CurContext), nullptr, CCC, 4998 Sema::CTK_ErrorRecovery)) { 4999 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5000 if (Corrected.isOverloaded()) { 5001 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5002 OverloadCandidateSet::iterator Best; 5003 for (NamedDecl *CD : Corrected) { 5004 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5005 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5006 OCS); 5007 } 5008 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5009 case OR_Success: 5010 ND = Best->FoundDecl; 5011 Corrected.setCorrectionDecl(ND); 5012 break; 5013 default: 5014 break; 5015 } 5016 } 5017 ND = ND->getUnderlyingDecl(); 5018 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5019 return Corrected; 5020 } 5021 } 5022 return TypoCorrection(); 5023 } 5024 5025 /// ConvertArgumentsForCall - Converts the arguments specified in 5026 /// Args/NumArgs to the parameter types of the function FDecl with 5027 /// function prototype Proto. Call is the call expression itself, and 5028 /// Fn is the function expression. For a C++ member function, this 5029 /// routine does not attempt to convert the object argument. Returns 5030 /// true if the call is ill-formed. 5031 bool 5032 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5033 FunctionDecl *FDecl, 5034 const FunctionProtoType *Proto, 5035 ArrayRef<Expr *> Args, 5036 SourceLocation RParenLoc, 5037 bool IsExecConfig) { 5038 // Bail out early if calling a builtin with custom typechecking. 5039 if (FDecl) 5040 if (unsigned ID = FDecl->getBuiltinID()) 5041 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5042 return false; 5043 5044 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5045 // assignment, to the types of the corresponding parameter, ... 5046 unsigned NumParams = Proto->getNumParams(); 5047 bool Invalid = false; 5048 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5049 unsigned FnKind = Fn->getType()->isBlockPointerType() 5050 ? 1 /* block */ 5051 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5052 : 0 /* function */); 5053 5054 // If too few arguments are available (and we don't have default 5055 // arguments for the remaining parameters), don't make the call. 5056 if (Args.size() < NumParams) { 5057 if (Args.size() < MinArgs) { 5058 TypoCorrection TC; 5059 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5060 unsigned diag_id = 5061 MinArgs == NumParams && !Proto->isVariadic() 5062 ? diag::err_typecheck_call_too_few_args_suggest 5063 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5064 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5065 << static_cast<unsigned>(Args.size()) 5066 << TC.getCorrectionRange()); 5067 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5068 Diag(RParenLoc, 5069 MinArgs == NumParams && !Proto->isVariadic() 5070 ? diag::err_typecheck_call_too_few_args_one 5071 : diag::err_typecheck_call_too_few_args_at_least_one) 5072 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5073 else 5074 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5075 ? diag::err_typecheck_call_too_few_args 5076 : diag::err_typecheck_call_too_few_args_at_least) 5077 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5078 << Fn->getSourceRange(); 5079 5080 // Emit the location of the prototype. 5081 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5082 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5083 5084 return true; 5085 } 5086 // We reserve space for the default arguments when we create 5087 // the call expression, before calling ConvertArgumentsForCall. 5088 assert((Call->getNumArgs() == NumParams) && 5089 "We should have reserved space for the default arguments before!"); 5090 } 5091 5092 // If too many are passed and not variadic, error on the extras and drop 5093 // them. 5094 if (Args.size() > NumParams) { 5095 if (!Proto->isVariadic()) { 5096 TypoCorrection TC; 5097 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5098 unsigned diag_id = 5099 MinArgs == NumParams && !Proto->isVariadic() 5100 ? diag::err_typecheck_call_too_many_args_suggest 5101 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5102 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5103 << static_cast<unsigned>(Args.size()) 5104 << TC.getCorrectionRange()); 5105 } else if (NumParams == 1 && FDecl && 5106 FDecl->getParamDecl(0)->getDeclName()) 5107 Diag(Args[NumParams]->getBeginLoc(), 5108 MinArgs == NumParams 5109 ? diag::err_typecheck_call_too_many_args_one 5110 : diag::err_typecheck_call_too_many_args_at_most_one) 5111 << FnKind << FDecl->getParamDecl(0) 5112 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5113 << SourceRange(Args[NumParams]->getBeginLoc(), 5114 Args.back()->getEndLoc()); 5115 else 5116 Diag(Args[NumParams]->getBeginLoc(), 5117 MinArgs == NumParams 5118 ? diag::err_typecheck_call_too_many_args 5119 : diag::err_typecheck_call_too_many_args_at_most) 5120 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5121 << Fn->getSourceRange() 5122 << SourceRange(Args[NumParams]->getBeginLoc(), 5123 Args.back()->getEndLoc()); 5124 5125 // Emit the location of the prototype. 5126 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5127 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5128 5129 // This deletes the extra arguments. 5130 Call->shrinkNumArgs(NumParams); 5131 return true; 5132 } 5133 } 5134 SmallVector<Expr *, 8> AllArgs; 5135 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5136 5137 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5138 AllArgs, CallType); 5139 if (Invalid) 5140 return true; 5141 unsigned TotalNumArgs = AllArgs.size(); 5142 for (unsigned i = 0; i < TotalNumArgs; ++i) 5143 Call->setArg(i, AllArgs[i]); 5144 5145 return false; 5146 } 5147 5148 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5149 const FunctionProtoType *Proto, 5150 unsigned FirstParam, ArrayRef<Expr *> Args, 5151 SmallVectorImpl<Expr *> &AllArgs, 5152 VariadicCallType CallType, bool AllowExplicit, 5153 bool IsListInitialization) { 5154 unsigned NumParams = Proto->getNumParams(); 5155 bool Invalid = false; 5156 size_t ArgIx = 0; 5157 // Continue to check argument types (even if we have too few/many args). 5158 for (unsigned i = FirstParam; i < NumParams; i++) { 5159 QualType ProtoArgType = Proto->getParamType(i); 5160 5161 Expr *Arg; 5162 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5163 if (ArgIx < Args.size()) { 5164 Arg = Args[ArgIx++]; 5165 5166 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5167 diag::err_call_incomplete_argument, Arg)) 5168 return true; 5169 5170 // Strip the unbridged-cast placeholder expression off, if applicable. 5171 bool CFAudited = false; 5172 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5173 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5174 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5175 Arg = stripARCUnbridgedCast(Arg); 5176 else if (getLangOpts().ObjCAutoRefCount && 5177 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5178 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5179 CFAudited = true; 5180 5181 if (Proto->getExtParameterInfo(i).isNoEscape()) 5182 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5183 BE->getBlockDecl()->setDoesNotEscape(); 5184 5185 InitializedEntity Entity = 5186 Param ? InitializedEntity::InitializeParameter(Context, Param, 5187 ProtoArgType) 5188 : InitializedEntity::InitializeParameter( 5189 Context, ProtoArgType, Proto->isParamConsumed(i)); 5190 5191 // Remember that parameter belongs to a CF audited API. 5192 if (CFAudited) 5193 Entity.setParameterCFAudited(); 5194 5195 ExprResult ArgE = PerformCopyInitialization( 5196 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5197 if (ArgE.isInvalid()) 5198 return true; 5199 5200 Arg = ArgE.getAs<Expr>(); 5201 } else { 5202 assert(Param && "can't use default arguments without a known callee"); 5203 5204 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5205 if (ArgExpr.isInvalid()) 5206 return true; 5207 5208 Arg = ArgExpr.getAs<Expr>(); 5209 } 5210 5211 // Check for array bounds violations for each argument to the call. This 5212 // check only triggers warnings when the argument isn't a more complex Expr 5213 // with its own checking, such as a BinaryOperator. 5214 CheckArrayAccess(Arg); 5215 5216 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5217 CheckStaticArrayArgument(CallLoc, Param, Arg); 5218 5219 AllArgs.push_back(Arg); 5220 } 5221 5222 // If this is a variadic call, handle args passed through "...". 5223 if (CallType != VariadicDoesNotApply) { 5224 // Assume that extern "C" functions with variadic arguments that 5225 // return __unknown_anytype aren't *really* variadic. 5226 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5227 FDecl->isExternC()) { 5228 for (Expr *A : Args.slice(ArgIx)) { 5229 QualType paramType; // ignored 5230 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5231 Invalid |= arg.isInvalid(); 5232 AllArgs.push_back(arg.get()); 5233 } 5234 5235 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5236 } else { 5237 for (Expr *A : Args.slice(ArgIx)) { 5238 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5239 Invalid |= Arg.isInvalid(); 5240 AllArgs.push_back(Arg.get()); 5241 } 5242 } 5243 5244 // Check for array bounds violations. 5245 for (Expr *A : Args.slice(ArgIx)) 5246 CheckArrayAccess(A); 5247 } 5248 return Invalid; 5249 } 5250 5251 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5252 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5253 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5254 TL = DTL.getOriginalLoc(); 5255 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5256 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5257 << ATL.getLocalSourceRange(); 5258 } 5259 5260 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5261 /// array parameter, check that it is non-null, and that if it is formed by 5262 /// array-to-pointer decay, the underlying array is sufficiently large. 5263 /// 5264 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5265 /// array type derivation, then for each call to the function, the value of the 5266 /// corresponding actual argument shall provide access to the first element of 5267 /// an array with at least as many elements as specified by the size expression. 5268 void 5269 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5270 ParmVarDecl *Param, 5271 const Expr *ArgExpr) { 5272 // Static array parameters are not supported in C++. 5273 if (!Param || getLangOpts().CPlusPlus) 5274 return; 5275 5276 QualType OrigTy = Param->getOriginalType(); 5277 5278 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5279 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5280 return; 5281 5282 if (ArgExpr->isNullPointerConstant(Context, 5283 Expr::NPC_NeverValueDependent)) { 5284 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5285 DiagnoseCalleeStaticArrayParam(*this, Param); 5286 return; 5287 } 5288 5289 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5290 if (!CAT) 5291 return; 5292 5293 const ConstantArrayType *ArgCAT = 5294 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5295 if (!ArgCAT) 5296 return; 5297 5298 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5299 ArgCAT->getElementType())) { 5300 if (ArgCAT->getSize().ult(CAT->getSize())) { 5301 Diag(CallLoc, diag::warn_static_array_too_small) 5302 << ArgExpr->getSourceRange() 5303 << (unsigned)ArgCAT->getSize().getZExtValue() 5304 << (unsigned)CAT->getSize().getZExtValue() << 0; 5305 DiagnoseCalleeStaticArrayParam(*this, Param); 5306 } 5307 return; 5308 } 5309 5310 Optional<CharUnits> ArgSize = 5311 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5312 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5313 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5314 Diag(CallLoc, diag::warn_static_array_too_small) 5315 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5316 << (unsigned)ParmSize->getQuantity() << 1; 5317 DiagnoseCalleeStaticArrayParam(*this, Param); 5318 } 5319 } 5320 5321 /// Given a function expression of unknown-any type, try to rebuild it 5322 /// to have a function type. 5323 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5324 5325 /// Is the given type a placeholder that we need to lower out 5326 /// immediately during argument processing? 5327 static bool isPlaceholderToRemoveAsArg(QualType type) { 5328 // Placeholders are never sugared. 5329 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5330 if (!placeholder) return false; 5331 5332 switch (placeholder->getKind()) { 5333 // Ignore all the non-placeholder types. 5334 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5335 case BuiltinType::Id: 5336 #include "clang/Basic/OpenCLImageTypes.def" 5337 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5338 case BuiltinType::Id: 5339 #include "clang/Basic/OpenCLExtensionTypes.def" 5340 // In practice we'll never use this, since all SVE types are sugared 5341 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5342 #define SVE_TYPE(Name, Id, SingletonId) \ 5343 case BuiltinType::Id: 5344 #include "clang/Basic/AArch64SVEACLETypes.def" 5345 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5346 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5347 #include "clang/AST/BuiltinTypes.def" 5348 return false; 5349 5350 // We cannot lower out overload sets; they might validly be resolved 5351 // by the call machinery. 5352 case BuiltinType::Overload: 5353 return false; 5354 5355 // Unbridged casts in ARC can be handled in some call positions and 5356 // should be left in place. 5357 case BuiltinType::ARCUnbridgedCast: 5358 return false; 5359 5360 // Pseudo-objects should be converted as soon as possible. 5361 case BuiltinType::PseudoObject: 5362 return true; 5363 5364 // The debugger mode could theoretically but currently does not try 5365 // to resolve unknown-typed arguments based on known parameter types. 5366 case BuiltinType::UnknownAny: 5367 return true; 5368 5369 // These are always invalid as call arguments and should be reported. 5370 case BuiltinType::BoundMember: 5371 case BuiltinType::BuiltinFn: 5372 case BuiltinType::OMPArraySection: 5373 return true; 5374 5375 } 5376 llvm_unreachable("bad builtin type kind"); 5377 } 5378 5379 /// Check an argument list for placeholders that we won't try to 5380 /// handle later. 5381 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5382 // Apply this processing to all the arguments at once instead of 5383 // dying at the first failure. 5384 bool hasInvalid = false; 5385 for (size_t i = 0, e = args.size(); i != e; i++) { 5386 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5387 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5388 if (result.isInvalid()) hasInvalid = true; 5389 else args[i] = result.get(); 5390 } else if (hasInvalid) { 5391 (void)S.CorrectDelayedTyposInExpr(args[i]); 5392 } 5393 } 5394 return hasInvalid; 5395 } 5396 5397 /// If a builtin function has a pointer argument with no explicit address 5398 /// space, then it should be able to accept a pointer to any address 5399 /// space as input. In order to do this, we need to replace the 5400 /// standard builtin declaration with one that uses the same address space 5401 /// as the call. 5402 /// 5403 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5404 /// it does not contain any pointer arguments without 5405 /// an address space qualifer. Otherwise the rewritten 5406 /// FunctionDecl is returned. 5407 /// TODO: Handle pointer return types. 5408 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5409 FunctionDecl *FDecl, 5410 MultiExprArg ArgExprs) { 5411 5412 QualType DeclType = FDecl->getType(); 5413 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5414 5415 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5416 ArgExprs.size() < FT->getNumParams()) 5417 return nullptr; 5418 5419 bool NeedsNewDecl = false; 5420 unsigned i = 0; 5421 SmallVector<QualType, 8> OverloadParams; 5422 5423 for (QualType ParamType : FT->param_types()) { 5424 5425 // Convert array arguments to pointer to simplify type lookup. 5426 ExprResult ArgRes = 5427 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5428 if (ArgRes.isInvalid()) 5429 return nullptr; 5430 Expr *Arg = ArgRes.get(); 5431 QualType ArgType = Arg->getType(); 5432 if (!ParamType->isPointerType() || 5433 ParamType.getQualifiers().hasAddressSpace() || 5434 !ArgType->isPointerType() || 5435 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5436 OverloadParams.push_back(ParamType); 5437 continue; 5438 } 5439 5440 QualType PointeeType = ParamType->getPointeeType(); 5441 if (PointeeType.getQualifiers().hasAddressSpace()) 5442 continue; 5443 5444 NeedsNewDecl = true; 5445 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5446 5447 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5448 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5449 } 5450 5451 if (!NeedsNewDecl) 5452 return nullptr; 5453 5454 FunctionProtoType::ExtProtoInfo EPI; 5455 EPI.Variadic = FT->isVariadic(); 5456 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5457 OverloadParams, EPI); 5458 DeclContext *Parent = FDecl->getParent(); 5459 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5460 FDecl->getLocation(), 5461 FDecl->getLocation(), 5462 FDecl->getIdentifier(), 5463 OverloadTy, 5464 /*TInfo=*/nullptr, 5465 SC_Extern, false, 5466 /*hasPrototype=*/true); 5467 SmallVector<ParmVarDecl*, 16> Params; 5468 FT = cast<FunctionProtoType>(OverloadTy); 5469 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5470 QualType ParamType = FT->getParamType(i); 5471 ParmVarDecl *Parm = 5472 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5473 SourceLocation(), nullptr, ParamType, 5474 /*TInfo=*/nullptr, SC_None, nullptr); 5475 Parm->setScopeInfo(0, i); 5476 Params.push_back(Parm); 5477 } 5478 OverloadDecl->setParams(Params); 5479 return OverloadDecl; 5480 } 5481 5482 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5483 FunctionDecl *Callee, 5484 MultiExprArg ArgExprs) { 5485 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5486 // similar attributes) really don't like it when functions are called with an 5487 // invalid number of args. 5488 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5489 /*PartialOverloading=*/false) && 5490 !Callee->isVariadic()) 5491 return; 5492 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5493 return; 5494 5495 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5496 S.Diag(Fn->getBeginLoc(), 5497 isa<CXXMethodDecl>(Callee) 5498 ? diag::err_ovl_no_viable_member_function_in_call 5499 : diag::err_ovl_no_viable_function_in_call) 5500 << Callee << Callee->getSourceRange(); 5501 S.Diag(Callee->getLocation(), 5502 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5503 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5504 return; 5505 } 5506 } 5507 5508 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5509 const UnresolvedMemberExpr *const UME, Sema &S) { 5510 5511 const auto GetFunctionLevelDCIfCXXClass = 5512 [](Sema &S) -> const CXXRecordDecl * { 5513 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5514 if (!DC || !DC->getParent()) 5515 return nullptr; 5516 5517 // If the call to some member function was made from within a member 5518 // function body 'M' return return 'M's parent. 5519 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5520 return MD->getParent()->getCanonicalDecl(); 5521 // else the call was made from within a default member initializer of a 5522 // class, so return the class. 5523 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5524 return RD->getCanonicalDecl(); 5525 return nullptr; 5526 }; 5527 // If our DeclContext is neither a member function nor a class (in the 5528 // case of a lambda in a default member initializer), we can't have an 5529 // enclosing 'this'. 5530 5531 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5532 if (!CurParentClass) 5533 return false; 5534 5535 // The naming class for implicit member functions call is the class in which 5536 // name lookup starts. 5537 const CXXRecordDecl *const NamingClass = 5538 UME->getNamingClass()->getCanonicalDecl(); 5539 assert(NamingClass && "Must have naming class even for implicit access"); 5540 5541 // If the unresolved member functions were found in a 'naming class' that is 5542 // related (either the same or derived from) to the class that contains the 5543 // member function that itself contained the implicit member access. 5544 5545 return CurParentClass == NamingClass || 5546 CurParentClass->isDerivedFrom(NamingClass); 5547 } 5548 5549 static void 5550 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5551 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5552 5553 if (!UME) 5554 return; 5555 5556 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5557 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5558 // already been captured, or if this is an implicit member function call (if 5559 // it isn't, an attempt to capture 'this' should already have been made). 5560 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5561 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5562 return; 5563 5564 // Check if the naming class in which the unresolved members were found is 5565 // related (same as or is a base of) to the enclosing class. 5566 5567 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5568 return; 5569 5570 5571 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5572 // If the enclosing function is not dependent, then this lambda is 5573 // capture ready, so if we can capture this, do so. 5574 if (!EnclosingFunctionCtx->isDependentContext()) { 5575 // If the current lambda and all enclosing lambdas can capture 'this' - 5576 // then go ahead and capture 'this' (since our unresolved overload set 5577 // contains at least one non-static member function). 5578 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5579 S.CheckCXXThisCapture(CallLoc); 5580 } else if (S.CurContext->isDependentContext()) { 5581 // ... since this is an implicit member reference, that might potentially 5582 // involve a 'this' capture, mark 'this' for potential capture in 5583 // enclosing lambdas. 5584 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5585 CurLSI->addPotentialThisCapture(CallLoc); 5586 } 5587 } 5588 5589 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5590 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5591 Expr *ExecConfig) { 5592 ExprResult Call = 5593 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5594 if (Call.isInvalid()) 5595 return Call; 5596 5597 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5598 // language modes. 5599 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5600 if (ULE->hasExplicitTemplateArgs() && 5601 ULE->decls_begin() == ULE->decls_end()) { 5602 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5603 ? diag::warn_cxx17_compat_adl_only_template_id 5604 : diag::ext_adl_only_template_id) 5605 << ULE->getName(); 5606 } 5607 } 5608 5609 return Call; 5610 } 5611 5612 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5613 /// This provides the location of the left/right parens and a list of comma 5614 /// locations. 5615 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5616 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5617 Expr *ExecConfig, bool IsExecConfig) { 5618 // Since this might be a postfix expression, get rid of ParenListExprs. 5619 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5620 if (Result.isInvalid()) return ExprError(); 5621 Fn = Result.get(); 5622 5623 if (checkArgsForPlaceholders(*this, ArgExprs)) 5624 return ExprError(); 5625 5626 if (getLangOpts().CPlusPlus) { 5627 // If this is a pseudo-destructor expression, build the call immediately. 5628 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5629 if (!ArgExprs.empty()) { 5630 // Pseudo-destructor calls should not have any arguments. 5631 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5632 << FixItHint::CreateRemoval( 5633 SourceRange(ArgExprs.front()->getBeginLoc(), 5634 ArgExprs.back()->getEndLoc())); 5635 } 5636 5637 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5638 VK_RValue, RParenLoc); 5639 } 5640 if (Fn->getType() == Context.PseudoObjectTy) { 5641 ExprResult result = CheckPlaceholderExpr(Fn); 5642 if (result.isInvalid()) return ExprError(); 5643 Fn = result.get(); 5644 } 5645 5646 // Determine whether this is a dependent call inside a C++ template, 5647 // in which case we won't do any semantic analysis now. 5648 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5649 if (ExecConfig) { 5650 return CUDAKernelCallExpr::Create( 5651 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5652 Context.DependentTy, VK_RValue, RParenLoc); 5653 } else { 5654 5655 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5656 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5657 Fn->getBeginLoc()); 5658 5659 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5660 VK_RValue, RParenLoc); 5661 } 5662 } 5663 5664 // Determine whether this is a call to an object (C++ [over.call.object]). 5665 if (Fn->getType()->isRecordType()) 5666 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5667 RParenLoc); 5668 5669 if (Fn->getType() == Context.UnknownAnyTy) { 5670 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5671 if (result.isInvalid()) return ExprError(); 5672 Fn = result.get(); 5673 } 5674 5675 if (Fn->getType() == Context.BoundMemberTy) { 5676 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5677 RParenLoc); 5678 } 5679 } 5680 5681 // Check for overloaded calls. This can happen even in C due to extensions. 5682 if (Fn->getType() == Context.OverloadTy) { 5683 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5684 5685 // We aren't supposed to apply this logic if there's an '&' involved. 5686 if (!find.HasFormOfMemberPointer) { 5687 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5688 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5689 VK_RValue, RParenLoc); 5690 OverloadExpr *ovl = find.Expression; 5691 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5692 return BuildOverloadedCallExpr( 5693 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5694 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5695 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5696 RParenLoc); 5697 } 5698 } 5699 5700 // If we're directly calling a function, get the appropriate declaration. 5701 if (Fn->getType() == Context.UnknownAnyTy) { 5702 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5703 if (result.isInvalid()) return ExprError(); 5704 Fn = result.get(); 5705 } 5706 5707 Expr *NakedFn = Fn->IgnoreParens(); 5708 5709 bool CallingNDeclIndirectly = false; 5710 NamedDecl *NDecl = nullptr; 5711 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5712 if (UnOp->getOpcode() == UO_AddrOf) { 5713 CallingNDeclIndirectly = true; 5714 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5715 } 5716 } 5717 5718 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5719 NDecl = DRE->getDecl(); 5720 5721 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5722 if (FDecl && FDecl->getBuiltinID()) { 5723 // Rewrite the function decl for this builtin by replacing parameters 5724 // with no explicit address space with the address space of the arguments 5725 // in ArgExprs. 5726 if ((FDecl = 5727 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5728 NDecl = FDecl; 5729 Fn = DeclRefExpr::Create( 5730 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5731 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5732 nullptr, DRE->isNonOdrUse()); 5733 } 5734 } 5735 } else if (isa<MemberExpr>(NakedFn)) 5736 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5737 5738 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5739 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5740 FD, /*Complain=*/true, Fn->getBeginLoc())) 5741 return ExprError(); 5742 5743 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5744 return ExprError(); 5745 5746 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5747 } 5748 5749 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5750 ExecConfig, IsExecConfig); 5751 } 5752 5753 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5754 /// 5755 /// __builtin_astype( value, dst type ) 5756 /// 5757 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5758 SourceLocation BuiltinLoc, 5759 SourceLocation RParenLoc) { 5760 ExprValueKind VK = VK_RValue; 5761 ExprObjectKind OK = OK_Ordinary; 5762 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5763 QualType SrcTy = E->getType(); 5764 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5765 return ExprError(Diag(BuiltinLoc, 5766 diag::err_invalid_astype_of_different_size) 5767 << DstTy 5768 << SrcTy 5769 << E->getSourceRange()); 5770 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5771 } 5772 5773 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5774 /// provided arguments. 5775 /// 5776 /// __builtin_convertvector( value, dst type ) 5777 /// 5778 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5779 SourceLocation BuiltinLoc, 5780 SourceLocation RParenLoc) { 5781 TypeSourceInfo *TInfo; 5782 GetTypeFromParser(ParsedDestTy, &TInfo); 5783 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5784 } 5785 5786 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5787 /// i.e. an expression not of \p OverloadTy. The expression should 5788 /// unary-convert to an expression of function-pointer or 5789 /// block-pointer type. 5790 /// 5791 /// \param NDecl the declaration being called, if available 5792 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5793 SourceLocation LParenLoc, 5794 ArrayRef<Expr *> Args, 5795 SourceLocation RParenLoc, Expr *Config, 5796 bool IsExecConfig, ADLCallKind UsesADL) { 5797 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5798 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5799 5800 // Functions with 'interrupt' attribute cannot be called directly. 5801 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5802 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5803 return ExprError(); 5804 } 5805 5806 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5807 // so there's some risk when calling out to non-interrupt handler functions 5808 // that the callee might not preserve them. This is easy to diagnose here, 5809 // but can be very challenging to debug. 5810 if (auto *Caller = getCurFunctionDecl()) 5811 if (Caller->hasAttr<ARMInterruptAttr>()) { 5812 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5813 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5814 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5815 } 5816 5817 // Promote the function operand. 5818 // We special-case function promotion here because we only allow promoting 5819 // builtin functions to function pointers in the callee of a call. 5820 ExprResult Result; 5821 QualType ResultTy; 5822 if (BuiltinID && 5823 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5824 // Extract the return type from the (builtin) function pointer type. 5825 // FIXME Several builtins still have setType in 5826 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5827 // Builtins.def to ensure they are correct before removing setType calls. 5828 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5829 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5830 ResultTy = FDecl->getCallResultType(); 5831 } else { 5832 Result = CallExprUnaryConversions(Fn); 5833 ResultTy = Context.BoolTy; 5834 } 5835 if (Result.isInvalid()) 5836 return ExprError(); 5837 Fn = Result.get(); 5838 5839 // Check for a valid function type, but only if it is not a builtin which 5840 // requires custom type checking. These will be handled by 5841 // CheckBuiltinFunctionCall below just after creation of the call expression. 5842 const FunctionType *FuncT = nullptr; 5843 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5844 retry: 5845 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5846 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5847 // have type pointer to function". 5848 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5849 if (!FuncT) 5850 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5851 << Fn->getType() << Fn->getSourceRange()); 5852 } else if (const BlockPointerType *BPT = 5853 Fn->getType()->getAs<BlockPointerType>()) { 5854 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5855 } else { 5856 // Handle calls to expressions of unknown-any type. 5857 if (Fn->getType() == Context.UnknownAnyTy) { 5858 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5859 if (rewrite.isInvalid()) 5860 return ExprError(); 5861 Fn = rewrite.get(); 5862 goto retry; 5863 } 5864 5865 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5866 << Fn->getType() << Fn->getSourceRange()); 5867 } 5868 } 5869 5870 // Get the number of parameters in the function prototype, if any. 5871 // We will allocate space for max(Args.size(), NumParams) arguments 5872 // in the call expression. 5873 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5874 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5875 5876 CallExpr *TheCall; 5877 if (Config) { 5878 assert(UsesADL == ADLCallKind::NotADL && 5879 "CUDAKernelCallExpr should not use ADL"); 5880 TheCall = 5881 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5882 ResultTy, VK_RValue, RParenLoc, NumParams); 5883 } else { 5884 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5885 RParenLoc, NumParams, UsesADL); 5886 } 5887 5888 if (!getLangOpts().CPlusPlus) { 5889 // Forget about the nulled arguments since typo correction 5890 // do not handle them well. 5891 TheCall->shrinkNumArgs(Args.size()); 5892 // C cannot always handle TypoExpr nodes in builtin calls and direct 5893 // function calls as their argument checking don't necessarily handle 5894 // dependent types properly, so make sure any TypoExprs have been 5895 // dealt with. 5896 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5897 if (!Result.isUsable()) return ExprError(); 5898 CallExpr *TheOldCall = TheCall; 5899 TheCall = dyn_cast<CallExpr>(Result.get()); 5900 bool CorrectedTypos = TheCall != TheOldCall; 5901 if (!TheCall) return Result; 5902 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5903 5904 // A new call expression node was created if some typos were corrected. 5905 // However it may not have been constructed with enough storage. In this 5906 // case, rebuild the node with enough storage. The waste of space is 5907 // immaterial since this only happens when some typos were corrected. 5908 if (CorrectedTypos && Args.size() < NumParams) { 5909 if (Config) 5910 TheCall = CUDAKernelCallExpr::Create( 5911 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5912 RParenLoc, NumParams); 5913 else 5914 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5915 RParenLoc, NumParams, UsesADL); 5916 } 5917 // We can now handle the nulled arguments for the default arguments. 5918 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5919 } 5920 5921 // Bail out early if calling a builtin with custom type checking. 5922 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5923 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5924 5925 if (getLangOpts().CUDA) { 5926 if (Config) { 5927 // CUDA: Kernel calls must be to global functions 5928 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5929 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5930 << FDecl << Fn->getSourceRange()); 5931 5932 // CUDA: Kernel function must have 'void' return type 5933 if (!FuncT->getReturnType()->isVoidType() && 5934 !FuncT->getReturnType()->getAs<AutoType>() && 5935 !FuncT->getReturnType()->isInstantiationDependentType()) 5936 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5937 << Fn->getType() << Fn->getSourceRange()); 5938 } else { 5939 // CUDA: Calls to global functions must be configured 5940 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5941 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5942 << FDecl << Fn->getSourceRange()); 5943 } 5944 } 5945 5946 // Check for a valid return type 5947 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5948 FDecl)) 5949 return ExprError(); 5950 5951 // We know the result type of the call, set it. 5952 TheCall->setType(FuncT->getCallResultType(Context)); 5953 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5954 5955 if (Proto) { 5956 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5957 IsExecConfig)) 5958 return ExprError(); 5959 } else { 5960 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5961 5962 if (FDecl) { 5963 // Check if we have too few/too many template arguments, based 5964 // on our knowledge of the function definition. 5965 const FunctionDecl *Def = nullptr; 5966 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5967 Proto = Def->getType()->getAs<FunctionProtoType>(); 5968 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5969 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5970 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5971 } 5972 5973 // If the function we're calling isn't a function prototype, but we have 5974 // a function prototype from a prior declaratiom, use that prototype. 5975 if (!FDecl->hasPrototype()) 5976 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5977 } 5978 5979 // Promote the arguments (C99 6.5.2.2p6). 5980 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5981 Expr *Arg = Args[i]; 5982 5983 if (Proto && i < Proto->getNumParams()) { 5984 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5985 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5986 ExprResult ArgE = 5987 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5988 if (ArgE.isInvalid()) 5989 return true; 5990 5991 Arg = ArgE.getAs<Expr>(); 5992 5993 } else { 5994 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5995 5996 if (ArgE.isInvalid()) 5997 return true; 5998 5999 Arg = ArgE.getAs<Expr>(); 6000 } 6001 6002 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6003 diag::err_call_incomplete_argument, Arg)) 6004 return ExprError(); 6005 6006 TheCall->setArg(i, Arg); 6007 } 6008 } 6009 6010 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6011 if (!Method->isStatic()) 6012 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6013 << Fn->getSourceRange()); 6014 6015 // Check for sentinels 6016 if (NDecl) 6017 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6018 6019 // Do special checking on direct calls to functions. 6020 if (FDecl) { 6021 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6022 return ExprError(); 6023 6024 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6025 6026 if (BuiltinID) 6027 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6028 } else if (NDecl) { 6029 if (CheckPointerCall(NDecl, TheCall, Proto)) 6030 return ExprError(); 6031 } else { 6032 if (CheckOtherCall(TheCall, Proto)) 6033 return ExprError(); 6034 } 6035 6036 return MaybeBindToTemporary(TheCall); 6037 } 6038 6039 ExprResult 6040 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6041 SourceLocation RParenLoc, Expr *InitExpr) { 6042 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6043 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6044 6045 TypeSourceInfo *TInfo; 6046 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6047 if (!TInfo) 6048 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6049 6050 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6051 } 6052 6053 ExprResult 6054 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6055 SourceLocation RParenLoc, Expr *LiteralExpr) { 6056 QualType literalType = TInfo->getType(); 6057 6058 if (literalType->isArrayType()) { 6059 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6060 diag::err_illegal_decl_array_incomplete_type, 6061 SourceRange(LParenLoc, 6062 LiteralExpr->getSourceRange().getEnd()))) 6063 return ExprError(); 6064 if (literalType->isVariableArrayType()) 6065 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6066 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6067 } else if (!literalType->isDependentType() && 6068 RequireCompleteType(LParenLoc, literalType, 6069 diag::err_typecheck_decl_incomplete_type, 6070 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6071 return ExprError(); 6072 6073 InitializedEntity Entity 6074 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6075 InitializationKind Kind 6076 = InitializationKind::CreateCStyleCast(LParenLoc, 6077 SourceRange(LParenLoc, RParenLoc), 6078 /*InitList=*/true); 6079 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6080 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6081 &literalType); 6082 if (Result.isInvalid()) 6083 return ExprError(); 6084 LiteralExpr = Result.get(); 6085 6086 bool isFileScope = !CurContext->isFunctionOrMethod(); 6087 6088 // In C, compound literals are l-values for some reason. 6089 // For GCC compatibility, in C++, file-scope array compound literals with 6090 // constant initializers are also l-values, and compound literals are 6091 // otherwise prvalues. 6092 // 6093 // (GCC also treats C++ list-initialized file-scope array prvalues with 6094 // constant initializers as l-values, but that's non-conforming, so we don't 6095 // follow it there.) 6096 // 6097 // FIXME: It would be better to handle the lvalue cases as materializing and 6098 // lifetime-extending a temporary object, but our materialized temporaries 6099 // representation only supports lifetime extension from a variable, not "out 6100 // of thin air". 6101 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6102 // is bound to the result of applying array-to-pointer decay to the compound 6103 // literal. 6104 // FIXME: GCC supports compound literals of reference type, which should 6105 // obviously have a value kind derived from the kind of reference involved. 6106 ExprValueKind VK = 6107 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6108 ? VK_RValue 6109 : VK_LValue; 6110 6111 if (isFileScope) 6112 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6113 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6114 Expr *Init = ILE->getInit(i); 6115 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6116 } 6117 6118 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6119 VK, LiteralExpr, isFileScope); 6120 if (isFileScope) { 6121 if (!LiteralExpr->isTypeDependent() && 6122 !LiteralExpr->isValueDependent() && 6123 !literalType->isDependentType()) // C99 6.5.2.5p3 6124 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6125 return ExprError(); 6126 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6127 literalType.getAddressSpace() != LangAS::Default) { 6128 // Embedded-C extensions to C99 6.5.2.5: 6129 // "If the compound literal occurs inside the body of a function, the 6130 // type name shall not be qualified by an address-space qualifier." 6131 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6132 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6133 return ExprError(); 6134 } 6135 6136 // Compound literals that have automatic storage duration are destroyed at 6137 // the end of the scope. Emit diagnostics if it is or contains a C union type 6138 // that is non-trivial to destruct. 6139 if (!isFileScope) 6140 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6141 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6142 NTCUC_CompoundLiteral, NTCUK_Destruct); 6143 6144 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6145 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6146 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6147 E->getInitializer()->getExprLoc()); 6148 6149 return MaybeBindToTemporary(E); 6150 } 6151 6152 ExprResult 6153 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6154 SourceLocation RBraceLoc) { 6155 // Only produce each kind of designated initialization diagnostic once. 6156 SourceLocation FirstDesignator; 6157 bool DiagnosedArrayDesignator = false; 6158 bool DiagnosedNestedDesignator = false; 6159 bool DiagnosedMixedDesignator = false; 6160 6161 // Check that any designated initializers are syntactically valid in the 6162 // current language mode. 6163 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6164 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6165 if (FirstDesignator.isInvalid()) 6166 FirstDesignator = DIE->getBeginLoc(); 6167 6168 if (!getLangOpts().CPlusPlus) 6169 break; 6170 6171 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6172 DiagnosedNestedDesignator = true; 6173 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6174 << DIE->getDesignatorsSourceRange(); 6175 } 6176 6177 for (auto &Desig : DIE->designators()) { 6178 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6179 DiagnosedArrayDesignator = true; 6180 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6181 << Desig.getSourceRange(); 6182 } 6183 } 6184 6185 if (!DiagnosedMixedDesignator && 6186 !isa<DesignatedInitExpr>(InitArgList[0])) { 6187 DiagnosedMixedDesignator = true; 6188 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6189 << DIE->getSourceRange(); 6190 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6191 << InitArgList[0]->getSourceRange(); 6192 } 6193 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6194 isa<DesignatedInitExpr>(InitArgList[0])) { 6195 DiagnosedMixedDesignator = true; 6196 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6197 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6198 << DIE->getSourceRange(); 6199 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6200 << InitArgList[I]->getSourceRange(); 6201 } 6202 } 6203 6204 if (FirstDesignator.isValid()) { 6205 // Only diagnose designated initiaization as a C++20 extension if we didn't 6206 // already diagnose use of (non-C++20) C99 designator syntax. 6207 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6208 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6209 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6210 ? diag::warn_cxx17_compat_designated_init 6211 : diag::ext_cxx_designated_init); 6212 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6213 Diag(FirstDesignator, diag::ext_designated_init); 6214 } 6215 } 6216 6217 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6218 } 6219 6220 ExprResult 6221 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6222 SourceLocation RBraceLoc) { 6223 // Semantic analysis for initializers is done by ActOnDeclarator() and 6224 // CheckInitializer() - it requires knowledge of the object being initialized. 6225 6226 // Immediately handle non-overload placeholders. Overloads can be 6227 // resolved contextually, but everything else here can't. 6228 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6229 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6230 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6231 6232 // Ignore failures; dropping the entire initializer list because 6233 // of one failure would be terrible for indexing/etc. 6234 if (result.isInvalid()) continue; 6235 6236 InitArgList[I] = result.get(); 6237 } 6238 } 6239 6240 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6241 RBraceLoc); 6242 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6243 return E; 6244 } 6245 6246 /// Do an explicit extend of the given block pointer if we're in ARC. 6247 void Sema::maybeExtendBlockObject(ExprResult &E) { 6248 assert(E.get()->getType()->isBlockPointerType()); 6249 assert(E.get()->isRValue()); 6250 6251 // Only do this in an r-value context. 6252 if (!getLangOpts().ObjCAutoRefCount) return; 6253 6254 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6255 CK_ARCExtendBlockObject, E.get(), 6256 /*base path*/ nullptr, VK_RValue); 6257 Cleanup.setExprNeedsCleanups(true); 6258 } 6259 6260 /// Prepare a conversion of the given expression to an ObjC object 6261 /// pointer type. 6262 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6263 QualType type = E.get()->getType(); 6264 if (type->isObjCObjectPointerType()) { 6265 return CK_BitCast; 6266 } else if (type->isBlockPointerType()) { 6267 maybeExtendBlockObject(E); 6268 return CK_BlockPointerToObjCPointerCast; 6269 } else { 6270 assert(type->isPointerType()); 6271 return CK_CPointerToObjCPointerCast; 6272 } 6273 } 6274 6275 /// Prepares for a scalar cast, performing all the necessary stages 6276 /// except the final cast and returning the kind required. 6277 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6278 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6279 // Also, callers should have filtered out the invalid cases with 6280 // pointers. Everything else should be possible. 6281 6282 QualType SrcTy = Src.get()->getType(); 6283 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6284 return CK_NoOp; 6285 6286 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6287 case Type::STK_MemberPointer: 6288 llvm_unreachable("member pointer type in C"); 6289 6290 case Type::STK_CPointer: 6291 case Type::STK_BlockPointer: 6292 case Type::STK_ObjCObjectPointer: 6293 switch (DestTy->getScalarTypeKind()) { 6294 case Type::STK_CPointer: { 6295 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6296 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6297 if (SrcAS != DestAS) 6298 return CK_AddressSpaceConversion; 6299 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6300 return CK_NoOp; 6301 return CK_BitCast; 6302 } 6303 case Type::STK_BlockPointer: 6304 return (SrcKind == Type::STK_BlockPointer 6305 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6306 case Type::STK_ObjCObjectPointer: 6307 if (SrcKind == Type::STK_ObjCObjectPointer) 6308 return CK_BitCast; 6309 if (SrcKind == Type::STK_CPointer) 6310 return CK_CPointerToObjCPointerCast; 6311 maybeExtendBlockObject(Src); 6312 return CK_BlockPointerToObjCPointerCast; 6313 case Type::STK_Bool: 6314 return CK_PointerToBoolean; 6315 case Type::STK_Integral: 6316 return CK_PointerToIntegral; 6317 case Type::STK_Floating: 6318 case Type::STK_FloatingComplex: 6319 case Type::STK_IntegralComplex: 6320 case Type::STK_MemberPointer: 6321 case Type::STK_FixedPoint: 6322 llvm_unreachable("illegal cast from pointer"); 6323 } 6324 llvm_unreachable("Should have returned before this"); 6325 6326 case Type::STK_FixedPoint: 6327 switch (DestTy->getScalarTypeKind()) { 6328 case Type::STK_FixedPoint: 6329 return CK_FixedPointCast; 6330 case Type::STK_Bool: 6331 return CK_FixedPointToBoolean; 6332 case Type::STK_Integral: 6333 return CK_FixedPointToIntegral; 6334 case Type::STK_Floating: 6335 case Type::STK_IntegralComplex: 6336 case Type::STK_FloatingComplex: 6337 Diag(Src.get()->getExprLoc(), 6338 diag::err_unimplemented_conversion_with_fixed_point_type) 6339 << DestTy; 6340 return CK_IntegralCast; 6341 case Type::STK_CPointer: 6342 case Type::STK_ObjCObjectPointer: 6343 case Type::STK_BlockPointer: 6344 case Type::STK_MemberPointer: 6345 llvm_unreachable("illegal cast to pointer type"); 6346 } 6347 llvm_unreachable("Should have returned before this"); 6348 6349 case Type::STK_Bool: // casting from bool is like casting from an integer 6350 case Type::STK_Integral: 6351 switch (DestTy->getScalarTypeKind()) { 6352 case Type::STK_CPointer: 6353 case Type::STK_ObjCObjectPointer: 6354 case Type::STK_BlockPointer: 6355 if (Src.get()->isNullPointerConstant(Context, 6356 Expr::NPC_ValueDependentIsNull)) 6357 return CK_NullToPointer; 6358 return CK_IntegralToPointer; 6359 case Type::STK_Bool: 6360 return CK_IntegralToBoolean; 6361 case Type::STK_Integral: 6362 return CK_IntegralCast; 6363 case Type::STK_Floating: 6364 return CK_IntegralToFloating; 6365 case Type::STK_IntegralComplex: 6366 Src = ImpCastExprToType(Src.get(), 6367 DestTy->castAs<ComplexType>()->getElementType(), 6368 CK_IntegralCast); 6369 return CK_IntegralRealToComplex; 6370 case Type::STK_FloatingComplex: 6371 Src = ImpCastExprToType(Src.get(), 6372 DestTy->castAs<ComplexType>()->getElementType(), 6373 CK_IntegralToFloating); 6374 return CK_FloatingRealToComplex; 6375 case Type::STK_MemberPointer: 6376 llvm_unreachable("member pointer type in C"); 6377 case Type::STK_FixedPoint: 6378 return CK_IntegralToFixedPoint; 6379 } 6380 llvm_unreachable("Should have returned before this"); 6381 6382 case Type::STK_Floating: 6383 switch (DestTy->getScalarTypeKind()) { 6384 case Type::STK_Floating: 6385 return CK_FloatingCast; 6386 case Type::STK_Bool: 6387 return CK_FloatingToBoolean; 6388 case Type::STK_Integral: 6389 return CK_FloatingToIntegral; 6390 case Type::STK_FloatingComplex: 6391 Src = ImpCastExprToType(Src.get(), 6392 DestTy->castAs<ComplexType>()->getElementType(), 6393 CK_FloatingCast); 6394 return CK_FloatingRealToComplex; 6395 case Type::STK_IntegralComplex: 6396 Src = ImpCastExprToType(Src.get(), 6397 DestTy->castAs<ComplexType>()->getElementType(), 6398 CK_FloatingToIntegral); 6399 return CK_IntegralRealToComplex; 6400 case Type::STK_CPointer: 6401 case Type::STK_ObjCObjectPointer: 6402 case Type::STK_BlockPointer: 6403 llvm_unreachable("valid float->pointer cast?"); 6404 case Type::STK_MemberPointer: 6405 llvm_unreachable("member pointer type in C"); 6406 case Type::STK_FixedPoint: 6407 Diag(Src.get()->getExprLoc(), 6408 diag::err_unimplemented_conversion_with_fixed_point_type) 6409 << SrcTy; 6410 return CK_IntegralCast; 6411 } 6412 llvm_unreachable("Should have returned before this"); 6413 6414 case Type::STK_FloatingComplex: 6415 switch (DestTy->getScalarTypeKind()) { 6416 case Type::STK_FloatingComplex: 6417 return CK_FloatingComplexCast; 6418 case Type::STK_IntegralComplex: 6419 return CK_FloatingComplexToIntegralComplex; 6420 case Type::STK_Floating: { 6421 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6422 if (Context.hasSameType(ET, DestTy)) 6423 return CK_FloatingComplexToReal; 6424 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6425 return CK_FloatingCast; 6426 } 6427 case Type::STK_Bool: 6428 return CK_FloatingComplexToBoolean; 6429 case Type::STK_Integral: 6430 Src = ImpCastExprToType(Src.get(), 6431 SrcTy->castAs<ComplexType>()->getElementType(), 6432 CK_FloatingComplexToReal); 6433 return CK_FloatingToIntegral; 6434 case Type::STK_CPointer: 6435 case Type::STK_ObjCObjectPointer: 6436 case Type::STK_BlockPointer: 6437 llvm_unreachable("valid complex float->pointer cast?"); 6438 case Type::STK_MemberPointer: 6439 llvm_unreachable("member pointer type in C"); 6440 case Type::STK_FixedPoint: 6441 Diag(Src.get()->getExprLoc(), 6442 diag::err_unimplemented_conversion_with_fixed_point_type) 6443 << SrcTy; 6444 return CK_IntegralCast; 6445 } 6446 llvm_unreachable("Should have returned before this"); 6447 6448 case Type::STK_IntegralComplex: 6449 switch (DestTy->getScalarTypeKind()) { 6450 case Type::STK_FloatingComplex: 6451 return CK_IntegralComplexToFloatingComplex; 6452 case Type::STK_IntegralComplex: 6453 return CK_IntegralComplexCast; 6454 case Type::STK_Integral: { 6455 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6456 if (Context.hasSameType(ET, DestTy)) 6457 return CK_IntegralComplexToReal; 6458 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6459 return CK_IntegralCast; 6460 } 6461 case Type::STK_Bool: 6462 return CK_IntegralComplexToBoolean; 6463 case Type::STK_Floating: 6464 Src = ImpCastExprToType(Src.get(), 6465 SrcTy->castAs<ComplexType>()->getElementType(), 6466 CK_IntegralComplexToReal); 6467 return CK_IntegralToFloating; 6468 case Type::STK_CPointer: 6469 case Type::STK_ObjCObjectPointer: 6470 case Type::STK_BlockPointer: 6471 llvm_unreachable("valid complex int->pointer cast?"); 6472 case Type::STK_MemberPointer: 6473 llvm_unreachable("member pointer type in C"); 6474 case Type::STK_FixedPoint: 6475 Diag(Src.get()->getExprLoc(), 6476 diag::err_unimplemented_conversion_with_fixed_point_type) 6477 << SrcTy; 6478 return CK_IntegralCast; 6479 } 6480 llvm_unreachable("Should have returned before this"); 6481 } 6482 6483 llvm_unreachable("Unhandled scalar cast"); 6484 } 6485 6486 static bool breakDownVectorType(QualType type, uint64_t &len, 6487 QualType &eltType) { 6488 // Vectors are simple. 6489 if (const VectorType *vecType = type->getAs<VectorType>()) { 6490 len = vecType->getNumElements(); 6491 eltType = vecType->getElementType(); 6492 assert(eltType->isScalarType()); 6493 return true; 6494 } 6495 6496 // We allow lax conversion to and from non-vector types, but only if 6497 // they're real types (i.e. non-complex, non-pointer scalar types). 6498 if (!type->isRealType()) return false; 6499 6500 len = 1; 6501 eltType = type; 6502 return true; 6503 } 6504 6505 /// Are the two types lax-compatible vector types? That is, given 6506 /// that one of them is a vector, do they have equal storage sizes, 6507 /// where the storage size is the number of elements times the element 6508 /// size? 6509 /// 6510 /// This will also return false if either of the types is neither a 6511 /// vector nor a real type. 6512 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6513 assert(destTy->isVectorType() || srcTy->isVectorType()); 6514 6515 // Disallow lax conversions between scalars and ExtVectors (these 6516 // conversions are allowed for other vector types because common headers 6517 // depend on them). Most scalar OP ExtVector cases are handled by the 6518 // splat path anyway, which does what we want (convert, not bitcast). 6519 // What this rules out for ExtVectors is crazy things like char4*float. 6520 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6521 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6522 6523 uint64_t srcLen, destLen; 6524 QualType srcEltTy, destEltTy; 6525 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6526 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6527 6528 // ASTContext::getTypeSize will return the size rounded up to a 6529 // power of 2, so instead of using that, we need to use the raw 6530 // element size multiplied by the element count. 6531 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6532 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6533 6534 return (srcLen * srcEltSize == destLen * destEltSize); 6535 } 6536 6537 /// Is this a legal conversion between two types, one of which is 6538 /// known to be a vector type? 6539 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6540 assert(destTy->isVectorType() || srcTy->isVectorType()); 6541 6542 switch (Context.getLangOpts().getLaxVectorConversions()) { 6543 case LangOptions::LaxVectorConversionKind::None: 6544 return false; 6545 6546 case LangOptions::LaxVectorConversionKind::Integer: 6547 if (!srcTy->isIntegralOrEnumerationType()) { 6548 auto *Vec = srcTy->getAs<VectorType>(); 6549 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6550 return false; 6551 } 6552 if (!destTy->isIntegralOrEnumerationType()) { 6553 auto *Vec = destTy->getAs<VectorType>(); 6554 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6555 return false; 6556 } 6557 // OK, integer (vector) -> integer (vector) bitcast. 6558 break; 6559 6560 case LangOptions::LaxVectorConversionKind::All: 6561 break; 6562 } 6563 6564 return areLaxCompatibleVectorTypes(srcTy, destTy); 6565 } 6566 6567 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6568 CastKind &Kind) { 6569 assert(VectorTy->isVectorType() && "Not a vector type!"); 6570 6571 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6572 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6573 return Diag(R.getBegin(), 6574 Ty->isVectorType() ? 6575 diag::err_invalid_conversion_between_vectors : 6576 diag::err_invalid_conversion_between_vector_and_integer) 6577 << VectorTy << Ty << R; 6578 } else 6579 return Diag(R.getBegin(), 6580 diag::err_invalid_conversion_between_vector_and_scalar) 6581 << VectorTy << Ty << R; 6582 6583 Kind = CK_BitCast; 6584 return false; 6585 } 6586 6587 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6588 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6589 6590 if (DestElemTy == SplattedExpr->getType()) 6591 return SplattedExpr; 6592 6593 assert(DestElemTy->isFloatingType() || 6594 DestElemTy->isIntegralOrEnumerationType()); 6595 6596 CastKind CK; 6597 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6598 // OpenCL requires that we convert `true` boolean expressions to -1, but 6599 // only when splatting vectors. 6600 if (DestElemTy->isFloatingType()) { 6601 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6602 // in two steps: boolean to signed integral, then to floating. 6603 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6604 CK_BooleanToSignedIntegral); 6605 SplattedExpr = CastExprRes.get(); 6606 CK = CK_IntegralToFloating; 6607 } else { 6608 CK = CK_BooleanToSignedIntegral; 6609 } 6610 } else { 6611 ExprResult CastExprRes = SplattedExpr; 6612 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6613 if (CastExprRes.isInvalid()) 6614 return ExprError(); 6615 SplattedExpr = CastExprRes.get(); 6616 } 6617 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6618 } 6619 6620 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6621 Expr *CastExpr, CastKind &Kind) { 6622 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6623 6624 QualType SrcTy = CastExpr->getType(); 6625 6626 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6627 // an ExtVectorType. 6628 // In OpenCL, casts between vectors of different types are not allowed. 6629 // (See OpenCL 6.2). 6630 if (SrcTy->isVectorType()) { 6631 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6632 (getLangOpts().OpenCL && 6633 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6634 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6635 << DestTy << SrcTy << R; 6636 return ExprError(); 6637 } 6638 Kind = CK_BitCast; 6639 return CastExpr; 6640 } 6641 6642 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6643 // conversion will take place first from scalar to elt type, and then 6644 // splat from elt type to vector. 6645 if (SrcTy->isPointerType()) 6646 return Diag(R.getBegin(), 6647 diag::err_invalid_conversion_between_vector_and_scalar) 6648 << DestTy << SrcTy << R; 6649 6650 Kind = CK_VectorSplat; 6651 return prepareVectorSplat(DestTy, CastExpr); 6652 } 6653 6654 ExprResult 6655 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6656 Declarator &D, ParsedType &Ty, 6657 SourceLocation RParenLoc, Expr *CastExpr) { 6658 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6659 "ActOnCastExpr(): missing type or expr"); 6660 6661 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6662 if (D.isInvalidType()) 6663 return ExprError(); 6664 6665 if (getLangOpts().CPlusPlus) { 6666 // Check that there are no default arguments (C++ only). 6667 CheckExtraCXXDefaultArguments(D); 6668 } else { 6669 // Make sure any TypoExprs have been dealt with. 6670 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6671 if (!Res.isUsable()) 6672 return ExprError(); 6673 CastExpr = Res.get(); 6674 } 6675 6676 checkUnusedDeclAttributes(D); 6677 6678 QualType castType = castTInfo->getType(); 6679 Ty = CreateParsedType(castType, castTInfo); 6680 6681 bool isVectorLiteral = false; 6682 6683 // Check for an altivec or OpenCL literal, 6684 // i.e. all the elements are integer constants. 6685 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6686 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6687 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6688 && castType->isVectorType() && (PE || PLE)) { 6689 if (PLE && PLE->getNumExprs() == 0) { 6690 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6691 return ExprError(); 6692 } 6693 if (PE || PLE->getNumExprs() == 1) { 6694 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6695 if (!E->getType()->isVectorType()) 6696 isVectorLiteral = true; 6697 } 6698 else 6699 isVectorLiteral = true; 6700 } 6701 6702 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6703 // then handle it as such. 6704 if (isVectorLiteral) 6705 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6706 6707 // If the Expr being casted is a ParenListExpr, handle it specially. 6708 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6709 // sequence of BinOp comma operators. 6710 if (isa<ParenListExpr>(CastExpr)) { 6711 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6712 if (Result.isInvalid()) return ExprError(); 6713 CastExpr = Result.get(); 6714 } 6715 6716 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6717 !getSourceManager().isInSystemMacro(LParenLoc)) 6718 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6719 6720 CheckTollFreeBridgeCast(castType, CastExpr); 6721 6722 CheckObjCBridgeRelatedCast(castType, CastExpr); 6723 6724 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6725 6726 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6727 } 6728 6729 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6730 SourceLocation RParenLoc, Expr *E, 6731 TypeSourceInfo *TInfo) { 6732 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6733 "Expected paren or paren list expression"); 6734 6735 Expr **exprs; 6736 unsigned numExprs; 6737 Expr *subExpr; 6738 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6739 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6740 LiteralLParenLoc = PE->getLParenLoc(); 6741 LiteralRParenLoc = PE->getRParenLoc(); 6742 exprs = PE->getExprs(); 6743 numExprs = PE->getNumExprs(); 6744 } else { // isa<ParenExpr> by assertion at function entrance 6745 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6746 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6747 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6748 exprs = &subExpr; 6749 numExprs = 1; 6750 } 6751 6752 QualType Ty = TInfo->getType(); 6753 assert(Ty->isVectorType() && "Expected vector type"); 6754 6755 SmallVector<Expr *, 8> initExprs; 6756 const VectorType *VTy = Ty->castAs<VectorType>(); 6757 unsigned numElems = VTy->getNumElements(); 6758 6759 // '(...)' form of vector initialization in AltiVec: the number of 6760 // initializers must be one or must match the size of the vector. 6761 // If a single value is specified in the initializer then it will be 6762 // replicated to all the components of the vector 6763 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6764 // The number of initializers must be one or must match the size of the 6765 // vector. If a single value is specified in the initializer then it will 6766 // be replicated to all the components of the vector 6767 if (numExprs == 1) { 6768 QualType ElemTy = VTy->getElementType(); 6769 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6770 if (Literal.isInvalid()) 6771 return ExprError(); 6772 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6773 PrepareScalarCast(Literal, ElemTy)); 6774 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6775 } 6776 else if (numExprs < numElems) { 6777 Diag(E->getExprLoc(), 6778 diag::err_incorrect_number_of_vector_initializers); 6779 return ExprError(); 6780 } 6781 else 6782 initExprs.append(exprs, exprs + numExprs); 6783 } 6784 else { 6785 // For OpenCL, when the number of initializers is a single value, 6786 // it will be replicated to all components of the vector. 6787 if (getLangOpts().OpenCL && 6788 VTy->getVectorKind() == VectorType::GenericVector && 6789 numExprs == 1) { 6790 QualType ElemTy = VTy->getElementType(); 6791 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6792 if (Literal.isInvalid()) 6793 return ExprError(); 6794 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6795 PrepareScalarCast(Literal, ElemTy)); 6796 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6797 } 6798 6799 initExprs.append(exprs, exprs + numExprs); 6800 } 6801 // FIXME: This means that pretty-printing the final AST will produce curly 6802 // braces instead of the original commas. 6803 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6804 initExprs, LiteralRParenLoc); 6805 initE->setType(Ty); 6806 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6807 } 6808 6809 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6810 /// the ParenListExpr into a sequence of comma binary operators. 6811 ExprResult 6812 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6813 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6814 if (!E) 6815 return OrigExpr; 6816 6817 ExprResult Result(E->getExpr(0)); 6818 6819 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6820 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6821 E->getExpr(i)); 6822 6823 if (Result.isInvalid()) return ExprError(); 6824 6825 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6826 } 6827 6828 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6829 SourceLocation R, 6830 MultiExprArg Val) { 6831 return ParenListExpr::Create(Context, L, Val, R); 6832 } 6833 6834 /// Emit a specialized diagnostic when one expression is a null pointer 6835 /// constant and the other is not a pointer. Returns true if a diagnostic is 6836 /// emitted. 6837 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6838 SourceLocation QuestionLoc) { 6839 Expr *NullExpr = LHSExpr; 6840 Expr *NonPointerExpr = RHSExpr; 6841 Expr::NullPointerConstantKind NullKind = 6842 NullExpr->isNullPointerConstant(Context, 6843 Expr::NPC_ValueDependentIsNotNull); 6844 6845 if (NullKind == Expr::NPCK_NotNull) { 6846 NullExpr = RHSExpr; 6847 NonPointerExpr = LHSExpr; 6848 NullKind = 6849 NullExpr->isNullPointerConstant(Context, 6850 Expr::NPC_ValueDependentIsNotNull); 6851 } 6852 6853 if (NullKind == Expr::NPCK_NotNull) 6854 return false; 6855 6856 if (NullKind == Expr::NPCK_ZeroExpression) 6857 return false; 6858 6859 if (NullKind == Expr::NPCK_ZeroLiteral) { 6860 // In this case, check to make sure that we got here from a "NULL" 6861 // string in the source code. 6862 NullExpr = NullExpr->IgnoreParenImpCasts(); 6863 SourceLocation loc = NullExpr->getExprLoc(); 6864 if (!findMacroSpelling(loc, "NULL")) 6865 return false; 6866 } 6867 6868 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6869 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6870 << NonPointerExpr->getType() << DiagType 6871 << NonPointerExpr->getSourceRange(); 6872 return true; 6873 } 6874 6875 /// Return false if the condition expression is valid, true otherwise. 6876 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6877 QualType CondTy = Cond->getType(); 6878 6879 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6880 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6881 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6882 << CondTy << Cond->getSourceRange(); 6883 return true; 6884 } 6885 6886 // C99 6.5.15p2 6887 if (CondTy->isScalarType()) return false; 6888 6889 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6890 << CondTy << Cond->getSourceRange(); 6891 return true; 6892 } 6893 6894 /// Handle when one or both operands are void type. 6895 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6896 ExprResult &RHS) { 6897 Expr *LHSExpr = LHS.get(); 6898 Expr *RHSExpr = RHS.get(); 6899 6900 if (!LHSExpr->getType()->isVoidType()) 6901 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6902 << RHSExpr->getSourceRange(); 6903 if (!RHSExpr->getType()->isVoidType()) 6904 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6905 << LHSExpr->getSourceRange(); 6906 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6907 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6908 return S.Context.VoidTy; 6909 } 6910 6911 /// Return false if the NullExpr can be promoted to PointerTy, 6912 /// true otherwise. 6913 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6914 QualType PointerTy) { 6915 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6916 !NullExpr.get()->isNullPointerConstant(S.Context, 6917 Expr::NPC_ValueDependentIsNull)) 6918 return true; 6919 6920 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6921 return false; 6922 } 6923 6924 /// Checks compatibility between two pointers and return the resulting 6925 /// type. 6926 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6927 ExprResult &RHS, 6928 SourceLocation Loc) { 6929 QualType LHSTy = LHS.get()->getType(); 6930 QualType RHSTy = RHS.get()->getType(); 6931 6932 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6933 // Two identical pointers types are always compatible. 6934 return LHSTy; 6935 } 6936 6937 QualType lhptee, rhptee; 6938 6939 // Get the pointee types. 6940 bool IsBlockPointer = false; 6941 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6942 lhptee = LHSBTy->getPointeeType(); 6943 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6944 IsBlockPointer = true; 6945 } else { 6946 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6947 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6948 } 6949 6950 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6951 // differently qualified versions of compatible types, the result type is 6952 // a pointer to an appropriately qualified version of the composite 6953 // type. 6954 6955 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6956 // clause doesn't make sense for our extensions. E.g. address space 2 should 6957 // be incompatible with address space 3: they may live on different devices or 6958 // anything. 6959 Qualifiers lhQual = lhptee.getQualifiers(); 6960 Qualifiers rhQual = rhptee.getQualifiers(); 6961 6962 LangAS ResultAddrSpace = LangAS::Default; 6963 LangAS LAddrSpace = lhQual.getAddressSpace(); 6964 LangAS RAddrSpace = rhQual.getAddressSpace(); 6965 6966 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6967 // spaces is disallowed. 6968 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6969 ResultAddrSpace = LAddrSpace; 6970 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6971 ResultAddrSpace = RAddrSpace; 6972 else { 6973 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6974 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6975 << RHS.get()->getSourceRange(); 6976 return QualType(); 6977 } 6978 6979 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6980 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6981 lhQual.removeCVRQualifiers(); 6982 rhQual.removeCVRQualifiers(); 6983 6984 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6985 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6986 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6987 // qual types are compatible iff 6988 // * corresponded types are compatible 6989 // * CVR qualifiers are equal 6990 // * address spaces are equal 6991 // Thus for conditional operator we merge CVR and address space unqualified 6992 // pointees and if there is a composite type we return a pointer to it with 6993 // merged qualifiers. 6994 LHSCastKind = 6995 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6996 RHSCastKind = 6997 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6998 lhQual.removeAddressSpace(); 6999 rhQual.removeAddressSpace(); 7000 7001 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7002 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7003 7004 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7005 7006 if (CompositeTy.isNull()) { 7007 // In this situation, we assume void* type. No especially good 7008 // reason, but this is what gcc does, and we do have to pick 7009 // to get a consistent AST. 7010 QualType incompatTy; 7011 incompatTy = S.Context.getPointerType( 7012 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7013 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7014 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7015 7016 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7017 // for casts between types with incompatible address space qualifiers. 7018 // For the following code the compiler produces casts between global and 7019 // local address spaces of the corresponded innermost pointees: 7020 // local int *global *a; 7021 // global int *global *b; 7022 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7023 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7024 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7025 << RHS.get()->getSourceRange(); 7026 7027 return incompatTy; 7028 } 7029 7030 // The pointer types are compatible. 7031 // In case of OpenCL ResultTy should have the address space qualifier 7032 // which is a superset of address spaces of both the 2nd and the 3rd 7033 // operands of the conditional operator. 7034 QualType ResultTy = [&, ResultAddrSpace]() { 7035 if (S.getLangOpts().OpenCL) { 7036 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7037 CompositeQuals.setAddressSpace(ResultAddrSpace); 7038 return S.Context 7039 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7040 .withCVRQualifiers(MergedCVRQual); 7041 } 7042 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7043 }(); 7044 if (IsBlockPointer) 7045 ResultTy = S.Context.getBlockPointerType(ResultTy); 7046 else 7047 ResultTy = S.Context.getPointerType(ResultTy); 7048 7049 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7050 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7051 return ResultTy; 7052 } 7053 7054 /// Return the resulting type when the operands are both block pointers. 7055 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7056 ExprResult &LHS, 7057 ExprResult &RHS, 7058 SourceLocation Loc) { 7059 QualType LHSTy = LHS.get()->getType(); 7060 QualType RHSTy = RHS.get()->getType(); 7061 7062 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7063 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7064 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7065 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7066 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7067 return destType; 7068 } 7069 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7070 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7071 << RHS.get()->getSourceRange(); 7072 return QualType(); 7073 } 7074 7075 // We have 2 block pointer types. 7076 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7077 } 7078 7079 /// Return the resulting type when the operands are both pointers. 7080 static QualType 7081 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7082 ExprResult &RHS, 7083 SourceLocation Loc) { 7084 // get the pointer types 7085 QualType LHSTy = LHS.get()->getType(); 7086 QualType RHSTy = RHS.get()->getType(); 7087 7088 // get the "pointed to" types 7089 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7090 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7091 7092 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7093 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7094 // Figure out necessary qualifiers (C99 6.5.15p6) 7095 QualType destPointee 7096 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7097 QualType destType = S.Context.getPointerType(destPointee); 7098 // Add qualifiers if necessary. 7099 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7100 // Promote to void*. 7101 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7102 return destType; 7103 } 7104 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7105 QualType destPointee 7106 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7107 QualType destType = S.Context.getPointerType(destPointee); 7108 // Add qualifiers if necessary. 7109 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7110 // Promote to void*. 7111 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7112 return destType; 7113 } 7114 7115 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7116 } 7117 7118 /// Return false if the first expression is not an integer and the second 7119 /// expression is not a pointer, true otherwise. 7120 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7121 Expr* PointerExpr, SourceLocation Loc, 7122 bool IsIntFirstExpr) { 7123 if (!PointerExpr->getType()->isPointerType() || 7124 !Int.get()->getType()->isIntegerType()) 7125 return false; 7126 7127 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7128 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7129 7130 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7131 << Expr1->getType() << Expr2->getType() 7132 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7133 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7134 CK_IntegralToPointer); 7135 return true; 7136 } 7137 7138 /// Simple conversion between integer and floating point types. 7139 /// 7140 /// Used when handling the OpenCL conditional operator where the 7141 /// condition is a vector while the other operands are scalar. 7142 /// 7143 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7144 /// types are either integer or floating type. Between the two 7145 /// operands, the type with the higher rank is defined as the "result 7146 /// type". The other operand needs to be promoted to the same type. No 7147 /// other type promotion is allowed. We cannot use 7148 /// UsualArithmeticConversions() for this purpose, since it always 7149 /// promotes promotable types. 7150 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7151 ExprResult &RHS, 7152 SourceLocation QuestionLoc) { 7153 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7154 if (LHS.isInvalid()) 7155 return QualType(); 7156 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7157 if (RHS.isInvalid()) 7158 return QualType(); 7159 7160 // For conversion purposes, we ignore any qualifiers. 7161 // For example, "const float" and "float" are equivalent. 7162 QualType LHSType = 7163 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7164 QualType RHSType = 7165 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7166 7167 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7168 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7169 << LHSType << LHS.get()->getSourceRange(); 7170 return QualType(); 7171 } 7172 7173 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7174 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7175 << RHSType << RHS.get()->getSourceRange(); 7176 return QualType(); 7177 } 7178 7179 // If both types are identical, no conversion is needed. 7180 if (LHSType == RHSType) 7181 return LHSType; 7182 7183 // Now handle "real" floating types (i.e. float, double, long double). 7184 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7185 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7186 /*IsCompAssign = */ false); 7187 7188 // Finally, we have two differing integer types. 7189 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7190 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7191 } 7192 7193 /// Convert scalar operands to a vector that matches the 7194 /// condition in length. 7195 /// 7196 /// Used when handling the OpenCL conditional operator where the 7197 /// condition is a vector while the other operands are scalar. 7198 /// 7199 /// We first compute the "result type" for the scalar operands 7200 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7201 /// into a vector of that type where the length matches the condition 7202 /// vector type. s6.11.6 requires that the element types of the result 7203 /// and the condition must have the same number of bits. 7204 static QualType 7205 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7206 QualType CondTy, SourceLocation QuestionLoc) { 7207 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7208 if (ResTy.isNull()) return QualType(); 7209 7210 const VectorType *CV = CondTy->getAs<VectorType>(); 7211 assert(CV); 7212 7213 // Determine the vector result type 7214 unsigned NumElements = CV->getNumElements(); 7215 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7216 7217 // Ensure that all types have the same number of bits 7218 if (S.Context.getTypeSize(CV->getElementType()) 7219 != S.Context.getTypeSize(ResTy)) { 7220 // Since VectorTy is created internally, it does not pretty print 7221 // with an OpenCL name. Instead, we just print a description. 7222 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7223 SmallString<64> Str; 7224 llvm::raw_svector_ostream OS(Str); 7225 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7226 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7227 << CondTy << OS.str(); 7228 return QualType(); 7229 } 7230 7231 // Convert operands to the vector result type 7232 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7233 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7234 7235 return VectorTy; 7236 } 7237 7238 /// Return false if this is a valid OpenCL condition vector 7239 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7240 SourceLocation QuestionLoc) { 7241 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7242 // integral type. 7243 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7244 assert(CondTy); 7245 QualType EleTy = CondTy->getElementType(); 7246 if (EleTy->isIntegerType()) return false; 7247 7248 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7249 << Cond->getType() << Cond->getSourceRange(); 7250 return true; 7251 } 7252 7253 /// Return false if the vector condition type and the vector 7254 /// result type are compatible. 7255 /// 7256 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7257 /// number of elements, and their element types have the same number 7258 /// of bits. 7259 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7260 SourceLocation QuestionLoc) { 7261 const VectorType *CV = CondTy->getAs<VectorType>(); 7262 const VectorType *RV = VecResTy->getAs<VectorType>(); 7263 assert(CV && RV); 7264 7265 if (CV->getNumElements() != RV->getNumElements()) { 7266 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7267 << CondTy << VecResTy; 7268 return true; 7269 } 7270 7271 QualType CVE = CV->getElementType(); 7272 QualType RVE = RV->getElementType(); 7273 7274 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7275 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7276 << CondTy << VecResTy; 7277 return true; 7278 } 7279 7280 return false; 7281 } 7282 7283 /// Return the resulting type for the conditional operator in 7284 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7285 /// s6.3.i) when the condition is a vector type. 7286 static QualType 7287 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7288 ExprResult &LHS, ExprResult &RHS, 7289 SourceLocation QuestionLoc) { 7290 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7291 if (Cond.isInvalid()) 7292 return QualType(); 7293 QualType CondTy = Cond.get()->getType(); 7294 7295 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7296 return QualType(); 7297 7298 // If either operand is a vector then find the vector type of the 7299 // result as specified in OpenCL v1.1 s6.3.i. 7300 if (LHS.get()->getType()->isVectorType() || 7301 RHS.get()->getType()->isVectorType()) { 7302 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7303 /*isCompAssign*/false, 7304 /*AllowBothBool*/true, 7305 /*AllowBoolConversions*/false); 7306 if (VecResTy.isNull()) return QualType(); 7307 // The result type must match the condition type as specified in 7308 // OpenCL v1.1 s6.11.6. 7309 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7310 return QualType(); 7311 return VecResTy; 7312 } 7313 7314 // Both operands are scalar. 7315 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7316 } 7317 7318 /// Return true if the Expr is block type 7319 static bool checkBlockType(Sema &S, const Expr *E) { 7320 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7321 QualType Ty = CE->getCallee()->getType(); 7322 if (Ty->isBlockPointerType()) { 7323 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7324 return true; 7325 } 7326 } 7327 return false; 7328 } 7329 7330 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7331 /// In that case, LHS = cond. 7332 /// C99 6.5.15 7333 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7334 ExprResult &RHS, ExprValueKind &VK, 7335 ExprObjectKind &OK, 7336 SourceLocation QuestionLoc) { 7337 7338 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7339 if (!LHSResult.isUsable()) return QualType(); 7340 LHS = LHSResult; 7341 7342 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7343 if (!RHSResult.isUsable()) return QualType(); 7344 RHS = RHSResult; 7345 7346 // C++ is sufficiently different to merit its own checker. 7347 if (getLangOpts().CPlusPlus) 7348 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7349 7350 VK = VK_RValue; 7351 OK = OK_Ordinary; 7352 7353 // The OpenCL operator with a vector condition is sufficiently 7354 // different to merit its own checker. 7355 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7356 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7357 7358 // First, check the condition. 7359 Cond = UsualUnaryConversions(Cond.get()); 7360 if (Cond.isInvalid()) 7361 return QualType(); 7362 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7363 return QualType(); 7364 7365 // Now check the two expressions. 7366 if (LHS.get()->getType()->isVectorType() || 7367 RHS.get()->getType()->isVectorType()) 7368 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7369 /*AllowBothBool*/true, 7370 /*AllowBoolConversions*/false); 7371 7372 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7373 if (LHS.isInvalid() || RHS.isInvalid()) 7374 return QualType(); 7375 7376 QualType LHSTy = LHS.get()->getType(); 7377 QualType RHSTy = RHS.get()->getType(); 7378 7379 // Diagnose attempts to convert between __float128 and long double where 7380 // such conversions currently can't be handled. 7381 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7382 Diag(QuestionLoc, 7383 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7384 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7385 return QualType(); 7386 } 7387 7388 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7389 // selection operator (?:). 7390 if (getLangOpts().OpenCL && 7391 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7392 return QualType(); 7393 } 7394 7395 // If both operands have arithmetic type, do the usual arithmetic conversions 7396 // to find a common type: C99 6.5.15p3,5. 7397 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7398 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7399 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7400 7401 return ResTy; 7402 } 7403 7404 // If both operands are the same structure or union type, the result is that 7405 // type. 7406 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7407 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7408 if (LHSRT->getDecl() == RHSRT->getDecl()) 7409 // "If both the operands have structure or union type, the result has 7410 // that type." This implies that CV qualifiers are dropped. 7411 return LHSTy.getUnqualifiedType(); 7412 // FIXME: Type of conditional expression must be complete in C mode. 7413 } 7414 7415 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7416 // The following || allows only one side to be void (a GCC-ism). 7417 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7418 return checkConditionalVoidType(*this, LHS, RHS); 7419 } 7420 7421 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7422 // the type of the other operand." 7423 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7424 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7425 7426 // All objective-c pointer type analysis is done here. 7427 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7428 QuestionLoc); 7429 if (LHS.isInvalid() || RHS.isInvalid()) 7430 return QualType(); 7431 if (!compositeType.isNull()) 7432 return compositeType; 7433 7434 7435 // Handle block pointer types. 7436 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7437 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7438 QuestionLoc); 7439 7440 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7441 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7442 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7443 QuestionLoc); 7444 7445 // GCC compatibility: soften pointer/integer mismatch. Note that 7446 // null pointers have been filtered out by this point. 7447 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7448 /*IsIntFirstExpr=*/true)) 7449 return RHSTy; 7450 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7451 /*IsIntFirstExpr=*/false)) 7452 return LHSTy; 7453 7454 // Emit a better diagnostic if one of the expressions is a null pointer 7455 // constant and the other is not a pointer type. In this case, the user most 7456 // likely forgot to take the address of the other expression. 7457 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7458 return QualType(); 7459 7460 // Otherwise, the operands are not compatible. 7461 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7462 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7463 << RHS.get()->getSourceRange(); 7464 return QualType(); 7465 } 7466 7467 /// FindCompositeObjCPointerType - Helper method to find composite type of 7468 /// two objective-c pointer types of the two input expressions. 7469 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7470 SourceLocation QuestionLoc) { 7471 QualType LHSTy = LHS.get()->getType(); 7472 QualType RHSTy = RHS.get()->getType(); 7473 7474 // Handle things like Class and struct objc_class*. Here we case the result 7475 // to the pseudo-builtin, because that will be implicitly cast back to the 7476 // redefinition type if an attempt is made to access its fields. 7477 if (LHSTy->isObjCClassType() && 7478 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7479 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7480 return LHSTy; 7481 } 7482 if (RHSTy->isObjCClassType() && 7483 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7484 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7485 return RHSTy; 7486 } 7487 // And the same for struct objc_object* / id 7488 if (LHSTy->isObjCIdType() && 7489 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7490 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7491 return LHSTy; 7492 } 7493 if (RHSTy->isObjCIdType() && 7494 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7495 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7496 return RHSTy; 7497 } 7498 // And the same for struct objc_selector* / SEL 7499 if (Context.isObjCSelType(LHSTy) && 7500 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7501 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7502 return LHSTy; 7503 } 7504 if (Context.isObjCSelType(RHSTy) && 7505 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7506 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7507 return RHSTy; 7508 } 7509 // Check constraints for Objective-C object pointers types. 7510 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7511 7512 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7513 // Two identical object pointer types are always compatible. 7514 return LHSTy; 7515 } 7516 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7517 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7518 QualType compositeType = LHSTy; 7519 7520 // If both operands are interfaces and either operand can be 7521 // assigned to the other, use that type as the composite 7522 // type. This allows 7523 // xxx ? (A*) a : (B*) b 7524 // where B is a subclass of A. 7525 // 7526 // Additionally, as for assignment, if either type is 'id' 7527 // allow silent coercion. Finally, if the types are 7528 // incompatible then make sure to use 'id' as the composite 7529 // type so the result is acceptable for sending messages to. 7530 7531 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7532 // It could return the composite type. 7533 if (!(compositeType = 7534 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7535 // Nothing more to do. 7536 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7537 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7538 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7539 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7540 } else if ((LHSOPT->isObjCQualifiedIdType() || 7541 RHSOPT->isObjCQualifiedIdType()) && 7542 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7543 true)) { 7544 // Need to handle "id<xx>" explicitly. 7545 // GCC allows qualified id and any Objective-C type to devolve to 7546 // id. Currently localizing to here until clear this should be 7547 // part of ObjCQualifiedIdTypesAreCompatible. 7548 compositeType = Context.getObjCIdType(); 7549 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7550 compositeType = Context.getObjCIdType(); 7551 } else { 7552 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7553 << LHSTy << RHSTy 7554 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7555 QualType incompatTy = Context.getObjCIdType(); 7556 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7557 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7558 return incompatTy; 7559 } 7560 // The object pointer types are compatible. 7561 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7562 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7563 return compositeType; 7564 } 7565 // Check Objective-C object pointer types and 'void *' 7566 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7567 if (getLangOpts().ObjCAutoRefCount) { 7568 // ARC forbids the implicit conversion of object pointers to 'void *', 7569 // so these types are not compatible. 7570 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7571 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7572 LHS = RHS = true; 7573 return QualType(); 7574 } 7575 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7576 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7577 QualType destPointee 7578 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7579 QualType destType = Context.getPointerType(destPointee); 7580 // Add qualifiers if necessary. 7581 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7582 // Promote to void*. 7583 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7584 return destType; 7585 } 7586 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7587 if (getLangOpts().ObjCAutoRefCount) { 7588 // ARC forbids the implicit conversion of object pointers to 'void *', 7589 // so these types are not compatible. 7590 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7591 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7592 LHS = RHS = true; 7593 return QualType(); 7594 } 7595 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7596 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7597 QualType destPointee 7598 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7599 QualType destType = Context.getPointerType(destPointee); 7600 // Add qualifiers if necessary. 7601 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7602 // Promote to void*. 7603 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7604 return destType; 7605 } 7606 return QualType(); 7607 } 7608 7609 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7610 /// ParenRange in parentheses. 7611 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7612 const PartialDiagnostic &Note, 7613 SourceRange ParenRange) { 7614 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7615 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7616 EndLoc.isValid()) { 7617 Self.Diag(Loc, Note) 7618 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7619 << FixItHint::CreateInsertion(EndLoc, ")"); 7620 } else { 7621 // We can't display the parentheses, so just show the bare note. 7622 Self.Diag(Loc, Note) << ParenRange; 7623 } 7624 } 7625 7626 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7627 return BinaryOperator::isAdditiveOp(Opc) || 7628 BinaryOperator::isMultiplicativeOp(Opc) || 7629 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7630 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7631 // not any of the logical operators. Bitwise-xor is commonly used as a 7632 // logical-xor because there is no logical-xor operator. The logical 7633 // operators, including uses of xor, have a high false positive rate for 7634 // precedence warnings. 7635 } 7636 7637 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7638 /// expression, either using a built-in or overloaded operator, 7639 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7640 /// expression. 7641 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7642 Expr **RHSExprs) { 7643 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7644 E = E->IgnoreImpCasts(); 7645 E = E->IgnoreConversionOperator(); 7646 E = E->IgnoreImpCasts(); 7647 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7648 E = MTE->GetTemporaryExpr(); 7649 E = E->IgnoreImpCasts(); 7650 } 7651 7652 // Built-in binary operator. 7653 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7654 if (IsArithmeticOp(OP->getOpcode())) { 7655 *Opcode = OP->getOpcode(); 7656 *RHSExprs = OP->getRHS(); 7657 return true; 7658 } 7659 } 7660 7661 // Overloaded operator. 7662 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7663 if (Call->getNumArgs() != 2) 7664 return false; 7665 7666 // Make sure this is really a binary operator that is safe to pass into 7667 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7668 OverloadedOperatorKind OO = Call->getOperator(); 7669 if (OO < OO_Plus || OO > OO_Arrow || 7670 OO == OO_PlusPlus || OO == OO_MinusMinus) 7671 return false; 7672 7673 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7674 if (IsArithmeticOp(OpKind)) { 7675 *Opcode = OpKind; 7676 *RHSExprs = Call->getArg(1); 7677 return true; 7678 } 7679 } 7680 7681 return false; 7682 } 7683 7684 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7685 /// or is a logical expression such as (x==y) which has int type, but is 7686 /// commonly interpreted as boolean. 7687 static bool ExprLooksBoolean(Expr *E) { 7688 E = E->IgnoreParenImpCasts(); 7689 7690 if (E->getType()->isBooleanType()) 7691 return true; 7692 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7693 return OP->isComparisonOp() || OP->isLogicalOp(); 7694 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7695 return OP->getOpcode() == UO_LNot; 7696 if (E->getType()->isPointerType()) 7697 return true; 7698 // FIXME: What about overloaded operator calls returning "unspecified boolean 7699 // type"s (commonly pointer-to-members)? 7700 7701 return false; 7702 } 7703 7704 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7705 /// and binary operator are mixed in a way that suggests the programmer assumed 7706 /// the conditional operator has higher precedence, for example: 7707 /// "int x = a + someBinaryCondition ? 1 : 2". 7708 static void DiagnoseConditionalPrecedence(Sema &Self, 7709 SourceLocation OpLoc, 7710 Expr *Condition, 7711 Expr *LHSExpr, 7712 Expr *RHSExpr) { 7713 BinaryOperatorKind CondOpcode; 7714 Expr *CondRHS; 7715 7716 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7717 return; 7718 if (!ExprLooksBoolean(CondRHS)) 7719 return; 7720 7721 // The condition is an arithmetic binary expression, with a right- 7722 // hand side that looks boolean, so warn. 7723 7724 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7725 ? diag::warn_precedence_bitwise_conditional 7726 : diag::warn_precedence_conditional; 7727 7728 Self.Diag(OpLoc, DiagID) 7729 << Condition->getSourceRange() 7730 << BinaryOperator::getOpcodeStr(CondOpcode); 7731 7732 SuggestParentheses( 7733 Self, OpLoc, 7734 Self.PDiag(diag::note_precedence_silence) 7735 << BinaryOperator::getOpcodeStr(CondOpcode), 7736 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7737 7738 SuggestParentheses(Self, OpLoc, 7739 Self.PDiag(diag::note_precedence_conditional_first), 7740 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7741 } 7742 7743 /// Compute the nullability of a conditional expression. 7744 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7745 QualType LHSTy, QualType RHSTy, 7746 ASTContext &Ctx) { 7747 if (!ResTy->isAnyPointerType()) 7748 return ResTy; 7749 7750 auto GetNullability = [&Ctx](QualType Ty) { 7751 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7752 if (Kind) 7753 return *Kind; 7754 return NullabilityKind::Unspecified; 7755 }; 7756 7757 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7758 NullabilityKind MergedKind; 7759 7760 // Compute nullability of a binary conditional expression. 7761 if (IsBin) { 7762 if (LHSKind == NullabilityKind::NonNull) 7763 MergedKind = NullabilityKind::NonNull; 7764 else 7765 MergedKind = RHSKind; 7766 // Compute nullability of a normal conditional expression. 7767 } else { 7768 if (LHSKind == NullabilityKind::Nullable || 7769 RHSKind == NullabilityKind::Nullable) 7770 MergedKind = NullabilityKind::Nullable; 7771 else if (LHSKind == NullabilityKind::NonNull) 7772 MergedKind = RHSKind; 7773 else if (RHSKind == NullabilityKind::NonNull) 7774 MergedKind = LHSKind; 7775 else 7776 MergedKind = NullabilityKind::Unspecified; 7777 } 7778 7779 // Return if ResTy already has the correct nullability. 7780 if (GetNullability(ResTy) == MergedKind) 7781 return ResTy; 7782 7783 // Strip all nullability from ResTy. 7784 while (ResTy->getNullability(Ctx)) 7785 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7786 7787 // Create a new AttributedType with the new nullability kind. 7788 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7789 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7790 } 7791 7792 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7793 /// in the case of a the GNU conditional expr extension. 7794 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7795 SourceLocation ColonLoc, 7796 Expr *CondExpr, Expr *LHSExpr, 7797 Expr *RHSExpr) { 7798 if (!getLangOpts().CPlusPlus) { 7799 // C cannot handle TypoExpr nodes in the condition because it 7800 // doesn't handle dependent types properly, so make sure any TypoExprs have 7801 // been dealt with before checking the operands. 7802 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7803 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7804 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7805 7806 if (!CondResult.isUsable()) 7807 return ExprError(); 7808 7809 if (LHSExpr) { 7810 if (!LHSResult.isUsable()) 7811 return ExprError(); 7812 } 7813 7814 if (!RHSResult.isUsable()) 7815 return ExprError(); 7816 7817 CondExpr = CondResult.get(); 7818 LHSExpr = LHSResult.get(); 7819 RHSExpr = RHSResult.get(); 7820 } 7821 7822 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7823 // was the condition. 7824 OpaqueValueExpr *opaqueValue = nullptr; 7825 Expr *commonExpr = nullptr; 7826 if (!LHSExpr) { 7827 commonExpr = CondExpr; 7828 // Lower out placeholder types first. This is important so that we don't 7829 // try to capture a placeholder. This happens in few cases in C++; such 7830 // as Objective-C++'s dictionary subscripting syntax. 7831 if (commonExpr->hasPlaceholderType()) { 7832 ExprResult result = CheckPlaceholderExpr(commonExpr); 7833 if (!result.isUsable()) return ExprError(); 7834 commonExpr = result.get(); 7835 } 7836 // We usually want to apply unary conversions *before* saving, except 7837 // in the special case of a C++ l-value conditional. 7838 if (!(getLangOpts().CPlusPlus 7839 && !commonExpr->isTypeDependent() 7840 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7841 && commonExpr->isGLValue() 7842 && commonExpr->isOrdinaryOrBitFieldObject() 7843 && RHSExpr->isOrdinaryOrBitFieldObject() 7844 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7845 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7846 if (commonRes.isInvalid()) 7847 return ExprError(); 7848 commonExpr = commonRes.get(); 7849 } 7850 7851 // If the common expression is a class or array prvalue, materialize it 7852 // so that we can safely refer to it multiple times. 7853 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7854 commonExpr->getType()->isArrayType())) { 7855 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7856 if (MatExpr.isInvalid()) 7857 return ExprError(); 7858 commonExpr = MatExpr.get(); 7859 } 7860 7861 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7862 commonExpr->getType(), 7863 commonExpr->getValueKind(), 7864 commonExpr->getObjectKind(), 7865 commonExpr); 7866 LHSExpr = CondExpr = opaqueValue; 7867 } 7868 7869 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7870 ExprValueKind VK = VK_RValue; 7871 ExprObjectKind OK = OK_Ordinary; 7872 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7873 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7874 VK, OK, QuestionLoc); 7875 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7876 RHS.isInvalid()) 7877 return ExprError(); 7878 7879 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7880 RHS.get()); 7881 7882 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7883 7884 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7885 Context); 7886 7887 if (!commonExpr) 7888 return new (Context) 7889 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7890 RHS.get(), result, VK, OK); 7891 7892 return new (Context) BinaryConditionalOperator( 7893 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7894 ColonLoc, result, VK, OK); 7895 } 7896 7897 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7898 // being closely modeled after the C99 spec:-). The odd characteristic of this 7899 // routine is it effectively iqnores the qualifiers on the top level pointee. 7900 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7901 // FIXME: add a couple examples in this comment. 7902 static Sema::AssignConvertType 7903 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7904 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7905 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7906 7907 // get the "pointed to" type (ignoring qualifiers at the top level) 7908 const Type *lhptee, *rhptee; 7909 Qualifiers lhq, rhq; 7910 std::tie(lhptee, lhq) = 7911 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7912 std::tie(rhptee, rhq) = 7913 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7914 7915 Sema::AssignConvertType ConvTy = Sema::Compatible; 7916 7917 // C99 6.5.16.1p1: This following citation is common to constraints 7918 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7919 // qualifiers of the type *pointed to* by the right; 7920 7921 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7922 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7923 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7924 // Ignore lifetime for further calculation. 7925 lhq.removeObjCLifetime(); 7926 rhq.removeObjCLifetime(); 7927 } 7928 7929 if (!lhq.compatiblyIncludes(rhq)) { 7930 // Treat address-space mismatches as fatal. 7931 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7932 return Sema::IncompatiblePointerDiscardsQualifiers; 7933 7934 // It's okay to add or remove GC or lifetime qualifiers when converting to 7935 // and from void*. 7936 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7937 .compatiblyIncludes( 7938 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7939 && (lhptee->isVoidType() || rhptee->isVoidType())) 7940 ; // keep old 7941 7942 // Treat lifetime mismatches as fatal. 7943 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7944 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7945 7946 // For GCC/MS compatibility, other qualifier mismatches are treated 7947 // as still compatible in C. 7948 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7949 } 7950 7951 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7952 // incomplete type and the other is a pointer to a qualified or unqualified 7953 // version of void... 7954 if (lhptee->isVoidType()) { 7955 if (rhptee->isIncompleteOrObjectType()) 7956 return ConvTy; 7957 7958 // As an extension, we allow cast to/from void* to function pointer. 7959 assert(rhptee->isFunctionType()); 7960 return Sema::FunctionVoidPointer; 7961 } 7962 7963 if (rhptee->isVoidType()) { 7964 if (lhptee->isIncompleteOrObjectType()) 7965 return ConvTy; 7966 7967 // As an extension, we allow cast to/from void* to function pointer. 7968 assert(lhptee->isFunctionType()); 7969 return Sema::FunctionVoidPointer; 7970 } 7971 7972 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7973 // unqualified versions of compatible types, ... 7974 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7975 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7976 // Check if the pointee types are compatible ignoring the sign. 7977 // We explicitly check for char so that we catch "char" vs 7978 // "unsigned char" on systems where "char" is unsigned. 7979 if (lhptee->isCharType()) 7980 ltrans = S.Context.UnsignedCharTy; 7981 else if (lhptee->hasSignedIntegerRepresentation()) 7982 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7983 7984 if (rhptee->isCharType()) 7985 rtrans = S.Context.UnsignedCharTy; 7986 else if (rhptee->hasSignedIntegerRepresentation()) 7987 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7988 7989 if (ltrans == rtrans) { 7990 // Types are compatible ignoring the sign. Qualifier incompatibility 7991 // takes priority over sign incompatibility because the sign 7992 // warning can be disabled. 7993 if (ConvTy != Sema::Compatible) 7994 return ConvTy; 7995 7996 return Sema::IncompatiblePointerSign; 7997 } 7998 7999 // If we are a multi-level pointer, it's possible that our issue is simply 8000 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8001 // the eventual target type is the same and the pointers have the same 8002 // level of indirection, this must be the issue. 8003 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8004 do { 8005 std::tie(lhptee, lhq) = 8006 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8007 std::tie(rhptee, rhq) = 8008 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8009 8010 // Inconsistent address spaces at this point is invalid, even if the 8011 // address spaces would be compatible. 8012 // FIXME: This doesn't catch address space mismatches for pointers of 8013 // different nesting levels, like: 8014 // __local int *** a; 8015 // int ** b = a; 8016 // It's not clear how to actually determine when such pointers are 8017 // invalidly incompatible. 8018 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8019 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8020 8021 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8022 8023 if (lhptee == rhptee) 8024 return Sema::IncompatibleNestedPointerQualifiers; 8025 } 8026 8027 // General pointer incompatibility takes priority over qualifiers. 8028 return Sema::IncompatiblePointer; 8029 } 8030 if (!S.getLangOpts().CPlusPlus && 8031 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8032 return Sema::IncompatiblePointer; 8033 return ConvTy; 8034 } 8035 8036 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8037 /// block pointer types are compatible or whether a block and normal pointer 8038 /// are compatible. It is more restrict than comparing two function pointer 8039 // types. 8040 static Sema::AssignConvertType 8041 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8042 QualType RHSType) { 8043 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8044 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8045 8046 QualType lhptee, rhptee; 8047 8048 // get the "pointed to" type (ignoring qualifiers at the top level) 8049 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8050 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8051 8052 // In C++, the types have to match exactly. 8053 if (S.getLangOpts().CPlusPlus) 8054 return Sema::IncompatibleBlockPointer; 8055 8056 Sema::AssignConvertType ConvTy = Sema::Compatible; 8057 8058 // For blocks we enforce that qualifiers are identical. 8059 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8060 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8061 if (S.getLangOpts().OpenCL) { 8062 LQuals.removeAddressSpace(); 8063 RQuals.removeAddressSpace(); 8064 } 8065 if (LQuals != RQuals) 8066 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8067 8068 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8069 // assignment. 8070 // The current behavior is similar to C++ lambdas. A block might be 8071 // assigned to a variable iff its return type and parameters are compatible 8072 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8073 // an assignment. Presumably it should behave in way that a function pointer 8074 // assignment does in C, so for each parameter and return type: 8075 // * CVR and address space of LHS should be a superset of CVR and address 8076 // space of RHS. 8077 // * unqualified types should be compatible. 8078 if (S.getLangOpts().OpenCL) { 8079 if (!S.Context.typesAreBlockPointerCompatible( 8080 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8081 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8082 return Sema::IncompatibleBlockPointer; 8083 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8084 return Sema::IncompatibleBlockPointer; 8085 8086 return ConvTy; 8087 } 8088 8089 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8090 /// for assignment compatibility. 8091 static Sema::AssignConvertType 8092 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8093 QualType RHSType) { 8094 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8095 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8096 8097 if (LHSType->isObjCBuiltinType()) { 8098 // Class is not compatible with ObjC object pointers. 8099 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8100 !RHSType->isObjCQualifiedClassType()) 8101 return Sema::IncompatiblePointer; 8102 return Sema::Compatible; 8103 } 8104 if (RHSType->isObjCBuiltinType()) { 8105 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8106 !LHSType->isObjCQualifiedClassType()) 8107 return Sema::IncompatiblePointer; 8108 return Sema::Compatible; 8109 } 8110 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8111 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8112 8113 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8114 // make an exception for id<P> 8115 !LHSType->isObjCQualifiedIdType()) 8116 return Sema::CompatiblePointerDiscardsQualifiers; 8117 8118 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8119 return Sema::Compatible; 8120 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8121 return Sema::IncompatibleObjCQualifiedId; 8122 return Sema::IncompatiblePointer; 8123 } 8124 8125 Sema::AssignConvertType 8126 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8127 QualType LHSType, QualType RHSType) { 8128 // Fake up an opaque expression. We don't actually care about what 8129 // cast operations are required, so if CheckAssignmentConstraints 8130 // adds casts to this they'll be wasted, but fortunately that doesn't 8131 // usually happen on valid code. 8132 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8133 ExprResult RHSPtr = &RHSExpr; 8134 CastKind K; 8135 8136 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8137 } 8138 8139 /// This helper function returns true if QT is a vector type that has element 8140 /// type ElementType. 8141 static bool isVector(QualType QT, QualType ElementType) { 8142 if (const VectorType *VT = QT->getAs<VectorType>()) 8143 return VT->getElementType() == ElementType; 8144 return false; 8145 } 8146 8147 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8148 /// has code to accommodate several GCC extensions when type checking 8149 /// pointers. Here are some objectionable examples that GCC considers warnings: 8150 /// 8151 /// int a, *pint; 8152 /// short *pshort; 8153 /// struct foo *pfoo; 8154 /// 8155 /// pint = pshort; // warning: assignment from incompatible pointer type 8156 /// a = pint; // warning: assignment makes integer from pointer without a cast 8157 /// pint = a; // warning: assignment makes pointer from integer without a cast 8158 /// pint = pfoo; // warning: assignment from incompatible pointer type 8159 /// 8160 /// As a result, the code for dealing with pointers is more complex than the 8161 /// C99 spec dictates. 8162 /// 8163 /// Sets 'Kind' for any result kind except Incompatible. 8164 Sema::AssignConvertType 8165 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8166 CastKind &Kind, bool ConvertRHS) { 8167 QualType RHSType = RHS.get()->getType(); 8168 QualType OrigLHSType = LHSType; 8169 8170 // Get canonical types. We're not formatting these types, just comparing 8171 // them. 8172 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8173 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8174 8175 // Common case: no conversion required. 8176 if (LHSType == RHSType) { 8177 Kind = CK_NoOp; 8178 return Compatible; 8179 } 8180 8181 // If we have an atomic type, try a non-atomic assignment, then just add an 8182 // atomic qualification step. 8183 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8184 Sema::AssignConvertType result = 8185 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8186 if (result != Compatible) 8187 return result; 8188 if (Kind != CK_NoOp && ConvertRHS) 8189 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8190 Kind = CK_NonAtomicToAtomic; 8191 return Compatible; 8192 } 8193 8194 // If the left-hand side is a reference type, then we are in a 8195 // (rare!) case where we've allowed the use of references in C, 8196 // e.g., as a parameter type in a built-in function. In this case, 8197 // just make sure that the type referenced is compatible with the 8198 // right-hand side type. The caller is responsible for adjusting 8199 // LHSType so that the resulting expression does not have reference 8200 // type. 8201 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8202 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8203 Kind = CK_LValueBitCast; 8204 return Compatible; 8205 } 8206 return Incompatible; 8207 } 8208 8209 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8210 // to the same ExtVector type. 8211 if (LHSType->isExtVectorType()) { 8212 if (RHSType->isExtVectorType()) 8213 return Incompatible; 8214 if (RHSType->isArithmeticType()) { 8215 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8216 if (ConvertRHS) 8217 RHS = prepareVectorSplat(LHSType, RHS.get()); 8218 Kind = CK_VectorSplat; 8219 return Compatible; 8220 } 8221 } 8222 8223 // Conversions to or from vector type. 8224 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8225 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8226 // Allow assignments of an AltiVec vector type to an equivalent GCC 8227 // vector type and vice versa 8228 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8229 Kind = CK_BitCast; 8230 return Compatible; 8231 } 8232 8233 // If we are allowing lax vector conversions, and LHS and RHS are both 8234 // vectors, the total size only needs to be the same. This is a bitcast; 8235 // no bits are changed but the result type is different. 8236 if (isLaxVectorConversion(RHSType, LHSType)) { 8237 Kind = CK_BitCast; 8238 return IncompatibleVectors; 8239 } 8240 } 8241 8242 // When the RHS comes from another lax conversion (e.g. binops between 8243 // scalars and vectors) the result is canonicalized as a vector. When the 8244 // LHS is also a vector, the lax is allowed by the condition above. Handle 8245 // the case where LHS is a scalar. 8246 if (LHSType->isScalarType()) { 8247 const VectorType *VecType = RHSType->getAs<VectorType>(); 8248 if (VecType && VecType->getNumElements() == 1 && 8249 isLaxVectorConversion(RHSType, LHSType)) { 8250 ExprResult *VecExpr = &RHS; 8251 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8252 Kind = CK_BitCast; 8253 return Compatible; 8254 } 8255 } 8256 8257 return Incompatible; 8258 } 8259 8260 // Diagnose attempts to convert between __float128 and long double where 8261 // such conversions currently can't be handled. 8262 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8263 return Incompatible; 8264 8265 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8266 // discards the imaginary part. 8267 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8268 !LHSType->getAs<ComplexType>()) 8269 return Incompatible; 8270 8271 // Arithmetic conversions. 8272 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8273 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8274 if (ConvertRHS) 8275 Kind = PrepareScalarCast(RHS, LHSType); 8276 return Compatible; 8277 } 8278 8279 // Conversions to normal pointers. 8280 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8281 // U* -> T* 8282 if (isa<PointerType>(RHSType)) { 8283 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8284 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8285 if (AddrSpaceL != AddrSpaceR) 8286 Kind = CK_AddressSpaceConversion; 8287 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8288 Kind = CK_NoOp; 8289 else 8290 Kind = CK_BitCast; 8291 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8292 } 8293 8294 // int -> T* 8295 if (RHSType->isIntegerType()) { 8296 Kind = CK_IntegralToPointer; // FIXME: null? 8297 return IntToPointer; 8298 } 8299 8300 // C pointers are not compatible with ObjC object pointers, 8301 // with two exceptions: 8302 if (isa<ObjCObjectPointerType>(RHSType)) { 8303 // - conversions to void* 8304 if (LHSPointer->getPointeeType()->isVoidType()) { 8305 Kind = CK_BitCast; 8306 return Compatible; 8307 } 8308 8309 // - conversions from 'Class' to the redefinition type 8310 if (RHSType->isObjCClassType() && 8311 Context.hasSameType(LHSType, 8312 Context.getObjCClassRedefinitionType())) { 8313 Kind = CK_BitCast; 8314 return Compatible; 8315 } 8316 8317 Kind = CK_BitCast; 8318 return IncompatiblePointer; 8319 } 8320 8321 // U^ -> void* 8322 if (RHSType->getAs<BlockPointerType>()) { 8323 if (LHSPointer->getPointeeType()->isVoidType()) { 8324 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8325 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8326 ->getPointeeType() 8327 .getAddressSpace(); 8328 Kind = 8329 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8330 return Compatible; 8331 } 8332 } 8333 8334 return Incompatible; 8335 } 8336 8337 // Conversions to block pointers. 8338 if (isa<BlockPointerType>(LHSType)) { 8339 // U^ -> T^ 8340 if (RHSType->isBlockPointerType()) { 8341 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8342 ->getPointeeType() 8343 .getAddressSpace(); 8344 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8345 ->getPointeeType() 8346 .getAddressSpace(); 8347 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8348 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8349 } 8350 8351 // int or null -> T^ 8352 if (RHSType->isIntegerType()) { 8353 Kind = CK_IntegralToPointer; // FIXME: null 8354 return IntToBlockPointer; 8355 } 8356 8357 // id -> T^ 8358 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8359 Kind = CK_AnyPointerToBlockPointerCast; 8360 return Compatible; 8361 } 8362 8363 // void* -> T^ 8364 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8365 if (RHSPT->getPointeeType()->isVoidType()) { 8366 Kind = CK_AnyPointerToBlockPointerCast; 8367 return Compatible; 8368 } 8369 8370 return Incompatible; 8371 } 8372 8373 // Conversions to Objective-C pointers. 8374 if (isa<ObjCObjectPointerType>(LHSType)) { 8375 // A* -> B* 8376 if (RHSType->isObjCObjectPointerType()) { 8377 Kind = CK_BitCast; 8378 Sema::AssignConvertType result = 8379 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8380 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8381 result == Compatible && 8382 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8383 result = IncompatibleObjCWeakRef; 8384 return result; 8385 } 8386 8387 // int or null -> A* 8388 if (RHSType->isIntegerType()) { 8389 Kind = CK_IntegralToPointer; // FIXME: null 8390 return IntToPointer; 8391 } 8392 8393 // In general, C pointers are not compatible with ObjC object pointers, 8394 // with two exceptions: 8395 if (isa<PointerType>(RHSType)) { 8396 Kind = CK_CPointerToObjCPointerCast; 8397 8398 // - conversions from 'void*' 8399 if (RHSType->isVoidPointerType()) { 8400 return Compatible; 8401 } 8402 8403 // - conversions to 'Class' from its redefinition type 8404 if (LHSType->isObjCClassType() && 8405 Context.hasSameType(RHSType, 8406 Context.getObjCClassRedefinitionType())) { 8407 return Compatible; 8408 } 8409 8410 return IncompatiblePointer; 8411 } 8412 8413 // Only under strict condition T^ is compatible with an Objective-C pointer. 8414 if (RHSType->isBlockPointerType() && 8415 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8416 if (ConvertRHS) 8417 maybeExtendBlockObject(RHS); 8418 Kind = CK_BlockPointerToObjCPointerCast; 8419 return Compatible; 8420 } 8421 8422 return Incompatible; 8423 } 8424 8425 // Conversions from pointers that are not covered by the above. 8426 if (isa<PointerType>(RHSType)) { 8427 // T* -> _Bool 8428 if (LHSType == Context.BoolTy) { 8429 Kind = CK_PointerToBoolean; 8430 return Compatible; 8431 } 8432 8433 // T* -> int 8434 if (LHSType->isIntegerType()) { 8435 Kind = CK_PointerToIntegral; 8436 return PointerToInt; 8437 } 8438 8439 return Incompatible; 8440 } 8441 8442 // Conversions from Objective-C pointers that are not covered by the above. 8443 if (isa<ObjCObjectPointerType>(RHSType)) { 8444 // T* -> _Bool 8445 if (LHSType == Context.BoolTy) { 8446 Kind = CK_PointerToBoolean; 8447 return Compatible; 8448 } 8449 8450 // T* -> int 8451 if (LHSType->isIntegerType()) { 8452 Kind = CK_PointerToIntegral; 8453 return PointerToInt; 8454 } 8455 8456 return Incompatible; 8457 } 8458 8459 // struct A -> struct B 8460 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8461 if (Context.typesAreCompatible(LHSType, RHSType)) { 8462 Kind = CK_NoOp; 8463 return Compatible; 8464 } 8465 } 8466 8467 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8468 Kind = CK_IntToOCLSampler; 8469 return Compatible; 8470 } 8471 8472 return Incompatible; 8473 } 8474 8475 /// Constructs a transparent union from an expression that is 8476 /// used to initialize the transparent union. 8477 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8478 ExprResult &EResult, QualType UnionType, 8479 FieldDecl *Field) { 8480 // Build an initializer list that designates the appropriate member 8481 // of the transparent union. 8482 Expr *E = EResult.get(); 8483 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8484 E, SourceLocation()); 8485 Initializer->setType(UnionType); 8486 Initializer->setInitializedFieldInUnion(Field); 8487 8488 // Build a compound literal constructing a value of the transparent 8489 // union type from this initializer list. 8490 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8491 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8492 VK_RValue, Initializer, false); 8493 } 8494 8495 Sema::AssignConvertType 8496 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8497 ExprResult &RHS) { 8498 QualType RHSType = RHS.get()->getType(); 8499 8500 // If the ArgType is a Union type, we want to handle a potential 8501 // transparent_union GCC extension. 8502 const RecordType *UT = ArgType->getAsUnionType(); 8503 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8504 return Incompatible; 8505 8506 // The field to initialize within the transparent union. 8507 RecordDecl *UD = UT->getDecl(); 8508 FieldDecl *InitField = nullptr; 8509 // It's compatible if the expression matches any of the fields. 8510 for (auto *it : UD->fields()) { 8511 if (it->getType()->isPointerType()) { 8512 // If the transparent union contains a pointer type, we allow: 8513 // 1) void pointer 8514 // 2) null pointer constant 8515 if (RHSType->isPointerType()) 8516 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8517 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8518 InitField = it; 8519 break; 8520 } 8521 8522 if (RHS.get()->isNullPointerConstant(Context, 8523 Expr::NPC_ValueDependentIsNull)) { 8524 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8525 CK_NullToPointer); 8526 InitField = it; 8527 break; 8528 } 8529 } 8530 8531 CastKind Kind; 8532 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8533 == Compatible) { 8534 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8535 InitField = it; 8536 break; 8537 } 8538 } 8539 8540 if (!InitField) 8541 return Incompatible; 8542 8543 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8544 return Compatible; 8545 } 8546 8547 Sema::AssignConvertType 8548 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8549 bool Diagnose, 8550 bool DiagnoseCFAudited, 8551 bool ConvertRHS) { 8552 // We need to be able to tell the caller whether we diagnosed a problem, if 8553 // they ask us to issue diagnostics. 8554 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8555 8556 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8557 // we can't avoid *all* modifications at the moment, so we need some somewhere 8558 // to put the updated value. 8559 ExprResult LocalRHS = CallerRHS; 8560 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8561 8562 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8563 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8564 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8565 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8566 Diag(RHS.get()->getExprLoc(), 8567 diag::warn_noderef_to_dereferenceable_pointer) 8568 << RHS.get()->getSourceRange(); 8569 } 8570 } 8571 } 8572 8573 if (getLangOpts().CPlusPlus) { 8574 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8575 // C++ 5.17p3: If the left operand is not of class type, the 8576 // expression is implicitly converted (C++ 4) to the 8577 // cv-unqualified type of the left operand. 8578 QualType RHSType = RHS.get()->getType(); 8579 if (Diagnose) { 8580 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8581 AA_Assigning); 8582 } else { 8583 ImplicitConversionSequence ICS = 8584 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8585 /*SuppressUserConversions=*/false, 8586 /*AllowExplicit=*/false, 8587 /*InOverloadResolution=*/false, 8588 /*CStyle=*/false, 8589 /*AllowObjCWritebackConversion=*/false); 8590 if (ICS.isFailure()) 8591 return Incompatible; 8592 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8593 ICS, AA_Assigning); 8594 } 8595 if (RHS.isInvalid()) 8596 return Incompatible; 8597 Sema::AssignConvertType result = Compatible; 8598 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8599 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8600 result = IncompatibleObjCWeakRef; 8601 return result; 8602 } 8603 8604 // FIXME: Currently, we fall through and treat C++ classes like C 8605 // structures. 8606 // FIXME: We also fall through for atomics; not sure what should 8607 // happen there, though. 8608 } else if (RHS.get()->getType() == Context.OverloadTy) { 8609 // As a set of extensions to C, we support overloading on functions. These 8610 // functions need to be resolved here. 8611 DeclAccessPair DAP; 8612 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8613 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8614 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8615 else 8616 return Incompatible; 8617 } 8618 8619 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8620 // a null pointer constant. 8621 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8622 LHSType->isBlockPointerType()) && 8623 RHS.get()->isNullPointerConstant(Context, 8624 Expr::NPC_ValueDependentIsNull)) { 8625 if (Diagnose || ConvertRHS) { 8626 CastKind Kind; 8627 CXXCastPath Path; 8628 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8629 /*IgnoreBaseAccess=*/false, Diagnose); 8630 if (ConvertRHS) 8631 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8632 } 8633 return Compatible; 8634 } 8635 8636 // OpenCL queue_t type assignment. 8637 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8638 Context, Expr::NPC_ValueDependentIsNull)) { 8639 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8640 return Compatible; 8641 } 8642 8643 // This check seems unnatural, however it is necessary to ensure the proper 8644 // conversion of functions/arrays. If the conversion were done for all 8645 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8646 // expressions that suppress this implicit conversion (&, sizeof). 8647 // 8648 // Suppress this for references: C++ 8.5.3p5. 8649 if (!LHSType->isReferenceType()) { 8650 // FIXME: We potentially allocate here even if ConvertRHS is false. 8651 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8652 if (RHS.isInvalid()) 8653 return Incompatible; 8654 } 8655 CastKind Kind; 8656 Sema::AssignConvertType result = 8657 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8658 8659 // C99 6.5.16.1p2: The value of the right operand is converted to the 8660 // type of the assignment expression. 8661 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8662 // so that we can use references in built-in functions even in C. 8663 // The getNonReferenceType() call makes sure that the resulting expression 8664 // does not have reference type. 8665 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8666 QualType Ty = LHSType.getNonLValueExprType(Context); 8667 Expr *E = RHS.get(); 8668 8669 // Check for various Objective-C errors. If we are not reporting 8670 // diagnostics and just checking for errors, e.g., during overload 8671 // resolution, return Incompatible to indicate the failure. 8672 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8673 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8674 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8675 if (!Diagnose) 8676 return Incompatible; 8677 } 8678 if (getLangOpts().ObjC && 8679 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8680 E->getType(), E, Diagnose) || 8681 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8682 if (!Diagnose) 8683 return Incompatible; 8684 // Replace the expression with a corrected version and continue so we 8685 // can find further errors. 8686 RHS = E; 8687 return Compatible; 8688 } 8689 8690 if (ConvertRHS) 8691 RHS = ImpCastExprToType(E, Ty, Kind); 8692 } 8693 8694 return result; 8695 } 8696 8697 namespace { 8698 /// The original operand to an operator, prior to the application of the usual 8699 /// arithmetic conversions and converting the arguments of a builtin operator 8700 /// candidate. 8701 struct OriginalOperand { 8702 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8703 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8704 Op = MTE->GetTemporaryExpr(); 8705 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8706 Op = BTE->getSubExpr(); 8707 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8708 Orig = ICE->getSubExprAsWritten(); 8709 Conversion = ICE->getConversionFunction(); 8710 } 8711 } 8712 8713 QualType getType() const { return Orig->getType(); } 8714 8715 Expr *Orig; 8716 NamedDecl *Conversion; 8717 }; 8718 } 8719 8720 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8721 ExprResult &RHS) { 8722 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8723 8724 Diag(Loc, diag::err_typecheck_invalid_operands) 8725 << OrigLHS.getType() << OrigRHS.getType() 8726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8727 8728 // If a user-defined conversion was applied to either of the operands prior 8729 // to applying the built-in operator rules, tell the user about it. 8730 if (OrigLHS.Conversion) { 8731 Diag(OrigLHS.Conversion->getLocation(), 8732 diag::note_typecheck_invalid_operands_converted) 8733 << 0 << LHS.get()->getType(); 8734 } 8735 if (OrigRHS.Conversion) { 8736 Diag(OrigRHS.Conversion->getLocation(), 8737 diag::note_typecheck_invalid_operands_converted) 8738 << 1 << RHS.get()->getType(); 8739 } 8740 8741 return QualType(); 8742 } 8743 8744 // Diagnose cases where a scalar was implicitly converted to a vector and 8745 // diagnose the underlying types. Otherwise, diagnose the error 8746 // as invalid vector logical operands for non-C++ cases. 8747 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8748 ExprResult &RHS) { 8749 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8750 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8751 8752 bool LHSNatVec = LHSType->isVectorType(); 8753 bool RHSNatVec = RHSType->isVectorType(); 8754 8755 if (!(LHSNatVec && RHSNatVec)) { 8756 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8757 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8758 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8759 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8760 << Vector->getSourceRange(); 8761 return QualType(); 8762 } 8763 8764 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8765 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8766 << RHS.get()->getSourceRange(); 8767 8768 return QualType(); 8769 } 8770 8771 /// Try to convert a value of non-vector type to a vector type by converting 8772 /// the type to the element type of the vector and then performing a splat. 8773 /// If the language is OpenCL, we only use conversions that promote scalar 8774 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8775 /// for float->int. 8776 /// 8777 /// OpenCL V2.0 6.2.6.p2: 8778 /// An error shall occur if any scalar operand type has greater rank 8779 /// than the type of the vector element. 8780 /// 8781 /// \param scalar - if non-null, actually perform the conversions 8782 /// \return true if the operation fails (but without diagnosing the failure) 8783 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8784 QualType scalarTy, 8785 QualType vectorEltTy, 8786 QualType vectorTy, 8787 unsigned &DiagID) { 8788 // The conversion to apply to the scalar before splatting it, 8789 // if necessary. 8790 CastKind scalarCast = CK_NoOp; 8791 8792 if (vectorEltTy->isIntegralType(S.Context)) { 8793 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8794 (scalarTy->isIntegerType() && 8795 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8796 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8797 return true; 8798 } 8799 if (!scalarTy->isIntegralType(S.Context)) 8800 return true; 8801 scalarCast = CK_IntegralCast; 8802 } else if (vectorEltTy->isRealFloatingType()) { 8803 if (scalarTy->isRealFloatingType()) { 8804 if (S.getLangOpts().OpenCL && 8805 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8806 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8807 return true; 8808 } 8809 scalarCast = CK_FloatingCast; 8810 } 8811 else if (scalarTy->isIntegralType(S.Context)) 8812 scalarCast = CK_IntegralToFloating; 8813 else 8814 return true; 8815 } else { 8816 return true; 8817 } 8818 8819 // Adjust scalar if desired. 8820 if (scalar) { 8821 if (scalarCast != CK_NoOp) 8822 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8823 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8824 } 8825 return false; 8826 } 8827 8828 /// Convert vector E to a vector with the same number of elements but different 8829 /// element type. 8830 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8831 const auto *VecTy = E->getType()->getAs<VectorType>(); 8832 assert(VecTy && "Expression E must be a vector"); 8833 QualType NewVecTy = S.Context.getVectorType(ElementType, 8834 VecTy->getNumElements(), 8835 VecTy->getVectorKind()); 8836 8837 // Look through the implicit cast. Return the subexpression if its type is 8838 // NewVecTy. 8839 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8840 if (ICE->getSubExpr()->getType() == NewVecTy) 8841 return ICE->getSubExpr(); 8842 8843 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8844 return S.ImpCastExprToType(E, NewVecTy, Cast); 8845 } 8846 8847 /// Test if a (constant) integer Int can be casted to another integer type 8848 /// IntTy without losing precision. 8849 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8850 QualType OtherIntTy) { 8851 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8852 8853 // Reject cases where the value of the Int is unknown as that would 8854 // possibly cause truncation, but accept cases where the scalar can be 8855 // demoted without loss of precision. 8856 Expr::EvalResult EVResult; 8857 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8858 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8859 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8860 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8861 8862 if (CstInt) { 8863 // If the scalar is constant and is of a higher order and has more active 8864 // bits that the vector element type, reject it. 8865 llvm::APSInt Result = EVResult.Val.getInt(); 8866 unsigned NumBits = IntSigned 8867 ? (Result.isNegative() ? Result.getMinSignedBits() 8868 : Result.getActiveBits()) 8869 : Result.getActiveBits(); 8870 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8871 return true; 8872 8873 // If the signedness of the scalar type and the vector element type 8874 // differs and the number of bits is greater than that of the vector 8875 // element reject it. 8876 return (IntSigned != OtherIntSigned && 8877 NumBits > S.Context.getIntWidth(OtherIntTy)); 8878 } 8879 8880 // Reject cases where the value of the scalar is not constant and it's 8881 // order is greater than that of the vector element type. 8882 return (Order < 0); 8883 } 8884 8885 /// Test if a (constant) integer Int can be casted to floating point type 8886 /// FloatTy without losing precision. 8887 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8888 QualType FloatTy) { 8889 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8890 8891 // Determine if the integer constant can be expressed as a floating point 8892 // number of the appropriate type. 8893 Expr::EvalResult EVResult; 8894 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8895 8896 uint64_t Bits = 0; 8897 if (CstInt) { 8898 // Reject constants that would be truncated if they were converted to 8899 // the floating point type. Test by simple to/from conversion. 8900 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8901 // could be avoided if there was a convertFromAPInt method 8902 // which could signal back if implicit truncation occurred. 8903 llvm::APSInt Result = EVResult.Val.getInt(); 8904 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8905 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8906 llvm::APFloat::rmTowardZero); 8907 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8908 !IntTy->hasSignedIntegerRepresentation()); 8909 bool Ignored = false; 8910 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8911 &Ignored); 8912 if (Result != ConvertBack) 8913 return true; 8914 } else { 8915 // Reject types that cannot be fully encoded into the mantissa of 8916 // the float. 8917 Bits = S.Context.getTypeSize(IntTy); 8918 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8919 S.Context.getFloatTypeSemantics(FloatTy)); 8920 if (Bits > FloatPrec) 8921 return true; 8922 } 8923 8924 return false; 8925 } 8926 8927 /// Attempt to convert and splat Scalar into a vector whose types matches 8928 /// Vector following GCC conversion rules. The rule is that implicit 8929 /// conversion can occur when Scalar can be casted to match Vector's element 8930 /// type without causing truncation of Scalar. 8931 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8932 ExprResult *Vector) { 8933 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8934 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8935 const VectorType *VT = VectorTy->getAs<VectorType>(); 8936 8937 assert(!isa<ExtVectorType>(VT) && 8938 "ExtVectorTypes should not be handled here!"); 8939 8940 QualType VectorEltTy = VT->getElementType(); 8941 8942 // Reject cases where the vector element type or the scalar element type are 8943 // not integral or floating point types. 8944 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8945 return true; 8946 8947 // The conversion to apply to the scalar before splatting it, 8948 // if necessary. 8949 CastKind ScalarCast = CK_NoOp; 8950 8951 // Accept cases where the vector elements are integers and the scalar is 8952 // an integer. 8953 // FIXME: Notionally if the scalar was a floating point value with a precise 8954 // integral representation, we could cast it to an appropriate integer 8955 // type and then perform the rest of the checks here. GCC will perform 8956 // this conversion in some cases as determined by the input language. 8957 // We should accept it on a language independent basis. 8958 if (VectorEltTy->isIntegralType(S.Context) && 8959 ScalarTy->isIntegralType(S.Context) && 8960 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8961 8962 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8963 return true; 8964 8965 ScalarCast = CK_IntegralCast; 8966 } else if (VectorEltTy->isRealFloatingType()) { 8967 if (ScalarTy->isRealFloatingType()) { 8968 8969 // Reject cases where the scalar type is not a constant and has a higher 8970 // Order than the vector element type. 8971 llvm::APFloat Result(0.0); 8972 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8973 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8974 if (!CstScalar && Order < 0) 8975 return true; 8976 8977 // If the scalar cannot be safely casted to the vector element type, 8978 // reject it. 8979 if (CstScalar) { 8980 bool Truncated = false; 8981 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8982 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8983 if (Truncated) 8984 return true; 8985 } 8986 8987 ScalarCast = CK_FloatingCast; 8988 } else if (ScalarTy->isIntegralType(S.Context)) { 8989 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8990 return true; 8991 8992 ScalarCast = CK_IntegralToFloating; 8993 } else 8994 return true; 8995 } 8996 8997 // Adjust scalar if desired. 8998 if (Scalar) { 8999 if (ScalarCast != CK_NoOp) 9000 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9001 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9002 } 9003 return false; 9004 } 9005 9006 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9007 SourceLocation Loc, bool IsCompAssign, 9008 bool AllowBothBool, 9009 bool AllowBoolConversions) { 9010 if (!IsCompAssign) { 9011 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9012 if (LHS.isInvalid()) 9013 return QualType(); 9014 } 9015 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9016 if (RHS.isInvalid()) 9017 return QualType(); 9018 9019 // For conversion purposes, we ignore any qualifiers. 9020 // For example, "const float" and "float" are equivalent. 9021 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9022 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9023 9024 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9025 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9026 assert(LHSVecType || RHSVecType); 9027 9028 // AltiVec-style "vector bool op vector bool" combinations are allowed 9029 // for some operators but not others. 9030 if (!AllowBothBool && 9031 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9032 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9033 return InvalidOperands(Loc, LHS, RHS); 9034 9035 // If the vector types are identical, return. 9036 if (Context.hasSameType(LHSType, RHSType)) 9037 return LHSType; 9038 9039 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9040 if (LHSVecType && RHSVecType && 9041 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9042 if (isa<ExtVectorType>(LHSVecType)) { 9043 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9044 return LHSType; 9045 } 9046 9047 if (!IsCompAssign) 9048 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9049 return RHSType; 9050 } 9051 9052 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9053 // can be mixed, with the result being the non-bool type. The non-bool 9054 // operand must have integer element type. 9055 if (AllowBoolConversions && LHSVecType && RHSVecType && 9056 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9057 (Context.getTypeSize(LHSVecType->getElementType()) == 9058 Context.getTypeSize(RHSVecType->getElementType()))) { 9059 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9060 LHSVecType->getElementType()->isIntegerType() && 9061 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9062 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9063 return LHSType; 9064 } 9065 if (!IsCompAssign && 9066 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9067 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9068 RHSVecType->getElementType()->isIntegerType()) { 9069 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9070 return RHSType; 9071 } 9072 } 9073 9074 // If there's a vector type and a scalar, try to convert the scalar to 9075 // the vector element type and splat. 9076 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9077 if (!RHSVecType) { 9078 if (isa<ExtVectorType>(LHSVecType)) { 9079 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9080 LHSVecType->getElementType(), LHSType, 9081 DiagID)) 9082 return LHSType; 9083 } else { 9084 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9085 return LHSType; 9086 } 9087 } 9088 if (!LHSVecType) { 9089 if (isa<ExtVectorType>(RHSVecType)) { 9090 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9091 LHSType, RHSVecType->getElementType(), 9092 RHSType, DiagID)) 9093 return RHSType; 9094 } else { 9095 if (LHS.get()->getValueKind() == VK_LValue || 9096 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9097 return RHSType; 9098 } 9099 } 9100 9101 // FIXME: The code below also handles conversion between vectors and 9102 // non-scalars, we should break this down into fine grained specific checks 9103 // and emit proper diagnostics. 9104 QualType VecType = LHSVecType ? LHSType : RHSType; 9105 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9106 QualType OtherType = LHSVecType ? RHSType : LHSType; 9107 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9108 if (isLaxVectorConversion(OtherType, VecType)) { 9109 // If we're allowing lax vector conversions, only the total (data) size 9110 // needs to be the same. For non compound assignment, if one of the types is 9111 // scalar, the result is always the vector type. 9112 if (!IsCompAssign) { 9113 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9114 return VecType; 9115 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9116 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9117 // type. Note that this is already done by non-compound assignments in 9118 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9119 // <1 x T> -> T. The result is also a vector type. 9120 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9121 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9122 ExprResult *RHSExpr = &RHS; 9123 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9124 return VecType; 9125 } 9126 } 9127 9128 // Okay, the expression is invalid. 9129 9130 // If there's a non-vector, non-real operand, diagnose that. 9131 if ((!RHSVecType && !RHSType->isRealType()) || 9132 (!LHSVecType && !LHSType->isRealType())) { 9133 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9134 << LHSType << RHSType 9135 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9136 return QualType(); 9137 } 9138 9139 // OpenCL V1.1 6.2.6.p1: 9140 // If the operands are of more than one vector type, then an error shall 9141 // occur. Implicit conversions between vector types are not permitted, per 9142 // section 6.2.1. 9143 if (getLangOpts().OpenCL && 9144 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9145 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9146 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9147 << RHSType; 9148 return QualType(); 9149 } 9150 9151 9152 // If there is a vector type that is not a ExtVector and a scalar, we reach 9153 // this point if scalar could not be converted to the vector's element type 9154 // without truncation. 9155 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9156 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9157 QualType Scalar = LHSVecType ? RHSType : LHSType; 9158 QualType Vector = LHSVecType ? LHSType : RHSType; 9159 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9160 Diag(Loc, 9161 diag::err_typecheck_vector_not_convertable_implict_truncation) 9162 << ScalarOrVector << Scalar << Vector; 9163 9164 return QualType(); 9165 } 9166 9167 // Otherwise, use the generic diagnostic. 9168 Diag(Loc, DiagID) 9169 << LHSType << RHSType 9170 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9171 return QualType(); 9172 } 9173 9174 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9175 // expression. These are mainly cases where the null pointer is used as an 9176 // integer instead of a pointer. 9177 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9178 SourceLocation Loc, bool IsCompare) { 9179 // The canonical way to check for a GNU null is with isNullPointerConstant, 9180 // but we use a bit of a hack here for speed; this is a relatively 9181 // hot path, and isNullPointerConstant is slow. 9182 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9183 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9184 9185 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9186 9187 // Avoid analyzing cases where the result will either be invalid (and 9188 // diagnosed as such) or entirely valid and not something to warn about. 9189 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9190 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9191 return; 9192 9193 // Comparison operations would not make sense with a null pointer no matter 9194 // what the other expression is. 9195 if (!IsCompare) { 9196 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9197 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9198 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9199 return; 9200 } 9201 9202 // The rest of the operations only make sense with a null pointer 9203 // if the other expression is a pointer. 9204 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9205 NonNullType->canDecayToPointerType()) 9206 return; 9207 9208 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9209 << LHSNull /* LHS is NULL */ << NonNullType 9210 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9211 } 9212 9213 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9214 SourceLocation Loc) { 9215 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9216 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9217 if (!LUE || !RUE) 9218 return; 9219 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9220 RUE->getKind() != UETT_SizeOf) 9221 return; 9222 9223 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9224 QualType LHSTy = LHSArg->getType(); 9225 QualType RHSTy; 9226 9227 if (RUE->isArgumentType()) 9228 RHSTy = RUE->getArgumentType(); 9229 else 9230 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9231 9232 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9233 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9234 return; 9235 9236 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9237 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9238 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9239 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9240 << LHSArgDecl; 9241 } 9242 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9243 QualType ArrayElemTy = ArrayTy->getElementType(); 9244 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9245 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9246 ArrayElemTy->isCharType() || 9247 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9248 return; 9249 S.Diag(Loc, diag::warn_division_sizeof_array) 9250 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9251 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9252 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9253 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9254 << LHSArgDecl; 9255 } 9256 9257 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9258 } 9259 } 9260 9261 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9262 ExprResult &RHS, 9263 SourceLocation Loc, bool IsDiv) { 9264 // Check for division/remainder by zero. 9265 Expr::EvalResult RHSValue; 9266 if (!RHS.get()->isValueDependent() && 9267 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9268 RHSValue.Val.getInt() == 0) 9269 S.DiagRuntimeBehavior(Loc, RHS.get(), 9270 S.PDiag(diag::warn_remainder_division_by_zero) 9271 << IsDiv << RHS.get()->getSourceRange()); 9272 } 9273 9274 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9275 SourceLocation Loc, 9276 bool IsCompAssign, bool IsDiv) { 9277 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9278 9279 if (LHS.get()->getType()->isVectorType() || 9280 RHS.get()->getType()->isVectorType()) 9281 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9282 /*AllowBothBool*/getLangOpts().AltiVec, 9283 /*AllowBoolConversions*/false); 9284 9285 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9286 if (LHS.isInvalid() || RHS.isInvalid()) 9287 return QualType(); 9288 9289 9290 if (compType.isNull() || !compType->isArithmeticType()) 9291 return InvalidOperands(Loc, LHS, RHS); 9292 if (IsDiv) { 9293 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9294 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9295 } 9296 return compType; 9297 } 9298 9299 QualType Sema::CheckRemainderOperands( 9300 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9301 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9302 9303 if (LHS.get()->getType()->isVectorType() || 9304 RHS.get()->getType()->isVectorType()) { 9305 if (LHS.get()->getType()->hasIntegerRepresentation() && 9306 RHS.get()->getType()->hasIntegerRepresentation()) 9307 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9308 /*AllowBothBool*/getLangOpts().AltiVec, 9309 /*AllowBoolConversions*/false); 9310 return InvalidOperands(Loc, LHS, RHS); 9311 } 9312 9313 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9314 if (LHS.isInvalid() || RHS.isInvalid()) 9315 return QualType(); 9316 9317 if (compType.isNull() || !compType->isIntegerType()) 9318 return InvalidOperands(Loc, LHS, RHS); 9319 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9320 return compType; 9321 } 9322 9323 /// Diagnose invalid arithmetic on two void pointers. 9324 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9325 Expr *LHSExpr, Expr *RHSExpr) { 9326 S.Diag(Loc, S.getLangOpts().CPlusPlus 9327 ? diag::err_typecheck_pointer_arith_void_type 9328 : diag::ext_gnu_void_ptr) 9329 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9330 << RHSExpr->getSourceRange(); 9331 } 9332 9333 /// Diagnose invalid arithmetic on a void pointer. 9334 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9335 Expr *Pointer) { 9336 S.Diag(Loc, S.getLangOpts().CPlusPlus 9337 ? diag::err_typecheck_pointer_arith_void_type 9338 : diag::ext_gnu_void_ptr) 9339 << 0 /* one pointer */ << Pointer->getSourceRange(); 9340 } 9341 9342 /// Diagnose invalid arithmetic on a null pointer. 9343 /// 9344 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9345 /// idiom, which we recognize as a GNU extension. 9346 /// 9347 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9348 Expr *Pointer, bool IsGNUIdiom) { 9349 if (IsGNUIdiom) 9350 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9351 << Pointer->getSourceRange(); 9352 else 9353 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9354 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9355 } 9356 9357 /// Diagnose invalid arithmetic on two function pointers. 9358 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9359 Expr *LHS, Expr *RHS) { 9360 assert(LHS->getType()->isAnyPointerType()); 9361 assert(RHS->getType()->isAnyPointerType()); 9362 S.Diag(Loc, S.getLangOpts().CPlusPlus 9363 ? diag::err_typecheck_pointer_arith_function_type 9364 : diag::ext_gnu_ptr_func_arith) 9365 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9366 // We only show the second type if it differs from the first. 9367 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9368 RHS->getType()) 9369 << RHS->getType()->getPointeeType() 9370 << LHS->getSourceRange() << RHS->getSourceRange(); 9371 } 9372 9373 /// Diagnose invalid arithmetic on a function pointer. 9374 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9375 Expr *Pointer) { 9376 assert(Pointer->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 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9381 << 0 /* one pointer, so only one type */ 9382 << Pointer->getSourceRange(); 9383 } 9384 9385 /// Emit error if Operand is incomplete pointer type 9386 /// 9387 /// \returns True if pointer has incomplete type 9388 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9389 Expr *Operand) { 9390 QualType ResType = Operand->getType(); 9391 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9392 ResType = ResAtomicType->getValueType(); 9393 9394 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9395 QualType PointeeTy = ResType->getPointeeType(); 9396 return S.RequireCompleteType(Loc, PointeeTy, 9397 diag::err_typecheck_arithmetic_incomplete_type, 9398 PointeeTy, Operand->getSourceRange()); 9399 } 9400 9401 /// Check the validity of an arithmetic pointer operand. 9402 /// 9403 /// If the operand has pointer type, this code will check for pointer types 9404 /// which are invalid in arithmetic operations. These will be diagnosed 9405 /// appropriately, including whether or not the use is supported as an 9406 /// extension. 9407 /// 9408 /// \returns True when the operand is valid to use (even if as an extension). 9409 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9410 Expr *Operand) { 9411 QualType ResType = Operand->getType(); 9412 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9413 ResType = ResAtomicType->getValueType(); 9414 9415 if (!ResType->isAnyPointerType()) return true; 9416 9417 QualType PointeeTy = ResType->getPointeeType(); 9418 if (PointeeTy->isVoidType()) { 9419 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9420 return !S.getLangOpts().CPlusPlus; 9421 } 9422 if (PointeeTy->isFunctionType()) { 9423 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9424 return !S.getLangOpts().CPlusPlus; 9425 } 9426 9427 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9428 9429 return true; 9430 } 9431 9432 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9433 /// operands. 9434 /// 9435 /// This routine will diagnose any invalid arithmetic on pointer operands much 9436 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9437 /// for emitting a single diagnostic even for operations where both LHS and RHS 9438 /// are (potentially problematic) pointers. 9439 /// 9440 /// \returns True when the operand is valid to use (even if as an extension). 9441 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9442 Expr *LHSExpr, Expr *RHSExpr) { 9443 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9444 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9445 if (!isLHSPointer && !isRHSPointer) return true; 9446 9447 QualType LHSPointeeTy, RHSPointeeTy; 9448 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9449 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9450 9451 // if both are pointers check if operation is valid wrt address spaces 9452 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9453 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9454 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9455 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9456 S.Diag(Loc, 9457 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9458 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9459 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9460 return false; 9461 } 9462 } 9463 9464 // Check for arithmetic on pointers to incomplete types. 9465 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9466 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9467 if (isLHSVoidPtr || isRHSVoidPtr) { 9468 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9469 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9470 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9471 9472 return !S.getLangOpts().CPlusPlus; 9473 } 9474 9475 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9476 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9477 if (isLHSFuncPtr || isRHSFuncPtr) { 9478 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9479 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9480 RHSExpr); 9481 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9482 9483 return !S.getLangOpts().CPlusPlus; 9484 } 9485 9486 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9487 return false; 9488 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9489 return false; 9490 9491 return true; 9492 } 9493 9494 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9495 /// literal. 9496 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9497 Expr *LHSExpr, Expr *RHSExpr) { 9498 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9499 Expr* IndexExpr = RHSExpr; 9500 if (!StrExpr) { 9501 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9502 IndexExpr = LHSExpr; 9503 } 9504 9505 bool IsStringPlusInt = StrExpr && 9506 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9507 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9508 return; 9509 9510 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9511 Self.Diag(OpLoc, diag::warn_string_plus_int) 9512 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9513 9514 // Only print a fixit for "str" + int, not for int + "str". 9515 if (IndexExpr == RHSExpr) { 9516 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9517 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9518 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9519 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9520 << FixItHint::CreateInsertion(EndLoc, "]"); 9521 } else 9522 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9523 } 9524 9525 /// Emit a warning when adding a char literal to a string. 9526 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9527 Expr *LHSExpr, Expr *RHSExpr) { 9528 const Expr *StringRefExpr = LHSExpr; 9529 const CharacterLiteral *CharExpr = 9530 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9531 9532 if (!CharExpr) { 9533 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9534 StringRefExpr = RHSExpr; 9535 } 9536 9537 if (!CharExpr || !StringRefExpr) 9538 return; 9539 9540 const QualType StringType = StringRefExpr->getType(); 9541 9542 // Return if not a PointerType. 9543 if (!StringType->isAnyPointerType()) 9544 return; 9545 9546 // Return if not a CharacterType. 9547 if (!StringType->getPointeeType()->isAnyCharacterType()) 9548 return; 9549 9550 ASTContext &Ctx = Self.getASTContext(); 9551 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9552 9553 const QualType CharType = CharExpr->getType(); 9554 if (!CharType->isAnyCharacterType() && 9555 CharType->isIntegerType() && 9556 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9557 Self.Diag(OpLoc, diag::warn_string_plus_char) 9558 << DiagRange << Ctx.CharTy; 9559 } else { 9560 Self.Diag(OpLoc, diag::warn_string_plus_char) 9561 << DiagRange << CharExpr->getType(); 9562 } 9563 9564 // Only print a fixit for str + char, not for char + str. 9565 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9566 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9567 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9568 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9569 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9570 << FixItHint::CreateInsertion(EndLoc, "]"); 9571 } else { 9572 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9573 } 9574 } 9575 9576 /// Emit error when two pointers are incompatible. 9577 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9578 Expr *LHSExpr, Expr *RHSExpr) { 9579 assert(LHSExpr->getType()->isAnyPointerType()); 9580 assert(RHSExpr->getType()->isAnyPointerType()); 9581 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9582 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9583 << RHSExpr->getSourceRange(); 9584 } 9585 9586 // C99 6.5.6 9587 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9588 SourceLocation Loc, BinaryOperatorKind Opc, 9589 QualType* CompLHSTy) { 9590 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9591 9592 if (LHS.get()->getType()->isVectorType() || 9593 RHS.get()->getType()->isVectorType()) { 9594 QualType compType = CheckVectorOperands( 9595 LHS, RHS, Loc, CompLHSTy, 9596 /*AllowBothBool*/getLangOpts().AltiVec, 9597 /*AllowBoolConversions*/getLangOpts().ZVector); 9598 if (CompLHSTy) *CompLHSTy = compType; 9599 return compType; 9600 } 9601 9602 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9603 if (LHS.isInvalid() || RHS.isInvalid()) 9604 return QualType(); 9605 9606 // Diagnose "string literal" '+' int and string '+' "char literal". 9607 if (Opc == BO_Add) { 9608 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9609 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9610 } 9611 9612 // handle the common case first (both operands are arithmetic). 9613 if (!compType.isNull() && compType->isArithmeticType()) { 9614 if (CompLHSTy) *CompLHSTy = compType; 9615 return compType; 9616 } 9617 9618 // Type-checking. Ultimately the pointer's going to be in PExp; 9619 // note that we bias towards the LHS being the pointer. 9620 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9621 9622 bool isObjCPointer; 9623 if (PExp->getType()->isPointerType()) { 9624 isObjCPointer = false; 9625 } else if (PExp->getType()->isObjCObjectPointerType()) { 9626 isObjCPointer = true; 9627 } else { 9628 std::swap(PExp, IExp); 9629 if (PExp->getType()->isPointerType()) { 9630 isObjCPointer = false; 9631 } else if (PExp->getType()->isObjCObjectPointerType()) { 9632 isObjCPointer = true; 9633 } else { 9634 return InvalidOperands(Loc, LHS, RHS); 9635 } 9636 } 9637 assert(PExp->getType()->isAnyPointerType()); 9638 9639 if (!IExp->getType()->isIntegerType()) 9640 return InvalidOperands(Loc, LHS, RHS); 9641 9642 // Adding to a null pointer results in undefined behavior. 9643 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9644 Context, Expr::NPC_ValueDependentIsNotNull)) { 9645 // In C++ adding zero to a null pointer is defined. 9646 Expr::EvalResult KnownVal; 9647 if (!getLangOpts().CPlusPlus || 9648 (!IExp->isValueDependent() && 9649 (!IExp->EvaluateAsInt(KnownVal, Context) || 9650 KnownVal.Val.getInt() != 0))) { 9651 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9652 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9653 Context, BO_Add, PExp, IExp); 9654 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9655 } 9656 } 9657 9658 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9659 return QualType(); 9660 9661 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9662 return QualType(); 9663 9664 // Check array bounds for pointer arithemtic 9665 CheckArrayAccess(PExp, IExp); 9666 9667 if (CompLHSTy) { 9668 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9669 if (LHSTy.isNull()) { 9670 LHSTy = LHS.get()->getType(); 9671 if (LHSTy->isPromotableIntegerType()) 9672 LHSTy = Context.getPromotedIntegerType(LHSTy); 9673 } 9674 *CompLHSTy = LHSTy; 9675 } 9676 9677 return PExp->getType(); 9678 } 9679 9680 // C99 6.5.6 9681 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9682 SourceLocation Loc, 9683 QualType* CompLHSTy) { 9684 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9685 9686 if (LHS.get()->getType()->isVectorType() || 9687 RHS.get()->getType()->isVectorType()) { 9688 QualType compType = CheckVectorOperands( 9689 LHS, RHS, Loc, CompLHSTy, 9690 /*AllowBothBool*/getLangOpts().AltiVec, 9691 /*AllowBoolConversions*/getLangOpts().ZVector); 9692 if (CompLHSTy) *CompLHSTy = compType; 9693 return compType; 9694 } 9695 9696 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9697 if (LHS.isInvalid() || RHS.isInvalid()) 9698 return QualType(); 9699 9700 // Enforce type constraints: C99 6.5.6p3. 9701 9702 // Handle the common case first (both operands are arithmetic). 9703 if (!compType.isNull() && compType->isArithmeticType()) { 9704 if (CompLHSTy) *CompLHSTy = compType; 9705 return compType; 9706 } 9707 9708 // Either ptr - int or ptr - ptr. 9709 if (LHS.get()->getType()->isAnyPointerType()) { 9710 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9711 9712 // Diagnose bad cases where we step over interface counts. 9713 if (LHS.get()->getType()->isObjCObjectPointerType() && 9714 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9715 return QualType(); 9716 9717 // The result type of a pointer-int computation is the pointer type. 9718 if (RHS.get()->getType()->isIntegerType()) { 9719 // Subtracting from a null pointer should produce a warning. 9720 // The last argument to the diagnose call says this doesn't match the 9721 // GNU int-to-pointer idiom. 9722 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9723 Expr::NPC_ValueDependentIsNotNull)) { 9724 // In C++ adding zero to a null pointer is defined. 9725 Expr::EvalResult KnownVal; 9726 if (!getLangOpts().CPlusPlus || 9727 (!RHS.get()->isValueDependent() && 9728 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9729 KnownVal.Val.getInt() != 0))) { 9730 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9731 } 9732 } 9733 9734 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9735 return QualType(); 9736 9737 // Check array bounds for pointer arithemtic 9738 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9739 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9740 9741 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9742 return LHS.get()->getType(); 9743 } 9744 9745 // Handle pointer-pointer subtractions. 9746 if (const PointerType *RHSPTy 9747 = RHS.get()->getType()->getAs<PointerType>()) { 9748 QualType rpointee = RHSPTy->getPointeeType(); 9749 9750 if (getLangOpts().CPlusPlus) { 9751 // Pointee types must be the same: C++ [expr.add] 9752 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9753 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9754 } 9755 } else { 9756 // Pointee types must be compatible C99 6.5.6p3 9757 if (!Context.typesAreCompatible( 9758 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9759 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9760 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9761 return QualType(); 9762 } 9763 } 9764 9765 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9766 LHS.get(), RHS.get())) 9767 return QualType(); 9768 9769 // FIXME: Add warnings for nullptr - ptr. 9770 9771 // The pointee type may have zero size. As an extension, a structure or 9772 // union may have zero size or an array may have zero length. In this 9773 // case subtraction does not make sense. 9774 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9775 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9776 if (ElementSize.isZero()) { 9777 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9778 << rpointee.getUnqualifiedType() 9779 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9780 } 9781 } 9782 9783 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9784 return Context.getPointerDiffType(); 9785 } 9786 } 9787 9788 return InvalidOperands(Loc, LHS, RHS); 9789 } 9790 9791 static bool isScopedEnumerationType(QualType T) { 9792 if (const EnumType *ET = T->getAs<EnumType>()) 9793 return ET->getDecl()->isScoped(); 9794 return false; 9795 } 9796 9797 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9798 SourceLocation Loc, BinaryOperatorKind Opc, 9799 QualType LHSType) { 9800 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9801 // so skip remaining warnings as we don't want to modify values within Sema. 9802 if (S.getLangOpts().OpenCL) 9803 return; 9804 9805 // Check right/shifter operand 9806 Expr::EvalResult RHSResult; 9807 if (RHS.get()->isValueDependent() || 9808 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9809 return; 9810 llvm::APSInt Right = RHSResult.Val.getInt(); 9811 9812 if (Right.isNegative()) { 9813 S.DiagRuntimeBehavior(Loc, RHS.get(), 9814 S.PDiag(diag::warn_shift_negative) 9815 << RHS.get()->getSourceRange()); 9816 return; 9817 } 9818 llvm::APInt LeftBits(Right.getBitWidth(), 9819 S.Context.getTypeSize(LHS.get()->getType())); 9820 if (Right.uge(LeftBits)) { 9821 S.DiagRuntimeBehavior(Loc, RHS.get(), 9822 S.PDiag(diag::warn_shift_gt_typewidth) 9823 << RHS.get()->getSourceRange()); 9824 return; 9825 } 9826 if (Opc != BO_Shl) 9827 return; 9828 9829 // When left shifting an ICE which is signed, we can check for overflow which 9830 // according to C++ standards prior to C++2a has undefined behavior 9831 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9832 // more than the maximum value representable in the result type, so never 9833 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9834 // expression is still probably a bug.) 9835 Expr::EvalResult LHSResult; 9836 if (LHS.get()->isValueDependent() || 9837 LHSType->hasUnsignedIntegerRepresentation() || 9838 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9839 return; 9840 llvm::APSInt Left = LHSResult.Val.getInt(); 9841 9842 // If LHS does not have a signed type and non-negative value 9843 // then, the behavior is undefined before C++2a. Warn about it. 9844 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9845 !S.getLangOpts().CPlusPlus2a) { 9846 S.DiagRuntimeBehavior(Loc, LHS.get(), 9847 S.PDiag(diag::warn_shift_lhs_negative) 9848 << LHS.get()->getSourceRange()); 9849 return; 9850 } 9851 9852 llvm::APInt ResultBits = 9853 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9854 if (LeftBits.uge(ResultBits)) 9855 return; 9856 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9857 Result = Result.shl(Right); 9858 9859 // Print the bit representation of the signed integer as an unsigned 9860 // hexadecimal number. 9861 SmallString<40> HexResult; 9862 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9863 9864 // If we are only missing a sign bit, this is less likely to result in actual 9865 // bugs -- if the result is cast back to an unsigned type, it will have the 9866 // expected value. Thus we place this behind a different warning that can be 9867 // turned off separately if needed. 9868 if (LeftBits == ResultBits - 1) { 9869 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9870 << HexResult << LHSType 9871 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9872 return; 9873 } 9874 9875 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9876 << HexResult.str() << Result.getMinSignedBits() << LHSType 9877 << Left.getBitWidth() << LHS.get()->getSourceRange() 9878 << RHS.get()->getSourceRange(); 9879 } 9880 9881 /// Return the resulting type when a vector is shifted 9882 /// by a scalar or vector shift amount. 9883 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9884 SourceLocation Loc, bool IsCompAssign) { 9885 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9886 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9887 !LHS.get()->getType()->isVectorType()) { 9888 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9889 << RHS.get()->getType() << LHS.get()->getType() 9890 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9891 return QualType(); 9892 } 9893 9894 if (!IsCompAssign) { 9895 LHS = S.UsualUnaryConversions(LHS.get()); 9896 if (LHS.isInvalid()) return QualType(); 9897 } 9898 9899 RHS = S.UsualUnaryConversions(RHS.get()); 9900 if (RHS.isInvalid()) return QualType(); 9901 9902 QualType LHSType = LHS.get()->getType(); 9903 // Note that LHS might be a scalar because the routine calls not only in 9904 // OpenCL case. 9905 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9906 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9907 9908 // Note that RHS might not be a vector. 9909 QualType RHSType = RHS.get()->getType(); 9910 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9911 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9912 9913 // The operands need to be integers. 9914 if (!LHSEleType->isIntegerType()) { 9915 S.Diag(Loc, diag::err_typecheck_expect_int) 9916 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9917 return QualType(); 9918 } 9919 9920 if (!RHSEleType->isIntegerType()) { 9921 S.Diag(Loc, diag::err_typecheck_expect_int) 9922 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9923 return QualType(); 9924 } 9925 9926 if (!LHSVecTy) { 9927 assert(RHSVecTy); 9928 if (IsCompAssign) 9929 return RHSType; 9930 if (LHSEleType != RHSEleType) { 9931 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9932 LHSEleType = RHSEleType; 9933 } 9934 QualType VecTy = 9935 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9936 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9937 LHSType = VecTy; 9938 } else if (RHSVecTy) { 9939 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9940 // are applied component-wise. So if RHS is a vector, then ensure 9941 // that the number of elements is the same as LHS... 9942 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9943 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9944 << LHS.get()->getType() << RHS.get()->getType() 9945 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9946 return QualType(); 9947 } 9948 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9949 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9950 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9951 if (LHSBT != RHSBT && 9952 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9953 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9954 << LHS.get()->getType() << RHS.get()->getType() 9955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9956 } 9957 } 9958 } else { 9959 // ...else expand RHS to match the number of elements in LHS. 9960 QualType VecTy = 9961 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9962 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9963 } 9964 9965 return LHSType; 9966 } 9967 9968 // C99 6.5.7 9969 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9970 SourceLocation Loc, BinaryOperatorKind Opc, 9971 bool IsCompAssign) { 9972 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9973 9974 // Vector shifts promote their scalar inputs to vector type. 9975 if (LHS.get()->getType()->isVectorType() || 9976 RHS.get()->getType()->isVectorType()) { 9977 if (LangOpts.ZVector) { 9978 // The shift operators for the z vector extensions work basically 9979 // like general shifts, except that neither the LHS nor the RHS is 9980 // allowed to be a "vector bool". 9981 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9982 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9983 return InvalidOperands(Loc, LHS, RHS); 9984 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9985 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9986 return InvalidOperands(Loc, LHS, RHS); 9987 } 9988 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9989 } 9990 9991 // Shifts don't perform usual arithmetic conversions, they just do integer 9992 // promotions on each operand. C99 6.5.7p3 9993 9994 // For the LHS, do usual unary conversions, but then reset them away 9995 // if this is a compound assignment. 9996 ExprResult OldLHS = LHS; 9997 LHS = UsualUnaryConversions(LHS.get()); 9998 if (LHS.isInvalid()) 9999 return QualType(); 10000 QualType LHSType = LHS.get()->getType(); 10001 if (IsCompAssign) LHS = OldLHS; 10002 10003 // The RHS is simpler. 10004 RHS = UsualUnaryConversions(RHS.get()); 10005 if (RHS.isInvalid()) 10006 return QualType(); 10007 QualType RHSType = RHS.get()->getType(); 10008 10009 // C99 6.5.7p2: Each of the operands shall have integer type. 10010 if (!LHSType->hasIntegerRepresentation() || 10011 !RHSType->hasIntegerRepresentation()) 10012 return InvalidOperands(Loc, LHS, RHS); 10013 10014 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10015 // hasIntegerRepresentation() above instead of this. 10016 if (isScopedEnumerationType(LHSType) || 10017 isScopedEnumerationType(RHSType)) { 10018 return InvalidOperands(Loc, LHS, RHS); 10019 } 10020 // Sanity-check shift operands 10021 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10022 10023 // "The type of the result is that of the promoted left operand." 10024 return LHSType; 10025 } 10026 10027 /// If two different enums are compared, raise a warning. 10028 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 10029 Expr *RHS) { 10030 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 10031 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 10032 10033 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 10034 if (!LHSEnumType) 10035 return; 10036 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 10037 if (!RHSEnumType) 10038 return; 10039 10040 // Ignore anonymous enums. 10041 if (!LHSEnumType->getDecl()->getIdentifier() && 10042 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10043 return; 10044 if (!RHSEnumType->getDecl()->getIdentifier() && 10045 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 10046 return; 10047 10048 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 10049 return; 10050 10051 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 10052 << LHSStrippedType << RHSStrippedType 10053 << LHS->getSourceRange() << RHS->getSourceRange(); 10054 } 10055 10056 /// Diagnose bad pointer comparisons. 10057 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10058 ExprResult &LHS, ExprResult &RHS, 10059 bool IsError) { 10060 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10061 : diag::ext_typecheck_comparison_of_distinct_pointers) 10062 << LHS.get()->getType() << RHS.get()->getType() 10063 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10064 } 10065 10066 /// Returns false if the pointers are converted to a composite type, 10067 /// true otherwise. 10068 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10069 ExprResult &LHS, ExprResult &RHS) { 10070 // C++ [expr.rel]p2: 10071 // [...] Pointer conversions (4.10) and qualification 10072 // conversions (4.4) are performed on pointer operands (or on 10073 // a pointer operand and a null pointer constant) to bring 10074 // them to their composite pointer type. [...] 10075 // 10076 // C++ [expr.eq]p1 uses the same notion for (in)equality 10077 // comparisons of pointers. 10078 10079 QualType LHSType = LHS.get()->getType(); 10080 QualType RHSType = RHS.get()->getType(); 10081 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10082 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10083 10084 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10085 if (T.isNull()) { 10086 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10087 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10088 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10089 else 10090 S.InvalidOperands(Loc, LHS, RHS); 10091 return true; 10092 } 10093 10094 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10095 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10096 return false; 10097 } 10098 10099 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10100 ExprResult &LHS, 10101 ExprResult &RHS, 10102 bool IsError) { 10103 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10104 : diag::ext_typecheck_comparison_of_fptr_to_void) 10105 << LHS.get()->getType() << RHS.get()->getType() 10106 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10107 } 10108 10109 static bool isObjCObjectLiteral(ExprResult &E) { 10110 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10111 case Stmt::ObjCArrayLiteralClass: 10112 case Stmt::ObjCDictionaryLiteralClass: 10113 case Stmt::ObjCStringLiteralClass: 10114 case Stmt::ObjCBoxedExprClass: 10115 return true; 10116 default: 10117 // Note that ObjCBoolLiteral is NOT an object literal! 10118 return false; 10119 } 10120 } 10121 10122 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10123 const ObjCObjectPointerType *Type = 10124 LHS->getType()->getAs<ObjCObjectPointerType>(); 10125 10126 // If this is not actually an Objective-C object, bail out. 10127 if (!Type) 10128 return false; 10129 10130 // Get the LHS object's interface type. 10131 QualType InterfaceType = Type->getPointeeType(); 10132 10133 // If the RHS isn't an Objective-C object, bail out. 10134 if (!RHS->getType()->isObjCObjectPointerType()) 10135 return false; 10136 10137 // Try to find the -isEqual: method. 10138 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10139 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10140 InterfaceType, 10141 /*IsInstance=*/true); 10142 if (!Method) { 10143 if (Type->isObjCIdType()) { 10144 // For 'id', just check the global pool. 10145 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10146 /*receiverId=*/true); 10147 } else { 10148 // Check protocols. 10149 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10150 /*IsInstance=*/true); 10151 } 10152 } 10153 10154 if (!Method) 10155 return false; 10156 10157 QualType T = Method->parameters()[0]->getType(); 10158 if (!T->isObjCObjectPointerType()) 10159 return false; 10160 10161 QualType R = Method->getReturnType(); 10162 if (!R->isScalarType()) 10163 return false; 10164 10165 return true; 10166 } 10167 10168 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10169 FromE = FromE->IgnoreParenImpCasts(); 10170 switch (FromE->getStmtClass()) { 10171 default: 10172 break; 10173 case Stmt::ObjCStringLiteralClass: 10174 // "string literal" 10175 return LK_String; 10176 case Stmt::ObjCArrayLiteralClass: 10177 // "array literal" 10178 return LK_Array; 10179 case Stmt::ObjCDictionaryLiteralClass: 10180 // "dictionary literal" 10181 return LK_Dictionary; 10182 case Stmt::BlockExprClass: 10183 return LK_Block; 10184 case Stmt::ObjCBoxedExprClass: { 10185 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10186 switch (Inner->getStmtClass()) { 10187 case Stmt::IntegerLiteralClass: 10188 case Stmt::FloatingLiteralClass: 10189 case Stmt::CharacterLiteralClass: 10190 case Stmt::ObjCBoolLiteralExprClass: 10191 case Stmt::CXXBoolLiteralExprClass: 10192 // "numeric literal" 10193 return LK_Numeric; 10194 case Stmt::ImplicitCastExprClass: { 10195 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10196 // Boolean literals can be represented by implicit casts. 10197 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10198 return LK_Numeric; 10199 break; 10200 } 10201 default: 10202 break; 10203 } 10204 return LK_Boxed; 10205 } 10206 } 10207 return LK_None; 10208 } 10209 10210 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10211 ExprResult &LHS, ExprResult &RHS, 10212 BinaryOperator::Opcode Opc){ 10213 Expr *Literal; 10214 Expr *Other; 10215 if (isObjCObjectLiteral(LHS)) { 10216 Literal = LHS.get(); 10217 Other = RHS.get(); 10218 } else { 10219 Literal = RHS.get(); 10220 Other = LHS.get(); 10221 } 10222 10223 // Don't warn on comparisons against nil. 10224 Other = Other->IgnoreParenCasts(); 10225 if (Other->isNullPointerConstant(S.getASTContext(), 10226 Expr::NPC_ValueDependentIsNotNull)) 10227 return; 10228 10229 // This should be kept in sync with warn_objc_literal_comparison. 10230 // LK_String should always be after the other literals, since it has its own 10231 // warning flag. 10232 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10233 assert(LiteralKind != Sema::LK_Block); 10234 if (LiteralKind == Sema::LK_None) { 10235 llvm_unreachable("Unknown Objective-C object literal kind"); 10236 } 10237 10238 if (LiteralKind == Sema::LK_String) 10239 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10240 << Literal->getSourceRange(); 10241 else 10242 S.Diag(Loc, diag::warn_objc_literal_comparison) 10243 << LiteralKind << Literal->getSourceRange(); 10244 10245 if (BinaryOperator::isEqualityOp(Opc) && 10246 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10247 SourceLocation Start = LHS.get()->getBeginLoc(); 10248 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10249 CharSourceRange OpRange = 10250 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10251 10252 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10253 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10254 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10255 << FixItHint::CreateInsertion(End, "]"); 10256 } 10257 } 10258 10259 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10260 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10261 ExprResult &RHS, SourceLocation Loc, 10262 BinaryOperatorKind Opc) { 10263 // Check that left hand side is !something. 10264 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10265 if (!UO || UO->getOpcode() != UO_LNot) return; 10266 10267 // Only check if the right hand side is non-bool arithmetic type. 10268 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10269 10270 // Make sure that the something in !something is not bool. 10271 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10272 if (SubExpr->isKnownToHaveBooleanValue()) return; 10273 10274 // Emit warning. 10275 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10276 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10277 << Loc << IsBitwiseOp; 10278 10279 // First note suggest !(x < y) 10280 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10281 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10282 FirstClose = S.getLocForEndOfToken(FirstClose); 10283 if (FirstClose.isInvalid()) 10284 FirstOpen = SourceLocation(); 10285 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10286 << IsBitwiseOp 10287 << FixItHint::CreateInsertion(FirstOpen, "(") 10288 << FixItHint::CreateInsertion(FirstClose, ")"); 10289 10290 // Second note suggests (!x) < y 10291 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10292 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10293 SecondClose = S.getLocForEndOfToken(SecondClose); 10294 if (SecondClose.isInvalid()) 10295 SecondOpen = SourceLocation(); 10296 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10297 << FixItHint::CreateInsertion(SecondOpen, "(") 10298 << FixItHint::CreateInsertion(SecondClose, ")"); 10299 } 10300 10301 // Returns true if E refers to a non-weak array. 10302 static bool checkForArray(const Expr *E) { 10303 const ValueDecl *D = nullptr; 10304 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10305 D = DR->getDecl(); 10306 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10307 if (Mem->isImplicitAccess()) 10308 D = Mem->getMemberDecl(); 10309 } 10310 if (!D) 10311 return false; 10312 return D->getType()->isArrayType() && !D->isWeak(); 10313 } 10314 10315 /// Diagnose some forms of syntactically-obvious tautological comparison. 10316 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10317 Expr *LHS, Expr *RHS, 10318 BinaryOperatorKind Opc) { 10319 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10320 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10321 10322 QualType LHSType = LHS->getType(); 10323 QualType RHSType = RHS->getType(); 10324 if (LHSType->hasFloatingRepresentation() || 10325 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10326 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10327 S.inTemplateInstantiation()) 10328 return; 10329 10330 // Comparisons between two array types are ill-formed for operator<=>, so 10331 // we shouldn't emit any additional warnings about it. 10332 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10333 return; 10334 10335 // For non-floating point types, check for self-comparisons of the form 10336 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10337 // often indicate logic errors in the program. 10338 // 10339 // NOTE: Don't warn about comparison expressions resulting from macro 10340 // expansion. Also don't warn about comparisons which are only self 10341 // comparisons within a template instantiation. The warnings should catch 10342 // obvious cases in the definition of the template anyways. The idea is to 10343 // warn when the typed comparison operator will always evaluate to the same 10344 // result. 10345 10346 // Used for indexing into %select in warn_comparison_always 10347 enum { 10348 AlwaysConstant, 10349 AlwaysTrue, 10350 AlwaysFalse, 10351 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10352 }; 10353 10354 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10355 unsigned Result; 10356 switch (Opc) { 10357 case BO_EQ: case BO_LE: case BO_GE: 10358 Result = AlwaysTrue; 10359 break; 10360 case BO_NE: case BO_LT: case BO_GT: 10361 Result = AlwaysFalse; 10362 break; 10363 case BO_Cmp: 10364 Result = AlwaysEqual; 10365 break; 10366 default: 10367 Result = AlwaysConstant; 10368 break; 10369 } 10370 S.DiagRuntimeBehavior(Loc, nullptr, 10371 S.PDiag(diag::warn_comparison_always) 10372 << 0 /*self-comparison*/ 10373 << Result); 10374 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10375 // What is it always going to evaluate to? 10376 unsigned Result; 10377 switch(Opc) { 10378 case BO_EQ: // e.g. array1 == array2 10379 Result = AlwaysFalse; 10380 break; 10381 case BO_NE: // e.g. array1 != array2 10382 Result = AlwaysTrue; 10383 break; 10384 default: // e.g. array1 <= array2 10385 // The best we can say is 'a constant' 10386 Result = AlwaysConstant; 10387 break; 10388 } 10389 S.DiagRuntimeBehavior(Loc, nullptr, 10390 S.PDiag(diag::warn_comparison_always) 10391 << 1 /*array comparison*/ 10392 << Result); 10393 } 10394 10395 if (isa<CastExpr>(LHSStripped)) 10396 LHSStripped = LHSStripped->IgnoreParenCasts(); 10397 if (isa<CastExpr>(RHSStripped)) 10398 RHSStripped = RHSStripped->IgnoreParenCasts(); 10399 10400 // Warn about comparisons against a string constant (unless the other 10401 // operand is null); the user probably wants strcmp. 10402 Expr *LiteralString = nullptr; 10403 Expr *LiteralStringStripped = nullptr; 10404 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10405 !RHSStripped->isNullPointerConstant(S.Context, 10406 Expr::NPC_ValueDependentIsNull)) { 10407 LiteralString = LHS; 10408 LiteralStringStripped = LHSStripped; 10409 } else if ((isa<StringLiteral>(RHSStripped) || 10410 isa<ObjCEncodeExpr>(RHSStripped)) && 10411 !LHSStripped->isNullPointerConstant(S.Context, 10412 Expr::NPC_ValueDependentIsNull)) { 10413 LiteralString = RHS; 10414 LiteralStringStripped = RHSStripped; 10415 } 10416 10417 if (LiteralString) { 10418 S.DiagRuntimeBehavior(Loc, nullptr, 10419 S.PDiag(diag::warn_stringcompare) 10420 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10421 << LiteralString->getSourceRange()); 10422 } 10423 } 10424 10425 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10426 switch (CK) { 10427 default: { 10428 #ifndef NDEBUG 10429 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10430 << "\n"; 10431 #endif 10432 llvm_unreachable("unhandled cast kind"); 10433 } 10434 case CK_UserDefinedConversion: 10435 return ICK_Identity; 10436 case CK_LValueToRValue: 10437 return ICK_Lvalue_To_Rvalue; 10438 case CK_ArrayToPointerDecay: 10439 return ICK_Array_To_Pointer; 10440 case CK_FunctionToPointerDecay: 10441 return ICK_Function_To_Pointer; 10442 case CK_IntegralCast: 10443 return ICK_Integral_Conversion; 10444 case CK_FloatingCast: 10445 return ICK_Floating_Conversion; 10446 case CK_IntegralToFloating: 10447 case CK_FloatingToIntegral: 10448 return ICK_Floating_Integral; 10449 case CK_IntegralComplexCast: 10450 case CK_FloatingComplexCast: 10451 case CK_FloatingComplexToIntegralComplex: 10452 case CK_IntegralComplexToFloatingComplex: 10453 return ICK_Complex_Conversion; 10454 case CK_FloatingComplexToReal: 10455 case CK_FloatingRealToComplex: 10456 case CK_IntegralComplexToReal: 10457 case CK_IntegralRealToComplex: 10458 return ICK_Complex_Real; 10459 } 10460 } 10461 10462 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10463 QualType FromType, 10464 SourceLocation Loc) { 10465 // Check for a narrowing implicit conversion. 10466 StandardConversionSequence SCS; 10467 SCS.setAsIdentityConversion(); 10468 SCS.setToType(0, FromType); 10469 SCS.setToType(1, ToType); 10470 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10471 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10472 10473 APValue PreNarrowingValue; 10474 QualType PreNarrowingType; 10475 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10476 PreNarrowingType, 10477 /*IgnoreFloatToIntegralConversion*/ true)) { 10478 case NK_Dependent_Narrowing: 10479 // Implicit conversion to a narrower type, but the expression is 10480 // value-dependent so we can't tell whether it's actually narrowing. 10481 case NK_Not_Narrowing: 10482 return false; 10483 10484 case NK_Constant_Narrowing: 10485 // Implicit conversion to a narrower type, and the value is not a constant 10486 // expression. 10487 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10488 << /*Constant*/ 1 10489 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10490 return true; 10491 10492 case NK_Variable_Narrowing: 10493 // Implicit conversion to a narrower type, and the value is not a constant 10494 // expression. 10495 case NK_Type_Narrowing: 10496 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10497 << /*Constant*/ 0 << FromType << ToType; 10498 // TODO: It's not a constant expression, but what if the user intended it 10499 // to be? Can we produce notes to help them figure out why it isn't? 10500 return true; 10501 } 10502 llvm_unreachable("unhandled case in switch"); 10503 } 10504 10505 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10506 ExprResult &LHS, 10507 ExprResult &RHS, 10508 SourceLocation Loc) { 10509 using CCT = ComparisonCategoryType; 10510 10511 QualType LHSType = LHS.get()->getType(); 10512 QualType RHSType = RHS.get()->getType(); 10513 // Dig out the original argument type and expression before implicit casts 10514 // were applied. These are the types/expressions we need to check the 10515 // [expr.spaceship] requirements against. 10516 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10517 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10518 QualType LHSStrippedType = LHSStripped.get()->getType(); 10519 QualType RHSStrippedType = RHSStripped.get()->getType(); 10520 10521 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10522 // other is not, the program is ill-formed. 10523 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10524 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10525 return QualType(); 10526 } 10527 10528 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10529 RHSStrippedType->isEnumeralType(); 10530 if (NumEnumArgs == 1) { 10531 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10532 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10533 if (OtherTy->hasFloatingRepresentation()) { 10534 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10535 return QualType(); 10536 } 10537 } 10538 if (NumEnumArgs == 2) { 10539 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10540 // type E, the operator yields the result of converting the operands 10541 // to the underlying type of E and applying <=> to the converted operands. 10542 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10543 S.InvalidOperands(Loc, LHS, RHS); 10544 return QualType(); 10545 } 10546 QualType IntType = 10547 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10548 assert(IntType->isArithmeticType()); 10549 10550 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10551 // promote the boolean type, and all other promotable integer types, to 10552 // avoid this. 10553 if (IntType->isPromotableIntegerType()) 10554 IntType = S.Context.getPromotedIntegerType(IntType); 10555 10556 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10557 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10558 LHSType = RHSType = IntType; 10559 } 10560 10561 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10562 // usual arithmetic conversions are applied to the operands. 10563 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10564 if (LHS.isInvalid() || RHS.isInvalid()) 10565 return QualType(); 10566 if (Type.isNull()) 10567 return S.InvalidOperands(Loc, LHS, RHS); 10568 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10569 10570 bool HasNarrowing = checkThreeWayNarrowingConversion( 10571 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10572 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10573 RHS.get()->getBeginLoc()); 10574 if (HasNarrowing) 10575 return QualType(); 10576 10577 assert(!Type.isNull() && "composite type for <=> has not been set"); 10578 10579 auto TypeKind = [&]() { 10580 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10581 if (CT->getElementType()->hasFloatingRepresentation()) 10582 return CCT::WeakEquality; 10583 return CCT::StrongEquality; 10584 } 10585 if (Type->isIntegralOrEnumerationType()) 10586 return CCT::StrongOrdering; 10587 if (Type->hasFloatingRepresentation()) 10588 return CCT::PartialOrdering; 10589 llvm_unreachable("other types are unimplemented"); 10590 }(); 10591 10592 return S.CheckComparisonCategoryType(TypeKind, Loc); 10593 } 10594 10595 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10596 ExprResult &RHS, 10597 SourceLocation Loc, 10598 BinaryOperatorKind Opc) { 10599 if (Opc == BO_Cmp) 10600 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10601 10602 // C99 6.5.8p3 / C99 6.5.9p4 10603 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10604 if (LHS.isInvalid() || RHS.isInvalid()) 10605 return QualType(); 10606 if (Type.isNull()) 10607 return S.InvalidOperands(Loc, LHS, RHS); 10608 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10609 10610 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10611 10612 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10613 return S.InvalidOperands(Loc, LHS, RHS); 10614 10615 // Check for comparisons of floating point operands using != and ==. 10616 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10617 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10618 10619 // The result of comparisons is 'bool' in C++, 'int' in C. 10620 return S.Context.getLogicalOperationType(); 10621 } 10622 10623 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10624 if (!NullE.get()->getType()->isAnyPointerType()) 10625 return; 10626 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10627 if (!E.get()->getType()->isAnyPointerType() && 10628 E.get()->isNullPointerConstant(Context, 10629 Expr::NPC_ValueDependentIsNotNull) == 10630 Expr::NPCK_ZeroExpression) { 10631 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10632 if (CL->getValue() == 0) 10633 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10634 << NullValue 10635 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10636 NullValue ? "NULL" : "(void *)0"); 10637 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10638 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10639 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10640 if (T == Context.CharTy) 10641 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10642 << NullValue 10643 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10644 NullValue ? "NULL" : "(void *)0"); 10645 } 10646 } 10647 } 10648 10649 // C99 6.5.8, C++ [expr.rel] 10650 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10651 SourceLocation Loc, 10652 BinaryOperatorKind Opc) { 10653 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10654 bool IsThreeWay = Opc == BO_Cmp; 10655 auto IsAnyPointerType = [](ExprResult E) { 10656 QualType Ty = E.get()->getType(); 10657 return Ty->isPointerType() || Ty->isMemberPointerType(); 10658 }; 10659 10660 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10661 // type, array-to-pointer, ..., conversions are performed on both operands to 10662 // bring them to their composite type. 10663 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10664 // any type-related checks. 10665 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10666 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10667 if (LHS.isInvalid()) 10668 return QualType(); 10669 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10670 if (RHS.isInvalid()) 10671 return QualType(); 10672 } else { 10673 LHS = DefaultLvalueConversion(LHS.get()); 10674 if (LHS.isInvalid()) 10675 return QualType(); 10676 RHS = DefaultLvalueConversion(RHS.get()); 10677 if (RHS.isInvalid()) 10678 return QualType(); 10679 } 10680 10681 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10682 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10683 CheckPtrComparisonWithNullChar(LHS, RHS); 10684 CheckPtrComparisonWithNullChar(RHS, LHS); 10685 } 10686 10687 // Handle vector comparisons separately. 10688 if (LHS.get()->getType()->isVectorType() || 10689 RHS.get()->getType()->isVectorType()) 10690 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10691 10692 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10693 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10694 10695 QualType LHSType = LHS.get()->getType(); 10696 QualType RHSType = RHS.get()->getType(); 10697 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10698 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10699 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10700 10701 const Expr::NullPointerConstantKind LHSNullKind = 10702 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10703 const Expr::NullPointerConstantKind RHSNullKind = 10704 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10705 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10706 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10707 10708 auto computeResultTy = [&]() { 10709 if (Opc != BO_Cmp) 10710 return Context.getLogicalOperationType(); 10711 assert(getLangOpts().CPlusPlus); 10712 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10713 10714 QualType CompositeTy = LHS.get()->getType(); 10715 assert(!CompositeTy->isReferenceType()); 10716 10717 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10718 return CheckComparisonCategoryType(Kind, Loc); 10719 }; 10720 10721 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10722 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10723 // result is of type std::strong_equality 10724 if (CompositeTy->isFunctionPointerType() || 10725 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10726 // FIXME: consider making the function pointer case produce 10727 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10728 // and direction polls 10729 return buildResultTy(ComparisonCategoryType::StrongEquality); 10730 10731 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10732 // pointer type, p <=> q is of type std::strong_ordering. 10733 if (CompositeTy->isPointerType()) { 10734 // P0946R0: Comparisons between a null pointer constant and an object 10735 // pointer result in std::strong_equality 10736 if (LHSIsNull != RHSIsNull) 10737 return buildResultTy(ComparisonCategoryType::StrongEquality); 10738 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10739 } 10740 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10741 // TODO: Extend support for operator<=> to ObjC types. 10742 return InvalidOperands(Loc, LHS, RHS); 10743 }; 10744 10745 10746 if (!IsRelational && LHSIsNull != RHSIsNull) { 10747 bool IsEquality = Opc == BO_EQ; 10748 if (RHSIsNull) 10749 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10750 RHS.get()->getSourceRange()); 10751 else 10752 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10753 LHS.get()->getSourceRange()); 10754 } 10755 10756 if ((LHSType->isIntegerType() && !LHSIsNull) || 10757 (RHSType->isIntegerType() && !RHSIsNull)) { 10758 // Skip normal pointer conversion checks in this case; we have better 10759 // diagnostics for this below. 10760 } else if (getLangOpts().CPlusPlus) { 10761 // Equality comparison of a function pointer to a void pointer is invalid, 10762 // but we allow it as an extension. 10763 // FIXME: If we really want to allow this, should it be part of composite 10764 // pointer type computation so it works in conditionals too? 10765 if (!IsRelational && 10766 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10767 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10768 // This is a gcc extension compatibility comparison. 10769 // In a SFINAE context, we treat this as a hard error to maintain 10770 // conformance with the C++ standard. 10771 diagnoseFunctionPointerToVoidComparison( 10772 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10773 10774 if (isSFINAEContext()) 10775 return QualType(); 10776 10777 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10778 return computeResultTy(); 10779 } 10780 10781 // C++ [expr.eq]p2: 10782 // If at least one operand is a pointer [...] bring them to their 10783 // composite pointer type. 10784 // C++ [expr.spaceship]p6 10785 // If at least one of the operands is of pointer type, [...] bring them 10786 // to their composite pointer type. 10787 // C++ [expr.rel]p2: 10788 // If both operands are pointers, [...] bring them to their composite 10789 // pointer type. 10790 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10791 (IsRelational ? 2 : 1) && 10792 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10793 RHSType->isObjCObjectPointerType()))) { 10794 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10795 return QualType(); 10796 return computeResultTy(); 10797 } 10798 } else if (LHSType->isPointerType() && 10799 RHSType->isPointerType()) { // C99 6.5.8p2 10800 // All of the following pointer-related warnings are GCC extensions, except 10801 // when handling null pointer constants. 10802 QualType LCanPointeeTy = 10803 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10804 QualType RCanPointeeTy = 10805 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10806 10807 // C99 6.5.9p2 and C99 6.5.8p2 10808 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10809 RCanPointeeTy.getUnqualifiedType())) { 10810 // Valid unless a relational comparison of function pointers 10811 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10812 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10813 << LHSType << RHSType << LHS.get()->getSourceRange() 10814 << RHS.get()->getSourceRange(); 10815 } 10816 } else if (!IsRelational && 10817 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10818 // Valid unless comparison between non-null pointer and function pointer 10819 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10820 && !LHSIsNull && !RHSIsNull) 10821 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10822 /*isError*/false); 10823 } else { 10824 // Invalid 10825 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10826 } 10827 if (LCanPointeeTy != RCanPointeeTy) { 10828 // Treat NULL constant as a special case in OpenCL. 10829 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10830 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10831 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10832 Diag(Loc, 10833 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10834 << LHSType << RHSType << 0 /* comparison */ 10835 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10836 } 10837 } 10838 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10839 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10840 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10841 : CK_BitCast; 10842 if (LHSIsNull && !RHSIsNull) 10843 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10844 else 10845 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10846 } 10847 return computeResultTy(); 10848 } 10849 10850 if (getLangOpts().CPlusPlus) { 10851 // C++ [expr.eq]p4: 10852 // Two operands of type std::nullptr_t or one operand of type 10853 // std::nullptr_t and the other a null pointer constant compare equal. 10854 if (!IsRelational && LHSIsNull && RHSIsNull) { 10855 if (LHSType->isNullPtrType()) { 10856 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10857 return computeResultTy(); 10858 } 10859 if (RHSType->isNullPtrType()) { 10860 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10861 return computeResultTy(); 10862 } 10863 } 10864 10865 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10866 // These aren't covered by the composite pointer type rules. 10867 if (!IsRelational && RHSType->isNullPtrType() && 10868 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10869 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10870 return computeResultTy(); 10871 } 10872 if (!IsRelational && LHSType->isNullPtrType() && 10873 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10874 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10875 return computeResultTy(); 10876 } 10877 10878 if (IsRelational && 10879 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10880 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10881 // HACK: Relational comparison of nullptr_t against a pointer type is 10882 // invalid per DR583, but we allow it within std::less<> and friends, 10883 // since otherwise common uses of it break. 10884 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10885 // friends to have std::nullptr_t overload candidates. 10886 DeclContext *DC = CurContext; 10887 if (isa<FunctionDecl>(DC)) 10888 DC = DC->getParent(); 10889 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10890 if (CTSD->isInStdNamespace() && 10891 llvm::StringSwitch<bool>(CTSD->getName()) 10892 .Cases("less", "less_equal", "greater", "greater_equal", true) 10893 .Default(false)) { 10894 if (RHSType->isNullPtrType()) 10895 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10896 else 10897 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10898 return computeResultTy(); 10899 } 10900 } 10901 } 10902 10903 // C++ [expr.eq]p2: 10904 // If at least one operand is a pointer to member, [...] bring them to 10905 // their composite pointer type. 10906 if (!IsRelational && 10907 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10908 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10909 return QualType(); 10910 else 10911 return computeResultTy(); 10912 } 10913 } 10914 10915 // Handle block pointer types. 10916 if (!IsRelational && LHSType->isBlockPointerType() && 10917 RHSType->isBlockPointerType()) { 10918 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10919 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10920 10921 if (!LHSIsNull && !RHSIsNull && 10922 !Context.typesAreCompatible(lpointee, rpointee)) { 10923 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10924 << LHSType << RHSType << LHS.get()->getSourceRange() 10925 << RHS.get()->getSourceRange(); 10926 } 10927 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10928 return computeResultTy(); 10929 } 10930 10931 // Allow block pointers to be compared with null pointer constants. 10932 if (!IsRelational 10933 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10934 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10935 if (!LHSIsNull && !RHSIsNull) { 10936 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10937 ->getPointeeType()->isVoidType()) 10938 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10939 ->getPointeeType()->isVoidType()))) 10940 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10941 << LHSType << RHSType << LHS.get()->getSourceRange() 10942 << RHS.get()->getSourceRange(); 10943 } 10944 if (LHSIsNull && !RHSIsNull) 10945 LHS = ImpCastExprToType(LHS.get(), RHSType, 10946 RHSType->isPointerType() ? CK_BitCast 10947 : CK_AnyPointerToBlockPointerCast); 10948 else 10949 RHS = ImpCastExprToType(RHS.get(), LHSType, 10950 LHSType->isPointerType() ? CK_BitCast 10951 : CK_AnyPointerToBlockPointerCast); 10952 return computeResultTy(); 10953 } 10954 10955 if (LHSType->isObjCObjectPointerType() || 10956 RHSType->isObjCObjectPointerType()) { 10957 const PointerType *LPT = LHSType->getAs<PointerType>(); 10958 const PointerType *RPT = RHSType->getAs<PointerType>(); 10959 if (LPT || RPT) { 10960 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10961 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10962 10963 if (!LPtrToVoid && !RPtrToVoid && 10964 !Context.typesAreCompatible(LHSType, RHSType)) { 10965 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10966 /*isError*/false); 10967 } 10968 if (LHSIsNull && !RHSIsNull) { 10969 Expr *E = LHS.get(); 10970 if (getLangOpts().ObjCAutoRefCount) 10971 CheckObjCConversion(SourceRange(), RHSType, E, 10972 CCK_ImplicitConversion); 10973 LHS = ImpCastExprToType(E, RHSType, 10974 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10975 } 10976 else { 10977 Expr *E = RHS.get(); 10978 if (getLangOpts().ObjCAutoRefCount) 10979 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10980 /*Diagnose=*/true, 10981 /*DiagnoseCFAudited=*/false, Opc); 10982 RHS = ImpCastExprToType(E, LHSType, 10983 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10984 } 10985 return computeResultTy(); 10986 } 10987 if (LHSType->isObjCObjectPointerType() && 10988 RHSType->isObjCObjectPointerType()) { 10989 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10990 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10991 /*isError*/false); 10992 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10993 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10994 10995 if (LHSIsNull && !RHSIsNull) 10996 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10997 else 10998 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10999 return computeResultTy(); 11000 } 11001 11002 if (!IsRelational && LHSType->isBlockPointerType() && 11003 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11004 LHS = ImpCastExprToType(LHS.get(), RHSType, 11005 CK_BlockPointerToObjCPointerCast); 11006 return computeResultTy(); 11007 } else if (!IsRelational && 11008 LHSType->isBlockCompatibleObjCPointerType(Context) && 11009 RHSType->isBlockPointerType()) { 11010 RHS = ImpCastExprToType(RHS.get(), LHSType, 11011 CK_BlockPointerToObjCPointerCast); 11012 return computeResultTy(); 11013 } 11014 } 11015 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11016 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11017 unsigned DiagID = 0; 11018 bool isError = false; 11019 if (LangOpts.DebuggerSupport) { 11020 // Under a debugger, allow the comparison of pointers to integers, 11021 // since users tend to want to compare addresses. 11022 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11023 (RHSIsNull && RHSType->isIntegerType())) { 11024 if (IsRelational) { 11025 isError = getLangOpts().CPlusPlus; 11026 DiagID = 11027 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11028 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11029 } 11030 } else if (getLangOpts().CPlusPlus) { 11031 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11032 isError = true; 11033 } else if (IsRelational) 11034 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11035 else 11036 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11037 11038 if (DiagID) { 11039 Diag(Loc, DiagID) 11040 << LHSType << RHSType << LHS.get()->getSourceRange() 11041 << RHS.get()->getSourceRange(); 11042 if (isError) 11043 return QualType(); 11044 } 11045 11046 if (LHSType->isIntegerType()) 11047 LHS = ImpCastExprToType(LHS.get(), RHSType, 11048 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11049 else 11050 RHS = ImpCastExprToType(RHS.get(), LHSType, 11051 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11052 return computeResultTy(); 11053 } 11054 11055 // Handle block pointers. 11056 if (!IsRelational && RHSIsNull 11057 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11058 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11059 return computeResultTy(); 11060 } 11061 if (!IsRelational && LHSIsNull 11062 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11063 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11064 return computeResultTy(); 11065 } 11066 11067 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11068 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11069 return computeResultTy(); 11070 } 11071 11072 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11073 return computeResultTy(); 11074 } 11075 11076 if (LHSIsNull && RHSType->isQueueT()) { 11077 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11078 return computeResultTy(); 11079 } 11080 11081 if (LHSType->isQueueT() && RHSIsNull) { 11082 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11083 return computeResultTy(); 11084 } 11085 } 11086 11087 return InvalidOperands(Loc, LHS, RHS); 11088 } 11089 11090 // Return a signed ext_vector_type that is of identical size and number of 11091 // elements. For floating point vectors, return an integer type of identical 11092 // size and number of elements. In the non ext_vector_type case, search from 11093 // the largest type to the smallest type to avoid cases where long long == long, 11094 // where long gets picked over long long. 11095 QualType Sema::GetSignedVectorType(QualType V) { 11096 const VectorType *VTy = V->castAs<VectorType>(); 11097 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11098 11099 if (isa<ExtVectorType>(VTy)) { 11100 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11101 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11102 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11103 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11104 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11105 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11106 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11107 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11108 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11109 "Unhandled vector element size in vector compare"); 11110 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11111 } 11112 11113 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11114 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11115 VectorType::GenericVector); 11116 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11117 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11118 VectorType::GenericVector); 11119 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11120 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11121 VectorType::GenericVector); 11122 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11123 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11124 VectorType::GenericVector); 11125 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11126 "Unhandled vector element size in vector compare"); 11127 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11128 VectorType::GenericVector); 11129 } 11130 11131 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11132 /// operates on extended vector types. Instead of producing an IntTy result, 11133 /// like a scalar comparison, a vector comparison produces a vector of integer 11134 /// types. 11135 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11136 SourceLocation Loc, 11137 BinaryOperatorKind Opc) { 11138 // Check to make sure we're operating on vectors of the same type and width, 11139 // Allowing one side to be a scalar of element type. 11140 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11141 /*AllowBothBool*/true, 11142 /*AllowBoolConversions*/getLangOpts().ZVector); 11143 if (vType.isNull()) 11144 return vType; 11145 11146 QualType LHSType = LHS.get()->getType(); 11147 11148 // If AltiVec, the comparison results in a numeric type, i.e. 11149 // bool for C++, int for C 11150 if (getLangOpts().AltiVec && 11151 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11152 return Context.getLogicalOperationType(); 11153 11154 // For non-floating point types, check for self-comparisons of the form 11155 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11156 // often indicate logic errors in the program. 11157 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11158 11159 // Check for comparisons of floating point operands using != and ==. 11160 if (BinaryOperator::isEqualityOp(Opc) && 11161 LHSType->hasFloatingRepresentation()) { 11162 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11163 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11164 } 11165 11166 // Return a signed type for the vector. 11167 return GetSignedVectorType(vType); 11168 } 11169 11170 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11171 const ExprResult &XorRHS, 11172 const SourceLocation Loc) { 11173 // Do not diagnose macros. 11174 if (Loc.isMacroID()) 11175 return; 11176 11177 bool Negative = false; 11178 bool ExplicitPlus = false; 11179 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11180 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11181 11182 if (!LHSInt) 11183 return; 11184 if (!RHSInt) { 11185 // Check negative literals. 11186 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11187 UnaryOperatorKind Opc = UO->getOpcode(); 11188 if (Opc != UO_Minus && Opc != UO_Plus) 11189 return; 11190 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11191 if (!RHSInt) 11192 return; 11193 Negative = (Opc == UO_Minus); 11194 ExplicitPlus = !Negative; 11195 } else { 11196 return; 11197 } 11198 } 11199 11200 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11201 llvm::APInt RightSideValue = RHSInt->getValue(); 11202 if (LeftSideValue != 2 && LeftSideValue != 10) 11203 return; 11204 11205 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11206 return; 11207 11208 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11209 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11210 llvm::StringRef ExprStr = 11211 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11212 11213 CharSourceRange XorRange = 11214 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11215 llvm::StringRef XorStr = 11216 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11217 // Do not diagnose if xor keyword/macro is used. 11218 if (XorStr == "xor") 11219 return; 11220 11221 std::string LHSStr = Lexer::getSourceText( 11222 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11223 S.getSourceManager(), S.getLangOpts()); 11224 std::string RHSStr = Lexer::getSourceText( 11225 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11226 S.getSourceManager(), S.getLangOpts()); 11227 11228 if (Negative) { 11229 RightSideValue = -RightSideValue; 11230 RHSStr = "-" + RHSStr; 11231 } else if (ExplicitPlus) { 11232 RHSStr = "+" + RHSStr; 11233 } 11234 11235 StringRef LHSStrRef = LHSStr; 11236 StringRef RHSStrRef = RHSStr; 11237 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11238 // literals. 11239 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11240 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11241 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11242 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11243 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11244 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11245 LHSStrRef.find('\'') != StringRef::npos || 11246 RHSStrRef.find('\'') != StringRef::npos) 11247 return; 11248 11249 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11250 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11251 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11252 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11253 std::string SuggestedExpr = "1 << " + RHSStr; 11254 bool Overflow = false; 11255 llvm::APInt One = (LeftSideValue - 1); 11256 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11257 if (Overflow) { 11258 if (RightSideIntValue < 64) 11259 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11260 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11261 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11262 else if (RightSideIntValue == 64) 11263 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11264 else 11265 return; 11266 } else { 11267 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11268 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11269 << PowValue.toString(10, true) 11270 << FixItHint::CreateReplacement( 11271 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11272 } 11273 11274 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11275 } else if (LeftSideValue == 10) { 11276 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11277 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11278 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11279 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11280 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11281 } 11282 } 11283 11284 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11285 SourceLocation Loc) { 11286 // Ensure that either both operands are of the same vector type, or 11287 // one operand is of a vector type and the other is of its element type. 11288 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11289 /*AllowBothBool*/true, 11290 /*AllowBoolConversions*/false); 11291 if (vType.isNull()) 11292 return InvalidOperands(Loc, LHS, RHS); 11293 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11294 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11295 return InvalidOperands(Loc, LHS, RHS); 11296 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11297 // usage of the logical operators && and || with vectors in C. This 11298 // check could be notionally dropped. 11299 if (!getLangOpts().CPlusPlus && 11300 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11301 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11302 11303 return GetSignedVectorType(LHS.get()->getType()); 11304 } 11305 11306 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11307 SourceLocation Loc, 11308 BinaryOperatorKind Opc) { 11309 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11310 11311 bool IsCompAssign = 11312 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11313 11314 if (LHS.get()->getType()->isVectorType() || 11315 RHS.get()->getType()->isVectorType()) { 11316 if (LHS.get()->getType()->hasIntegerRepresentation() && 11317 RHS.get()->getType()->hasIntegerRepresentation()) 11318 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11319 /*AllowBothBool*/true, 11320 /*AllowBoolConversions*/getLangOpts().ZVector); 11321 return InvalidOperands(Loc, LHS, RHS); 11322 } 11323 11324 if (Opc == BO_And) 11325 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11326 11327 ExprResult LHSResult = LHS, RHSResult = RHS; 11328 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 11329 IsCompAssign); 11330 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11331 return QualType(); 11332 LHS = LHSResult.get(); 11333 RHS = RHSResult.get(); 11334 11335 if (Opc == BO_Xor) 11336 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11337 11338 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11339 return compType; 11340 return InvalidOperands(Loc, LHS, RHS); 11341 } 11342 11343 // C99 6.5.[13,14] 11344 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11345 SourceLocation Loc, 11346 BinaryOperatorKind Opc) { 11347 // Check vector operands differently. 11348 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11349 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11350 11351 bool EnumConstantInBoolContext = false; 11352 for (const ExprResult &HS : {LHS, RHS}) { 11353 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11354 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11355 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11356 EnumConstantInBoolContext = true; 11357 } 11358 } 11359 11360 if (EnumConstantInBoolContext) 11361 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11362 11363 // Diagnose cases where the user write a logical and/or but probably meant a 11364 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11365 // is a constant. 11366 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11367 !LHS.get()->getType()->isBooleanType() && 11368 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11369 // Don't warn in macros or template instantiations. 11370 !Loc.isMacroID() && !inTemplateInstantiation()) { 11371 // If the RHS can be constant folded, and if it constant folds to something 11372 // that isn't 0 or 1 (which indicate a potential logical operation that 11373 // happened to fold to true/false) then warn. 11374 // Parens on the RHS are ignored. 11375 Expr::EvalResult EVResult; 11376 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11377 llvm::APSInt Result = EVResult.Val.getInt(); 11378 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11379 !RHS.get()->getExprLoc().isMacroID()) || 11380 (Result != 0 && Result != 1)) { 11381 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11382 << RHS.get()->getSourceRange() 11383 << (Opc == BO_LAnd ? "&&" : "||"); 11384 // Suggest replacing the logical operator with the bitwise version 11385 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11386 << (Opc == BO_LAnd ? "&" : "|") 11387 << FixItHint::CreateReplacement(SourceRange( 11388 Loc, getLocForEndOfToken(Loc)), 11389 Opc == BO_LAnd ? "&" : "|"); 11390 if (Opc == BO_LAnd) 11391 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11392 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11393 << FixItHint::CreateRemoval( 11394 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11395 RHS.get()->getEndLoc())); 11396 } 11397 } 11398 } 11399 11400 if (!Context.getLangOpts().CPlusPlus) { 11401 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11402 // not operate on the built-in scalar and vector float types. 11403 if (Context.getLangOpts().OpenCL && 11404 Context.getLangOpts().OpenCLVersion < 120) { 11405 if (LHS.get()->getType()->isFloatingType() || 11406 RHS.get()->getType()->isFloatingType()) 11407 return InvalidOperands(Loc, LHS, RHS); 11408 } 11409 11410 LHS = UsualUnaryConversions(LHS.get()); 11411 if (LHS.isInvalid()) 11412 return QualType(); 11413 11414 RHS = UsualUnaryConversions(RHS.get()); 11415 if (RHS.isInvalid()) 11416 return QualType(); 11417 11418 if (!LHS.get()->getType()->isScalarType() || 11419 !RHS.get()->getType()->isScalarType()) 11420 return InvalidOperands(Loc, LHS, RHS); 11421 11422 return Context.IntTy; 11423 } 11424 11425 // The following is safe because we only use this method for 11426 // non-overloadable operands. 11427 11428 // C++ [expr.log.and]p1 11429 // C++ [expr.log.or]p1 11430 // The operands are both contextually converted to type bool. 11431 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11432 if (LHSRes.isInvalid()) 11433 return InvalidOperands(Loc, LHS, RHS); 11434 LHS = LHSRes; 11435 11436 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11437 if (RHSRes.isInvalid()) 11438 return InvalidOperands(Loc, LHS, RHS); 11439 RHS = RHSRes; 11440 11441 // C++ [expr.log.and]p2 11442 // C++ [expr.log.or]p2 11443 // The result is a bool. 11444 return Context.BoolTy; 11445 } 11446 11447 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11448 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11449 if (!ME) return false; 11450 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11451 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11452 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11453 if (!Base) return false; 11454 return Base->getMethodDecl() != nullptr; 11455 } 11456 11457 /// Is the given expression (which must be 'const') a reference to a 11458 /// variable which was originally non-const, but which has become 11459 /// 'const' due to being captured within a block? 11460 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11461 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11462 assert(E->isLValue() && E->getType().isConstQualified()); 11463 E = E->IgnoreParens(); 11464 11465 // Must be a reference to a declaration from an enclosing scope. 11466 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11467 if (!DRE) return NCCK_None; 11468 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11469 11470 // The declaration must be a variable which is not declared 'const'. 11471 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11472 if (!var) return NCCK_None; 11473 if (var->getType().isConstQualified()) return NCCK_None; 11474 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11475 11476 // Decide whether the first capture was for a block or a lambda. 11477 DeclContext *DC = S.CurContext, *Prev = nullptr; 11478 // Decide whether the first capture was for a block or a lambda. 11479 while (DC) { 11480 // For init-capture, it is possible that the variable belongs to the 11481 // template pattern of the current context. 11482 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11483 if (var->isInitCapture() && 11484 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11485 break; 11486 if (DC == var->getDeclContext()) 11487 break; 11488 Prev = DC; 11489 DC = DC->getParent(); 11490 } 11491 // Unless we have an init-capture, we've gone one step too far. 11492 if (!var->isInitCapture()) 11493 DC = Prev; 11494 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11495 } 11496 11497 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11498 Ty = Ty.getNonReferenceType(); 11499 if (IsDereference && Ty->isPointerType()) 11500 Ty = Ty->getPointeeType(); 11501 return !Ty.isConstQualified(); 11502 } 11503 11504 // Update err_typecheck_assign_const and note_typecheck_assign_const 11505 // when this enum is changed. 11506 enum { 11507 ConstFunction, 11508 ConstVariable, 11509 ConstMember, 11510 ConstMethod, 11511 NestedConstMember, 11512 ConstUnknown, // Keep as last element 11513 }; 11514 11515 /// Emit the "read-only variable not assignable" error and print notes to give 11516 /// more information about why the variable is not assignable, such as pointing 11517 /// to the declaration of a const variable, showing that a method is const, or 11518 /// that the function is returning a const reference. 11519 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11520 SourceLocation Loc) { 11521 SourceRange ExprRange = E->getSourceRange(); 11522 11523 // Only emit one error on the first const found. All other consts will emit 11524 // a note to the error. 11525 bool DiagnosticEmitted = false; 11526 11527 // Track if the current expression is the result of a dereference, and if the 11528 // next checked expression is the result of a dereference. 11529 bool IsDereference = false; 11530 bool NextIsDereference = false; 11531 11532 // Loop to process MemberExpr chains. 11533 while (true) { 11534 IsDereference = NextIsDereference; 11535 11536 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11537 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11538 NextIsDereference = ME->isArrow(); 11539 const ValueDecl *VD = ME->getMemberDecl(); 11540 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11541 // Mutable fields can be modified even if the class is const. 11542 if (Field->isMutable()) { 11543 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11544 break; 11545 } 11546 11547 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11548 if (!DiagnosticEmitted) { 11549 S.Diag(Loc, diag::err_typecheck_assign_const) 11550 << ExprRange << ConstMember << false /*static*/ << Field 11551 << Field->getType(); 11552 DiagnosticEmitted = true; 11553 } 11554 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11555 << ConstMember << false /*static*/ << Field << Field->getType() 11556 << Field->getSourceRange(); 11557 } 11558 E = ME->getBase(); 11559 continue; 11560 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11561 if (VDecl->getType().isConstQualified()) { 11562 if (!DiagnosticEmitted) { 11563 S.Diag(Loc, diag::err_typecheck_assign_const) 11564 << ExprRange << ConstMember << true /*static*/ << VDecl 11565 << VDecl->getType(); 11566 DiagnosticEmitted = true; 11567 } 11568 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11569 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11570 << VDecl->getSourceRange(); 11571 } 11572 // Static fields do not inherit constness from parents. 11573 break; 11574 } 11575 break; // End MemberExpr 11576 } else if (const ArraySubscriptExpr *ASE = 11577 dyn_cast<ArraySubscriptExpr>(E)) { 11578 E = ASE->getBase()->IgnoreParenImpCasts(); 11579 continue; 11580 } else if (const ExtVectorElementExpr *EVE = 11581 dyn_cast<ExtVectorElementExpr>(E)) { 11582 E = EVE->getBase()->IgnoreParenImpCasts(); 11583 continue; 11584 } 11585 break; 11586 } 11587 11588 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11589 // Function calls 11590 const FunctionDecl *FD = CE->getDirectCallee(); 11591 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11592 if (!DiagnosticEmitted) { 11593 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11594 << ConstFunction << FD; 11595 DiagnosticEmitted = true; 11596 } 11597 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11598 diag::note_typecheck_assign_const) 11599 << ConstFunction << FD << FD->getReturnType() 11600 << FD->getReturnTypeSourceRange(); 11601 } 11602 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11603 // Point to variable declaration. 11604 if (const ValueDecl *VD = DRE->getDecl()) { 11605 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11606 if (!DiagnosticEmitted) { 11607 S.Diag(Loc, diag::err_typecheck_assign_const) 11608 << ExprRange << ConstVariable << VD << VD->getType(); 11609 DiagnosticEmitted = true; 11610 } 11611 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11612 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11613 } 11614 } 11615 } else if (isa<CXXThisExpr>(E)) { 11616 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11617 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11618 if (MD->isConst()) { 11619 if (!DiagnosticEmitted) { 11620 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11621 << ConstMethod << MD; 11622 DiagnosticEmitted = true; 11623 } 11624 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11625 << ConstMethod << MD << MD->getSourceRange(); 11626 } 11627 } 11628 } 11629 } 11630 11631 if (DiagnosticEmitted) 11632 return; 11633 11634 // Can't determine a more specific message, so display the generic error. 11635 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11636 } 11637 11638 enum OriginalExprKind { 11639 OEK_Variable, 11640 OEK_Member, 11641 OEK_LValue 11642 }; 11643 11644 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11645 const RecordType *Ty, 11646 SourceLocation Loc, SourceRange Range, 11647 OriginalExprKind OEK, 11648 bool &DiagnosticEmitted) { 11649 std::vector<const RecordType *> RecordTypeList; 11650 RecordTypeList.push_back(Ty); 11651 unsigned NextToCheckIndex = 0; 11652 // We walk the record hierarchy breadth-first to ensure that we print 11653 // diagnostics in field nesting order. 11654 while (RecordTypeList.size() > NextToCheckIndex) { 11655 bool IsNested = NextToCheckIndex > 0; 11656 for (const FieldDecl *Field : 11657 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11658 // First, check every field for constness. 11659 QualType FieldTy = Field->getType(); 11660 if (FieldTy.isConstQualified()) { 11661 if (!DiagnosticEmitted) { 11662 S.Diag(Loc, diag::err_typecheck_assign_const) 11663 << Range << NestedConstMember << OEK << VD 11664 << IsNested << Field; 11665 DiagnosticEmitted = true; 11666 } 11667 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11668 << NestedConstMember << IsNested << Field 11669 << FieldTy << Field->getSourceRange(); 11670 } 11671 11672 // Then we append it to the list to check next in order. 11673 FieldTy = FieldTy.getCanonicalType(); 11674 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11675 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11676 RecordTypeList.push_back(FieldRecTy); 11677 } 11678 } 11679 ++NextToCheckIndex; 11680 } 11681 } 11682 11683 /// Emit an error for the case where a record we are trying to assign to has a 11684 /// const-qualified field somewhere in its hierarchy. 11685 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11686 SourceLocation Loc) { 11687 QualType Ty = E->getType(); 11688 assert(Ty->isRecordType() && "lvalue was not record?"); 11689 SourceRange Range = E->getSourceRange(); 11690 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11691 bool DiagEmitted = false; 11692 11693 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11694 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11695 Range, OEK_Member, DiagEmitted); 11696 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11697 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11698 Range, OEK_Variable, DiagEmitted); 11699 else 11700 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11701 Range, OEK_LValue, DiagEmitted); 11702 if (!DiagEmitted) 11703 DiagnoseConstAssignment(S, E, Loc); 11704 } 11705 11706 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11707 /// emit an error and return true. If so, return false. 11708 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11709 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11710 11711 S.CheckShadowingDeclModification(E, Loc); 11712 11713 SourceLocation OrigLoc = Loc; 11714 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11715 &Loc); 11716 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11717 IsLV = Expr::MLV_InvalidMessageExpression; 11718 if (IsLV == Expr::MLV_Valid) 11719 return false; 11720 11721 unsigned DiagID = 0; 11722 bool NeedType = false; 11723 switch (IsLV) { // C99 6.5.16p2 11724 case Expr::MLV_ConstQualified: 11725 // Use a specialized diagnostic when we're assigning to an object 11726 // from an enclosing function or block. 11727 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11728 if (NCCK == NCCK_Block) 11729 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11730 else 11731 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11732 break; 11733 } 11734 11735 // In ARC, use some specialized diagnostics for occasions where we 11736 // infer 'const'. These are always pseudo-strong variables. 11737 if (S.getLangOpts().ObjCAutoRefCount) { 11738 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11739 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11740 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11741 11742 // Use the normal diagnostic if it's pseudo-__strong but the 11743 // user actually wrote 'const'. 11744 if (var->isARCPseudoStrong() && 11745 (!var->getTypeSourceInfo() || 11746 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11747 // There are three pseudo-strong cases: 11748 // - self 11749 ObjCMethodDecl *method = S.getCurMethodDecl(); 11750 if (method && var == method->getSelfDecl()) { 11751 DiagID = method->isClassMethod() 11752 ? diag::err_typecheck_arc_assign_self_class_method 11753 : diag::err_typecheck_arc_assign_self; 11754 11755 // - Objective-C externally_retained attribute. 11756 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11757 isa<ParmVarDecl>(var)) { 11758 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11759 11760 // - fast enumeration variables 11761 } else { 11762 DiagID = diag::err_typecheck_arr_assign_enumeration; 11763 } 11764 11765 SourceRange Assign; 11766 if (Loc != OrigLoc) 11767 Assign = SourceRange(OrigLoc, OrigLoc); 11768 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11769 // We need to preserve the AST regardless, so migration tool 11770 // can do its job. 11771 return false; 11772 } 11773 } 11774 } 11775 11776 // If none of the special cases above are triggered, then this is a 11777 // simple const assignment. 11778 if (DiagID == 0) { 11779 DiagnoseConstAssignment(S, E, Loc); 11780 return true; 11781 } 11782 11783 break; 11784 case Expr::MLV_ConstAddrSpace: 11785 DiagnoseConstAssignment(S, E, Loc); 11786 return true; 11787 case Expr::MLV_ConstQualifiedField: 11788 DiagnoseRecursiveConstFields(S, E, Loc); 11789 return true; 11790 case Expr::MLV_ArrayType: 11791 case Expr::MLV_ArrayTemporary: 11792 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11793 NeedType = true; 11794 break; 11795 case Expr::MLV_NotObjectType: 11796 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11797 NeedType = true; 11798 break; 11799 case Expr::MLV_LValueCast: 11800 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11801 break; 11802 case Expr::MLV_Valid: 11803 llvm_unreachable("did not take early return for MLV_Valid"); 11804 case Expr::MLV_InvalidExpression: 11805 case Expr::MLV_MemberFunction: 11806 case Expr::MLV_ClassTemporary: 11807 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11808 break; 11809 case Expr::MLV_IncompleteType: 11810 case Expr::MLV_IncompleteVoidType: 11811 return S.RequireCompleteType(Loc, E->getType(), 11812 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11813 case Expr::MLV_DuplicateVectorComponents: 11814 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11815 break; 11816 case Expr::MLV_NoSetterProperty: 11817 llvm_unreachable("readonly properties should be processed differently"); 11818 case Expr::MLV_InvalidMessageExpression: 11819 DiagID = diag::err_readonly_message_assignment; 11820 break; 11821 case Expr::MLV_SubObjCPropertySetting: 11822 DiagID = diag::err_no_subobject_property_setting; 11823 break; 11824 } 11825 11826 SourceRange Assign; 11827 if (Loc != OrigLoc) 11828 Assign = SourceRange(OrigLoc, OrigLoc); 11829 if (NeedType) 11830 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11831 else 11832 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11833 return true; 11834 } 11835 11836 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11837 SourceLocation Loc, 11838 Sema &Sema) { 11839 if (Sema.inTemplateInstantiation()) 11840 return; 11841 if (Sema.isUnevaluatedContext()) 11842 return; 11843 if (Loc.isInvalid() || Loc.isMacroID()) 11844 return; 11845 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11846 return; 11847 11848 // C / C++ fields 11849 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11850 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11851 if (ML && MR) { 11852 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11853 return; 11854 const ValueDecl *LHSDecl = 11855 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11856 const ValueDecl *RHSDecl = 11857 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11858 if (LHSDecl != RHSDecl) 11859 return; 11860 if (LHSDecl->getType().isVolatileQualified()) 11861 return; 11862 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11863 if (RefTy->getPointeeType().isVolatileQualified()) 11864 return; 11865 11866 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11867 } 11868 11869 // Objective-C instance variables 11870 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11871 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11872 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11873 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11874 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11875 if (RL && RR && RL->getDecl() == RR->getDecl()) 11876 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11877 } 11878 } 11879 11880 // C99 6.5.16.1 11881 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11882 SourceLocation Loc, 11883 QualType CompoundType) { 11884 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11885 11886 // Verify that LHS is a modifiable lvalue, and emit error if not. 11887 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11888 return QualType(); 11889 11890 QualType LHSType = LHSExpr->getType(); 11891 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11892 CompoundType; 11893 // OpenCL v1.2 s6.1.1.1 p2: 11894 // The half data type can only be used to declare a pointer to a buffer that 11895 // contains half values 11896 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11897 LHSType->isHalfType()) { 11898 Diag(Loc, diag::err_opencl_half_load_store) << 1 11899 << LHSType.getUnqualifiedType(); 11900 return QualType(); 11901 } 11902 11903 AssignConvertType ConvTy; 11904 if (CompoundType.isNull()) { 11905 Expr *RHSCheck = RHS.get(); 11906 11907 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11908 11909 QualType LHSTy(LHSType); 11910 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11911 if (RHS.isInvalid()) 11912 return QualType(); 11913 // Special case of NSObject attributes on c-style pointer types. 11914 if (ConvTy == IncompatiblePointer && 11915 ((Context.isObjCNSObjectType(LHSType) && 11916 RHSType->isObjCObjectPointerType()) || 11917 (Context.isObjCNSObjectType(RHSType) && 11918 LHSType->isObjCObjectPointerType()))) 11919 ConvTy = Compatible; 11920 11921 if (ConvTy == Compatible && 11922 LHSType->isObjCObjectType()) 11923 Diag(Loc, diag::err_objc_object_assignment) 11924 << LHSType; 11925 11926 // If the RHS is a unary plus or minus, check to see if they = and + are 11927 // right next to each other. If so, the user may have typo'd "x =+ 4" 11928 // instead of "x += 4". 11929 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11930 RHSCheck = ICE->getSubExpr(); 11931 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11932 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11933 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11934 // Only if the two operators are exactly adjacent. 11935 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11936 // And there is a space or other character before the subexpr of the 11937 // unary +/-. We don't want to warn on "x=-1". 11938 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11939 UO->getSubExpr()->getBeginLoc().isFileID()) { 11940 Diag(Loc, diag::warn_not_compound_assign) 11941 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11942 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11943 } 11944 } 11945 11946 if (ConvTy == Compatible) { 11947 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11948 // Warn about retain cycles where a block captures the LHS, but 11949 // not if the LHS is a simple variable into which the block is 11950 // being stored...unless that variable can be captured by reference! 11951 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11952 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11953 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11954 checkRetainCycles(LHSExpr, RHS.get()); 11955 } 11956 11957 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11958 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11959 // It is safe to assign a weak reference into a strong variable. 11960 // Although this code can still have problems: 11961 // id x = self.weakProp; 11962 // id y = self.weakProp; 11963 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11964 // paths through the function. This should be revisited if 11965 // -Wrepeated-use-of-weak is made flow-sensitive. 11966 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11967 // variable, which will be valid for the current autorelease scope. 11968 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11969 RHS.get()->getBeginLoc())) 11970 getCurFunction()->markSafeWeakUse(RHS.get()); 11971 11972 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11973 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11974 } 11975 } 11976 } else { 11977 // Compound assignment "x += y" 11978 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11979 } 11980 11981 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11982 RHS.get(), AA_Assigning)) 11983 return QualType(); 11984 11985 CheckForNullPointerDereference(*this, LHSExpr); 11986 11987 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 11988 if (CompoundType.isNull()) { 11989 // C++2a [expr.ass]p5: 11990 // A simple-assignment whose left operand is of a volatile-qualified 11991 // type is deprecated unless the assignment is either a discarded-value 11992 // expression or an unevaluated operand 11993 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 11994 } else { 11995 // C++2a [expr.ass]p6: 11996 // [Compound-assignment] expressions are deprecated if E1 has 11997 // volatile-qualified type 11998 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 11999 } 12000 } 12001 12002 // C99 6.5.16p3: The type of an assignment expression is the type of the 12003 // left operand unless the left operand has qualified type, in which case 12004 // it is the unqualified version of the type of the left operand. 12005 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12006 // is converted to the type of the assignment expression (above). 12007 // C++ 5.17p1: the type of the assignment expression is that of its left 12008 // operand. 12009 return (getLangOpts().CPlusPlus 12010 ? LHSType : LHSType.getUnqualifiedType()); 12011 } 12012 12013 // Only ignore explicit casts to void. 12014 static bool IgnoreCommaOperand(const Expr *E) { 12015 E = E->IgnoreParens(); 12016 12017 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12018 if (CE->getCastKind() == CK_ToVoid) { 12019 return true; 12020 } 12021 12022 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12023 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12024 CE->getSubExpr()->getType()->isDependentType()) { 12025 return true; 12026 } 12027 } 12028 12029 return false; 12030 } 12031 12032 // Look for instances where it is likely the comma operator is confused with 12033 // another operator. There is a whitelist of acceptable expressions for the 12034 // left hand side of the comma operator, otherwise emit a warning. 12035 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12036 // No warnings in macros 12037 if (Loc.isMacroID()) 12038 return; 12039 12040 // Don't warn in template instantiations. 12041 if (inTemplateInstantiation()) 12042 return; 12043 12044 // Scope isn't fine-grained enough to whitelist the specific cases, so 12045 // instead, skip more than needed, then call back into here with the 12046 // CommaVisitor in SemaStmt.cpp. 12047 // The whitelisted locations are the initialization and increment portions 12048 // of a for loop. The additional checks are on the condition of 12049 // if statements, do/while loops, and for loops. 12050 // Differences in scope flags for C89 mode requires the extra logic. 12051 const unsigned ForIncrementFlags = 12052 getLangOpts().C99 || getLangOpts().CPlusPlus 12053 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12054 : Scope::ContinueScope | Scope::BreakScope; 12055 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12056 const unsigned ScopeFlags = getCurScope()->getFlags(); 12057 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12058 (ScopeFlags & ForInitFlags) == ForInitFlags) 12059 return; 12060 12061 // If there are multiple comma operators used together, get the RHS of the 12062 // of the comma operator as the LHS. 12063 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12064 if (BO->getOpcode() != BO_Comma) 12065 break; 12066 LHS = BO->getRHS(); 12067 } 12068 12069 // Only allow some expressions on LHS to not warn. 12070 if (IgnoreCommaOperand(LHS)) 12071 return; 12072 12073 Diag(Loc, diag::warn_comma_operator); 12074 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12075 << LHS->getSourceRange() 12076 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12077 LangOpts.CPlusPlus ? "static_cast<void>(" 12078 : "(void)(") 12079 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12080 ")"); 12081 } 12082 12083 // C99 6.5.17 12084 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12085 SourceLocation Loc) { 12086 LHS = S.CheckPlaceholderExpr(LHS.get()); 12087 RHS = S.CheckPlaceholderExpr(RHS.get()); 12088 if (LHS.isInvalid() || RHS.isInvalid()) 12089 return QualType(); 12090 12091 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12092 // operands, but not unary promotions. 12093 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12094 12095 // So we treat the LHS as a ignored value, and in C++ we allow the 12096 // containing site to determine what should be done with the RHS. 12097 LHS = S.IgnoredValueConversions(LHS.get()); 12098 if (LHS.isInvalid()) 12099 return QualType(); 12100 12101 S.DiagnoseUnusedExprResult(LHS.get()); 12102 12103 if (!S.getLangOpts().CPlusPlus) { 12104 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12105 if (RHS.isInvalid()) 12106 return QualType(); 12107 if (!RHS.get()->getType()->isVoidType()) 12108 S.RequireCompleteType(Loc, RHS.get()->getType(), 12109 diag::err_incomplete_type); 12110 } 12111 12112 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12113 S.DiagnoseCommaOperator(LHS.get(), Loc); 12114 12115 return RHS.get()->getType(); 12116 } 12117 12118 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12119 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12120 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12121 ExprValueKind &VK, 12122 ExprObjectKind &OK, 12123 SourceLocation OpLoc, 12124 bool IsInc, bool IsPrefix) { 12125 if (Op->isTypeDependent()) 12126 return S.Context.DependentTy; 12127 12128 QualType ResType = Op->getType(); 12129 // Atomic types can be used for increment / decrement where the non-atomic 12130 // versions can, so ignore the _Atomic() specifier for the purpose of 12131 // checking. 12132 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12133 ResType = ResAtomicType->getValueType(); 12134 12135 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12136 12137 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12138 // Decrement of bool is not allowed. 12139 if (!IsInc) { 12140 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12141 return QualType(); 12142 } 12143 // Increment of bool sets it to true, but is deprecated. 12144 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12145 : diag::warn_increment_bool) 12146 << Op->getSourceRange(); 12147 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12148 // Error on enum increments and decrements in C++ mode 12149 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12150 return QualType(); 12151 } else if (ResType->isRealType()) { 12152 // OK! 12153 } else if (ResType->isPointerType()) { 12154 // C99 6.5.2.4p2, 6.5.6p2 12155 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12156 return QualType(); 12157 } else if (ResType->isObjCObjectPointerType()) { 12158 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12159 // Otherwise, we just need a complete type. 12160 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12161 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12162 return QualType(); 12163 } else if (ResType->isAnyComplexType()) { 12164 // C99 does not support ++/-- on complex types, we allow as an extension. 12165 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12166 << ResType << Op->getSourceRange(); 12167 } else if (ResType->isPlaceholderType()) { 12168 ExprResult PR = S.CheckPlaceholderExpr(Op); 12169 if (PR.isInvalid()) return QualType(); 12170 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12171 IsInc, IsPrefix); 12172 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12173 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12174 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12175 (ResType->castAs<VectorType>()->getVectorKind() != 12176 VectorType::AltiVecBool)) { 12177 // The z vector extensions allow ++ and -- for non-bool vectors. 12178 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12179 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12180 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12181 } else { 12182 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12183 << ResType << int(IsInc) << Op->getSourceRange(); 12184 return QualType(); 12185 } 12186 // At this point, we know we have a real, complex or pointer type. 12187 // Now make sure the operand is a modifiable lvalue. 12188 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12189 return QualType(); 12190 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12191 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12192 // An operand with volatile-qualified type is deprecated 12193 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12194 << IsInc << ResType; 12195 } 12196 // In C++, a prefix increment is the same type as the operand. Otherwise 12197 // (in C or with postfix), the increment is the unqualified type of the 12198 // operand. 12199 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12200 VK = VK_LValue; 12201 OK = Op->getObjectKind(); 12202 return ResType; 12203 } else { 12204 VK = VK_RValue; 12205 return ResType.getUnqualifiedType(); 12206 } 12207 } 12208 12209 12210 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12211 /// This routine allows us to typecheck complex/recursive expressions 12212 /// where the declaration is needed for type checking. We only need to 12213 /// handle cases when the expression references a function designator 12214 /// or is an lvalue. Here are some examples: 12215 /// - &(x) => x 12216 /// - &*****f => f for f a function designator. 12217 /// - &s.xx => s 12218 /// - &s.zz[1].yy -> s, if zz is an array 12219 /// - *(x + 1) -> x, if x is an array 12220 /// - &"123"[2] -> 0 12221 /// - & __real__ x -> x 12222 static ValueDecl *getPrimaryDecl(Expr *E) { 12223 switch (E->getStmtClass()) { 12224 case Stmt::DeclRefExprClass: 12225 return cast<DeclRefExpr>(E)->getDecl(); 12226 case Stmt::MemberExprClass: 12227 // If this is an arrow operator, the address is an offset from 12228 // the base's value, so the object the base refers to is 12229 // irrelevant. 12230 if (cast<MemberExpr>(E)->isArrow()) 12231 return nullptr; 12232 // Otherwise, the expression refers to a part of the base 12233 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12234 case Stmt::ArraySubscriptExprClass: { 12235 // FIXME: This code shouldn't be necessary! We should catch the implicit 12236 // promotion of register arrays earlier. 12237 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12238 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12239 if (ICE->getSubExpr()->getType()->isArrayType()) 12240 return getPrimaryDecl(ICE->getSubExpr()); 12241 } 12242 return nullptr; 12243 } 12244 case Stmt::UnaryOperatorClass: { 12245 UnaryOperator *UO = cast<UnaryOperator>(E); 12246 12247 switch(UO->getOpcode()) { 12248 case UO_Real: 12249 case UO_Imag: 12250 case UO_Extension: 12251 return getPrimaryDecl(UO->getSubExpr()); 12252 default: 12253 return nullptr; 12254 } 12255 } 12256 case Stmt::ParenExprClass: 12257 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12258 case Stmt::ImplicitCastExprClass: 12259 // If the result of an implicit cast is an l-value, we care about 12260 // the sub-expression; otherwise, the result here doesn't matter. 12261 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12262 default: 12263 return nullptr; 12264 } 12265 } 12266 12267 namespace { 12268 enum { 12269 AO_Bit_Field = 0, 12270 AO_Vector_Element = 1, 12271 AO_Property_Expansion = 2, 12272 AO_Register_Variable = 3, 12273 AO_No_Error = 4 12274 }; 12275 } 12276 /// Diagnose invalid operand for address of operations. 12277 /// 12278 /// \param Type The type of operand which cannot have its address taken. 12279 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12280 Expr *E, unsigned Type) { 12281 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12282 } 12283 12284 /// CheckAddressOfOperand - The operand of & must be either a function 12285 /// designator or an lvalue designating an object. If it is an lvalue, the 12286 /// object cannot be declared with storage class register or be a bit field. 12287 /// Note: The usual conversions are *not* applied to the operand of the & 12288 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12289 /// In C++, the operand might be an overloaded function name, in which case 12290 /// we allow the '&' but retain the overloaded-function type. 12291 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12292 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12293 if (PTy->getKind() == BuiltinType::Overload) { 12294 Expr *E = OrigOp.get()->IgnoreParens(); 12295 if (!isa<OverloadExpr>(E)) { 12296 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12297 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12298 << OrigOp.get()->getSourceRange(); 12299 return QualType(); 12300 } 12301 12302 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12303 if (isa<UnresolvedMemberExpr>(Ovl)) 12304 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12305 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12306 << OrigOp.get()->getSourceRange(); 12307 return QualType(); 12308 } 12309 12310 return Context.OverloadTy; 12311 } 12312 12313 if (PTy->getKind() == BuiltinType::UnknownAny) 12314 return Context.UnknownAnyTy; 12315 12316 if (PTy->getKind() == BuiltinType::BoundMember) { 12317 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12318 << OrigOp.get()->getSourceRange(); 12319 return QualType(); 12320 } 12321 12322 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12323 if (OrigOp.isInvalid()) return QualType(); 12324 } 12325 12326 if (OrigOp.get()->isTypeDependent()) 12327 return Context.DependentTy; 12328 12329 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12330 12331 // Make sure to ignore parentheses in subsequent checks 12332 Expr *op = OrigOp.get()->IgnoreParens(); 12333 12334 // In OpenCL captures for blocks called as lambda functions 12335 // are located in the private address space. Blocks used in 12336 // enqueue_kernel can be located in a different address space 12337 // depending on a vendor implementation. Thus preventing 12338 // taking an address of the capture to avoid invalid AS casts. 12339 if (LangOpts.OpenCL) { 12340 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12341 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12342 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12343 return QualType(); 12344 } 12345 } 12346 12347 if (getLangOpts().C99) { 12348 // Implement C99-only parts of addressof rules. 12349 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12350 if (uOp->getOpcode() == UO_Deref) 12351 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12352 // (assuming the deref expression is valid). 12353 return uOp->getSubExpr()->getType(); 12354 } 12355 // Technically, there should be a check for array subscript 12356 // expressions here, but the result of one is always an lvalue anyway. 12357 } 12358 ValueDecl *dcl = getPrimaryDecl(op); 12359 12360 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12361 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12362 op->getBeginLoc())) 12363 return QualType(); 12364 12365 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12366 unsigned AddressOfError = AO_No_Error; 12367 12368 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12369 bool sfinae = (bool)isSFINAEContext(); 12370 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12371 : diag::ext_typecheck_addrof_temporary) 12372 << op->getType() << op->getSourceRange(); 12373 if (sfinae) 12374 return QualType(); 12375 // Materialize the temporary as an lvalue so that we can take its address. 12376 OrigOp = op = 12377 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12378 } else if (isa<ObjCSelectorExpr>(op)) { 12379 return Context.getPointerType(op->getType()); 12380 } else if (lval == Expr::LV_MemberFunction) { 12381 // If it's an instance method, make a member pointer. 12382 // The expression must have exactly the form &A::foo. 12383 12384 // If the underlying expression isn't a decl ref, give up. 12385 if (!isa<DeclRefExpr>(op)) { 12386 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12387 << OrigOp.get()->getSourceRange(); 12388 return QualType(); 12389 } 12390 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12391 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12392 12393 // The id-expression was parenthesized. 12394 if (OrigOp.get() != DRE) { 12395 Diag(OpLoc, diag::err_parens_pointer_member_function) 12396 << OrigOp.get()->getSourceRange(); 12397 12398 // The method was named without a qualifier. 12399 } else if (!DRE->getQualifier()) { 12400 if (MD->getParent()->getName().empty()) 12401 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12402 << op->getSourceRange(); 12403 else { 12404 SmallString<32> Str; 12405 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12406 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12407 << op->getSourceRange() 12408 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12409 } 12410 } 12411 12412 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12413 if (isa<CXXDestructorDecl>(MD)) 12414 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12415 12416 QualType MPTy = Context.getMemberPointerType( 12417 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12418 // Under the MS ABI, lock down the inheritance model now. 12419 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12420 (void)isCompleteType(OpLoc, MPTy); 12421 return MPTy; 12422 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12423 // C99 6.5.3.2p1 12424 // The operand must be either an l-value or a function designator 12425 if (!op->getType()->isFunctionType()) { 12426 // Use a special diagnostic for loads from property references. 12427 if (isa<PseudoObjectExpr>(op)) { 12428 AddressOfError = AO_Property_Expansion; 12429 } else { 12430 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12431 << op->getType() << op->getSourceRange(); 12432 return QualType(); 12433 } 12434 } 12435 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12436 // The operand cannot be a bit-field 12437 AddressOfError = AO_Bit_Field; 12438 } else if (op->getObjectKind() == OK_VectorComponent) { 12439 // The operand cannot be an element of a vector 12440 AddressOfError = AO_Vector_Element; 12441 } else if (dcl) { // C99 6.5.3.2p1 12442 // We have an lvalue with a decl. Make sure the decl is not declared 12443 // with the register storage-class specifier. 12444 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12445 // in C++ it is not error to take address of a register 12446 // variable (c++03 7.1.1P3) 12447 if (vd->getStorageClass() == SC_Register && 12448 !getLangOpts().CPlusPlus) { 12449 AddressOfError = AO_Register_Variable; 12450 } 12451 } else if (isa<MSPropertyDecl>(dcl)) { 12452 AddressOfError = AO_Property_Expansion; 12453 } else if (isa<FunctionTemplateDecl>(dcl)) { 12454 return Context.OverloadTy; 12455 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12456 // Okay: we can take the address of a field. 12457 // Could be a pointer to member, though, if there is an explicit 12458 // scope qualifier for the class. 12459 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12460 DeclContext *Ctx = dcl->getDeclContext(); 12461 if (Ctx && Ctx->isRecord()) { 12462 if (dcl->getType()->isReferenceType()) { 12463 Diag(OpLoc, 12464 diag::err_cannot_form_pointer_to_member_of_reference_type) 12465 << dcl->getDeclName() << dcl->getType(); 12466 return QualType(); 12467 } 12468 12469 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12470 Ctx = Ctx->getParent(); 12471 12472 QualType MPTy = Context.getMemberPointerType( 12473 op->getType(), 12474 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12475 // Under the MS ABI, lock down the inheritance model now. 12476 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12477 (void)isCompleteType(OpLoc, MPTy); 12478 return MPTy; 12479 } 12480 } 12481 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12482 !isa<BindingDecl>(dcl)) 12483 llvm_unreachable("Unknown/unexpected decl type"); 12484 } 12485 12486 if (AddressOfError != AO_No_Error) { 12487 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12488 return QualType(); 12489 } 12490 12491 if (lval == Expr::LV_IncompleteVoidType) { 12492 // Taking the address of a void variable is technically illegal, but we 12493 // allow it in cases which are otherwise valid. 12494 // Example: "extern void x; void* y = &x;". 12495 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12496 } 12497 12498 // If the operand has type "type", the result has type "pointer to type". 12499 if (op->getType()->isObjCObjectType()) 12500 return Context.getObjCObjectPointerType(op->getType()); 12501 12502 CheckAddressOfPackedMember(op); 12503 12504 return Context.getPointerType(op->getType()); 12505 } 12506 12507 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12508 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12509 if (!DRE) 12510 return; 12511 const Decl *D = DRE->getDecl(); 12512 if (!D) 12513 return; 12514 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12515 if (!Param) 12516 return; 12517 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12518 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12519 return; 12520 if (FunctionScopeInfo *FD = S.getCurFunction()) 12521 if (!FD->ModifiedNonNullParams.count(Param)) 12522 FD->ModifiedNonNullParams.insert(Param); 12523 } 12524 12525 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12526 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12527 SourceLocation OpLoc) { 12528 if (Op->isTypeDependent()) 12529 return S.Context.DependentTy; 12530 12531 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12532 if (ConvResult.isInvalid()) 12533 return QualType(); 12534 Op = ConvResult.get(); 12535 QualType OpTy = Op->getType(); 12536 QualType Result; 12537 12538 if (isa<CXXReinterpretCastExpr>(Op)) { 12539 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12540 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12541 Op->getSourceRange()); 12542 } 12543 12544 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12545 { 12546 Result = PT->getPointeeType(); 12547 } 12548 else if (const ObjCObjectPointerType *OPT = 12549 OpTy->getAs<ObjCObjectPointerType>()) 12550 Result = OPT->getPointeeType(); 12551 else { 12552 ExprResult PR = S.CheckPlaceholderExpr(Op); 12553 if (PR.isInvalid()) return QualType(); 12554 if (PR.get() != Op) 12555 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12556 } 12557 12558 if (Result.isNull()) { 12559 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12560 << OpTy << Op->getSourceRange(); 12561 return QualType(); 12562 } 12563 12564 // Note that per both C89 and C99, indirection is always legal, even if Result 12565 // is an incomplete type or void. It would be possible to warn about 12566 // dereferencing a void pointer, but it's completely well-defined, and such a 12567 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12568 // for pointers to 'void' but is fine for any other pointer type: 12569 // 12570 // C++ [expr.unary.op]p1: 12571 // [...] the expression to which [the unary * operator] is applied shall 12572 // be a pointer to an object type, or a pointer to a function type 12573 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12574 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12575 << OpTy << Op->getSourceRange(); 12576 12577 // Dereferences are usually l-values... 12578 VK = VK_LValue; 12579 12580 // ...except that certain expressions are never l-values in C. 12581 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12582 VK = VK_RValue; 12583 12584 return Result; 12585 } 12586 12587 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12588 BinaryOperatorKind Opc; 12589 switch (Kind) { 12590 default: llvm_unreachable("Unknown binop!"); 12591 case tok::periodstar: Opc = BO_PtrMemD; break; 12592 case tok::arrowstar: Opc = BO_PtrMemI; break; 12593 case tok::star: Opc = BO_Mul; break; 12594 case tok::slash: Opc = BO_Div; break; 12595 case tok::percent: Opc = BO_Rem; break; 12596 case tok::plus: Opc = BO_Add; break; 12597 case tok::minus: Opc = BO_Sub; break; 12598 case tok::lessless: Opc = BO_Shl; break; 12599 case tok::greatergreater: Opc = BO_Shr; break; 12600 case tok::lessequal: Opc = BO_LE; break; 12601 case tok::less: Opc = BO_LT; break; 12602 case tok::greaterequal: Opc = BO_GE; break; 12603 case tok::greater: Opc = BO_GT; break; 12604 case tok::exclaimequal: Opc = BO_NE; break; 12605 case tok::equalequal: Opc = BO_EQ; break; 12606 case tok::spaceship: Opc = BO_Cmp; break; 12607 case tok::amp: Opc = BO_And; break; 12608 case tok::caret: Opc = BO_Xor; break; 12609 case tok::pipe: Opc = BO_Or; break; 12610 case tok::ampamp: Opc = BO_LAnd; break; 12611 case tok::pipepipe: Opc = BO_LOr; break; 12612 case tok::equal: Opc = BO_Assign; break; 12613 case tok::starequal: Opc = BO_MulAssign; break; 12614 case tok::slashequal: Opc = BO_DivAssign; break; 12615 case tok::percentequal: Opc = BO_RemAssign; break; 12616 case tok::plusequal: Opc = BO_AddAssign; break; 12617 case tok::minusequal: Opc = BO_SubAssign; break; 12618 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12619 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12620 case tok::ampequal: Opc = BO_AndAssign; break; 12621 case tok::caretequal: Opc = BO_XorAssign; break; 12622 case tok::pipeequal: Opc = BO_OrAssign; break; 12623 case tok::comma: Opc = BO_Comma; break; 12624 } 12625 return Opc; 12626 } 12627 12628 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12629 tok::TokenKind Kind) { 12630 UnaryOperatorKind Opc; 12631 switch (Kind) { 12632 default: llvm_unreachable("Unknown unary op!"); 12633 case tok::plusplus: Opc = UO_PreInc; break; 12634 case tok::minusminus: Opc = UO_PreDec; break; 12635 case tok::amp: Opc = UO_AddrOf; break; 12636 case tok::star: Opc = UO_Deref; break; 12637 case tok::plus: Opc = UO_Plus; break; 12638 case tok::minus: Opc = UO_Minus; break; 12639 case tok::tilde: Opc = UO_Not; break; 12640 case tok::exclaim: Opc = UO_LNot; break; 12641 case tok::kw___real: Opc = UO_Real; break; 12642 case tok::kw___imag: Opc = UO_Imag; break; 12643 case tok::kw___extension__: Opc = UO_Extension; break; 12644 } 12645 return Opc; 12646 } 12647 12648 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12649 /// This warning suppressed in the event of macro expansions. 12650 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12651 SourceLocation OpLoc, bool IsBuiltin) { 12652 if (S.inTemplateInstantiation()) 12653 return; 12654 if (S.isUnevaluatedContext()) 12655 return; 12656 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12657 return; 12658 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12659 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12660 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12661 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12662 if (!LHSDeclRef || !RHSDeclRef || 12663 LHSDeclRef->getLocation().isMacroID() || 12664 RHSDeclRef->getLocation().isMacroID()) 12665 return; 12666 const ValueDecl *LHSDecl = 12667 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12668 const ValueDecl *RHSDecl = 12669 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12670 if (LHSDecl != RHSDecl) 12671 return; 12672 if (LHSDecl->getType().isVolatileQualified()) 12673 return; 12674 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12675 if (RefTy->getPointeeType().isVolatileQualified()) 12676 return; 12677 12678 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12679 : diag::warn_self_assignment_overloaded) 12680 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12681 << RHSExpr->getSourceRange(); 12682 } 12683 12684 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12685 /// is usually indicative of introspection within the Objective-C pointer. 12686 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12687 SourceLocation OpLoc) { 12688 if (!S.getLangOpts().ObjC) 12689 return; 12690 12691 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12692 const Expr *LHS = L.get(); 12693 const Expr *RHS = R.get(); 12694 12695 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12696 ObjCPointerExpr = LHS; 12697 OtherExpr = RHS; 12698 } 12699 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12700 ObjCPointerExpr = RHS; 12701 OtherExpr = LHS; 12702 } 12703 12704 // This warning is deliberately made very specific to reduce false 12705 // positives with logic that uses '&' for hashing. This logic mainly 12706 // looks for code trying to introspect into tagged pointers, which 12707 // code should generally never do. 12708 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12709 unsigned Diag = diag::warn_objc_pointer_masking; 12710 // Determine if we are introspecting the result of performSelectorXXX. 12711 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12712 // Special case messages to -performSelector and friends, which 12713 // can return non-pointer values boxed in a pointer value. 12714 // Some clients may wish to silence warnings in this subcase. 12715 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12716 Selector S = ME->getSelector(); 12717 StringRef SelArg0 = S.getNameForSlot(0); 12718 if (SelArg0.startswith("performSelector")) 12719 Diag = diag::warn_objc_pointer_masking_performSelector; 12720 } 12721 12722 S.Diag(OpLoc, Diag) 12723 << ObjCPointerExpr->getSourceRange(); 12724 } 12725 } 12726 12727 static NamedDecl *getDeclFromExpr(Expr *E) { 12728 if (!E) 12729 return nullptr; 12730 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12731 return DRE->getDecl(); 12732 if (auto *ME = dyn_cast<MemberExpr>(E)) 12733 return ME->getMemberDecl(); 12734 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12735 return IRE->getDecl(); 12736 return nullptr; 12737 } 12738 12739 // This helper function promotes a binary operator's operands (which are of a 12740 // half vector type) to a vector of floats and then truncates the result to 12741 // a vector of either half or short. 12742 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12743 BinaryOperatorKind Opc, QualType ResultTy, 12744 ExprValueKind VK, ExprObjectKind OK, 12745 bool IsCompAssign, SourceLocation OpLoc, 12746 FPOptions FPFeatures) { 12747 auto &Context = S.getASTContext(); 12748 assert((isVector(ResultTy, Context.HalfTy) || 12749 isVector(ResultTy, Context.ShortTy)) && 12750 "Result must be a vector of half or short"); 12751 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12752 isVector(RHS.get()->getType(), Context.HalfTy) && 12753 "both operands expected to be a half vector"); 12754 12755 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12756 QualType BinOpResTy = RHS.get()->getType(); 12757 12758 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12759 // change BinOpResTy to a vector of ints. 12760 if (isVector(ResultTy, Context.ShortTy)) 12761 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12762 12763 if (IsCompAssign) 12764 return new (Context) CompoundAssignOperator( 12765 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12766 OpLoc, FPFeatures); 12767 12768 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12769 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12770 VK, OK, OpLoc, FPFeatures); 12771 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12772 } 12773 12774 static std::pair<ExprResult, ExprResult> 12775 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12776 Expr *RHSExpr) { 12777 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12778 if (!S.getLangOpts().CPlusPlus) { 12779 // C cannot handle TypoExpr nodes on either side of a binop because it 12780 // doesn't handle dependent types properly, so make sure any TypoExprs have 12781 // been dealt with before checking the operands. 12782 LHS = S.CorrectDelayedTyposInExpr(LHS); 12783 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12784 if (Opc != BO_Assign) 12785 return ExprResult(E); 12786 // Avoid correcting the RHS to the same Expr as the LHS. 12787 Decl *D = getDeclFromExpr(E); 12788 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12789 }); 12790 } 12791 return std::make_pair(LHS, RHS); 12792 } 12793 12794 /// Returns true if conversion between vectors of halfs and vectors of floats 12795 /// is needed. 12796 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12797 QualType SrcType) { 12798 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12799 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12800 isVector(SrcType, Ctx.HalfTy); 12801 } 12802 12803 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12804 /// operator @p Opc at location @c TokLoc. This routine only supports 12805 /// built-in operations; ActOnBinOp handles overloaded operators. 12806 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12807 BinaryOperatorKind Opc, 12808 Expr *LHSExpr, Expr *RHSExpr) { 12809 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12810 // The syntax only allows initializer lists on the RHS of assignment, 12811 // so we don't need to worry about accepting invalid code for 12812 // non-assignment operators. 12813 // C++11 5.17p9: 12814 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12815 // of x = {} is x = T(). 12816 InitializationKind Kind = InitializationKind::CreateDirectList( 12817 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12818 InitializedEntity Entity = 12819 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12820 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12821 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12822 if (Init.isInvalid()) 12823 return Init; 12824 RHSExpr = Init.get(); 12825 } 12826 12827 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12828 QualType ResultTy; // Result type of the binary operator. 12829 // The following two variables are used for compound assignment operators 12830 QualType CompLHSTy; // Type of LHS after promotions for computation 12831 QualType CompResultTy; // Type of computation result 12832 ExprValueKind VK = VK_RValue; 12833 ExprObjectKind OK = OK_Ordinary; 12834 bool ConvertHalfVec = false; 12835 12836 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12837 if (!LHS.isUsable() || !RHS.isUsable()) 12838 return ExprError(); 12839 12840 if (getLangOpts().OpenCL) { 12841 QualType LHSTy = LHSExpr->getType(); 12842 QualType RHSTy = RHSExpr->getType(); 12843 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12844 // the ATOMIC_VAR_INIT macro. 12845 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12846 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12847 if (BO_Assign == Opc) 12848 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12849 else 12850 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12851 return ExprError(); 12852 } 12853 12854 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12855 // only with a builtin functions and therefore should be disallowed here. 12856 if (LHSTy->isImageType() || RHSTy->isImageType() || 12857 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12858 LHSTy->isPipeType() || RHSTy->isPipeType() || 12859 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12860 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12861 return ExprError(); 12862 } 12863 } 12864 12865 // Diagnose operations on the unsupported types for OpenMP device compilation. 12866 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12867 if (Opc != BO_Assign && Opc != BO_Comma) { 12868 checkOpenMPDeviceExpr(LHSExpr); 12869 checkOpenMPDeviceExpr(RHSExpr); 12870 } 12871 } 12872 12873 switch (Opc) { 12874 case BO_Assign: 12875 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12876 if (getLangOpts().CPlusPlus && 12877 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12878 VK = LHS.get()->getValueKind(); 12879 OK = LHS.get()->getObjectKind(); 12880 } 12881 if (!ResultTy.isNull()) { 12882 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12883 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12884 12885 // Avoid copying a block to the heap if the block is assigned to a local 12886 // auto variable that is declared in the same scope as the block. This 12887 // optimization is unsafe if the local variable is declared in an outer 12888 // scope. For example: 12889 // 12890 // BlockTy b; 12891 // { 12892 // b = ^{...}; 12893 // } 12894 // // It is unsafe to invoke the block here if it wasn't copied to the 12895 // // heap. 12896 // b(); 12897 12898 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12899 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12900 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12901 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12902 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12903 12904 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12905 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12906 NTCUC_Assignment, NTCUK_Copy); 12907 } 12908 RecordModifiableNonNullParam(*this, LHS.get()); 12909 break; 12910 case BO_PtrMemD: 12911 case BO_PtrMemI: 12912 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12913 Opc == BO_PtrMemI); 12914 break; 12915 case BO_Mul: 12916 case BO_Div: 12917 ConvertHalfVec = true; 12918 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12919 Opc == BO_Div); 12920 break; 12921 case BO_Rem: 12922 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12923 break; 12924 case BO_Add: 12925 ConvertHalfVec = true; 12926 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12927 break; 12928 case BO_Sub: 12929 ConvertHalfVec = true; 12930 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12931 break; 12932 case BO_Shl: 12933 case BO_Shr: 12934 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12935 break; 12936 case BO_LE: 12937 case BO_LT: 12938 case BO_GE: 12939 case BO_GT: 12940 ConvertHalfVec = true; 12941 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12942 break; 12943 case BO_EQ: 12944 case BO_NE: 12945 ConvertHalfVec = true; 12946 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12947 break; 12948 case BO_Cmp: 12949 ConvertHalfVec = true; 12950 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12951 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12952 break; 12953 case BO_And: 12954 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12955 LLVM_FALLTHROUGH; 12956 case BO_Xor: 12957 case BO_Or: 12958 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12959 break; 12960 case BO_LAnd: 12961 case BO_LOr: 12962 ConvertHalfVec = true; 12963 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12964 break; 12965 case BO_MulAssign: 12966 case BO_DivAssign: 12967 ConvertHalfVec = true; 12968 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12969 Opc == BO_DivAssign); 12970 CompLHSTy = CompResultTy; 12971 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12972 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12973 break; 12974 case BO_RemAssign: 12975 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12976 CompLHSTy = CompResultTy; 12977 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12978 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12979 break; 12980 case BO_AddAssign: 12981 ConvertHalfVec = true; 12982 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12983 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12984 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12985 break; 12986 case BO_SubAssign: 12987 ConvertHalfVec = true; 12988 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12989 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12990 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12991 break; 12992 case BO_ShlAssign: 12993 case BO_ShrAssign: 12994 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12995 CompLHSTy = CompResultTy; 12996 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12997 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12998 break; 12999 case BO_AndAssign: 13000 case BO_OrAssign: // fallthrough 13001 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13002 LLVM_FALLTHROUGH; 13003 case BO_XorAssign: 13004 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13005 CompLHSTy = CompResultTy; 13006 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13007 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13008 break; 13009 case BO_Comma: 13010 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13011 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13012 VK = RHS.get()->getValueKind(); 13013 OK = RHS.get()->getObjectKind(); 13014 } 13015 break; 13016 } 13017 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13018 return ExprError(); 13019 13020 // Some of the binary operations require promoting operands of half vector to 13021 // float vectors and truncating the result back to half vector. For now, we do 13022 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13023 // arm64). 13024 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13025 isVector(LHS.get()->getType(), Context.HalfTy) && 13026 "both sides are half vectors or neither sides are"); 13027 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13028 LHS.get()->getType()); 13029 13030 // Check for array bounds violations for both sides of the BinaryOperator 13031 CheckArrayAccess(LHS.get()); 13032 CheckArrayAccess(RHS.get()); 13033 13034 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13035 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13036 &Context.Idents.get("object_setClass"), 13037 SourceLocation(), LookupOrdinaryName); 13038 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13039 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13040 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13041 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13042 "object_setClass(") 13043 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13044 ",") 13045 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13046 } 13047 else 13048 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13049 } 13050 else if (const ObjCIvarRefExpr *OIRE = 13051 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13052 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13053 13054 // Opc is not a compound assignment if CompResultTy is null. 13055 if (CompResultTy.isNull()) { 13056 if (ConvertHalfVec) 13057 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13058 OpLoc, FPFeatures); 13059 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13060 OK, OpLoc, FPFeatures); 13061 } 13062 13063 // Handle compound assignments. 13064 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13065 OK_ObjCProperty) { 13066 VK = VK_LValue; 13067 OK = LHS.get()->getObjectKind(); 13068 } 13069 13070 if (ConvertHalfVec) 13071 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13072 OpLoc, FPFeatures); 13073 13074 return new (Context) CompoundAssignOperator( 13075 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13076 OpLoc, FPFeatures); 13077 } 13078 13079 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13080 /// operators are mixed in a way that suggests that the programmer forgot that 13081 /// comparison operators have higher precedence. The most typical example of 13082 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13083 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13084 SourceLocation OpLoc, Expr *LHSExpr, 13085 Expr *RHSExpr) { 13086 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13087 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13088 13089 // Check that one of the sides is a comparison operator and the other isn't. 13090 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13091 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13092 if (isLeftComp == isRightComp) 13093 return; 13094 13095 // Bitwise operations are sometimes used as eager logical ops. 13096 // Don't diagnose this. 13097 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13098 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13099 if (isLeftBitwise || isRightBitwise) 13100 return; 13101 13102 SourceRange DiagRange = isLeftComp 13103 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13104 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13105 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13106 SourceRange ParensRange = 13107 isLeftComp 13108 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13109 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13110 13111 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13112 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13113 SuggestParentheses(Self, OpLoc, 13114 Self.PDiag(diag::note_precedence_silence) << OpStr, 13115 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13116 SuggestParentheses(Self, OpLoc, 13117 Self.PDiag(diag::note_precedence_bitwise_first) 13118 << BinaryOperator::getOpcodeStr(Opc), 13119 ParensRange); 13120 } 13121 13122 /// It accepts a '&&' expr that is inside a '||' one. 13123 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13124 /// in parentheses. 13125 static void 13126 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13127 BinaryOperator *Bop) { 13128 assert(Bop->getOpcode() == BO_LAnd); 13129 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13130 << Bop->getSourceRange() << OpLoc; 13131 SuggestParentheses(Self, Bop->getOperatorLoc(), 13132 Self.PDiag(diag::note_precedence_silence) 13133 << Bop->getOpcodeStr(), 13134 Bop->getSourceRange()); 13135 } 13136 13137 /// Returns true if the given expression can be evaluated as a constant 13138 /// 'true'. 13139 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13140 bool Res; 13141 return !E->isValueDependent() && 13142 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13143 } 13144 13145 /// Returns true if the given expression can be evaluated as a constant 13146 /// 'false'. 13147 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13148 bool Res; 13149 return !E->isValueDependent() && 13150 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13151 } 13152 13153 /// Look for '&&' in the left hand of a '||' expr. 13154 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13155 Expr *LHSExpr, Expr *RHSExpr) { 13156 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13157 if (Bop->getOpcode() == BO_LAnd) { 13158 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13159 if (EvaluatesAsFalse(S, RHSExpr)) 13160 return; 13161 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13162 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13163 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13164 } else if (Bop->getOpcode() == BO_LOr) { 13165 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13166 // If it's "a || b && 1 || c" we didn't warn earlier for 13167 // "a || b && 1", but warn now. 13168 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13169 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13170 } 13171 } 13172 } 13173 } 13174 13175 /// Look for '&&' in the right hand of a '||' expr. 13176 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13177 Expr *LHSExpr, Expr *RHSExpr) { 13178 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13179 if (Bop->getOpcode() == BO_LAnd) { 13180 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13181 if (EvaluatesAsFalse(S, LHSExpr)) 13182 return; 13183 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13184 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13185 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13186 } 13187 } 13188 } 13189 13190 /// Look for bitwise op in the left or right hand of a bitwise op with 13191 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13192 /// the '&' expression in parentheses. 13193 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13194 SourceLocation OpLoc, Expr *SubExpr) { 13195 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13196 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13197 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13198 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13199 << Bop->getSourceRange() << OpLoc; 13200 SuggestParentheses(S, Bop->getOperatorLoc(), 13201 S.PDiag(diag::note_precedence_silence) 13202 << Bop->getOpcodeStr(), 13203 Bop->getSourceRange()); 13204 } 13205 } 13206 } 13207 13208 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13209 Expr *SubExpr, StringRef Shift) { 13210 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13211 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13212 StringRef Op = Bop->getOpcodeStr(); 13213 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13214 << Bop->getSourceRange() << OpLoc << Shift << Op; 13215 SuggestParentheses(S, Bop->getOperatorLoc(), 13216 S.PDiag(diag::note_precedence_silence) << Op, 13217 Bop->getSourceRange()); 13218 } 13219 } 13220 } 13221 13222 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13223 Expr *LHSExpr, Expr *RHSExpr) { 13224 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13225 if (!OCE) 13226 return; 13227 13228 FunctionDecl *FD = OCE->getDirectCallee(); 13229 if (!FD || !FD->isOverloadedOperator()) 13230 return; 13231 13232 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13233 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13234 return; 13235 13236 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13237 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13238 << (Kind == OO_LessLess); 13239 SuggestParentheses(S, OCE->getOperatorLoc(), 13240 S.PDiag(diag::note_precedence_silence) 13241 << (Kind == OO_LessLess ? "<<" : ">>"), 13242 OCE->getSourceRange()); 13243 SuggestParentheses( 13244 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13245 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13246 } 13247 13248 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13249 /// precedence. 13250 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13251 SourceLocation OpLoc, Expr *LHSExpr, 13252 Expr *RHSExpr){ 13253 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13254 if (BinaryOperator::isBitwiseOp(Opc)) 13255 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13256 13257 // Diagnose "arg1 & arg2 | arg3" 13258 if ((Opc == BO_Or || Opc == BO_Xor) && 13259 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13260 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13261 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13262 } 13263 13264 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13265 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13266 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13267 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13268 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13269 } 13270 13271 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13272 || Opc == BO_Shr) { 13273 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13274 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13275 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13276 } 13277 13278 // Warn on overloaded shift operators and comparisons, such as: 13279 // cout << 5 == 4; 13280 if (BinaryOperator::isComparisonOp(Opc)) 13281 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13282 } 13283 13284 // Binary Operators. 'Tok' is the token for the operator. 13285 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13286 tok::TokenKind Kind, 13287 Expr *LHSExpr, Expr *RHSExpr) { 13288 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13289 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13290 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13291 13292 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13293 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13294 13295 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13296 } 13297 13298 /// Build an overloaded binary operator expression in the given scope. 13299 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13300 BinaryOperatorKind Opc, 13301 Expr *LHS, Expr *RHS) { 13302 switch (Opc) { 13303 case BO_Assign: 13304 case BO_DivAssign: 13305 case BO_RemAssign: 13306 case BO_SubAssign: 13307 case BO_AndAssign: 13308 case BO_OrAssign: 13309 case BO_XorAssign: 13310 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13311 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13312 break; 13313 default: 13314 break; 13315 } 13316 13317 // Find all of the overloaded operators visible from this 13318 // point. We perform both an operator-name lookup from the local 13319 // scope and an argument-dependent lookup based on the types of 13320 // the arguments. 13321 UnresolvedSet<16> Functions; 13322 OverloadedOperatorKind OverOp 13323 = BinaryOperator::getOverloadedOperator(Opc); 13324 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13325 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13326 RHS->getType(), Functions); 13327 13328 // In C++20 onwards, we may have a second operator to look up. 13329 if (S.getLangOpts().CPlusPlus2a) { 13330 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13331 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13332 RHS->getType(), Functions); 13333 } 13334 13335 // Build the (potentially-overloaded, potentially-dependent) 13336 // binary operation. 13337 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13338 } 13339 13340 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13341 BinaryOperatorKind Opc, 13342 Expr *LHSExpr, Expr *RHSExpr) { 13343 ExprResult LHS, RHS; 13344 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13345 if (!LHS.isUsable() || !RHS.isUsable()) 13346 return ExprError(); 13347 LHSExpr = LHS.get(); 13348 RHSExpr = RHS.get(); 13349 13350 // We want to end up calling one of checkPseudoObjectAssignment 13351 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13352 // both expressions are overloadable or either is type-dependent), 13353 // or CreateBuiltinBinOp (in any other case). We also want to get 13354 // any placeholder types out of the way. 13355 13356 // Handle pseudo-objects in the LHS. 13357 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13358 // Assignments with a pseudo-object l-value need special analysis. 13359 if (pty->getKind() == BuiltinType::PseudoObject && 13360 BinaryOperator::isAssignmentOp(Opc)) 13361 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13362 13363 // Don't resolve overloads if the other type is overloadable. 13364 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13365 // We can't actually test that if we still have a placeholder, 13366 // though. Fortunately, none of the exceptions we see in that 13367 // code below are valid when the LHS is an overload set. Note 13368 // that an overload set can be dependently-typed, but it never 13369 // instantiates to having an overloadable type. 13370 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13371 if (resolvedRHS.isInvalid()) return ExprError(); 13372 RHSExpr = resolvedRHS.get(); 13373 13374 if (RHSExpr->isTypeDependent() || 13375 RHSExpr->getType()->isOverloadableType()) 13376 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13377 } 13378 13379 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13380 // template, diagnose the missing 'template' keyword instead of diagnosing 13381 // an invalid use of a bound member function. 13382 // 13383 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13384 // to C++1z [over.over]/1.4, but we already checked for that case above. 13385 if (Opc == BO_LT && inTemplateInstantiation() && 13386 (pty->getKind() == BuiltinType::BoundMember || 13387 pty->getKind() == BuiltinType::Overload)) { 13388 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13389 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13390 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13391 return isa<FunctionTemplateDecl>(ND); 13392 })) { 13393 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13394 : OE->getNameLoc(), 13395 diag::err_template_kw_missing) 13396 << OE->getName().getAsString() << ""; 13397 return ExprError(); 13398 } 13399 } 13400 13401 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13402 if (LHS.isInvalid()) return ExprError(); 13403 LHSExpr = LHS.get(); 13404 } 13405 13406 // Handle pseudo-objects in the RHS. 13407 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13408 // An overload in the RHS can potentially be resolved by the type 13409 // being assigned to. 13410 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13411 if (getLangOpts().CPlusPlus && 13412 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13413 LHSExpr->getType()->isOverloadableType())) 13414 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13415 13416 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13417 } 13418 13419 // Don't resolve overloads if the other type is overloadable. 13420 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13421 LHSExpr->getType()->isOverloadableType()) 13422 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13423 13424 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13425 if (!resolvedRHS.isUsable()) return ExprError(); 13426 RHSExpr = resolvedRHS.get(); 13427 } 13428 13429 if (getLangOpts().CPlusPlus) { 13430 // If either expression is type-dependent, always build an 13431 // overloaded op. 13432 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13433 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13434 13435 // Otherwise, build an overloaded op if either expression has an 13436 // overloadable type. 13437 if (LHSExpr->getType()->isOverloadableType() || 13438 RHSExpr->getType()->isOverloadableType()) 13439 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13440 } 13441 13442 // Build a built-in binary operation. 13443 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13444 } 13445 13446 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13447 if (T.isNull() || T->isDependentType()) 13448 return false; 13449 13450 if (!T->isPromotableIntegerType()) 13451 return true; 13452 13453 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13454 } 13455 13456 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13457 UnaryOperatorKind Opc, 13458 Expr *InputExpr) { 13459 ExprResult Input = InputExpr; 13460 ExprValueKind VK = VK_RValue; 13461 ExprObjectKind OK = OK_Ordinary; 13462 QualType resultType; 13463 bool CanOverflow = false; 13464 13465 bool ConvertHalfVec = false; 13466 if (getLangOpts().OpenCL) { 13467 QualType Ty = InputExpr->getType(); 13468 // The only legal unary operation for atomics is '&'. 13469 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13470 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13471 // only with a builtin functions and therefore should be disallowed here. 13472 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13473 || Ty->isBlockPointerType())) { 13474 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13475 << InputExpr->getType() 13476 << Input.get()->getSourceRange()); 13477 } 13478 } 13479 // Diagnose operations on the unsupported types for OpenMP device compilation. 13480 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13481 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13482 UnaryOperator::isArithmeticOp(Opc)) 13483 checkOpenMPDeviceExpr(InputExpr); 13484 } 13485 13486 switch (Opc) { 13487 case UO_PreInc: 13488 case UO_PreDec: 13489 case UO_PostInc: 13490 case UO_PostDec: 13491 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13492 OpLoc, 13493 Opc == UO_PreInc || 13494 Opc == UO_PostInc, 13495 Opc == UO_PreInc || 13496 Opc == UO_PreDec); 13497 CanOverflow = isOverflowingIntegerType(Context, resultType); 13498 break; 13499 case UO_AddrOf: 13500 resultType = CheckAddressOfOperand(Input, OpLoc); 13501 CheckAddressOfNoDeref(InputExpr); 13502 RecordModifiableNonNullParam(*this, InputExpr); 13503 break; 13504 case UO_Deref: { 13505 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13506 if (Input.isInvalid()) return ExprError(); 13507 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13508 break; 13509 } 13510 case UO_Plus: 13511 case UO_Minus: 13512 CanOverflow = Opc == UO_Minus && 13513 isOverflowingIntegerType(Context, Input.get()->getType()); 13514 Input = UsualUnaryConversions(Input.get()); 13515 if (Input.isInvalid()) return ExprError(); 13516 // Unary plus and minus require promoting an operand of half vector to a 13517 // float vector and truncating the result back to a half vector. For now, we 13518 // do this only when HalfArgsAndReturns is set (that is, when the target is 13519 // arm or arm64). 13520 ConvertHalfVec = 13521 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13522 13523 // If the operand is a half vector, promote it to a float vector. 13524 if (ConvertHalfVec) 13525 Input = convertVector(Input.get(), Context.FloatTy, *this); 13526 resultType = Input.get()->getType(); 13527 if (resultType->isDependentType()) 13528 break; 13529 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13530 break; 13531 else if (resultType->isVectorType() && 13532 // The z vector extensions don't allow + or - with bool vectors. 13533 (!Context.getLangOpts().ZVector || 13534 resultType->castAs<VectorType>()->getVectorKind() != 13535 VectorType::AltiVecBool)) 13536 break; 13537 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13538 Opc == UO_Plus && 13539 resultType->isPointerType()) 13540 break; 13541 13542 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13543 << resultType << Input.get()->getSourceRange()); 13544 13545 case UO_Not: // bitwise complement 13546 Input = UsualUnaryConversions(Input.get()); 13547 if (Input.isInvalid()) 13548 return ExprError(); 13549 resultType = Input.get()->getType(); 13550 if (resultType->isDependentType()) 13551 break; 13552 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13553 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13554 // C99 does not support '~' for complex conjugation. 13555 Diag(OpLoc, diag::ext_integer_complement_complex) 13556 << resultType << Input.get()->getSourceRange(); 13557 else if (resultType->hasIntegerRepresentation()) 13558 break; 13559 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13560 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13561 // on vector float types. 13562 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13563 if (!T->isIntegerType()) 13564 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13565 << resultType << Input.get()->getSourceRange()); 13566 } else { 13567 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13568 << resultType << Input.get()->getSourceRange()); 13569 } 13570 break; 13571 13572 case UO_LNot: // logical negation 13573 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13574 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13575 if (Input.isInvalid()) return ExprError(); 13576 resultType = Input.get()->getType(); 13577 13578 // Though we still have to promote half FP to float... 13579 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13580 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13581 resultType = Context.FloatTy; 13582 } 13583 13584 if (resultType->isDependentType()) 13585 break; 13586 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13587 // C99 6.5.3.3p1: ok, fallthrough; 13588 if (Context.getLangOpts().CPlusPlus) { 13589 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13590 // operand contextually converted to bool. 13591 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13592 ScalarTypeToBooleanCastKind(resultType)); 13593 } else if (Context.getLangOpts().OpenCL && 13594 Context.getLangOpts().OpenCLVersion < 120) { 13595 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13596 // operate on scalar float types. 13597 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13598 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13599 << resultType << Input.get()->getSourceRange()); 13600 } 13601 } else if (resultType->isExtVectorType()) { 13602 if (Context.getLangOpts().OpenCL && 13603 Context.getLangOpts().OpenCLVersion < 120 && 13604 !Context.getLangOpts().OpenCLCPlusPlus) { 13605 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13606 // operate on vector float types. 13607 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13608 if (!T->isIntegerType()) 13609 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13610 << resultType << Input.get()->getSourceRange()); 13611 } 13612 // Vector logical not returns the signed variant of the operand type. 13613 resultType = GetSignedVectorType(resultType); 13614 break; 13615 } else { 13616 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13617 // type in C++. We should allow that here too. 13618 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13619 << resultType << Input.get()->getSourceRange()); 13620 } 13621 13622 // LNot always has type int. C99 6.5.3.3p5. 13623 // In C++, it's bool. C++ 5.3.1p8 13624 resultType = Context.getLogicalOperationType(); 13625 break; 13626 case UO_Real: 13627 case UO_Imag: 13628 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13629 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13630 // complex l-values to ordinary l-values and all other values to r-values. 13631 if (Input.isInvalid()) return ExprError(); 13632 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13633 if (Input.get()->getValueKind() != VK_RValue && 13634 Input.get()->getObjectKind() == OK_Ordinary) 13635 VK = Input.get()->getValueKind(); 13636 } else if (!getLangOpts().CPlusPlus) { 13637 // In C, a volatile scalar is read by __imag. In C++, it is not. 13638 Input = DefaultLvalueConversion(Input.get()); 13639 } 13640 break; 13641 case UO_Extension: 13642 resultType = Input.get()->getType(); 13643 VK = Input.get()->getValueKind(); 13644 OK = Input.get()->getObjectKind(); 13645 break; 13646 case UO_Coawait: 13647 // It's unnecessary to represent the pass-through operator co_await in the 13648 // AST; just return the input expression instead. 13649 assert(!Input.get()->getType()->isDependentType() && 13650 "the co_await expression must be non-dependant before " 13651 "building operator co_await"); 13652 return Input; 13653 } 13654 if (resultType.isNull() || Input.isInvalid()) 13655 return ExprError(); 13656 13657 // Check for array bounds violations in the operand of the UnaryOperator, 13658 // except for the '*' and '&' operators that have to be handled specially 13659 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13660 // that are explicitly defined as valid by the standard). 13661 if (Opc != UO_AddrOf && Opc != UO_Deref) 13662 CheckArrayAccess(Input.get()); 13663 13664 auto *UO = new (Context) 13665 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13666 13667 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13668 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13669 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13670 13671 // Convert the result back to a half vector. 13672 if (ConvertHalfVec) 13673 return convertVector(UO, Context.HalfTy, *this); 13674 return UO; 13675 } 13676 13677 /// Determine whether the given expression is a qualified member 13678 /// access expression, of a form that could be turned into a pointer to member 13679 /// with the address-of operator. 13680 bool Sema::isQualifiedMemberAccess(Expr *E) { 13681 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13682 if (!DRE->getQualifier()) 13683 return false; 13684 13685 ValueDecl *VD = DRE->getDecl(); 13686 if (!VD->isCXXClassMember()) 13687 return false; 13688 13689 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13690 return true; 13691 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13692 return Method->isInstance(); 13693 13694 return false; 13695 } 13696 13697 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13698 if (!ULE->getQualifier()) 13699 return false; 13700 13701 for (NamedDecl *D : ULE->decls()) { 13702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13703 if (Method->isInstance()) 13704 return true; 13705 } else { 13706 // Overload set does not contain methods. 13707 break; 13708 } 13709 } 13710 13711 return false; 13712 } 13713 13714 return false; 13715 } 13716 13717 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13718 UnaryOperatorKind Opc, Expr *Input) { 13719 // First things first: handle placeholders so that the 13720 // overloaded-operator check considers the right type. 13721 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13722 // Increment and decrement of pseudo-object references. 13723 if (pty->getKind() == BuiltinType::PseudoObject && 13724 UnaryOperator::isIncrementDecrementOp(Opc)) 13725 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13726 13727 // extension is always a builtin operator. 13728 if (Opc == UO_Extension) 13729 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13730 13731 // & gets special logic for several kinds of placeholder. 13732 // The builtin code knows what to do. 13733 if (Opc == UO_AddrOf && 13734 (pty->getKind() == BuiltinType::Overload || 13735 pty->getKind() == BuiltinType::UnknownAny || 13736 pty->getKind() == BuiltinType::BoundMember)) 13737 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13738 13739 // Anything else needs to be handled now. 13740 ExprResult Result = CheckPlaceholderExpr(Input); 13741 if (Result.isInvalid()) return ExprError(); 13742 Input = Result.get(); 13743 } 13744 13745 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13746 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13747 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13748 // Find all of the overloaded operators visible from this 13749 // point. We perform both an operator-name lookup from the local 13750 // scope and an argument-dependent lookup based on the types of 13751 // the arguments. 13752 UnresolvedSet<16> Functions; 13753 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13754 if (S && OverOp != OO_None) 13755 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13756 Functions); 13757 13758 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13759 } 13760 13761 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13762 } 13763 13764 // Unary Operators. 'Tok' is the token for the operator. 13765 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13766 tok::TokenKind Op, Expr *Input) { 13767 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13768 } 13769 13770 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13771 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13772 LabelDecl *TheDecl) { 13773 TheDecl->markUsed(Context); 13774 // Create the AST node. The address of a label always has type 'void*'. 13775 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13776 Context.getPointerType(Context.VoidTy)); 13777 } 13778 13779 void Sema::ActOnStartStmtExpr() { 13780 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13781 } 13782 13783 void Sema::ActOnStmtExprError() { 13784 // Note that function is also called by TreeTransform when leaving a 13785 // StmtExpr scope without rebuilding anything. 13786 13787 DiscardCleanupsInEvaluationContext(); 13788 PopExpressionEvaluationContext(); 13789 } 13790 13791 ExprResult 13792 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13793 SourceLocation RPLoc) { // "({..})" 13794 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13795 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13796 13797 if (hasAnyUnrecoverableErrorsInThisFunction()) 13798 DiscardCleanupsInEvaluationContext(); 13799 assert(!Cleanup.exprNeedsCleanups() && 13800 "cleanups within StmtExpr not correctly bound!"); 13801 PopExpressionEvaluationContext(); 13802 13803 // FIXME: there are a variety of strange constraints to enforce here, for 13804 // example, it is not possible to goto into a stmt expression apparently. 13805 // More semantic analysis is needed. 13806 13807 // If there are sub-stmts in the compound stmt, take the type of the last one 13808 // as the type of the stmtexpr. 13809 QualType Ty = Context.VoidTy; 13810 bool StmtExprMayBindToTemp = false; 13811 if (!Compound->body_empty()) { 13812 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13813 if (const auto *LastStmt = 13814 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13815 if (const Expr *Value = LastStmt->getExprStmt()) { 13816 StmtExprMayBindToTemp = true; 13817 Ty = Value->getType(); 13818 } 13819 } 13820 } 13821 13822 // FIXME: Check that expression type is complete/non-abstract; statement 13823 // expressions are not lvalues. 13824 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13825 if (StmtExprMayBindToTemp) 13826 return MaybeBindToTemporary(ResStmtExpr); 13827 return ResStmtExpr; 13828 } 13829 13830 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13831 if (ER.isInvalid()) 13832 return ExprError(); 13833 13834 // Do function/array conversion on the last expression, but not 13835 // lvalue-to-rvalue. However, initialize an unqualified type. 13836 ER = DefaultFunctionArrayConversion(ER.get()); 13837 if (ER.isInvalid()) 13838 return ExprError(); 13839 Expr *E = ER.get(); 13840 13841 if (E->isTypeDependent()) 13842 return E; 13843 13844 // In ARC, if the final expression ends in a consume, splice 13845 // the consume out and bind it later. In the alternate case 13846 // (when dealing with a retainable type), the result 13847 // initialization will create a produce. In both cases the 13848 // result will be +1, and we'll need to balance that out with 13849 // a bind. 13850 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13851 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13852 return Cast->getSubExpr(); 13853 13854 // FIXME: Provide a better location for the initialization. 13855 return PerformCopyInitialization( 13856 InitializedEntity::InitializeStmtExprResult( 13857 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13858 SourceLocation(), E); 13859 } 13860 13861 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13862 TypeSourceInfo *TInfo, 13863 ArrayRef<OffsetOfComponent> Components, 13864 SourceLocation RParenLoc) { 13865 QualType ArgTy = TInfo->getType(); 13866 bool Dependent = ArgTy->isDependentType(); 13867 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13868 13869 // We must have at least one component that refers to the type, and the first 13870 // one is known to be a field designator. Verify that the ArgTy represents 13871 // a struct/union/class. 13872 if (!Dependent && !ArgTy->isRecordType()) 13873 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13874 << ArgTy << TypeRange); 13875 13876 // Type must be complete per C99 7.17p3 because a declaring a variable 13877 // with an incomplete type would be ill-formed. 13878 if (!Dependent 13879 && RequireCompleteType(BuiltinLoc, ArgTy, 13880 diag::err_offsetof_incomplete_type, TypeRange)) 13881 return ExprError(); 13882 13883 bool DidWarnAboutNonPOD = false; 13884 QualType CurrentType = ArgTy; 13885 SmallVector<OffsetOfNode, 4> Comps; 13886 SmallVector<Expr*, 4> Exprs; 13887 for (const OffsetOfComponent &OC : Components) { 13888 if (OC.isBrackets) { 13889 // Offset of an array sub-field. TODO: Should we allow vector elements? 13890 if (!CurrentType->isDependentType()) { 13891 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13892 if(!AT) 13893 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13894 << CurrentType); 13895 CurrentType = AT->getElementType(); 13896 } else 13897 CurrentType = Context.DependentTy; 13898 13899 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13900 if (IdxRval.isInvalid()) 13901 return ExprError(); 13902 Expr *Idx = IdxRval.get(); 13903 13904 // The expression must be an integral expression. 13905 // FIXME: An integral constant expression? 13906 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13907 !Idx->getType()->isIntegerType()) 13908 return ExprError( 13909 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13910 << Idx->getSourceRange()); 13911 13912 // Record this array index. 13913 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13914 Exprs.push_back(Idx); 13915 continue; 13916 } 13917 13918 // Offset of a field. 13919 if (CurrentType->isDependentType()) { 13920 // We have the offset of a field, but we can't look into the dependent 13921 // type. Just record the identifier of the field. 13922 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13923 CurrentType = Context.DependentTy; 13924 continue; 13925 } 13926 13927 // We need to have a complete type to look into. 13928 if (RequireCompleteType(OC.LocStart, CurrentType, 13929 diag::err_offsetof_incomplete_type)) 13930 return ExprError(); 13931 13932 // Look for the designated field. 13933 const RecordType *RC = CurrentType->getAs<RecordType>(); 13934 if (!RC) 13935 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13936 << CurrentType); 13937 RecordDecl *RD = RC->getDecl(); 13938 13939 // C++ [lib.support.types]p5: 13940 // The macro offsetof accepts a restricted set of type arguments in this 13941 // International Standard. type shall be a POD structure or a POD union 13942 // (clause 9). 13943 // C++11 [support.types]p4: 13944 // If type is not a standard-layout class (Clause 9), the results are 13945 // undefined. 13946 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13947 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13948 unsigned DiagID = 13949 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13950 : diag::ext_offsetof_non_pod_type; 13951 13952 if (!IsSafe && !DidWarnAboutNonPOD && 13953 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13954 PDiag(DiagID) 13955 << SourceRange(Components[0].LocStart, OC.LocEnd) 13956 << CurrentType)) 13957 DidWarnAboutNonPOD = true; 13958 } 13959 13960 // Look for the field. 13961 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13962 LookupQualifiedName(R, RD); 13963 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13964 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13965 if (!MemberDecl) { 13966 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13967 MemberDecl = IndirectMemberDecl->getAnonField(); 13968 } 13969 13970 if (!MemberDecl) 13971 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13972 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13973 OC.LocEnd)); 13974 13975 // C99 7.17p3: 13976 // (If the specified member is a bit-field, the behavior is undefined.) 13977 // 13978 // We diagnose this as an error. 13979 if (MemberDecl->isBitField()) { 13980 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13981 << MemberDecl->getDeclName() 13982 << SourceRange(BuiltinLoc, RParenLoc); 13983 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13984 return ExprError(); 13985 } 13986 13987 RecordDecl *Parent = MemberDecl->getParent(); 13988 if (IndirectMemberDecl) 13989 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13990 13991 // If the member was found in a base class, introduce OffsetOfNodes for 13992 // the base class indirections. 13993 CXXBasePaths Paths; 13994 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13995 Paths)) { 13996 if (Paths.getDetectedVirtual()) { 13997 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13998 << MemberDecl->getDeclName() 13999 << SourceRange(BuiltinLoc, RParenLoc); 14000 return ExprError(); 14001 } 14002 14003 CXXBasePath &Path = Paths.front(); 14004 for (const CXXBasePathElement &B : Path) 14005 Comps.push_back(OffsetOfNode(B.Base)); 14006 } 14007 14008 if (IndirectMemberDecl) { 14009 for (auto *FI : IndirectMemberDecl->chain()) { 14010 assert(isa<FieldDecl>(FI)); 14011 Comps.push_back(OffsetOfNode(OC.LocStart, 14012 cast<FieldDecl>(FI), OC.LocEnd)); 14013 } 14014 } else 14015 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14016 14017 CurrentType = MemberDecl->getType().getNonReferenceType(); 14018 } 14019 14020 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14021 Comps, Exprs, RParenLoc); 14022 } 14023 14024 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14025 SourceLocation BuiltinLoc, 14026 SourceLocation TypeLoc, 14027 ParsedType ParsedArgTy, 14028 ArrayRef<OffsetOfComponent> Components, 14029 SourceLocation RParenLoc) { 14030 14031 TypeSourceInfo *ArgTInfo; 14032 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14033 if (ArgTy.isNull()) 14034 return ExprError(); 14035 14036 if (!ArgTInfo) 14037 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14038 14039 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14040 } 14041 14042 14043 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14044 Expr *CondExpr, 14045 Expr *LHSExpr, Expr *RHSExpr, 14046 SourceLocation RPLoc) { 14047 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14048 14049 ExprValueKind VK = VK_RValue; 14050 ExprObjectKind OK = OK_Ordinary; 14051 QualType resType; 14052 bool ValueDependent = false; 14053 bool CondIsTrue = false; 14054 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14055 resType = Context.DependentTy; 14056 ValueDependent = true; 14057 } else { 14058 // The conditional expression is required to be a constant expression. 14059 llvm::APSInt condEval(32); 14060 ExprResult CondICE 14061 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14062 diag::err_typecheck_choose_expr_requires_constant, false); 14063 if (CondICE.isInvalid()) 14064 return ExprError(); 14065 CondExpr = CondICE.get(); 14066 CondIsTrue = condEval.getZExtValue(); 14067 14068 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14069 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14070 14071 resType = ActiveExpr->getType(); 14072 ValueDependent = ActiveExpr->isValueDependent(); 14073 VK = ActiveExpr->getValueKind(); 14074 OK = ActiveExpr->getObjectKind(); 14075 } 14076 14077 return new (Context) 14078 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14079 CondIsTrue, resType->isDependentType(), ValueDependent); 14080 } 14081 14082 //===----------------------------------------------------------------------===// 14083 // Clang Extensions. 14084 //===----------------------------------------------------------------------===// 14085 14086 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14087 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14088 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14089 14090 if (LangOpts.CPlusPlus) { 14091 MangleNumberingContext *MCtx; 14092 Decl *ManglingContextDecl; 14093 std::tie(MCtx, ManglingContextDecl) = 14094 getCurrentMangleNumberContext(Block->getDeclContext()); 14095 if (MCtx) { 14096 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14097 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14098 } 14099 } 14100 14101 PushBlockScope(CurScope, Block); 14102 CurContext->addDecl(Block); 14103 if (CurScope) 14104 PushDeclContext(CurScope, Block); 14105 else 14106 CurContext = Block; 14107 14108 getCurBlock()->HasImplicitReturnType = true; 14109 14110 // Enter a new evaluation context to insulate the block from any 14111 // cleanups from the enclosing full-expression. 14112 PushExpressionEvaluationContext( 14113 ExpressionEvaluationContext::PotentiallyEvaluated); 14114 } 14115 14116 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14117 Scope *CurScope) { 14118 assert(ParamInfo.getIdentifier() == nullptr && 14119 "block-id should have no identifier!"); 14120 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14121 BlockScopeInfo *CurBlock = getCurBlock(); 14122 14123 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14124 QualType T = Sig->getType(); 14125 14126 // FIXME: We should allow unexpanded parameter packs here, but that would, 14127 // in turn, make the block expression contain unexpanded parameter packs. 14128 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14129 // Drop the parameters. 14130 FunctionProtoType::ExtProtoInfo EPI; 14131 EPI.HasTrailingReturn = false; 14132 EPI.TypeQuals.addConst(); 14133 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14134 Sig = Context.getTrivialTypeSourceInfo(T); 14135 } 14136 14137 // GetTypeForDeclarator always produces a function type for a block 14138 // literal signature. Furthermore, it is always a FunctionProtoType 14139 // unless the function was written with a typedef. 14140 assert(T->isFunctionType() && 14141 "GetTypeForDeclarator made a non-function block signature"); 14142 14143 // Look for an explicit signature in that function type. 14144 FunctionProtoTypeLoc ExplicitSignature; 14145 14146 if ((ExplicitSignature = Sig->getTypeLoc() 14147 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14148 14149 // Check whether that explicit signature was synthesized by 14150 // GetTypeForDeclarator. If so, don't save that as part of the 14151 // written signature. 14152 if (ExplicitSignature.getLocalRangeBegin() == 14153 ExplicitSignature.getLocalRangeEnd()) { 14154 // This would be much cheaper if we stored TypeLocs instead of 14155 // TypeSourceInfos. 14156 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14157 unsigned Size = Result.getFullDataSize(); 14158 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14159 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14160 14161 ExplicitSignature = FunctionProtoTypeLoc(); 14162 } 14163 } 14164 14165 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14166 CurBlock->FunctionType = T; 14167 14168 const FunctionType *Fn = T->getAs<FunctionType>(); 14169 QualType RetTy = Fn->getReturnType(); 14170 bool isVariadic = 14171 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14172 14173 CurBlock->TheDecl->setIsVariadic(isVariadic); 14174 14175 // Context.DependentTy is used as a placeholder for a missing block 14176 // return type. TODO: what should we do with declarators like: 14177 // ^ * { ... } 14178 // If the answer is "apply template argument deduction".... 14179 if (RetTy != Context.DependentTy) { 14180 CurBlock->ReturnType = RetTy; 14181 CurBlock->TheDecl->setBlockMissingReturnType(false); 14182 CurBlock->HasImplicitReturnType = false; 14183 } 14184 14185 // Push block parameters from the declarator if we had them. 14186 SmallVector<ParmVarDecl*, 8> Params; 14187 if (ExplicitSignature) { 14188 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14189 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14190 if (Param->getIdentifier() == nullptr && 14191 !Param->isImplicit() && 14192 !Param->isInvalidDecl() && 14193 !getLangOpts().CPlusPlus) 14194 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14195 Params.push_back(Param); 14196 } 14197 14198 // Fake up parameter variables if we have a typedef, like 14199 // ^ fntype { ... } 14200 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14201 for (const auto &I : Fn->param_types()) { 14202 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14203 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14204 Params.push_back(Param); 14205 } 14206 } 14207 14208 // Set the parameters on the block decl. 14209 if (!Params.empty()) { 14210 CurBlock->TheDecl->setParams(Params); 14211 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14212 /*CheckParameterNames=*/false); 14213 } 14214 14215 // Finally we can process decl attributes. 14216 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14217 14218 // Put the parameter variables in scope. 14219 for (auto AI : CurBlock->TheDecl->parameters()) { 14220 AI->setOwningFunction(CurBlock->TheDecl); 14221 14222 // If this has an identifier, add it to the scope stack. 14223 if (AI->getIdentifier()) { 14224 CheckShadow(CurBlock->TheScope, AI); 14225 14226 PushOnScopeChains(AI, CurBlock->TheScope); 14227 } 14228 } 14229 } 14230 14231 /// ActOnBlockError - If there is an error parsing a block, this callback 14232 /// is invoked to pop the information about the block from the action impl. 14233 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14234 // Leave the expression-evaluation context. 14235 DiscardCleanupsInEvaluationContext(); 14236 PopExpressionEvaluationContext(); 14237 14238 // Pop off CurBlock, handle nested blocks. 14239 PopDeclContext(); 14240 PopFunctionScopeInfo(); 14241 } 14242 14243 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14244 /// literal was successfully completed. ^(int x){...} 14245 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14246 Stmt *Body, Scope *CurScope) { 14247 // If blocks are disabled, emit an error. 14248 if (!LangOpts.Blocks) 14249 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14250 14251 // Leave the expression-evaluation context. 14252 if (hasAnyUnrecoverableErrorsInThisFunction()) 14253 DiscardCleanupsInEvaluationContext(); 14254 assert(!Cleanup.exprNeedsCleanups() && 14255 "cleanups within block not correctly bound!"); 14256 PopExpressionEvaluationContext(); 14257 14258 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14259 BlockDecl *BD = BSI->TheDecl; 14260 14261 if (BSI->HasImplicitReturnType) 14262 deduceClosureReturnType(*BSI); 14263 14264 QualType RetTy = Context.VoidTy; 14265 if (!BSI->ReturnType.isNull()) 14266 RetTy = BSI->ReturnType; 14267 14268 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14269 QualType BlockTy; 14270 14271 // If the user wrote a function type in some form, try to use that. 14272 if (!BSI->FunctionType.isNull()) { 14273 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14274 14275 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14276 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14277 14278 // Turn protoless block types into nullary block types. 14279 if (isa<FunctionNoProtoType>(FTy)) { 14280 FunctionProtoType::ExtProtoInfo EPI; 14281 EPI.ExtInfo = Ext; 14282 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14283 14284 // Otherwise, if we don't need to change anything about the function type, 14285 // preserve its sugar structure. 14286 } else if (FTy->getReturnType() == RetTy && 14287 (!NoReturn || FTy->getNoReturnAttr())) { 14288 BlockTy = BSI->FunctionType; 14289 14290 // Otherwise, make the minimal modifications to the function type. 14291 } else { 14292 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14293 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14294 EPI.TypeQuals = Qualifiers(); 14295 EPI.ExtInfo = Ext; 14296 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14297 } 14298 14299 // If we don't have a function type, just build one from nothing. 14300 } else { 14301 FunctionProtoType::ExtProtoInfo EPI; 14302 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14303 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14304 } 14305 14306 DiagnoseUnusedParameters(BD->parameters()); 14307 BlockTy = Context.getBlockPointerType(BlockTy); 14308 14309 // If needed, diagnose invalid gotos and switches in the block. 14310 if (getCurFunction()->NeedsScopeChecking() && 14311 !PP.isCodeCompletionEnabled()) 14312 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14313 14314 BD->setBody(cast<CompoundStmt>(Body)); 14315 14316 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14317 DiagnoseUnguardedAvailabilityViolations(BD); 14318 14319 // Try to apply the named return value optimization. We have to check again 14320 // if we can do this, though, because blocks keep return statements around 14321 // to deduce an implicit return type. 14322 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14323 !BD->isDependentContext()) 14324 computeNRVO(Body, BSI); 14325 14326 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14327 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14328 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14329 NTCUK_Destruct|NTCUK_Copy); 14330 14331 PopDeclContext(); 14332 14333 // Pop the block scope now but keep it alive to the end of this function. 14334 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14335 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14336 14337 // Set the captured variables on the block. 14338 SmallVector<BlockDecl::Capture, 4> Captures; 14339 for (Capture &Cap : BSI->Captures) { 14340 if (Cap.isInvalid() || Cap.isThisCapture()) 14341 continue; 14342 14343 VarDecl *Var = Cap.getVariable(); 14344 Expr *CopyExpr = nullptr; 14345 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14346 if (const RecordType *Record = 14347 Cap.getCaptureType()->getAs<RecordType>()) { 14348 // The capture logic needs the destructor, so make sure we mark it. 14349 // Usually this is unnecessary because most local variables have 14350 // their destructors marked at declaration time, but parameters are 14351 // an exception because it's technically only the call site that 14352 // actually requires the destructor. 14353 if (isa<ParmVarDecl>(Var)) 14354 FinalizeVarWithDestructor(Var, Record); 14355 14356 // Enter a separate potentially-evaluated context while building block 14357 // initializers to isolate their cleanups from those of the block 14358 // itself. 14359 // FIXME: Is this appropriate even when the block itself occurs in an 14360 // unevaluated operand? 14361 EnterExpressionEvaluationContext EvalContext( 14362 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14363 14364 SourceLocation Loc = Cap.getLocation(); 14365 14366 ExprResult Result = BuildDeclarationNameExpr( 14367 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14368 14369 // According to the blocks spec, the capture of a variable from 14370 // the stack requires a const copy constructor. This is not true 14371 // of the copy/move done to move a __block variable to the heap. 14372 if (!Result.isInvalid() && 14373 !Result.get()->getType().isConstQualified()) { 14374 Result = ImpCastExprToType(Result.get(), 14375 Result.get()->getType().withConst(), 14376 CK_NoOp, VK_LValue); 14377 } 14378 14379 if (!Result.isInvalid()) { 14380 Result = PerformCopyInitialization( 14381 InitializedEntity::InitializeBlock(Var->getLocation(), 14382 Cap.getCaptureType(), false), 14383 Loc, Result.get()); 14384 } 14385 14386 // Build a full-expression copy expression if initialization 14387 // succeeded and used a non-trivial constructor. Recover from 14388 // errors by pretending that the copy isn't necessary. 14389 if (!Result.isInvalid() && 14390 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14391 ->isTrivial()) { 14392 Result = MaybeCreateExprWithCleanups(Result); 14393 CopyExpr = Result.get(); 14394 } 14395 } 14396 } 14397 14398 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14399 CopyExpr); 14400 Captures.push_back(NewCap); 14401 } 14402 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14403 14404 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14405 14406 // If the block isn't obviously global, i.e. it captures anything at 14407 // all, then we need to do a few things in the surrounding context: 14408 if (Result->getBlockDecl()->hasCaptures()) { 14409 // First, this expression has a new cleanup object. 14410 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14411 Cleanup.setExprNeedsCleanups(true); 14412 14413 // It also gets a branch-protected scope if any of the captured 14414 // variables needs destruction. 14415 for (const auto &CI : Result->getBlockDecl()->captures()) { 14416 const VarDecl *var = CI.getVariable(); 14417 if (var->getType().isDestructedType() != QualType::DK_none) { 14418 setFunctionHasBranchProtectedScope(); 14419 break; 14420 } 14421 } 14422 } 14423 14424 if (getCurFunction()) 14425 getCurFunction()->addBlock(BD); 14426 14427 return Result; 14428 } 14429 14430 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14431 SourceLocation RPLoc) { 14432 TypeSourceInfo *TInfo; 14433 GetTypeFromParser(Ty, &TInfo); 14434 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14435 } 14436 14437 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14438 Expr *E, TypeSourceInfo *TInfo, 14439 SourceLocation RPLoc) { 14440 Expr *OrigExpr = E; 14441 bool IsMS = false; 14442 14443 // CUDA device code does not support varargs. 14444 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14445 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14446 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14447 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14448 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14449 } 14450 } 14451 14452 // NVPTX does not support va_arg expression. 14453 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14454 Context.getTargetInfo().getTriple().isNVPTX()) 14455 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14456 14457 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14458 // as Microsoft ABI on an actual Microsoft platform, where 14459 // __builtin_ms_va_list and __builtin_va_list are the same.) 14460 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14461 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14462 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14463 if (Context.hasSameType(MSVaListType, E->getType())) { 14464 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14465 return ExprError(); 14466 IsMS = true; 14467 } 14468 } 14469 14470 // Get the va_list type 14471 QualType VaListType = Context.getBuiltinVaListType(); 14472 if (!IsMS) { 14473 if (VaListType->isArrayType()) { 14474 // Deal with implicit array decay; for example, on x86-64, 14475 // va_list is an array, but it's supposed to decay to 14476 // a pointer for va_arg. 14477 VaListType = Context.getArrayDecayedType(VaListType); 14478 // Make sure the input expression also decays appropriately. 14479 ExprResult Result = UsualUnaryConversions(E); 14480 if (Result.isInvalid()) 14481 return ExprError(); 14482 E = Result.get(); 14483 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14484 // If va_list is a record type and we are compiling in C++ mode, 14485 // check the argument using reference binding. 14486 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14487 Context, Context.getLValueReferenceType(VaListType), false); 14488 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14489 if (Init.isInvalid()) 14490 return ExprError(); 14491 E = Init.getAs<Expr>(); 14492 } else { 14493 // Otherwise, the va_list argument must be an l-value because 14494 // it is modified by va_arg. 14495 if (!E->isTypeDependent() && 14496 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14497 return ExprError(); 14498 } 14499 } 14500 14501 if (!IsMS && !E->isTypeDependent() && 14502 !Context.hasSameType(VaListType, E->getType())) 14503 return ExprError( 14504 Diag(E->getBeginLoc(), 14505 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14506 << OrigExpr->getType() << E->getSourceRange()); 14507 14508 if (!TInfo->getType()->isDependentType()) { 14509 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14510 diag::err_second_parameter_to_va_arg_incomplete, 14511 TInfo->getTypeLoc())) 14512 return ExprError(); 14513 14514 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14515 TInfo->getType(), 14516 diag::err_second_parameter_to_va_arg_abstract, 14517 TInfo->getTypeLoc())) 14518 return ExprError(); 14519 14520 if (!TInfo->getType().isPODType(Context)) { 14521 Diag(TInfo->getTypeLoc().getBeginLoc(), 14522 TInfo->getType()->isObjCLifetimeType() 14523 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14524 : diag::warn_second_parameter_to_va_arg_not_pod) 14525 << TInfo->getType() 14526 << TInfo->getTypeLoc().getSourceRange(); 14527 } 14528 14529 // Check for va_arg where arguments of the given type will be promoted 14530 // (i.e. this va_arg is guaranteed to have undefined behavior). 14531 QualType PromoteType; 14532 if (TInfo->getType()->isPromotableIntegerType()) { 14533 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14534 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14535 PromoteType = QualType(); 14536 } 14537 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14538 PromoteType = Context.DoubleTy; 14539 if (!PromoteType.isNull()) 14540 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14541 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14542 << TInfo->getType() 14543 << PromoteType 14544 << TInfo->getTypeLoc().getSourceRange()); 14545 } 14546 14547 QualType T = TInfo->getType().getNonLValueExprType(Context); 14548 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14549 } 14550 14551 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14552 // The type of __null will be int or long, depending on the size of 14553 // pointers on the target. 14554 QualType Ty; 14555 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14556 if (pw == Context.getTargetInfo().getIntWidth()) 14557 Ty = Context.IntTy; 14558 else if (pw == Context.getTargetInfo().getLongWidth()) 14559 Ty = Context.LongTy; 14560 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14561 Ty = Context.LongLongTy; 14562 else { 14563 llvm_unreachable("I don't know size of pointer!"); 14564 } 14565 14566 return new (Context) GNUNullExpr(Ty, TokenLoc); 14567 } 14568 14569 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14570 SourceLocation BuiltinLoc, 14571 SourceLocation RPLoc) { 14572 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14573 } 14574 14575 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14576 SourceLocation BuiltinLoc, 14577 SourceLocation RPLoc, 14578 DeclContext *ParentContext) { 14579 return new (Context) 14580 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14581 } 14582 14583 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14584 bool Diagnose) { 14585 if (!getLangOpts().ObjC) 14586 return false; 14587 14588 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14589 if (!PT) 14590 return false; 14591 14592 if (!PT->isObjCIdType()) { 14593 // Check if the destination is the 'NSString' interface. 14594 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14595 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14596 return false; 14597 } 14598 14599 // Ignore any parens, implicit casts (should only be 14600 // array-to-pointer decays), and not-so-opaque values. The last is 14601 // important for making this trigger for property assignments. 14602 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14603 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14604 if (OV->getSourceExpr()) 14605 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14606 14607 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14608 if (!SL || !SL->isAscii()) 14609 return false; 14610 if (Diagnose) { 14611 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14612 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14613 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14614 } 14615 return true; 14616 } 14617 14618 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14619 const Expr *SrcExpr) { 14620 if (!DstType->isFunctionPointerType() || 14621 !SrcExpr->getType()->isFunctionType()) 14622 return false; 14623 14624 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14625 if (!DRE) 14626 return false; 14627 14628 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14629 if (!FD) 14630 return false; 14631 14632 return !S.checkAddressOfFunctionIsAvailable(FD, 14633 /*Complain=*/true, 14634 SrcExpr->getBeginLoc()); 14635 } 14636 14637 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14638 SourceLocation Loc, 14639 QualType DstType, QualType SrcType, 14640 Expr *SrcExpr, AssignmentAction Action, 14641 bool *Complained) { 14642 if (Complained) 14643 *Complained = false; 14644 14645 // Decode the result (notice that AST's are still created for extensions). 14646 bool CheckInferredResultType = false; 14647 bool isInvalid = false; 14648 unsigned DiagKind = 0; 14649 FixItHint Hint; 14650 ConversionFixItGenerator ConvHints; 14651 bool MayHaveConvFixit = false; 14652 bool MayHaveFunctionDiff = false; 14653 const ObjCInterfaceDecl *IFace = nullptr; 14654 const ObjCProtocolDecl *PDecl = nullptr; 14655 14656 switch (ConvTy) { 14657 case Compatible: 14658 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14659 return false; 14660 14661 case PointerToInt: 14662 DiagKind = diag::ext_typecheck_convert_pointer_int; 14663 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14664 MayHaveConvFixit = true; 14665 break; 14666 case IntToPointer: 14667 DiagKind = diag::ext_typecheck_convert_int_pointer; 14668 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14669 MayHaveConvFixit = true; 14670 break; 14671 case IncompatiblePointer: 14672 if (Action == AA_Passing_CFAudited) 14673 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14674 else if (SrcType->isFunctionPointerType() && 14675 DstType->isFunctionPointerType()) 14676 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14677 else 14678 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14679 14680 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14681 SrcType->isObjCObjectPointerType(); 14682 if (Hint.isNull() && !CheckInferredResultType) { 14683 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14684 } 14685 else if (CheckInferredResultType) { 14686 SrcType = SrcType.getUnqualifiedType(); 14687 DstType = DstType.getUnqualifiedType(); 14688 } 14689 MayHaveConvFixit = true; 14690 break; 14691 case IncompatiblePointerSign: 14692 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14693 break; 14694 case FunctionVoidPointer: 14695 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14696 break; 14697 case IncompatiblePointerDiscardsQualifiers: { 14698 // Perform array-to-pointer decay if necessary. 14699 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14700 14701 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14702 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14703 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14704 DiagKind = diag::err_typecheck_incompatible_address_space; 14705 break; 14706 14707 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14708 DiagKind = diag::err_typecheck_incompatible_ownership; 14709 break; 14710 } 14711 14712 llvm_unreachable("unknown error case for discarding qualifiers!"); 14713 // fallthrough 14714 } 14715 case CompatiblePointerDiscardsQualifiers: 14716 // If the qualifiers lost were because we were applying the 14717 // (deprecated) C++ conversion from a string literal to a char* 14718 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14719 // Ideally, this check would be performed in 14720 // checkPointerTypesForAssignment. However, that would require a 14721 // bit of refactoring (so that the second argument is an 14722 // expression, rather than a type), which should be done as part 14723 // of a larger effort to fix checkPointerTypesForAssignment for 14724 // C++ semantics. 14725 if (getLangOpts().CPlusPlus && 14726 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14727 return false; 14728 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14729 break; 14730 case IncompatibleNestedPointerQualifiers: 14731 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14732 break; 14733 case IncompatibleNestedPointerAddressSpaceMismatch: 14734 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14735 break; 14736 case IntToBlockPointer: 14737 DiagKind = diag::err_int_to_block_pointer; 14738 break; 14739 case IncompatibleBlockPointer: 14740 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14741 break; 14742 case IncompatibleObjCQualifiedId: { 14743 if (SrcType->isObjCQualifiedIdType()) { 14744 const ObjCObjectPointerType *srcOPT = 14745 SrcType->castAs<ObjCObjectPointerType>(); 14746 for (auto *srcProto : srcOPT->quals()) { 14747 PDecl = srcProto; 14748 break; 14749 } 14750 if (const ObjCInterfaceType *IFaceT = 14751 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14752 IFace = IFaceT->getDecl(); 14753 } 14754 else if (DstType->isObjCQualifiedIdType()) { 14755 const ObjCObjectPointerType *dstOPT = 14756 DstType->castAs<ObjCObjectPointerType>(); 14757 for (auto *dstProto : dstOPT->quals()) { 14758 PDecl = dstProto; 14759 break; 14760 } 14761 if (const ObjCInterfaceType *IFaceT = 14762 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14763 IFace = IFaceT->getDecl(); 14764 } 14765 DiagKind = diag::warn_incompatible_qualified_id; 14766 break; 14767 } 14768 case IncompatibleVectors: 14769 DiagKind = diag::warn_incompatible_vectors; 14770 break; 14771 case IncompatibleObjCWeakRef: 14772 DiagKind = diag::err_arc_weak_unavailable_assign; 14773 break; 14774 case Incompatible: 14775 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14776 if (Complained) 14777 *Complained = true; 14778 return true; 14779 } 14780 14781 DiagKind = diag::err_typecheck_convert_incompatible; 14782 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14783 MayHaveConvFixit = true; 14784 isInvalid = true; 14785 MayHaveFunctionDiff = true; 14786 break; 14787 } 14788 14789 QualType FirstType, SecondType; 14790 switch (Action) { 14791 case AA_Assigning: 14792 case AA_Initializing: 14793 // The destination type comes first. 14794 FirstType = DstType; 14795 SecondType = SrcType; 14796 break; 14797 14798 case AA_Returning: 14799 case AA_Passing: 14800 case AA_Passing_CFAudited: 14801 case AA_Converting: 14802 case AA_Sending: 14803 case AA_Casting: 14804 // The source type comes first. 14805 FirstType = SrcType; 14806 SecondType = DstType; 14807 break; 14808 } 14809 14810 PartialDiagnostic FDiag = PDiag(DiagKind); 14811 if (Action == AA_Passing_CFAudited) 14812 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14813 else 14814 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14815 14816 // If we can fix the conversion, suggest the FixIts. 14817 assert(ConvHints.isNull() || Hint.isNull()); 14818 if (!ConvHints.isNull()) { 14819 for (FixItHint &H : ConvHints.Hints) 14820 FDiag << H; 14821 } else { 14822 FDiag << Hint; 14823 } 14824 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14825 14826 if (MayHaveFunctionDiff) 14827 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14828 14829 Diag(Loc, FDiag); 14830 if (DiagKind == diag::warn_incompatible_qualified_id && 14831 PDecl && IFace && !IFace->hasDefinition()) 14832 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14833 << IFace << PDecl; 14834 14835 if (SecondType == Context.OverloadTy) 14836 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14837 FirstType, /*TakingAddress=*/true); 14838 14839 if (CheckInferredResultType) 14840 EmitRelatedResultTypeNote(SrcExpr); 14841 14842 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14843 EmitRelatedResultTypeNoteForReturn(DstType); 14844 14845 if (Complained) 14846 *Complained = true; 14847 return isInvalid; 14848 } 14849 14850 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14851 llvm::APSInt *Result) { 14852 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14853 public: 14854 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14855 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14856 } 14857 } Diagnoser; 14858 14859 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14860 } 14861 14862 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14863 llvm::APSInt *Result, 14864 unsigned DiagID, 14865 bool AllowFold) { 14866 class IDDiagnoser : public VerifyICEDiagnoser { 14867 unsigned DiagID; 14868 14869 public: 14870 IDDiagnoser(unsigned DiagID) 14871 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14872 14873 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14874 S.Diag(Loc, DiagID) << SR; 14875 } 14876 } Diagnoser(DiagID); 14877 14878 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14879 } 14880 14881 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14882 SourceRange SR) { 14883 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14884 } 14885 14886 ExprResult 14887 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14888 VerifyICEDiagnoser &Diagnoser, 14889 bool AllowFold) { 14890 SourceLocation DiagLoc = E->getBeginLoc(); 14891 14892 if (getLangOpts().CPlusPlus11) { 14893 // C++11 [expr.const]p5: 14894 // If an expression of literal class type is used in a context where an 14895 // integral constant expression is required, then that class type shall 14896 // have a single non-explicit conversion function to an integral or 14897 // unscoped enumeration type 14898 ExprResult Converted; 14899 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14900 public: 14901 CXX11ConvertDiagnoser(bool Silent) 14902 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14903 Silent, true) {} 14904 14905 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14906 QualType T) override { 14907 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14908 } 14909 14910 SemaDiagnosticBuilder diagnoseIncomplete( 14911 Sema &S, SourceLocation Loc, QualType T) override { 14912 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14913 } 14914 14915 SemaDiagnosticBuilder diagnoseExplicitConv( 14916 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14917 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14918 } 14919 14920 SemaDiagnosticBuilder noteExplicitConv( 14921 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14922 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14923 << ConvTy->isEnumeralType() << ConvTy; 14924 } 14925 14926 SemaDiagnosticBuilder diagnoseAmbiguous( 14927 Sema &S, SourceLocation Loc, QualType T) override { 14928 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14929 } 14930 14931 SemaDiagnosticBuilder noteAmbiguous( 14932 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14933 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14934 << ConvTy->isEnumeralType() << ConvTy; 14935 } 14936 14937 SemaDiagnosticBuilder diagnoseConversion( 14938 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14939 llvm_unreachable("conversion functions are permitted"); 14940 } 14941 } ConvertDiagnoser(Diagnoser.Suppress); 14942 14943 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14944 ConvertDiagnoser); 14945 if (Converted.isInvalid()) 14946 return Converted; 14947 E = Converted.get(); 14948 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14949 return ExprError(); 14950 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14951 // An ICE must be of integral or unscoped enumeration type. 14952 if (!Diagnoser.Suppress) 14953 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14954 return ExprError(); 14955 } 14956 14957 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14958 // in the non-ICE case. 14959 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14960 if (Result) 14961 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14962 if (!isa<ConstantExpr>(E)) 14963 E = ConstantExpr::Create(Context, E); 14964 return E; 14965 } 14966 14967 Expr::EvalResult EvalResult; 14968 SmallVector<PartialDiagnosticAt, 8> Notes; 14969 EvalResult.Diag = &Notes; 14970 14971 // Try to evaluate the expression, and produce diagnostics explaining why it's 14972 // not a constant expression as a side-effect. 14973 bool Folded = 14974 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 14975 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14976 14977 if (!isa<ConstantExpr>(E)) 14978 E = ConstantExpr::Create(Context, E, EvalResult.Val); 14979 14980 // In C++11, we can rely on diagnostics being produced for any expression 14981 // which is not a constant expression. If no diagnostics were produced, then 14982 // this is a constant expression. 14983 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14984 if (Result) 14985 *Result = EvalResult.Val.getInt(); 14986 return E; 14987 } 14988 14989 // If our only note is the usual "invalid subexpression" note, just point 14990 // the caret at its location rather than producing an essentially 14991 // redundant note. 14992 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14993 diag::note_invalid_subexpr_in_const_expr) { 14994 DiagLoc = Notes[0].first; 14995 Notes.clear(); 14996 } 14997 14998 if (!Folded || !AllowFold) { 14999 if (!Diagnoser.Suppress) { 15000 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15001 for (const PartialDiagnosticAt &Note : Notes) 15002 Diag(Note.first, Note.second); 15003 } 15004 15005 return ExprError(); 15006 } 15007 15008 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15009 for (const PartialDiagnosticAt &Note : Notes) 15010 Diag(Note.first, Note.second); 15011 15012 if (Result) 15013 *Result = EvalResult.Val.getInt(); 15014 return E; 15015 } 15016 15017 namespace { 15018 // Handle the case where we conclude a expression which we speculatively 15019 // considered to be unevaluated is actually evaluated. 15020 class TransformToPE : public TreeTransform<TransformToPE> { 15021 typedef TreeTransform<TransformToPE> BaseTransform; 15022 15023 public: 15024 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15025 15026 // Make sure we redo semantic analysis 15027 bool AlwaysRebuild() { return true; } 15028 bool ReplacingOriginal() { return true; } 15029 15030 // We need to special-case DeclRefExprs referring to FieldDecls which 15031 // are not part of a member pointer formation; normal TreeTransforming 15032 // doesn't catch this case because of the way we represent them in the AST. 15033 // FIXME: This is a bit ugly; is it really the best way to handle this 15034 // case? 15035 // 15036 // Error on DeclRefExprs referring to FieldDecls. 15037 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15038 if (isa<FieldDecl>(E->getDecl()) && 15039 !SemaRef.isUnevaluatedContext()) 15040 return SemaRef.Diag(E->getLocation(), 15041 diag::err_invalid_non_static_member_use) 15042 << E->getDecl() << E->getSourceRange(); 15043 15044 return BaseTransform::TransformDeclRefExpr(E); 15045 } 15046 15047 // Exception: filter out member pointer formation 15048 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15049 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15050 return E; 15051 15052 return BaseTransform::TransformUnaryOperator(E); 15053 } 15054 15055 // The body of a lambda-expression is in a separate expression evaluation 15056 // context so never needs to be transformed. 15057 // FIXME: Ideally we wouldn't transform the closure type either, and would 15058 // just recreate the capture expressions and lambda expression. 15059 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15060 return SkipLambdaBody(E, Body); 15061 } 15062 }; 15063 } 15064 15065 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15066 assert(isUnevaluatedContext() && 15067 "Should only transform unevaluated expressions"); 15068 ExprEvalContexts.back().Context = 15069 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15070 if (isUnevaluatedContext()) 15071 return E; 15072 return TransformToPE(*this).TransformExpr(E); 15073 } 15074 15075 void 15076 Sema::PushExpressionEvaluationContext( 15077 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15078 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15079 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15080 LambdaContextDecl, ExprContext); 15081 Cleanup.reset(); 15082 if (!MaybeODRUseExprs.empty()) 15083 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15084 } 15085 15086 void 15087 Sema::PushExpressionEvaluationContext( 15088 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15089 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15090 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15091 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15092 } 15093 15094 namespace { 15095 15096 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15097 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15098 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15099 if (E->getOpcode() == UO_Deref) 15100 return CheckPossibleDeref(S, E->getSubExpr()); 15101 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15102 return CheckPossibleDeref(S, E->getBase()); 15103 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15104 return CheckPossibleDeref(S, E->getBase()); 15105 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15106 QualType Inner; 15107 QualType Ty = E->getType(); 15108 if (const auto *Ptr = Ty->getAs<PointerType>()) 15109 Inner = Ptr->getPointeeType(); 15110 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15111 Inner = Arr->getElementType(); 15112 else 15113 return nullptr; 15114 15115 if (Inner->hasAttr(attr::NoDeref)) 15116 return E; 15117 } 15118 return nullptr; 15119 } 15120 15121 } // namespace 15122 15123 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15124 for (const Expr *E : Rec.PossibleDerefs) { 15125 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15126 if (DeclRef) { 15127 const ValueDecl *Decl = DeclRef->getDecl(); 15128 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15129 << Decl->getName() << E->getSourceRange(); 15130 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15131 } else { 15132 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15133 << E->getSourceRange(); 15134 } 15135 } 15136 Rec.PossibleDerefs.clear(); 15137 } 15138 15139 /// Check whether E, which is either a discarded-value expression or an 15140 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15141 /// and if so, remove it from the list of volatile-qualified assignments that 15142 /// we are going to warn are deprecated. 15143 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15144 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15145 return; 15146 15147 // Note: ignoring parens here is not justified by the standard rules, but 15148 // ignoring parentheses seems like a more reasonable approach, and this only 15149 // drives a deprecation warning so doesn't affect conformance. 15150 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15151 if (BO->getOpcode() == BO_Assign) { 15152 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15153 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15154 LHSs.end()); 15155 } 15156 } 15157 } 15158 15159 void Sema::PopExpressionEvaluationContext() { 15160 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15161 unsigned NumTypos = Rec.NumTypos; 15162 15163 if (!Rec.Lambdas.empty()) { 15164 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15165 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15166 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15167 unsigned D; 15168 if (Rec.isUnevaluated()) { 15169 // C++11 [expr.prim.lambda]p2: 15170 // A lambda-expression shall not appear in an unevaluated operand 15171 // (Clause 5). 15172 D = diag::err_lambda_unevaluated_operand; 15173 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15174 // C++1y [expr.const]p2: 15175 // A conditional-expression e is a core constant expression unless the 15176 // evaluation of e, following the rules of the abstract machine, would 15177 // evaluate [...] a lambda-expression. 15178 D = diag::err_lambda_in_constant_expression; 15179 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15180 // C++17 [expr.prim.lamda]p2: 15181 // A lambda-expression shall not appear [...] in a template-argument. 15182 D = diag::err_lambda_in_invalid_context; 15183 } else 15184 llvm_unreachable("Couldn't infer lambda error message."); 15185 15186 for (const auto *L : Rec.Lambdas) 15187 Diag(L->getBeginLoc(), D); 15188 } 15189 } 15190 15191 WarnOnPendingNoDerefs(Rec); 15192 15193 // Warn on any volatile-qualified simple-assignments that are not discarded- 15194 // value expressions nor unevaluated operands (those cases get removed from 15195 // this list by CheckUnusedVolatileAssignment). 15196 for (auto *BO : Rec.VolatileAssignmentLHSs) 15197 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15198 << BO->getType(); 15199 15200 // When are coming out of an unevaluated context, clear out any 15201 // temporaries that we may have created as part of the evaluation of 15202 // the expression in that context: they aren't relevant because they 15203 // will never be constructed. 15204 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15205 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15206 ExprCleanupObjects.end()); 15207 Cleanup = Rec.ParentCleanup; 15208 CleanupVarDeclMarking(); 15209 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15210 // Otherwise, merge the contexts together. 15211 } else { 15212 Cleanup.mergeFrom(Rec.ParentCleanup); 15213 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15214 Rec.SavedMaybeODRUseExprs.end()); 15215 } 15216 15217 // Pop the current expression evaluation context off the stack. 15218 ExprEvalContexts.pop_back(); 15219 15220 // The global expression evaluation context record is never popped. 15221 ExprEvalContexts.back().NumTypos += NumTypos; 15222 } 15223 15224 void Sema::DiscardCleanupsInEvaluationContext() { 15225 ExprCleanupObjects.erase( 15226 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15227 ExprCleanupObjects.end()); 15228 Cleanup.reset(); 15229 MaybeODRUseExprs.clear(); 15230 } 15231 15232 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15233 ExprResult Result = CheckPlaceholderExpr(E); 15234 if (Result.isInvalid()) 15235 return ExprError(); 15236 E = Result.get(); 15237 if (!E->getType()->isVariablyModifiedType()) 15238 return E; 15239 return TransformToPotentiallyEvaluated(E); 15240 } 15241 15242 /// Are we in a context that is potentially constant evaluated per C++20 15243 /// [expr.const]p12? 15244 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15245 /// C++2a [expr.const]p12: 15246 // An expression or conversion is potentially constant evaluated if it is 15247 switch (SemaRef.ExprEvalContexts.back().Context) { 15248 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15249 // -- a manifestly constant-evaluated expression, 15250 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15251 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15252 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15253 // -- a potentially-evaluated expression, 15254 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15255 // -- an immediate subexpression of a braced-init-list, 15256 15257 // -- [FIXME] an expression of the form & cast-expression that occurs 15258 // within a templated entity 15259 // -- a subexpression of one of the above that is not a subexpression of 15260 // a nested unevaluated operand. 15261 return true; 15262 15263 case Sema::ExpressionEvaluationContext::Unevaluated: 15264 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15265 // Expressions in this context are never evaluated. 15266 return false; 15267 } 15268 llvm_unreachable("Invalid context"); 15269 } 15270 15271 /// Return true if this function has a calling convention that requires mangling 15272 /// in the size of the parameter pack. 15273 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15274 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15275 // we don't need parameter type sizes. 15276 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15277 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15278 TT.getArch() != llvm::Triple::x86_64)) 15279 return false; 15280 15281 // If this is C++ and this isn't an extern "C" function, parameters do not 15282 // need to be complete. In this case, C++ mangling will apply, which doesn't 15283 // use the size of the parameters. 15284 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15285 return false; 15286 15287 // Stdcall, fastcall, and vectorcall need this special treatment. 15288 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15289 switch (CC) { 15290 case CC_X86StdCall: 15291 case CC_X86FastCall: 15292 case CC_X86VectorCall: 15293 return true; 15294 default: 15295 break; 15296 } 15297 return false; 15298 } 15299 15300 /// Require that all of the parameter types of function be complete. Normally, 15301 /// parameter types are only required to be complete when a function is called 15302 /// or defined, but to mangle functions with certain calling conventions, the 15303 /// mangler needs to know the size of the parameter list. In this situation, 15304 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15305 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15306 /// result in a linker error. Clang doesn't implement this behavior, and instead 15307 /// attempts to error at compile time. 15308 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15309 SourceLocation Loc) { 15310 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15311 FunctionDecl *FD; 15312 ParmVarDecl *Param; 15313 15314 public: 15315 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15316 : FD(FD), Param(Param) {} 15317 15318 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15319 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15320 StringRef CCName; 15321 switch (CC) { 15322 case CC_X86StdCall: 15323 CCName = "stdcall"; 15324 break; 15325 case CC_X86FastCall: 15326 CCName = "fastcall"; 15327 break; 15328 case CC_X86VectorCall: 15329 CCName = "vectorcall"; 15330 break; 15331 default: 15332 llvm_unreachable("CC does not need mangling"); 15333 } 15334 15335 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15336 << Param->getDeclName() << FD->getDeclName() << CCName; 15337 } 15338 }; 15339 15340 for (ParmVarDecl *Param : FD->parameters()) { 15341 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15342 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15343 } 15344 } 15345 15346 namespace { 15347 enum class OdrUseContext { 15348 /// Declarations in this context are not odr-used. 15349 None, 15350 /// Declarations in this context are formally odr-used, but this is a 15351 /// dependent context. 15352 Dependent, 15353 /// Declarations in this context are odr-used but not actually used (yet). 15354 FormallyOdrUsed, 15355 /// Declarations in this context are used. 15356 Used 15357 }; 15358 } 15359 15360 /// Are we within a context in which references to resolved functions or to 15361 /// variables result in odr-use? 15362 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15363 OdrUseContext Result; 15364 15365 switch (SemaRef.ExprEvalContexts.back().Context) { 15366 case Sema::ExpressionEvaluationContext::Unevaluated: 15367 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15368 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15369 return OdrUseContext::None; 15370 15371 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15372 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15373 Result = OdrUseContext::Used; 15374 break; 15375 15376 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15377 Result = OdrUseContext::FormallyOdrUsed; 15378 break; 15379 15380 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15381 // A default argument formally results in odr-use, but doesn't actually 15382 // result in a use in any real sense until it itself is used. 15383 Result = OdrUseContext::FormallyOdrUsed; 15384 break; 15385 } 15386 15387 if (SemaRef.CurContext->isDependentContext()) 15388 return OdrUseContext::Dependent; 15389 15390 return Result; 15391 } 15392 15393 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15394 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 15395 return Func->isConstexpr() && 15396 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 15397 } 15398 15399 /// Mark a function referenced, and check whether it is odr-used 15400 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15401 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15402 bool MightBeOdrUse) { 15403 assert(Func && "No function?"); 15404 15405 Func->setReferenced(); 15406 15407 // Recursive functions aren't really used until they're used from some other 15408 // context. 15409 bool IsRecursiveCall = CurContext == Func; 15410 15411 // C++11 [basic.def.odr]p3: 15412 // A function whose name appears as a potentially-evaluated expression is 15413 // odr-used if it is the unique lookup result or the selected member of a 15414 // set of overloaded functions [...]. 15415 // 15416 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15417 // can just check that here. 15418 OdrUseContext OdrUse = 15419 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15420 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15421 OdrUse = OdrUseContext::FormallyOdrUsed; 15422 15423 // Trivial default constructors and destructors are never actually used. 15424 // FIXME: What about other special members? 15425 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15426 OdrUse == OdrUseContext::Used) { 15427 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15428 if (Constructor->isDefaultConstructor()) 15429 OdrUse = OdrUseContext::FormallyOdrUsed; 15430 if (isa<CXXDestructorDecl>(Func)) 15431 OdrUse = OdrUseContext::FormallyOdrUsed; 15432 } 15433 15434 // C++20 [expr.const]p12: 15435 // A function [...] is needed for constant evaluation if it is [...] a 15436 // constexpr function that is named by an expression that is potentially 15437 // constant evaluated 15438 bool NeededForConstantEvaluation = 15439 isPotentiallyConstantEvaluatedContext(*this) && 15440 isImplicitlyDefinableConstexprFunction(Func); 15441 15442 // Determine whether we require a function definition to exist, per 15443 // C++11 [temp.inst]p3: 15444 // Unless a function template specialization has been explicitly 15445 // instantiated or explicitly specialized, the function template 15446 // specialization is implicitly instantiated when the specialization is 15447 // referenced in a context that requires a function definition to exist. 15448 // C++20 [temp.inst]p7: 15449 // The existence of a definition of a [...] function is considered to 15450 // affect the semantics of the program if the [...] function is needed for 15451 // constant evaluation by an expression 15452 // C++20 [basic.def.odr]p10: 15453 // Every program shall contain exactly one definition of every non-inline 15454 // function or variable that is odr-used in that program outside of a 15455 // discarded statement 15456 // C++20 [special]p1: 15457 // The implementation will implicitly define [defaulted special members] 15458 // if they are odr-used or needed for constant evaluation. 15459 // 15460 // Note that we skip the implicit instantiation of templates that are only 15461 // used in unused default arguments or by recursive calls to themselves. 15462 // This is formally non-conforming, but seems reasonable in practice. 15463 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15464 NeededForConstantEvaluation); 15465 15466 // C++14 [temp.expl.spec]p6: 15467 // If a template [...] is explicitly specialized then that specialization 15468 // shall be declared before the first use of that specialization that would 15469 // cause an implicit instantiation to take place, in every translation unit 15470 // in which such a use occurs 15471 if (NeedDefinition && 15472 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15473 Func->getMemberSpecializationInfo())) 15474 checkSpecializationVisibility(Loc, Func); 15475 15476 // C++14 [except.spec]p17: 15477 // An exception-specification is considered to be needed when: 15478 // - the function is odr-used or, if it appears in an unevaluated operand, 15479 // would be odr-used if the expression were potentially-evaluated; 15480 // 15481 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15482 // function is a pure virtual function we're calling, and in that case the 15483 // function was selected by overload resolution and we need to resolve its 15484 // exception specification for a different reason. 15485 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15486 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15487 ResolveExceptionSpec(Loc, FPT); 15488 15489 if (getLangOpts().CUDA) 15490 CheckCUDACall(Loc, Func); 15491 15492 // If we need a definition, try to create one. 15493 if (NeedDefinition && !Func->getBody()) { 15494 runWithSufficientStackSpace(Loc, [&] { 15495 if (CXXConstructorDecl *Constructor = 15496 dyn_cast<CXXConstructorDecl>(Func)) { 15497 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15498 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15499 if (Constructor->isDefaultConstructor()) { 15500 if (Constructor->isTrivial() && 15501 !Constructor->hasAttr<DLLExportAttr>()) 15502 return; 15503 DefineImplicitDefaultConstructor(Loc, Constructor); 15504 } else if (Constructor->isCopyConstructor()) { 15505 DefineImplicitCopyConstructor(Loc, Constructor); 15506 } else if (Constructor->isMoveConstructor()) { 15507 DefineImplicitMoveConstructor(Loc, Constructor); 15508 } 15509 } else if (Constructor->getInheritedConstructor()) { 15510 DefineInheritingConstructor(Loc, Constructor); 15511 } 15512 } else if (CXXDestructorDecl *Destructor = 15513 dyn_cast<CXXDestructorDecl>(Func)) { 15514 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15515 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15516 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15517 return; 15518 DefineImplicitDestructor(Loc, Destructor); 15519 } 15520 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15521 MarkVTableUsed(Loc, Destructor->getParent()); 15522 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15523 if (MethodDecl->isOverloadedOperator() && 15524 MethodDecl->getOverloadedOperator() == OO_Equal) { 15525 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15526 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15527 if (MethodDecl->isCopyAssignmentOperator()) 15528 DefineImplicitCopyAssignment(Loc, MethodDecl); 15529 else if (MethodDecl->isMoveAssignmentOperator()) 15530 DefineImplicitMoveAssignment(Loc, MethodDecl); 15531 } 15532 } else if (isa<CXXConversionDecl>(MethodDecl) && 15533 MethodDecl->getParent()->isLambda()) { 15534 CXXConversionDecl *Conversion = 15535 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15536 if (Conversion->isLambdaToBlockPointerConversion()) 15537 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15538 else 15539 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15540 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15541 MarkVTableUsed(Loc, MethodDecl->getParent()); 15542 } 15543 15544 // Implicit instantiation of function templates and member functions of 15545 // class templates. 15546 if (Func->isImplicitlyInstantiable()) { 15547 TemplateSpecializationKind TSK = 15548 Func->getTemplateSpecializationKindForInstantiation(); 15549 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15550 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15551 if (FirstInstantiation) { 15552 PointOfInstantiation = Loc; 15553 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15554 } else if (TSK != TSK_ImplicitInstantiation) { 15555 // Use the point of use as the point of instantiation, instead of the 15556 // point of explicit instantiation (which we track as the actual point 15557 // of instantiation). This gives better backtraces in diagnostics. 15558 PointOfInstantiation = Loc; 15559 } 15560 15561 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15562 Func->isConstexpr()) { 15563 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15564 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15565 CodeSynthesisContexts.size()) 15566 PendingLocalImplicitInstantiations.push_back( 15567 std::make_pair(Func, PointOfInstantiation)); 15568 else if (Func->isConstexpr()) 15569 // Do not defer instantiations of constexpr functions, to avoid the 15570 // expression evaluator needing to call back into Sema if it sees a 15571 // call to such a function. 15572 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15573 else { 15574 Func->setInstantiationIsPending(true); 15575 PendingInstantiations.push_back( 15576 std::make_pair(Func, PointOfInstantiation)); 15577 // Notify the consumer that a function was implicitly instantiated. 15578 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15579 } 15580 } 15581 } else { 15582 // Walk redefinitions, as some of them may be instantiable. 15583 for (auto i : Func->redecls()) { 15584 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15585 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15586 } 15587 } 15588 }); 15589 } 15590 15591 // If this is the first "real" use, act on that. 15592 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15593 // Keep track of used but undefined functions. 15594 if (!Func->isDefined()) { 15595 if (mightHaveNonExternalLinkage(Func)) 15596 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15597 else if (Func->getMostRecentDecl()->isInlined() && 15598 !LangOpts.GNUInline && 15599 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15600 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15601 else if (isExternalWithNoLinkageType(Func)) 15602 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15603 } 15604 15605 // Some x86 Windows calling conventions mangle the size of the parameter 15606 // pack into the name. Computing the size of the parameters requires the 15607 // parameter types to be complete. Check that now. 15608 if (funcHasParameterSizeMangling(*this, Func)) 15609 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15610 15611 Func->markUsed(Context); 15612 } 15613 15614 if (LangOpts.OpenMP) { 15615 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15616 if (LangOpts.OpenMPIsDevice) 15617 checkOpenMPDeviceFunction(Loc, Func); 15618 else 15619 checkOpenMPHostFunction(Loc, Func); 15620 } 15621 } 15622 15623 /// Directly mark a variable odr-used. Given a choice, prefer to use 15624 /// MarkVariableReferenced since it does additional checks and then 15625 /// calls MarkVarDeclODRUsed. 15626 /// If the variable must be captured: 15627 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15628 /// - else capture it in the DeclContext that maps to the 15629 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15630 static void 15631 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15632 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15633 // Keep track of used but undefined variables. 15634 // FIXME: We shouldn't suppress this warning for static data members. 15635 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15636 (!Var->isExternallyVisible() || Var->isInline() || 15637 SemaRef.isExternalWithNoLinkageType(Var)) && 15638 !(Var->isStaticDataMember() && Var->hasInit())) { 15639 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15640 if (old.isInvalid()) 15641 old = Loc; 15642 } 15643 QualType CaptureType, DeclRefType; 15644 if (SemaRef.LangOpts.OpenMP) 15645 SemaRef.tryCaptureOpenMPLambdas(Var); 15646 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15647 /*EllipsisLoc*/ SourceLocation(), 15648 /*BuildAndDiagnose*/ true, 15649 CaptureType, DeclRefType, 15650 FunctionScopeIndexToStopAt); 15651 15652 Var->markUsed(SemaRef.Context); 15653 } 15654 15655 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15656 SourceLocation Loc, 15657 unsigned CapturingScopeIndex) { 15658 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15659 } 15660 15661 static void 15662 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15663 ValueDecl *var, DeclContext *DC) { 15664 DeclContext *VarDC = var->getDeclContext(); 15665 15666 // If the parameter still belongs to the translation unit, then 15667 // we're actually just using one parameter in the declaration of 15668 // the next. 15669 if (isa<ParmVarDecl>(var) && 15670 isa<TranslationUnitDecl>(VarDC)) 15671 return; 15672 15673 // For C code, don't diagnose about capture if we're not actually in code 15674 // right now; it's impossible to write a non-constant expression outside of 15675 // function context, so we'll get other (more useful) diagnostics later. 15676 // 15677 // For C++, things get a bit more nasty... it would be nice to suppress this 15678 // diagnostic for certain cases like using a local variable in an array bound 15679 // for a member of a local class, but the correct predicate is not obvious. 15680 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15681 return; 15682 15683 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15684 unsigned ContextKind = 3; // unknown 15685 if (isa<CXXMethodDecl>(VarDC) && 15686 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15687 ContextKind = 2; 15688 } else if (isa<FunctionDecl>(VarDC)) { 15689 ContextKind = 0; 15690 } else if (isa<BlockDecl>(VarDC)) { 15691 ContextKind = 1; 15692 } 15693 15694 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15695 << var << ValueKind << ContextKind << VarDC; 15696 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15697 << var; 15698 15699 // FIXME: Add additional diagnostic info about class etc. which prevents 15700 // capture. 15701 } 15702 15703 15704 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15705 bool &SubCapturesAreNested, 15706 QualType &CaptureType, 15707 QualType &DeclRefType) { 15708 // Check whether we've already captured it. 15709 if (CSI->CaptureMap.count(Var)) { 15710 // If we found a capture, any subcaptures are nested. 15711 SubCapturesAreNested = true; 15712 15713 // Retrieve the capture type for this variable. 15714 CaptureType = CSI->getCapture(Var).getCaptureType(); 15715 15716 // Compute the type of an expression that refers to this variable. 15717 DeclRefType = CaptureType.getNonReferenceType(); 15718 15719 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15720 // are mutable in the sense that user can change their value - they are 15721 // private instances of the captured declarations. 15722 const Capture &Cap = CSI->getCapture(Var); 15723 if (Cap.isCopyCapture() && 15724 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15725 !(isa<CapturedRegionScopeInfo>(CSI) && 15726 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15727 DeclRefType.addConst(); 15728 return true; 15729 } 15730 return false; 15731 } 15732 15733 // Only block literals, captured statements, and lambda expressions can 15734 // capture; other scopes don't work. 15735 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15736 SourceLocation Loc, 15737 const bool Diagnose, Sema &S) { 15738 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15739 return getLambdaAwareParentOfDeclContext(DC); 15740 else if (Var->hasLocalStorage()) { 15741 if (Diagnose) 15742 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15743 } 15744 return nullptr; 15745 } 15746 15747 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15748 // certain types of variables (unnamed, variably modified types etc.) 15749 // so check for eligibility. 15750 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15751 SourceLocation Loc, 15752 const bool Diagnose, Sema &S) { 15753 15754 bool IsBlock = isa<BlockScopeInfo>(CSI); 15755 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15756 15757 // Lambdas are not allowed to capture unnamed variables 15758 // (e.g. anonymous unions). 15759 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15760 // assuming that's the intent. 15761 if (IsLambda && !Var->getDeclName()) { 15762 if (Diagnose) { 15763 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15764 S.Diag(Var->getLocation(), diag::note_declared_at); 15765 } 15766 return false; 15767 } 15768 15769 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15770 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15771 if (Diagnose) { 15772 S.Diag(Loc, diag::err_ref_vm_type); 15773 S.Diag(Var->getLocation(), diag::note_previous_decl) 15774 << Var->getDeclName(); 15775 } 15776 return false; 15777 } 15778 // Prohibit structs with flexible array members too. 15779 // We cannot capture what is in the tail end of the struct. 15780 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15781 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15782 if (Diagnose) { 15783 if (IsBlock) 15784 S.Diag(Loc, diag::err_ref_flexarray_type); 15785 else 15786 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15787 << Var->getDeclName(); 15788 S.Diag(Var->getLocation(), diag::note_previous_decl) 15789 << Var->getDeclName(); 15790 } 15791 return false; 15792 } 15793 } 15794 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15795 // Lambdas and captured statements are not allowed to capture __block 15796 // variables; they don't support the expected semantics. 15797 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15798 if (Diagnose) { 15799 S.Diag(Loc, diag::err_capture_block_variable) 15800 << Var->getDeclName() << !IsLambda; 15801 S.Diag(Var->getLocation(), diag::note_previous_decl) 15802 << Var->getDeclName(); 15803 } 15804 return false; 15805 } 15806 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15807 if (S.getLangOpts().OpenCL && IsBlock && 15808 Var->getType()->isBlockPointerType()) { 15809 if (Diagnose) 15810 S.Diag(Loc, diag::err_opencl_block_ref_block); 15811 return false; 15812 } 15813 15814 return true; 15815 } 15816 15817 // Returns true if the capture by block was successful. 15818 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15819 SourceLocation Loc, 15820 const bool BuildAndDiagnose, 15821 QualType &CaptureType, 15822 QualType &DeclRefType, 15823 const bool Nested, 15824 Sema &S, bool Invalid) { 15825 bool ByRef = false; 15826 15827 // Blocks are not allowed to capture arrays, excepting OpenCL. 15828 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15829 // (decayed to pointers). 15830 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15831 if (BuildAndDiagnose) { 15832 S.Diag(Loc, diag::err_ref_array_type); 15833 S.Diag(Var->getLocation(), diag::note_previous_decl) 15834 << Var->getDeclName(); 15835 Invalid = true; 15836 } else { 15837 return false; 15838 } 15839 } 15840 15841 // Forbid the block-capture of autoreleasing variables. 15842 if (!Invalid && 15843 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15844 if (BuildAndDiagnose) { 15845 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15846 << /*block*/ 0; 15847 S.Diag(Var->getLocation(), diag::note_previous_decl) 15848 << Var->getDeclName(); 15849 Invalid = true; 15850 } else { 15851 return false; 15852 } 15853 } 15854 15855 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15856 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15857 QualType PointeeTy = PT->getPointeeType(); 15858 15859 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15860 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15861 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15862 if (BuildAndDiagnose) { 15863 SourceLocation VarLoc = Var->getLocation(); 15864 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15865 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15866 } 15867 } 15868 } 15869 15870 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15871 if (HasBlocksAttr || CaptureType->isReferenceType() || 15872 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15873 // Block capture by reference does not change the capture or 15874 // declaration reference types. 15875 ByRef = true; 15876 } else { 15877 // Block capture by copy introduces 'const'. 15878 CaptureType = CaptureType.getNonReferenceType().withConst(); 15879 DeclRefType = CaptureType; 15880 } 15881 15882 // Actually capture the variable. 15883 if (BuildAndDiagnose) 15884 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15885 CaptureType, Invalid); 15886 15887 return !Invalid; 15888 } 15889 15890 15891 /// Capture the given variable in the captured region. 15892 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15893 VarDecl *Var, 15894 SourceLocation Loc, 15895 const bool BuildAndDiagnose, 15896 QualType &CaptureType, 15897 QualType &DeclRefType, 15898 const bool RefersToCapturedVariable, 15899 Sema &S, bool Invalid) { 15900 // By default, capture variables by reference. 15901 bool ByRef = true; 15902 // Using an LValue reference type is consistent with Lambdas (see below). 15903 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15904 if (S.isOpenMPCapturedDecl(Var)) { 15905 bool HasConst = DeclRefType.isConstQualified(); 15906 DeclRefType = DeclRefType.getUnqualifiedType(); 15907 // Don't lose diagnostics about assignments to const. 15908 if (HasConst) 15909 DeclRefType.addConst(); 15910 } 15911 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 15912 RSI->OpenMPCaptureLevel); 15913 } 15914 15915 if (ByRef) 15916 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15917 else 15918 CaptureType = DeclRefType; 15919 15920 // Actually capture the variable. 15921 if (BuildAndDiagnose) 15922 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 15923 Loc, SourceLocation(), CaptureType, Invalid); 15924 15925 return !Invalid; 15926 } 15927 15928 /// Capture the given variable in the lambda. 15929 static bool captureInLambda(LambdaScopeInfo *LSI, 15930 VarDecl *Var, 15931 SourceLocation Loc, 15932 const bool BuildAndDiagnose, 15933 QualType &CaptureType, 15934 QualType &DeclRefType, 15935 const bool RefersToCapturedVariable, 15936 const Sema::TryCaptureKind Kind, 15937 SourceLocation EllipsisLoc, 15938 const bool IsTopScope, 15939 Sema &S, bool Invalid) { 15940 // Determine whether we are capturing by reference or by value. 15941 bool ByRef = false; 15942 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15943 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15944 } else { 15945 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15946 } 15947 15948 // Compute the type of the field that will capture this variable. 15949 if (ByRef) { 15950 // C++11 [expr.prim.lambda]p15: 15951 // An entity is captured by reference if it is implicitly or 15952 // explicitly captured but not captured by copy. It is 15953 // unspecified whether additional unnamed non-static data 15954 // members are declared in the closure type for entities 15955 // captured by reference. 15956 // 15957 // FIXME: It is not clear whether we want to build an lvalue reference 15958 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15959 // to do the former, while EDG does the latter. Core issue 1249 will 15960 // clarify, but for now we follow GCC because it's a more permissive and 15961 // easily defensible position. 15962 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15963 } else { 15964 // C++11 [expr.prim.lambda]p14: 15965 // For each entity captured by copy, an unnamed non-static 15966 // data member is declared in the closure type. The 15967 // declaration order of these members is unspecified. The type 15968 // of such a data member is the type of the corresponding 15969 // captured entity if the entity is not a reference to an 15970 // object, or the referenced type otherwise. [Note: If the 15971 // captured entity is a reference to a function, the 15972 // corresponding data member is also a reference to a 15973 // function. - end note ] 15974 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15975 if (!RefType->getPointeeType()->isFunctionType()) 15976 CaptureType = RefType->getPointeeType(); 15977 } 15978 15979 // Forbid the lambda copy-capture of autoreleasing variables. 15980 if (!Invalid && 15981 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15982 if (BuildAndDiagnose) { 15983 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15984 S.Diag(Var->getLocation(), diag::note_previous_decl) 15985 << Var->getDeclName(); 15986 Invalid = true; 15987 } else { 15988 return false; 15989 } 15990 } 15991 15992 // Make sure that by-copy captures are of a complete and non-abstract type. 15993 if (!Invalid && BuildAndDiagnose) { 15994 if (!CaptureType->isDependentType() && 15995 S.RequireCompleteType(Loc, CaptureType, 15996 diag::err_capture_of_incomplete_type, 15997 Var->getDeclName())) 15998 Invalid = true; 15999 else if (S.RequireNonAbstractType(Loc, CaptureType, 16000 diag::err_capture_of_abstract_type)) 16001 Invalid = true; 16002 } 16003 } 16004 16005 // Compute the type of a reference to this captured variable. 16006 if (ByRef) 16007 DeclRefType = CaptureType.getNonReferenceType(); 16008 else { 16009 // C++ [expr.prim.lambda]p5: 16010 // The closure type for a lambda-expression has a public inline 16011 // function call operator [...]. This function call operator is 16012 // declared const (9.3.1) if and only if the lambda-expression's 16013 // parameter-declaration-clause is not followed by mutable. 16014 DeclRefType = CaptureType.getNonReferenceType(); 16015 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16016 DeclRefType.addConst(); 16017 } 16018 16019 // Add the capture. 16020 if (BuildAndDiagnose) 16021 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16022 Loc, EllipsisLoc, CaptureType, Invalid); 16023 16024 return !Invalid; 16025 } 16026 16027 bool Sema::tryCaptureVariable( 16028 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16029 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16030 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16031 // An init-capture is notionally from the context surrounding its 16032 // declaration, but its parent DC is the lambda class. 16033 DeclContext *VarDC = Var->getDeclContext(); 16034 if (Var->isInitCapture()) 16035 VarDC = VarDC->getParent(); 16036 16037 DeclContext *DC = CurContext; 16038 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16039 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16040 // We need to sync up the Declaration Context with the 16041 // FunctionScopeIndexToStopAt 16042 if (FunctionScopeIndexToStopAt) { 16043 unsigned FSIndex = FunctionScopes.size() - 1; 16044 while (FSIndex != MaxFunctionScopesIndex) { 16045 DC = getLambdaAwareParentOfDeclContext(DC); 16046 --FSIndex; 16047 } 16048 } 16049 16050 16051 // If the variable is declared in the current context, there is no need to 16052 // capture it. 16053 if (VarDC == DC) return true; 16054 16055 // Capture global variables if it is required to use private copy of this 16056 // variable. 16057 bool IsGlobal = !Var->hasLocalStorage(); 16058 if (IsGlobal && 16059 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16060 MaxFunctionScopesIndex))) 16061 return true; 16062 Var = Var->getCanonicalDecl(); 16063 16064 // Walk up the stack to determine whether we can capture the variable, 16065 // performing the "simple" checks that don't depend on type. We stop when 16066 // we've either hit the declared scope of the variable or find an existing 16067 // capture of that variable. We start from the innermost capturing-entity 16068 // (the DC) and ensure that all intervening capturing-entities 16069 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16070 // declcontext can either capture the variable or have already captured 16071 // the variable. 16072 CaptureType = Var->getType(); 16073 DeclRefType = CaptureType.getNonReferenceType(); 16074 bool Nested = false; 16075 bool Explicit = (Kind != TryCapture_Implicit); 16076 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16077 do { 16078 // Only block literals, captured statements, and lambda expressions can 16079 // capture; other scopes don't work. 16080 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16081 ExprLoc, 16082 BuildAndDiagnose, 16083 *this); 16084 // We need to check for the parent *first* because, if we *have* 16085 // private-captured a global variable, we need to recursively capture it in 16086 // intermediate blocks, lambdas, etc. 16087 if (!ParentDC) { 16088 if (IsGlobal) { 16089 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16090 break; 16091 } 16092 return true; 16093 } 16094 16095 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16096 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16097 16098 16099 // Check whether we've already captured it. 16100 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16101 DeclRefType)) { 16102 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16103 break; 16104 } 16105 // If we are instantiating a generic lambda call operator body, 16106 // we do not want to capture new variables. What was captured 16107 // during either a lambdas transformation or initial parsing 16108 // should be used. 16109 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16110 if (BuildAndDiagnose) { 16111 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16112 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16113 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16114 Diag(Var->getLocation(), diag::note_previous_decl) 16115 << Var->getDeclName(); 16116 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16117 } else 16118 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16119 } 16120 return true; 16121 } 16122 16123 // Try to capture variable-length arrays types. 16124 if (Var->getType()->isVariablyModifiedType()) { 16125 // We're going to walk down into the type and look for VLA 16126 // expressions. 16127 QualType QTy = Var->getType(); 16128 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16129 QTy = PVD->getOriginalType(); 16130 captureVariablyModifiedType(Context, QTy, CSI); 16131 } 16132 16133 if (getLangOpts().OpenMP) { 16134 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16135 // OpenMP private variables should not be captured in outer scope, so 16136 // just break here. Similarly, global variables that are captured in a 16137 // target region should not be captured outside the scope of the region. 16138 if (RSI->CapRegionKind == CR_OpenMP) { 16139 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16140 // If the variable is private (i.e. not captured) and has variably 16141 // modified type, we still need to capture the type for correct 16142 // codegen in all regions, associated with the construct. Currently, 16143 // it is captured in the innermost captured region only. 16144 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16145 QualType QTy = Var->getType(); 16146 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16147 QTy = PVD->getOriginalType(); 16148 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16149 I < E; ++I) { 16150 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16151 FunctionScopes[FunctionScopesIndex - I]); 16152 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16153 "Wrong number of captured regions associated with the " 16154 "OpenMP construct."); 16155 captureVariablyModifiedType(Context, QTy, OuterRSI); 16156 } 16157 } 16158 bool IsTargetCap = !IsOpenMPPrivateDecl && 16159 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16160 // When we detect target captures we are looking from inside the 16161 // target region, therefore we need to propagate the capture from the 16162 // enclosing region. Therefore, the capture is not initially nested. 16163 if (IsTargetCap) 16164 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16165 16166 if (IsTargetCap || IsOpenMPPrivateDecl) { 16167 Nested = !IsTargetCap; 16168 DeclRefType = DeclRefType.getUnqualifiedType(); 16169 CaptureType = Context.getLValueReferenceType(DeclRefType); 16170 break; 16171 } 16172 } 16173 } 16174 } 16175 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16176 // No capture-default, and this is not an explicit capture 16177 // so cannot capture this variable. 16178 if (BuildAndDiagnose) { 16179 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16180 Diag(Var->getLocation(), diag::note_previous_decl) 16181 << Var->getDeclName(); 16182 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16183 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16184 diag::note_lambda_decl); 16185 // FIXME: If we error out because an outer lambda can not implicitly 16186 // capture a variable that an inner lambda explicitly captures, we 16187 // should have the inner lambda do the explicit capture - because 16188 // it makes for cleaner diagnostics later. This would purely be done 16189 // so that the diagnostic does not misleadingly claim that a variable 16190 // can not be captured by a lambda implicitly even though it is captured 16191 // explicitly. Suggestion: 16192 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16193 // at the function head 16194 // - cache the StartingDeclContext - this must be a lambda 16195 // - captureInLambda in the innermost lambda the variable. 16196 } 16197 return true; 16198 } 16199 16200 FunctionScopesIndex--; 16201 DC = ParentDC; 16202 Explicit = false; 16203 } while (!VarDC->Equals(DC)); 16204 16205 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16206 // computing the type of the capture at each step, checking type-specific 16207 // requirements, and adding captures if requested. 16208 // If the variable had already been captured previously, we start capturing 16209 // at the lambda nested within that one. 16210 bool Invalid = false; 16211 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16212 ++I) { 16213 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16214 16215 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16216 // certain types of variables (unnamed, variably modified types etc.) 16217 // so check for eligibility. 16218 if (!Invalid) 16219 Invalid = 16220 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16221 16222 // After encountering an error, if we're actually supposed to capture, keep 16223 // capturing in nested contexts to suppress any follow-on diagnostics. 16224 if (Invalid && !BuildAndDiagnose) 16225 return true; 16226 16227 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16228 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16229 DeclRefType, Nested, *this, Invalid); 16230 Nested = true; 16231 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16232 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16233 CaptureType, DeclRefType, Nested, 16234 *this, Invalid); 16235 Nested = true; 16236 } else { 16237 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16238 Invalid = 16239 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16240 DeclRefType, Nested, Kind, EllipsisLoc, 16241 /*IsTopScope*/ I == N - 1, *this, Invalid); 16242 Nested = true; 16243 } 16244 16245 if (Invalid && !BuildAndDiagnose) 16246 return true; 16247 } 16248 return Invalid; 16249 } 16250 16251 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16252 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16253 QualType CaptureType; 16254 QualType DeclRefType; 16255 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16256 /*BuildAndDiagnose=*/true, CaptureType, 16257 DeclRefType, nullptr); 16258 } 16259 16260 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16261 QualType CaptureType; 16262 QualType DeclRefType; 16263 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16264 /*BuildAndDiagnose=*/false, CaptureType, 16265 DeclRefType, nullptr); 16266 } 16267 16268 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16269 QualType CaptureType; 16270 QualType DeclRefType; 16271 16272 // Determine whether we can capture this variable. 16273 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16274 /*BuildAndDiagnose=*/false, CaptureType, 16275 DeclRefType, nullptr)) 16276 return QualType(); 16277 16278 return DeclRefType; 16279 } 16280 16281 namespace { 16282 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16283 // The produced TemplateArgumentListInfo* points to data stored within this 16284 // object, so should only be used in contexts where the pointer will not be 16285 // used after the CopiedTemplateArgs object is destroyed. 16286 class CopiedTemplateArgs { 16287 bool HasArgs; 16288 TemplateArgumentListInfo TemplateArgStorage; 16289 public: 16290 template<typename RefExpr> 16291 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16292 if (HasArgs) 16293 E->copyTemplateArgumentsInto(TemplateArgStorage); 16294 } 16295 operator TemplateArgumentListInfo*() 16296 #ifdef __has_cpp_attribute 16297 #if __has_cpp_attribute(clang::lifetimebound) 16298 [[clang::lifetimebound]] 16299 #endif 16300 #endif 16301 { 16302 return HasArgs ? &TemplateArgStorage : nullptr; 16303 } 16304 }; 16305 } 16306 16307 /// Walk the set of potential results of an expression and mark them all as 16308 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16309 /// 16310 /// \return A new expression if we found any potential results, ExprEmpty() if 16311 /// not, and ExprError() if we diagnosed an error. 16312 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16313 NonOdrUseReason NOUR) { 16314 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16315 // an object that satisfies the requirements for appearing in a 16316 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16317 // is immediately applied." This function handles the lvalue-to-rvalue 16318 // conversion part. 16319 // 16320 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16321 // transform it into the relevant kind of non-odr-use node and rebuild the 16322 // tree of nodes leading to it. 16323 // 16324 // This is a mini-TreeTransform that only transforms a restricted subset of 16325 // nodes (and only certain operands of them). 16326 16327 // Rebuild a subexpression. 16328 auto Rebuild = [&](Expr *Sub) { 16329 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16330 }; 16331 16332 // Check whether a potential result satisfies the requirements of NOUR. 16333 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16334 // Any entity other than a VarDecl is always odr-used whenever it's named 16335 // in a potentially-evaluated expression. 16336 auto *VD = dyn_cast<VarDecl>(D); 16337 if (!VD) 16338 return true; 16339 16340 // C++2a [basic.def.odr]p4: 16341 // A variable x whose name appears as a potentially-evalauted expression 16342 // e is odr-used by e unless 16343 // -- x is a reference that is usable in constant expressions, or 16344 // -- x is a variable of non-reference type that is usable in constant 16345 // expressions and has no mutable subobjects, and e is an element of 16346 // the set of potential results of an expression of 16347 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16348 // conversion is applied, or 16349 // -- x is a variable of non-reference type, and e is an element of the 16350 // set of potential results of a discarded-value expression to which 16351 // the lvalue-to-rvalue conversion is not applied 16352 // 16353 // We check the first bullet and the "potentially-evaluated" condition in 16354 // BuildDeclRefExpr. We check the type requirements in the second bullet 16355 // in CheckLValueToRValueConversionOperand below. 16356 switch (NOUR) { 16357 case NOUR_None: 16358 case NOUR_Unevaluated: 16359 llvm_unreachable("unexpected non-odr-use-reason"); 16360 16361 case NOUR_Constant: 16362 // Constant references were handled when they were built. 16363 if (VD->getType()->isReferenceType()) 16364 return true; 16365 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16366 if (RD->hasMutableFields()) 16367 return true; 16368 if (!VD->isUsableInConstantExpressions(S.Context)) 16369 return true; 16370 break; 16371 16372 case NOUR_Discarded: 16373 if (VD->getType()->isReferenceType()) 16374 return true; 16375 break; 16376 } 16377 return false; 16378 }; 16379 16380 // Mark that this expression does not constitute an odr-use. 16381 auto MarkNotOdrUsed = [&] { 16382 S.MaybeODRUseExprs.erase(E); 16383 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16384 LSI->markVariableExprAsNonODRUsed(E); 16385 }; 16386 16387 // C++2a [basic.def.odr]p2: 16388 // The set of potential results of an expression e is defined as follows: 16389 switch (E->getStmtClass()) { 16390 // -- If e is an id-expression, ... 16391 case Expr::DeclRefExprClass: { 16392 auto *DRE = cast<DeclRefExpr>(E); 16393 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16394 break; 16395 16396 // Rebuild as a non-odr-use DeclRefExpr. 16397 MarkNotOdrUsed(); 16398 return DeclRefExpr::Create( 16399 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16400 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16401 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16402 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16403 } 16404 16405 case Expr::FunctionParmPackExprClass: { 16406 auto *FPPE = cast<FunctionParmPackExpr>(E); 16407 // If any of the declarations in the pack is odr-used, then the expression 16408 // as a whole constitutes an odr-use. 16409 for (VarDecl *D : *FPPE) 16410 if (IsPotentialResultOdrUsed(D)) 16411 return ExprEmpty(); 16412 16413 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16414 // nothing cares about whether we marked this as an odr-use, but it might 16415 // be useful for non-compiler tools. 16416 MarkNotOdrUsed(); 16417 break; 16418 } 16419 16420 // -- If e is a subscripting operation with an array operand... 16421 case Expr::ArraySubscriptExprClass: { 16422 auto *ASE = cast<ArraySubscriptExpr>(E); 16423 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16424 if (!OldBase->getType()->isArrayType()) 16425 break; 16426 ExprResult Base = Rebuild(OldBase); 16427 if (!Base.isUsable()) 16428 return Base; 16429 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16430 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16431 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16432 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16433 ASE->getRBracketLoc()); 16434 } 16435 16436 case Expr::MemberExprClass: { 16437 auto *ME = cast<MemberExpr>(E); 16438 // -- If e is a class member access expression [...] naming a non-static 16439 // data member... 16440 if (isa<FieldDecl>(ME->getMemberDecl())) { 16441 ExprResult Base = Rebuild(ME->getBase()); 16442 if (!Base.isUsable()) 16443 return Base; 16444 return MemberExpr::Create( 16445 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16446 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16447 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16448 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16449 ME->getObjectKind(), ME->isNonOdrUse()); 16450 } 16451 16452 if (ME->getMemberDecl()->isCXXInstanceMember()) 16453 break; 16454 16455 // -- If e is a class member access expression naming a static data member, 16456 // ... 16457 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16458 break; 16459 16460 // Rebuild as a non-odr-use MemberExpr. 16461 MarkNotOdrUsed(); 16462 return MemberExpr::Create( 16463 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16464 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16465 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16466 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16467 return ExprEmpty(); 16468 } 16469 16470 case Expr::BinaryOperatorClass: { 16471 auto *BO = cast<BinaryOperator>(E); 16472 Expr *LHS = BO->getLHS(); 16473 Expr *RHS = BO->getRHS(); 16474 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16475 if (BO->getOpcode() == BO_PtrMemD) { 16476 ExprResult Sub = Rebuild(LHS); 16477 if (!Sub.isUsable()) 16478 return Sub; 16479 LHS = Sub.get(); 16480 // -- If e is a comma expression, ... 16481 } else if (BO->getOpcode() == BO_Comma) { 16482 ExprResult Sub = Rebuild(RHS); 16483 if (!Sub.isUsable()) 16484 return Sub; 16485 RHS = Sub.get(); 16486 } else { 16487 break; 16488 } 16489 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16490 LHS, RHS); 16491 } 16492 16493 // -- If e has the form (e1)... 16494 case Expr::ParenExprClass: { 16495 auto *PE = cast<ParenExpr>(E); 16496 ExprResult Sub = Rebuild(PE->getSubExpr()); 16497 if (!Sub.isUsable()) 16498 return Sub; 16499 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16500 } 16501 16502 // -- If e is a glvalue conditional expression, ... 16503 // We don't apply this to a binary conditional operator. FIXME: Should we? 16504 case Expr::ConditionalOperatorClass: { 16505 auto *CO = cast<ConditionalOperator>(E); 16506 ExprResult LHS = Rebuild(CO->getLHS()); 16507 if (LHS.isInvalid()) 16508 return ExprError(); 16509 ExprResult RHS = Rebuild(CO->getRHS()); 16510 if (RHS.isInvalid()) 16511 return ExprError(); 16512 if (!LHS.isUsable() && !RHS.isUsable()) 16513 return ExprEmpty(); 16514 if (!LHS.isUsable()) 16515 LHS = CO->getLHS(); 16516 if (!RHS.isUsable()) 16517 RHS = CO->getRHS(); 16518 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16519 CO->getCond(), LHS.get(), RHS.get()); 16520 } 16521 16522 // [Clang extension] 16523 // -- If e has the form __extension__ e1... 16524 case Expr::UnaryOperatorClass: { 16525 auto *UO = cast<UnaryOperator>(E); 16526 if (UO->getOpcode() != UO_Extension) 16527 break; 16528 ExprResult Sub = Rebuild(UO->getSubExpr()); 16529 if (!Sub.isUsable()) 16530 return Sub; 16531 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16532 Sub.get()); 16533 } 16534 16535 // [Clang extension] 16536 // -- If e has the form _Generic(...), the set of potential results is the 16537 // union of the sets of potential results of the associated expressions. 16538 case Expr::GenericSelectionExprClass: { 16539 auto *GSE = cast<GenericSelectionExpr>(E); 16540 16541 SmallVector<Expr *, 4> AssocExprs; 16542 bool AnyChanged = false; 16543 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16544 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16545 if (AssocExpr.isInvalid()) 16546 return ExprError(); 16547 if (AssocExpr.isUsable()) { 16548 AssocExprs.push_back(AssocExpr.get()); 16549 AnyChanged = true; 16550 } else { 16551 AssocExprs.push_back(OrigAssocExpr); 16552 } 16553 } 16554 16555 return AnyChanged ? S.CreateGenericSelectionExpr( 16556 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16557 GSE->getRParenLoc(), GSE->getControllingExpr(), 16558 GSE->getAssocTypeSourceInfos(), AssocExprs) 16559 : ExprEmpty(); 16560 } 16561 16562 // [Clang extension] 16563 // -- If e has the form __builtin_choose_expr(...), the set of potential 16564 // results is the union of the sets of potential results of the 16565 // second and third subexpressions. 16566 case Expr::ChooseExprClass: { 16567 auto *CE = cast<ChooseExpr>(E); 16568 16569 ExprResult LHS = Rebuild(CE->getLHS()); 16570 if (LHS.isInvalid()) 16571 return ExprError(); 16572 16573 ExprResult RHS = Rebuild(CE->getLHS()); 16574 if (RHS.isInvalid()) 16575 return ExprError(); 16576 16577 if (!LHS.get() && !RHS.get()) 16578 return ExprEmpty(); 16579 if (!LHS.isUsable()) 16580 LHS = CE->getLHS(); 16581 if (!RHS.isUsable()) 16582 RHS = CE->getRHS(); 16583 16584 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16585 RHS.get(), CE->getRParenLoc()); 16586 } 16587 16588 // Step through non-syntactic nodes. 16589 case Expr::ConstantExprClass: { 16590 auto *CE = cast<ConstantExpr>(E); 16591 ExprResult Sub = Rebuild(CE->getSubExpr()); 16592 if (!Sub.isUsable()) 16593 return Sub; 16594 return ConstantExpr::Create(S.Context, Sub.get()); 16595 } 16596 16597 // We could mostly rely on the recursive rebuilding to rebuild implicit 16598 // casts, but not at the top level, so rebuild them here. 16599 case Expr::ImplicitCastExprClass: { 16600 auto *ICE = cast<ImplicitCastExpr>(E); 16601 // Only step through the narrow set of cast kinds we expect to encounter. 16602 // Anything else suggests we've left the region in which potential results 16603 // can be found. 16604 switch (ICE->getCastKind()) { 16605 case CK_NoOp: 16606 case CK_DerivedToBase: 16607 case CK_UncheckedDerivedToBase: { 16608 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16609 if (!Sub.isUsable()) 16610 return Sub; 16611 CXXCastPath Path(ICE->path()); 16612 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16613 ICE->getValueKind(), &Path); 16614 } 16615 16616 default: 16617 break; 16618 } 16619 break; 16620 } 16621 16622 default: 16623 break; 16624 } 16625 16626 // Can't traverse through this node. Nothing to do. 16627 return ExprEmpty(); 16628 } 16629 16630 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16631 // Check whether the operand is or contains an object of non-trivial C union 16632 // type. 16633 if (E->getType().isVolatileQualified() && 16634 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16635 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16636 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16637 Sema::NTCUC_LValueToRValueVolatile, 16638 NTCUK_Destruct|NTCUK_Copy); 16639 16640 // C++2a [basic.def.odr]p4: 16641 // [...] an expression of non-volatile-qualified non-class type to which 16642 // the lvalue-to-rvalue conversion is applied [...] 16643 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16644 return E; 16645 16646 ExprResult Result = 16647 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16648 if (Result.isInvalid()) 16649 return ExprError(); 16650 return Result.get() ? Result : E; 16651 } 16652 16653 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16654 Res = CorrectDelayedTyposInExpr(Res); 16655 16656 if (!Res.isUsable()) 16657 return Res; 16658 16659 // If a constant-expression is a reference to a variable where we delay 16660 // deciding whether it is an odr-use, just assume we will apply the 16661 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16662 // (a non-type template argument), we have special handling anyway. 16663 return CheckLValueToRValueConversionOperand(Res.get()); 16664 } 16665 16666 void Sema::CleanupVarDeclMarking() { 16667 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16668 // call. 16669 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16670 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16671 16672 for (Expr *E : LocalMaybeODRUseExprs) { 16673 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16674 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16675 DRE->getLocation(), *this); 16676 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16677 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16678 *this); 16679 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16680 for (VarDecl *VD : *FP) 16681 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16682 } else { 16683 llvm_unreachable("Unexpected expression"); 16684 } 16685 } 16686 16687 assert(MaybeODRUseExprs.empty() && 16688 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16689 } 16690 16691 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16692 VarDecl *Var, Expr *E) { 16693 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16694 isa<FunctionParmPackExpr>(E)) && 16695 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16696 Var->setReferenced(); 16697 16698 if (Var->isInvalidDecl()) 16699 return; 16700 16701 auto *MSI = Var->getMemberSpecializationInfo(); 16702 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16703 : Var->getTemplateSpecializationKind(); 16704 16705 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16706 bool UsableInConstantExpr = 16707 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16708 16709 // C++20 [expr.const]p12: 16710 // A variable [...] is needed for constant evaluation if it is [...] a 16711 // variable whose name appears as a potentially constant evaluated 16712 // expression that is either a contexpr variable or is of non-volatile 16713 // const-qualified integral type or of reference type 16714 bool NeededForConstantEvaluation = 16715 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16716 16717 bool NeedDefinition = 16718 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16719 16720 VarTemplateSpecializationDecl *VarSpec = 16721 dyn_cast<VarTemplateSpecializationDecl>(Var); 16722 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16723 "Can't instantiate a partial template specialization."); 16724 16725 // If this might be a member specialization of a static data member, check 16726 // the specialization is visible. We already did the checks for variable 16727 // template specializations when we created them. 16728 if (NeedDefinition && TSK != TSK_Undeclared && 16729 !isa<VarTemplateSpecializationDecl>(Var)) 16730 SemaRef.checkSpecializationVisibility(Loc, Var); 16731 16732 // Perform implicit instantiation of static data members, static data member 16733 // templates of class templates, and variable template specializations. Delay 16734 // instantiations of variable templates, except for those that could be used 16735 // in a constant expression. 16736 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16737 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16738 // instantiation declaration if a variable is usable in a constant 16739 // expression (among other cases). 16740 bool TryInstantiating = 16741 TSK == TSK_ImplicitInstantiation || 16742 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16743 16744 if (TryInstantiating) { 16745 SourceLocation PointOfInstantiation = 16746 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16747 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16748 if (FirstInstantiation) { 16749 PointOfInstantiation = Loc; 16750 if (MSI) 16751 MSI->setPointOfInstantiation(PointOfInstantiation); 16752 else 16753 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16754 } 16755 16756 bool InstantiationDependent = false; 16757 bool IsNonDependent = 16758 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16759 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16760 : true; 16761 16762 // Do not instantiate specializations that are still type-dependent. 16763 if (IsNonDependent) { 16764 if (UsableInConstantExpr) { 16765 // Do not defer instantiations of variables that could be used in a 16766 // constant expression. 16767 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16768 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16769 }); 16770 } else if (FirstInstantiation || 16771 isa<VarTemplateSpecializationDecl>(Var)) { 16772 // FIXME: For a specialization of a variable template, we don't 16773 // distinguish between "declaration and type implicitly instantiated" 16774 // and "implicit instantiation of definition requested", so we have 16775 // no direct way to avoid enqueueing the pending instantiation 16776 // multiple times. 16777 SemaRef.PendingInstantiations 16778 .push_back(std::make_pair(Var, PointOfInstantiation)); 16779 } 16780 } 16781 } 16782 } 16783 16784 // C++2a [basic.def.odr]p4: 16785 // A variable x whose name appears as a potentially-evaluated expression e 16786 // is odr-used by e unless 16787 // -- x is a reference that is usable in constant expressions 16788 // -- x is a variable of non-reference type that is usable in constant 16789 // expressions and has no mutable subobjects [FIXME], and e is an 16790 // element of the set of potential results of an expression of 16791 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16792 // conversion is applied 16793 // -- x is a variable of non-reference type, and e is an element of the set 16794 // of potential results of a discarded-value expression to which the 16795 // lvalue-to-rvalue conversion is not applied [FIXME] 16796 // 16797 // We check the first part of the second bullet here, and 16798 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16799 // FIXME: To get the third bullet right, we need to delay this even for 16800 // variables that are not usable in constant expressions. 16801 16802 // If we already know this isn't an odr-use, there's nothing more to do. 16803 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16804 if (DRE->isNonOdrUse()) 16805 return; 16806 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16807 if (ME->isNonOdrUse()) 16808 return; 16809 16810 switch (OdrUse) { 16811 case OdrUseContext::None: 16812 assert((!E || isa<FunctionParmPackExpr>(E)) && 16813 "missing non-odr-use marking for unevaluated decl ref"); 16814 break; 16815 16816 case OdrUseContext::FormallyOdrUsed: 16817 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16818 // behavior. 16819 break; 16820 16821 case OdrUseContext::Used: 16822 // If we might later find that this expression isn't actually an odr-use, 16823 // delay the marking. 16824 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16825 SemaRef.MaybeODRUseExprs.insert(E); 16826 else 16827 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16828 break; 16829 16830 case OdrUseContext::Dependent: 16831 // If this is a dependent context, we don't need to mark variables as 16832 // odr-used, but we may still need to track them for lambda capture. 16833 // FIXME: Do we also need to do this inside dependent typeid expressions 16834 // (which are modeled as unevaluated at this point)? 16835 const bool RefersToEnclosingScope = 16836 (SemaRef.CurContext != Var->getDeclContext() && 16837 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16838 if (RefersToEnclosingScope) { 16839 LambdaScopeInfo *const LSI = 16840 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16841 if (LSI && (!LSI->CallOperator || 16842 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16843 // If a variable could potentially be odr-used, defer marking it so 16844 // until we finish analyzing the full expression for any 16845 // lvalue-to-rvalue 16846 // or discarded value conversions that would obviate odr-use. 16847 // Add it to the list of potential captures that will be analyzed 16848 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16849 // unless the variable is a reference that was initialized by a constant 16850 // expression (this will never need to be captured or odr-used). 16851 // 16852 // FIXME: We can simplify this a lot after implementing P0588R1. 16853 assert(E && "Capture variable should be used in an expression."); 16854 if (!Var->getType()->isReferenceType() || 16855 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16856 LSI->addPotentialCapture(E->IgnoreParens()); 16857 } 16858 } 16859 break; 16860 } 16861 } 16862 16863 /// Mark a variable referenced, and check whether it is odr-used 16864 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16865 /// used directly for normal expressions referring to VarDecl. 16866 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16867 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16868 } 16869 16870 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16871 Decl *D, Expr *E, bool MightBeOdrUse) { 16872 if (SemaRef.isInOpenMPDeclareTargetContext()) 16873 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16874 16875 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16876 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16877 return; 16878 } 16879 16880 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16881 16882 // If this is a call to a method via a cast, also mark the method in the 16883 // derived class used in case codegen can devirtualize the call. 16884 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16885 if (!ME) 16886 return; 16887 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16888 if (!MD) 16889 return; 16890 // Only attempt to devirtualize if this is truly a virtual call. 16891 bool IsVirtualCall = MD->isVirtual() && 16892 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16893 if (!IsVirtualCall) 16894 return; 16895 16896 // If it's possible to devirtualize the call, mark the called function 16897 // referenced. 16898 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16899 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16900 if (DM) 16901 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16902 } 16903 16904 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16905 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16906 // TODO: update this with DR# once a defect report is filed. 16907 // C++11 defect. The address of a pure member should not be an ODR use, even 16908 // if it's a qualified reference. 16909 bool OdrUse = true; 16910 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 16911 if (Method->isVirtual() && 16912 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 16913 OdrUse = false; 16914 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 16915 } 16916 16917 /// Perform reference-marking and odr-use handling for a MemberExpr. 16918 void Sema::MarkMemberReferenced(MemberExpr *E) { 16919 // C++11 [basic.def.odr]p2: 16920 // A non-overloaded function whose name appears as a potentially-evaluated 16921 // expression or a member of a set of candidate functions, if selected by 16922 // overload resolution when referred to from a potentially-evaluated 16923 // expression, is odr-used, unless it is a pure virtual function and its 16924 // name is not explicitly qualified. 16925 bool MightBeOdrUse = true; 16926 if (E->performsVirtualDispatch(getLangOpts())) { 16927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 16928 if (Method->isPure()) 16929 MightBeOdrUse = false; 16930 } 16931 SourceLocation Loc = 16932 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 16933 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 16934 } 16935 16936 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 16937 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 16938 for (VarDecl *VD : *E) 16939 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 16940 } 16941 16942 /// Perform marking for a reference to an arbitrary declaration. It 16943 /// marks the declaration referenced, and performs odr-use checking for 16944 /// functions and variables. This method should not be used when building a 16945 /// normal expression which refers to a variable. 16946 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 16947 bool MightBeOdrUse) { 16948 if (MightBeOdrUse) { 16949 if (auto *VD = dyn_cast<VarDecl>(D)) { 16950 MarkVariableReferenced(Loc, VD); 16951 return; 16952 } 16953 } 16954 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 16955 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 16956 return; 16957 } 16958 D->setReferenced(); 16959 } 16960 16961 namespace { 16962 // Mark all of the declarations used by a type as referenced. 16963 // FIXME: Not fully implemented yet! We need to have a better understanding 16964 // of when we're entering a context we should not recurse into. 16965 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 16966 // TreeTransforms rebuilding the type in a new context. Rather than 16967 // duplicating the TreeTransform logic, we should consider reusing it here. 16968 // Currently that causes problems when rebuilding LambdaExprs. 16969 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 16970 Sema &S; 16971 SourceLocation Loc; 16972 16973 public: 16974 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 16975 16976 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 16977 16978 bool TraverseTemplateArgument(const TemplateArgument &Arg); 16979 }; 16980 } 16981 16982 bool MarkReferencedDecls::TraverseTemplateArgument( 16983 const TemplateArgument &Arg) { 16984 { 16985 // A non-type template argument is a constant-evaluated context. 16986 EnterExpressionEvaluationContext Evaluated( 16987 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 16988 if (Arg.getKind() == TemplateArgument::Declaration) { 16989 if (Decl *D = Arg.getAsDecl()) 16990 S.MarkAnyDeclReferenced(Loc, D, true); 16991 } else if (Arg.getKind() == TemplateArgument::Expression) { 16992 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 16993 } 16994 } 16995 16996 return Inherited::TraverseTemplateArgument(Arg); 16997 } 16998 16999 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17000 MarkReferencedDecls Marker(*this, Loc); 17001 Marker.TraverseType(T); 17002 } 17003 17004 namespace { 17005 /// Helper class that marks all of the declarations referenced by 17006 /// potentially-evaluated subexpressions as "referenced". 17007 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17008 Sema &S; 17009 bool SkipLocalVariables; 17010 17011 public: 17012 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17013 17014 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17015 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17016 17017 void VisitDeclRefExpr(DeclRefExpr *E) { 17018 // If we were asked not to visit local variables, don't. 17019 if (SkipLocalVariables) { 17020 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17021 if (VD->hasLocalStorage()) 17022 return; 17023 } 17024 17025 S.MarkDeclRefReferenced(E); 17026 } 17027 17028 void VisitMemberExpr(MemberExpr *E) { 17029 S.MarkMemberReferenced(E); 17030 Inherited::VisitMemberExpr(E); 17031 } 17032 17033 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17034 S.MarkFunctionReferenced( 17035 E->getBeginLoc(), 17036 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17037 Visit(E->getSubExpr()); 17038 } 17039 17040 void VisitCXXNewExpr(CXXNewExpr *E) { 17041 if (E->getOperatorNew()) 17042 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17043 if (E->getOperatorDelete()) 17044 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17045 Inherited::VisitCXXNewExpr(E); 17046 } 17047 17048 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17049 if (E->getOperatorDelete()) 17050 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17051 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17052 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17053 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17054 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17055 } 17056 17057 Inherited::VisitCXXDeleteExpr(E); 17058 } 17059 17060 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17061 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17062 Inherited::VisitCXXConstructExpr(E); 17063 } 17064 17065 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17066 Visit(E->getExpr()); 17067 } 17068 }; 17069 } 17070 17071 /// Mark any declarations that appear within this expression or any 17072 /// potentially-evaluated subexpressions as "referenced". 17073 /// 17074 /// \param SkipLocalVariables If true, don't mark local variables as 17075 /// 'referenced'. 17076 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17077 bool SkipLocalVariables) { 17078 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17079 } 17080 17081 /// Emit a diagnostic that describes an effect on the run-time behavior 17082 /// of the program being compiled. 17083 /// 17084 /// This routine emits the given diagnostic when the code currently being 17085 /// type-checked is "potentially evaluated", meaning that there is a 17086 /// possibility that the code will actually be executable. Code in sizeof() 17087 /// expressions, code used only during overload resolution, etc., are not 17088 /// potentially evaluated. This routine will suppress such diagnostics or, 17089 /// in the absolutely nutty case of potentially potentially evaluated 17090 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17091 /// later. 17092 /// 17093 /// This routine should be used for all diagnostics that describe the run-time 17094 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17095 /// Failure to do so will likely result in spurious diagnostics or failures 17096 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17097 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17098 const PartialDiagnostic &PD) { 17099 switch (ExprEvalContexts.back().Context) { 17100 case ExpressionEvaluationContext::Unevaluated: 17101 case ExpressionEvaluationContext::UnevaluatedList: 17102 case ExpressionEvaluationContext::UnevaluatedAbstract: 17103 case ExpressionEvaluationContext::DiscardedStatement: 17104 // The argument will never be evaluated, so don't complain. 17105 break; 17106 17107 case ExpressionEvaluationContext::ConstantEvaluated: 17108 // Relevant diagnostics should be produced by constant evaluation. 17109 break; 17110 17111 case ExpressionEvaluationContext::PotentiallyEvaluated: 17112 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17113 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17114 FunctionScopes.back()->PossiblyUnreachableDiags. 17115 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17116 return true; 17117 } 17118 17119 // The initializer of a constexpr variable or of the first declaration of a 17120 // static data member is not syntactically a constant evaluated constant, 17121 // but nonetheless is always required to be a constant expression, so we 17122 // can skip diagnosing. 17123 // FIXME: Using the mangling context here is a hack. 17124 if (auto *VD = dyn_cast_or_null<VarDecl>( 17125 ExprEvalContexts.back().ManglingContextDecl)) { 17126 if (VD->isConstexpr() || 17127 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17128 break; 17129 // FIXME: For any other kind of variable, we should build a CFG for its 17130 // initializer and check whether the context in question is reachable. 17131 } 17132 17133 Diag(Loc, PD); 17134 return true; 17135 } 17136 17137 return false; 17138 } 17139 17140 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17141 const PartialDiagnostic &PD) { 17142 return DiagRuntimeBehavior( 17143 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17144 } 17145 17146 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17147 CallExpr *CE, FunctionDecl *FD) { 17148 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17149 return false; 17150 17151 // If we're inside a decltype's expression, don't check for a valid return 17152 // type or construct temporaries until we know whether this is the last call. 17153 if (ExprEvalContexts.back().ExprContext == 17154 ExpressionEvaluationContextRecord::EK_Decltype) { 17155 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17156 return false; 17157 } 17158 17159 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17160 FunctionDecl *FD; 17161 CallExpr *CE; 17162 17163 public: 17164 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17165 : FD(FD), CE(CE) { } 17166 17167 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17168 if (!FD) { 17169 S.Diag(Loc, diag::err_call_incomplete_return) 17170 << T << CE->getSourceRange(); 17171 return; 17172 } 17173 17174 S.Diag(Loc, diag::err_call_function_incomplete_return) 17175 << CE->getSourceRange() << FD->getDeclName() << T; 17176 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17177 << FD->getDeclName(); 17178 } 17179 } Diagnoser(FD, CE); 17180 17181 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17182 return true; 17183 17184 return false; 17185 } 17186 17187 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17188 // will prevent this condition from triggering, which is what we want. 17189 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17190 SourceLocation Loc; 17191 17192 unsigned diagnostic = diag::warn_condition_is_assignment; 17193 bool IsOrAssign = false; 17194 17195 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17196 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17197 return; 17198 17199 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17200 17201 // Greylist some idioms by putting them into a warning subcategory. 17202 if (ObjCMessageExpr *ME 17203 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17204 Selector Sel = ME->getSelector(); 17205 17206 // self = [<foo> init...] 17207 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17208 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17209 17210 // <foo> = [<bar> nextObject] 17211 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17212 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17213 } 17214 17215 Loc = Op->getOperatorLoc(); 17216 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17217 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17218 return; 17219 17220 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17221 Loc = Op->getOperatorLoc(); 17222 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17223 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17224 else { 17225 // Not an assignment. 17226 return; 17227 } 17228 17229 Diag(Loc, diagnostic) << E->getSourceRange(); 17230 17231 SourceLocation Open = E->getBeginLoc(); 17232 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17233 Diag(Loc, diag::note_condition_assign_silence) 17234 << FixItHint::CreateInsertion(Open, "(") 17235 << FixItHint::CreateInsertion(Close, ")"); 17236 17237 if (IsOrAssign) 17238 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17239 << FixItHint::CreateReplacement(Loc, "!="); 17240 else 17241 Diag(Loc, diag::note_condition_assign_to_comparison) 17242 << FixItHint::CreateReplacement(Loc, "=="); 17243 } 17244 17245 /// Redundant parentheses over an equality comparison can indicate 17246 /// that the user intended an assignment used as condition. 17247 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17248 // Don't warn if the parens came from a macro. 17249 SourceLocation parenLoc = ParenE->getBeginLoc(); 17250 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17251 return; 17252 // Don't warn for dependent expressions. 17253 if (ParenE->isTypeDependent()) 17254 return; 17255 17256 Expr *E = ParenE->IgnoreParens(); 17257 17258 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17259 if (opE->getOpcode() == BO_EQ && 17260 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17261 == Expr::MLV_Valid) { 17262 SourceLocation Loc = opE->getOperatorLoc(); 17263 17264 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17265 SourceRange ParenERange = ParenE->getSourceRange(); 17266 Diag(Loc, diag::note_equality_comparison_silence) 17267 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17268 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17269 Diag(Loc, diag::note_equality_comparison_to_assign) 17270 << FixItHint::CreateReplacement(Loc, "="); 17271 } 17272 } 17273 17274 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17275 bool IsConstexpr) { 17276 DiagnoseAssignmentAsCondition(E); 17277 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17278 DiagnoseEqualityWithExtraParens(parenE); 17279 17280 ExprResult result = CheckPlaceholderExpr(E); 17281 if (result.isInvalid()) return ExprError(); 17282 E = result.get(); 17283 17284 if (!E->isTypeDependent()) { 17285 if (getLangOpts().CPlusPlus) 17286 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17287 17288 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17289 if (ERes.isInvalid()) 17290 return ExprError(); 17291 E = ERes.get(); 17292 17293 QualType T = E->getType(); 17294 if (!T->isScalarType()) { // C99 6.8.4.1p1 17295 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17296 << T << E->getSourceRange(); 17297 return ExprError(); 17298 } 17299 CheckBoolLikeConversion(E, Loc); 17300 } 17301 17302 return E; 17303 } 17304 17305 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17306 Expr *SubExpr, ConditionKind CK) { 17307 // Empty conditions are valid in for-statements. 17308 if (!SubExpr) 17309 return ConditionResult(); 17310 17311 ExprResult Cond; 17312 switch (CK) { 17313 case ConditionKind::Boolean: 17314 Cond = CheckBooleanCondition(Loc, SubExpr); 17315 break; 17316 17317 case ConditionKind::ConstexprIf: 17318 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17319 break; 17320 17321 case ConditionKind::Switch: 17322 Cond = CheckSwitchCondition(Loc, SubExpr); 17323 break; 17324 } 17325 if (Cond.isInvalid()) 17326 return ConditionError(); 17327 17328 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17329 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17330 if (!FullExpr.get()) 17331 return ConditionError(); 17332 17333 return ConditionResult(*this, nullptr, FullExpr, 17334 CK == ConditionKind::ConstexprIf); 17335 } 17336 17337 namespace { 17338 /// A visitor for rebuilding a call to an __unknown_any expression 17339 /// to have an appropriate type. 17340 struct RebuildUnknownAnyFunction 17341 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17342 17343 Sema &S; 17344 17345 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17346 17347 ExprResult VisitStmt(Stmt *S) { 17348 llvm_unreachable("unexpected statement!"); 17349 } 17350 17351 ExprResult VisitExpr(Expr *E) { 17352 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17353 << E->getSourceRange(); 17354 return ExprError(); 17355 } 17356 17357 /// Rebuild an expression which simply semantically wraps another 17358 /// expression which it shares the type and value kind of. 17359 template <class T> ExprResult rebuildSugarExpr(T *E) { 17360 ExprResult SubResult = Visit(E->getSubExpr()); 17361 if (SubResult.isInvalid()) return ExprError(); 17362 17363 Expr *SubExpr = SubResult.get(); 17364 E->setSubExpr(SubExpr); 17365 E->setType(SubExpr->getType()); 17366 E->setValueKind(SubExpr->getValueKind()); 17367 assert(E->getObjectKind() == OK_Ordinary); 17368 return E; 17369 } 17370 17371 ExprResult VisitParenExpr(ParenExpr *E) { 17372 return rebuildSugarExpr(E); 17373 } 17374 17375 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17376 return rebuildSugarExpr(E); 17377 } 17378 17379 ExprResult VisitUnaryAddrOf(UnaryOperator *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(S.Context.getPointerType(SubExpr->getType())); 17386 assert(E->getValueKind() == VK_RValue); 17387 assert(E->getObjectKind() == OK_Ordinary); 17388 return E; 17389 } 17390 17391 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17392 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17393 17394 E->setType(VD->getType()); 17395 17396 assert(E->getValueKind() == VK_RValue); 17397 if (S.getLangOpts().CPlusPlus && 17398 !(isa<CXXMethodDecl>(VD) && 17399 cast<CXXMethodDecl>(VD)->isInstance())) 17400 E->setValueKind(VK_LValue); 17401 17402 return E; 17403 } 17404 17405 ExprResult VisitMemberExpr(MemberExpr *E) { 17406 return resolveDecl(E, E->getMemberDecl()); 17407 } 17408 17409 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17410 return resolveDecl(E, E->getDecl()); 17411 } 17412 }; 17413 } 17414 17415 /// Given a function expression of unknown-any type, try to rebuild it 17416 /// to have a function type. 17417 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17418 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17419 if (Result.isInvalid()) return ExprError(); 17420 return S.DefaultFunctionArrayConversion(Result.get()); 17421 } 17422 17423 namespace { 17424 /// A visitor for rebuilding an expression of type __unknown_anytype 17425 /// into one which resolves the type directly on the referring 17426 /// expression. Strict preservation of the original source 17427 /// structure is not a goal. 17428 struct RebuildUnknownAnyExpr 17429 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17430 17431 Sema &S; 17432 17433 /// The current destination type. 17434 QualType DestType; 17435 17436 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17437 : S(S), DestType(CastType) {} 17438 17439 ExprResult VisitStmt(Stmt *S) { 17440 llvm_unreachable("unexpected statement!"); 17441 } 17442 17443 ExprResult VisitExpr(Expr *E) { 17444 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17445 << E->getSourceRange(); 17446 return ExprError(); 17447 } 17448 17449 ExprResult VisitCallExpr(CallExpr *E); 17450 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17451 17452 /// Rebuild an expression which simply semantically wraps another 17453 /// expression which it shares the type and value kind of. 17454 template <class T> ExprResult rebuildSugarExpr(T *E) { 17455 ExprResult SubResult = Visit(E->getSubExpr()); 17456 if (SubResult.isInvalid()) return ExprError(); 17457 Expr *SubExpr = SubResult.get(); 17458 E->setSubExpr(SubExpr); 17459 E->setType(SubExpr->getType()); 17460 E->setValueKind(SubExpr->getValueKind()); 17461 assert(E->getObjectKind() == OK_Ordinary); 17462 return E; 17463 } 17464 17465 ExprResult VisitParenExpr(ParenExpr *E) { 17466 return rebuildSugarExpr(E); 17467 } 17468 17469 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17470 return rebuildSugarExpr(E); 17471 } 17472 17473 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17474 const PointerType *Ptr = DestType->getAs<PointerType>(); 17475 if (!Ptr) { 17476 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17477 << E->getSourceRange(); 17478 return ExprError(); 17479 } 17480 17481 if (isa<CallExpr>(E->getSubExpr())) { 17482 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17483 << E->getSourceRange(); 17484 return ExprError(); 17485 } 17486 17487 assert(E->getValueKind() == VK_RValue); 17488 assert(E->getObjectKind() == OK_Ordinary); 17489 E->setType(DestType); 17490 17491 // Build the sub-expression as if it were an object of the pointee type. 17492 DestType = Ptr->getPointeeType(); 17493 ExprResult SubResult = Visit(E->getSubExpr()); 17494 if (SubResult.isInvalid()) return ExprError(); 17495 E->setSubExpr(SubResult.get()); 17496 return E; 17497 } 17498 17499 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17500 17501 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17502 17503 ExprResult VisitMemberExpr(MemberExpr *E) { 17504 return resolveDecl(E, E->getMemberDecl()); 17505 } 17506 17507 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17508 return resolveDecl(E, E->getDecl()); 17509 } 17510 }; 17511 } 17512 17513 /// Rebuilds a call expression which yielded __unknown_anytype. 17514 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17515 Expr *CalleeExpr = E->getCallee(); 17516 17517 enum FnKind { 17518 FK_MemberFunction, 17519 FK_FunctionPointer, 17520 FK_BlockPointer 17521 }; 17522 17523 FnKind Kind; 17524 QualType CalleeType = CalleeExpr->getType(); 17525 if (CalleeType == S.Context.BoundMemberTy) { 17526 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17527 Kind = FK_MemberFunction; 17528 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17529 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17530 CalleeType = Ptr->getPointeeType(); 17531 Kind = FK_FunctionPointer; 17532 } else { 17533 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17534 Kind = FK_BlockPointer; 17535 } 17536 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17537 17538 // Verify that this is a legal result type of a function. 17539 if (DestType->isArrayType() || DestType->isFunctionType()) { 17540 unsigned diagID = diag::err_func_returning_array_function; 17541 if (Kind == FK_BlockPointer) 17542 diagID = diag::err_block_returning_array_function; 17543 17544 S.Diag(E->getExprLoc(), diagID) 17545 << DestType->isFunctionType() << DestType; 17546 return ExprError(); 17547 } 17548 17549 // Otherwise, go ahead and set DestType as the call's result. 17550 E->setType(DestType.getNonLValueExprType(S.Context)); 17551 E->setValueKind(Expr::getValueKindForType(DestType)); 17552 assert(E->getObjectKind() == OK_Ordinary); 17553 17554 // Rebuild the function type, replacing the result type with DestType. 17555 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17556 if (Proto) { 17557 // __unknown_anytype(...) is a special case used by the debugger when 17558 // it has no idea what a function's signature is. 17559 // 17560 // We want to build this call essentially under the K&R 17561 // unprototyped rules, but making a FunctionNoProtoType in C++ 17562 // would foul up all sorts of assumptions. However, we cannot 17563 // simply pass all arguments as variadic arguments, nor can we 17564 // portably just call the function under a non-variadic type; see 17565 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17566 // However, it turns out that in practice it is generally safe to 17567 // call a function declared as "A foo(B,C,D);" under the prototype 17568 // "A foo(B,C,D,...);". The only known exception is with the 17569 // Windows ABI, where any variadic function is implicitly cdecl 17570 // regardless of its normal CC. Therefore we change the parameter 17571 // types to match the types of the arguments. 17572 // 17573 // This is a hack, but it is far superior to moving the 17574 // corresponding target-specific code from IR-gen to Sema/AST. 17575 17576 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17577 SmallVector<QualType, 8> ArgTypes; 17578 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17579 ArgTypes.reserve(E->getNumArgs()); 17580 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17581 Expr *Arg = E->getArg(i); 17582 QualType ArgType = Arg->getType(); 17583 if (E->isLValue()) { 17584 ArgType = S.Context.getLValueReferenceType(ArgType); 17585 } else if (E->isXValue()) { 17586 ArgType = S.Context.getRValueReferenceType(ArgType); 17587 } 17588 ArgTypes.push_back(ArgType); 17589 } 17590 ParamTypes = ArgTypes; 17591 } 17592 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17593 Proto->getExtProtoInfo()); 17594 } else { 17595 DestType = S.Context.getFunctionNoProtoType(DestType, 17596 FnType->getExtInfo()); 17597 } 17598 17599 // Rebuild the appropriate pointer-to-function type. 17600 switch (Kind) { 17601 case FK_MemberFunction: 17602 // Nothing to do. 17603 break; 17604 17605 case FK_FunctionPointer: 17606 DestType = S.Context.getPointerType(DestType); 17607 break; 17608 17609 case FK_BlockPointer: 17610 DestType = S.Context.getBlockPointerType(DestType); 17611 break; 17612 } 17613 17614 // Finally, we can recurse. 17615 ExprResult CalleeResult = Visit(CalleeExpr); 17616 if (!CalleeResult.isUsable()) return ExprError(); 17617 E->setCallee(CalleeResult.get()); 17618 17619 // Bind a temporary if necessary. 17620 return S.MaybeBindToTemporary(E); 17621 } 17622 17623 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17624 // Verify that this is a legal result type of a call. 17625 if (DestType->isArrayType() || DestType->isFunctionType()) { 17626 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17627 << DestType->isFunctionType() << DestType; 17628 return ExprError(); 17629 } 17630 17631 // Rewrite the method result type if available. 17632 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17633 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17634 Method->setReturnType(DestType); 17635 } 17636 17637 // Change the type of the message. 17638 E->setType(DestType.getNonReferenceType()); 17639 E->setValueKind(Expr::getValueKindForType(DestType)); 17640 17641 return S.MaybeBindToTemporary(E); 17642 } 17643 17644 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17645 // The only case we should ever see here is a function-to-pointer decay. 17646 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17647 assert(E->getValueKind() == VK_RValue); 17648 assert(E->getObjectKind() == OK_Ordinary); 17649 17650 E->setType(DestType); 17651 17652 // Rebuild the sub-expression as the pointee (function) type. 17653 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17654 17655 ExprResult Result = Visit(E->getSubExpr()); 17656 if (!Result.isUsable()) return ExprError(); 17657 17658 E->setSubExpr(Result.get()); 17659 return E; 17660 } else if (E->getCastKind() == CK_LValueToRValue) { 17661 assert(E->getValueKind() == VK_RValue); 17662 assert(E->getObjectKind() == OK_Ordinary); 17663 17664 assert(isa<BlockPointerType>(E->getType())); 17665 17666 E->setType(DestType); 17667 17668 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17669 DestType = S.Context.getLValueReferenceType(DestType); 17670 17671 ExprResult Result = Visit(E->getSubExpr()); 17672 if (!Result.isUsable()) return ExprError(); 17673 17674 E->setSubExpr(Result.get()); 17675 return E; 17676 } else { 17677 llvm_unreachable("Unhandled cast type!"); 17678 } 17679 } 17680 17681 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17682 ExprValueKind ValueKind = VK_LValue; 17683 QualType Type = DestType; 17684 17685 // We know how to make this work for certain kinds of decls: 17686 17687 // - functions 17688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17689 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17690 DestType = Ptr->getPointeeType(); 17691 ExprResult Result = resolveDecl(E, VD); 17692 if (Result.isInvalid()) return ExprError(); 17693 return S.ImpCastExprToType(Result.get(), Type, 17694 CK_FunctionToPointerDecay, VK_RValue); 17695 } 17696 17697 if (!Type->isFunctionType()) { 17698 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17699 << VD << E->getSourceRange(); 17700 return ExprError(); 17701 } 17702 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17703 // We must match the FunctionDecl's type to the hack introduced in 17704 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17705 // type. See the lengthy commentary in that routine. 17706 QualType FDT = FD->getType(); 17707 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17708 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17709 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17710 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17711 SourceLocation Loc = FD->getLocation(); 17712 FunctionDecl *NewFD = FunctionDecl::Create( 17713 S.Context, FD->getDeclContext(), Loc, Loc, 17714 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17715 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17716 /*ConstexprKind*/ CSK_unspecified); 17717 17718 if (FD->getQualifier()) 17719 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17720 17721 SmallVector<ParmVarDecl*, 16> Params; 17722 for (const auto &AI : FT->param_types()) { 17723 ParmVarDecl *Param = 17724 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17725 Param->setScopeInfo(0, Params.size()); 17726 Params.push_back(Param); 17727 } 17728 NewFD->setParams(Params); 17729 DRE->setDecl(NewFD); 17730 VD = DRE->getDecl(); 17731 } 17732 } 17733 17734 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17735 if (MD->isInstance()) { 17736 ValueKind = VK_RValue; 17737 Type = S.Context.BoundMemberTy; 17738 } 17739 17740 // Function references aren't l-values in C. 17741 if (!S.getLangOpts().CPlusPlus) 17742 ValueKind = VK_RValue; 17743 17744 // - variables 17745 } else if (isa<VarDecl>(VD)) { 17746 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17747 Type = RefTy->getPointeeType(); 17748 } else if (Type->isFunctionType()) { 17749 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17750 << VD << E->getSourceRange(); 17751 return ExprError(); 17752 } 17753 17754 // - nothing else 17755 } else { 17756 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17757 << VD << E->getSourceRange(); 17758 return ExprError(); 17759 } 17760 17761 // Modifying the declaration like this is friendly to IR-gen but 17762 // also really dangerous. 17763 VD->setType(DestType); 17764 E->setType(Type); 17765 E->setValueKind(ValueKind); 17766 return E; 17767 } 17768 17769 /// Check a cast of an unknown-any type. We intentionally only 17770 /// trigger this for C-style casts. 17771 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17772 Expr *CastExpr, CastKind &CastKind, 17773 ExprValueKind &VK, CXXCastPath &Path) { 17774 // The type we're casting to must be either void or complete. 17775 if (!CastType->isVoidType() && 17776 RequireCompleteType(TypeRange.getBegin(), CastType, 17777 diag::err_typecheck_cast_to_incomplete)) 17778 return ExprError(); 17779 17780 // Rewrite the casted expression from scratch. 17781 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17782 if (!result.isUsable()) return ExprError(); 17783 17784 CastExpr = result.get(); 17785 VK = CastExpr->getValueKind(); 17786 CastKind = CK_NoOp; 17787 17788 return CastExpr; 17789 } 17790 17791 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17792 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17793 } 17794 17795 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17796 Expr *arg, QualType ¶mType) { 17797 // If the syntactic form of the argument is not an explicit cast of 17798 // any sort, just do default argument promotion. 17799 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17800 if (!castArg) { 17801 ExprResult result = DefaultArgumentPromotion(arg); 17802 if (result.isInvalid()) return ExprError(); 17803 paramType = result.get()->getType(); 17804 return result; 17805 } 17806 17807 // Otherwise, use the type that was written in the explicit cast. 17808 assert(!arg->hasPlaceholderType()); 17809 paramType = castArg->getTypeAsWritten(); 17810 17811 // Copy-initialize a parameter of that type. 17812 InitializedEntity entity = 17813 InitializedEntity::InitializeParameter(Context, paramType, 17814 /*consumed*/ false); 17815 return PerformCopyInitialization(entity, callLoc, arg); 17816 } 17817 17818 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17819 Expr *orig = E; 17820 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17821 while (true) { 17822 E = E->IgnoreParenImpCasts(); 17823 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17824 E = call->getCallee(); 17825 diagID = diag::err_uncasted_call_of_unknown_any; 17826 } else { 17827 break; 17828 } 17829 } 17830 17831 SourceLocation loc; 17832 NamedDecl *d; 17833 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17834 loc = ref->getLocation(); 17835 d = ref->getDecl(); 17836 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17837 loc = mem->getMemberLoc(); 17838 d = mem->getMemberDecl(); 17839 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17840 diagID = diag::err_uncasted_call_of_unknown_any; 17841 loc = msg->getSelectorStartLoc(); 17842 d = msg->getMethodDecl(); 17843 if (!d) { 17844 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17845 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17846 << orig->getSourceRange(); 17847 return ExprError(); 17848 } 17849 } else { 17850 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17851 << E->getSourceRange(); 17852 return ExprError(); 17853 } 17854 17855 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17856 17857 // Never recoverable. 17858 return ExprError(); 17859 } 17860 17861 /// Check for operands with placeholder types and complain if found. 17862 /// Returns ExprError() if there was an error and no recovery was possible. 17863 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17864 if (!getLangOpts().CPlusPlus) { 17865 // C cannot handle TypoExpr nodes on either side of a binop because it 17866 // doesn't handle dependent types properly, so make sure any TypoExprs have 17867 // been dealt with before checking the operands. 17868 ExprResult Result = CorrectDelayedTyposInExpr(E); 17869 if (!Result.isUsable()) return ExprError(); 17870 E = Result.get(); 17871 } 17872 17873 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17874 if (!placeholderType) return E; 17875 17876 switch (placeholderType->getKind()) { 17877 17878 // Overloaded expressions. 17879 case BuiltinType::Overload: { 17880 // Try to resolve a single function template specialization. 17881 // This is obligatory. 17882 ExprResult Result = E; 17883 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17884 return Result; 17885 17886 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17887 // leaves Result unchanged on failure. 17888 Result = E; 17889 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17890 return Result; 17891 17892 // If that failed, try to recover with a call. 17893 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17894 /*complain*/ true); 17895 return Result; 17896 } 17897 17898 // Bound member functions. 17899 case BuiltinType::BoundMember: { 17900 ExprResult result = E; 17901 const Expr *BME = E->IgnoreParens(); 17902 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17903 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17904 if (isa<CXXPseudoDestructorExpr>(BME)) { 17905 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17906 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17907 if (ME->getMemberNameInfo().getName().getNameKind() == 17908 DeclarationName::CXXDestructorName) 17909 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 17910 } 17911 tryToRecoverWithCall(result, PD, 17912 /*complain*/ true); 17913 return result; 17914 } 17915 17916 // ARC unbridged casts. 17917 case BuiltinType::ARCUnbridgedCast: { 17918 Expr *realCast = stripARCUnbridgedCast(E); 17919 diagnoseARCUnbridgedCast(realCast); 17920 return realCast; 17921 } 17922 17923 // Expressions of unknown type. 17924 case BuiltinType::UnknownAny: 17925 return diagnoseUnknownAnyExpr(*this, E); 17926 17927 // Pseudo-objects. 17928 case BuiltinType::PseudoObject: 17929 return checkPseudoObjectRValue(E); 17930 17931 case BuiltinType::BuiltinFn: { 17932 // Accept __noop without parens by implicitly converting it to a call expr. 17933 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 17934 if (DRE) { 17935 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 17936 if (FD->getBuiltinID() == Builtin::BI__noop) { 17937 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 17938 CK_BuiltinFnToFnPtr) 17939 .get(); 17940 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 17941 VK_RValue, SourceLocation()); 17942 } 17943 } 17944 17945 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 17946 return ExprError(); 17947 } 17948 17949 // Expressions of unknown type. 17950 case BuiltinType::OMPArraySection: 17951 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 17952 return ExprError(); 17953 17954 // Everything else should be impossible. 17955 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 17956 case BuiltinType::Id: 17957 #include "clang/Basic/OpenCLImageTypes.def" 17958 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 17959 case BuiltinType::Id: 17960 #include "clang/Basic/OpenCLExtensionTypes.def" 17961 #define SVE_TYPE(Name, Id, SingletonId) \ 17962 case BuiltinType::Id: 17963 #include "clang/Basic/AArch64SVEACLETypes.def" 17964 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 17965 #define PLACEHOLDER_TYPE(Id, SingletonId) 17966 #include "clang/AST/BuiltinTypes.def" 17967 break; 17968 } 17969 17970 llvm_unreachable("invalid placeholder type!"); 17971 } 17972 17973 bool Sema::CheckCaseExpression(Expr *E) { 17974 if (E->isTypeDependent()) 17975 return true; 17976 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 17977 return E->getType()->isIntegralOrEnumerationType(); 17978 return false; 17979 } 17980 17981 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 17982 ExprResult 17983 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 17984 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 17985 "Unknown Objective-C Boolean value!"); 17986 QualType BoolT = Context.ObjCBuiltinBoolTy; 17987 if (!Context.getBOOLDecl()) { 17988 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 17989 Sema::LookupOrdinaryName); 17990 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 17991 NamedDecl *ND = Result.getFoundDecl(); 17992 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 17993 Context.setBOOLDecl(TD); 17994 } 17995 } 17996 if (Context.getBOOLDecl()) 17997 BoolT = Context.getBOOLType(); 17998 return new (Context) 17999 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18000 } 18001 18002 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18003 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18004 SourceLocation RParen) { 18005 18006 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18007 18008 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18009 return Spec.getPlatform() == Platform; 18010 }); 18011 18012 VersionTuple Version; 18013 if (Spec != AvailSpecs.end()) 18014 Version = Spec->getVersion(); 18015 18016 // The use of `@available` in the enclosing function should be analyzed to 18017 // warn when it's used inappropriately (i.e. not if(@available)). 18018 if (getCurFunctionOrMethodDecl()) 18019 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18020 else if (getCurBlock() || getCurLambda()) 18021 getCurFunction()->HasPotentialAvailabilityViolations = true; 18022 18023 return new (Context) 18024 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18025 } 18026