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 /// Retrieve the message suffix that should be added to a 337 /// diagnostic complaining about the given function being deleted or 338 /// unavailable. 339 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 340 std::string Message; 341 if (FD->getAvailability(&Message)) 342 return ": " + Message; 343 344 return std::string(); 345 } 346 347 /// DiagnoseSentinelCalls - This routine checks whether a call or 348 /// message-send is to a declaration with the sentinel attribute, and 349 /// if so, it checks that the requirements of the sentinel are 350 /// satisfied. 351 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 352 ArrayRef<Expr *> Args) { 353 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 354 if (!attr) 355 return; 356 357 // The number of formal parameters of the declaration. 358 unsigned numFormalParams; 359 360 // The kind of declaration. This is also an index into a %select in 361 // the diagnostic. 362 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 363 364 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 365 numFormalParams = MD->param_size(); 366 calleeType = CT_Method; 367 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 368 numFormalParams = FD->param_size(); 369 calleeType = CT_Function; 370 } else if (isa<VarDecl>(D)) { 371 QualType type = cast<ValueDecl>(D)->getType(); 372 const FunctionType *fn = nullptr; 373 if (const PointerType *ptr = type->getAs<PointerType>()) { 374 fn = ptr->getPointeeType()->getAs<FunctionType>(); 375 if (!fn) return; 376 calleeType = CT_Function; 377 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 378 fn = ptr->getPointeeType()->castAs<FunctionType>(); 379 calleeType = CT_Block; 380 } else { 381 return; 382 } 383 384 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 385 numFormalParams = proto->getNumParams(); 386 } else { 387 numFormalParams = 0; 388 } 389 } else { 390 return; 391 } 392 393 // "nullPos" is the number of formal parameters at the end which 394 // effectively count as part of the variadic arguments. This is 395 // useful if you would prefer to not have *any* formal parameters, 396 // but the language forces you to have at least one. 397 unsigned nullPos = attr->getNullPos(); 398 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 399 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 400 401 // The number of arguments which should follow the sentinel. 402 unsigned numArgsAfterSentinel = attr->getSentinel(); 403 404 // If there aren't enough arguments for all the formal parameters, 405 // the sentinel, and the args after the sentinel, complain. 406 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 407 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 408 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 409 return; 410 } 411 412 // Otherwise, find the sentinel expression. 413 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 414 if (!sentinelExpr) return; 415 if (sentinelExpr->isValueDependent()) return; 416 if (Context.isSentinelNullExpr(sentinelExpr)) return; 417 418 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 419 // or 'NULL' if those are actually defined in the context. Only use 420 // 'nil' for ObjC methods, where it's much more likely that the 421 // variadic arguments form a list of object pointers. 422 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 423 std::string NullValue; 424 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 425 NullValue = "nil"; 426 else if (getLangOpts().CPlusPlus11) 427 NullValue = "nullptr"; 428 else if (PP.isMacroDefined("NULL")) 429 NullValue = "NULL"; 430 else 431 NullValue = "(void*) 0"; 432 433 if (MissingNilLoc.isInvalid()) 434 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 435 else 436 Diag(MissingNilLoc, diag::warn_missing_sentinel) 437 << int(calleeType) 438 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 439 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 440 } 441 442 SourceRange Sema::getExprRange(Expr *E) const { 443 return E ? E->getSourceRange() : SourceRange(); 444 } 445 446 //===----------------------------------------------------------------------===// 447 // Standard Promotions and Conversions 448 //===----------------------------------------------------------------------===// 449 450 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 451 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 452 // Handle any placeholder expressions which made it here. 453 if (E->getType()->isPlaceholderType()) { 454 ExprResult result = CheckPlaceholderExpr(E); 455 if (result.isInvalid()) return ExprError(); 456 E = result.get(); 457 } 458 459 QualType Ty = E->getType(); 460 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 461 462 if (Ty->isFunctionType()) { 463 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 464 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 465 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 466 return ExprError(); 467 468 E = ImpCastExprToType(E, Context.getPointerType(Ty), 469 CK_FunctionToPointerDecay).get(); 470 } else if (Ty->isArrayType()) { 471 // In C90 mode, arrays only promote to pointers if the array expression is 472 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 473 // type 'array of type' is converted to an expression that has type 'pointer 474 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 475 // that has type 'array of type' ...". The relevant change is "an lvalue" 476 // (C90) to "an expression" (C99). 477 // 478 // C++ 4.2p1: 479 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 480 // T" can be converted to an rvalue of type "pointer to T". 481 // 482 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 483 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 484 CK_ArrayToPointerDecay).get(); 485 } 486 return E; 487 } 488 489 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 490 // Check to see if we are dereferencing a null pointer. If so, 491 // and if not volatile-qualified, this is undefined behavior that the 492 // optimizer will delete, so warn about it. People sometimes try to use this 493 // to get a deterministic trap and are surprised by clang's behavior. This 494 // only handles the pattern "*null", which is a very syntactic check. 495 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 496 if (UO->getOpcode() == UO_Deref && 497 UO->getSubExpr()->IgnoreParenCasts()-> 498 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 499 !UO->getType().isVolatileQualified()) { 500 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 501 S.PDiag(diag::warn_indirection_through_null) 502 << UO->getSubExpr()->getSourceRange()); 503 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 504 S.PDiag(diag::note_indirection_through_null)); 505 } 506 } 507 508 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 509 SourceLocation AssignLoc, 510 const Expr* RHS) { 511 const ObjCIvarDecl *IV = OIRE->getDecl(); 512 if (!IV) 513 return; 514 515 DeclarationName MemberName = IV->getDeclName(); 516 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 517 if (!Member || !Member->isStr("isa")) 518 return; 519 520 const Expr *Base = OIRE->getBase(); 521 QualType BaseType = Base->getType(); 522 if (OIRE->isArrow()) 523 BaseType = BaseType->getPointeeType(); 524 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 525 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 526 ObjCInterfaceDecl *ClassDeclared = nullptr; 527 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 528 if (!ClassDeclared->getSuperClass() 529 && (*ClassDeclared->ivar_begin()) == IV) { 530 if (RHS) { 531 NamedDecl *ObjectSetClass = 532 S.LookupSingleName(S.TUScope, 533 &S.Context.Idents.get("object_setClass"), 534 SourceLocation(), S.LookupOrdinaryName); 535 if (ObjectSetClass) { 536 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 537 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 538 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 539 "object_setClass(") 540 << FixItHint::CreateReplacement( 541 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 542 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 543 } 544 else 545 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 546 } else { 547 NamedDecl *ObjectGetClass = 548 S.LookupSingleName(S.TUScope, 549 &S.Context.Idents.get("object_getClass"), 550 SourceLocation(), S.LookupOrdinaryName); 551 if (ObjectGetClass) 552 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 553 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 554 "object_getClass(") 555 << FixItHint::CreateReplacement( 556 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 557 else 558 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 559 } 560 S.Diag(IV->getLocation(), diag::note_ivar_decl); 561 } 562 } 563 } 564 565 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 566 // Handle any placeholder expressions which made it here. 567 if (E->getType()->isPlaceholderType()) { 568 ExprResult result = CheckPlaceholderExpr(E); 569 if (result.isInvalid()) return ExprError(); 570 E = result.get(); 571 } 572 573 // C++ [conv.lval]p1: 574 // A glvalue of a non-function, non-array type T can be 575 // converted to a prvalue. 576 if (!E->isGLValue()) return E; 577 578 QualType T = E->getType(); 579 assert(!T.isNull() && "r-value conversion on typeless expression?"); 580 581 // We don't want to throw lvalue-to-rvalue casts on top of 582 // expressions of certain types in C++. 583 if (getLangOpts().CPlusPlus && 584 (E->getType() == Context.OverloadTy || 585 T->isDependentType() || 586 T->isRecordType())) 587 return E; 588 589 // The C standard is actually really unclear on this point, and 590 // DR106 tells us what the result should be but not why. It's 591 // generally best to say that void types just doesn't undergo 592 // lvalue-to-rvalue at all. Note that expressions of unqualified 593 // 'void' type are never l-values, but qualified void can be. 594 if (T->isVoidType()) 595 return E; 596 597 // OpenCL usually rejects direct accesses to values of 'half' type. 598 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 599 T->isHalfType()) { 600 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 601 << 0 << T; 602 return ExprError(); 603 } 604 605 CheckForNullPointerDereference(*this, E); 606 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 607 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 608 &Context.Idents.get("object_getClass"), 609 SourceLocation(), LookupOrdinaryName); 610 if (ObjectGetClass) 611 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 612 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 613 << FixItHint::CreateReplacement( 614 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 615 else 616 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 617 } 618 else if (const ObjCIvarRefExpr *OIRE = 619 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 620 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 621 622 // C++ [conv.lval]p1: 623 // [...] If T is a non-class type, the type of the prvalue is the 624 // cv-unqualified version of T. Otherwise, the type of the 625 // rvalue is T. 626 // 627 // C99 6.3.2.1p2: 628 // If the lvalue has qualified type, the value has the unqualified 629 // version of the type of the lvalue; otherwise, the value has the 630 // type of the lvalue. 631 if (T.hasQualifiers()) 632 T = T.getUnqualifiedType(); 633 634 // Under the MS ABI, lock down the inheritance model now. 635 if (T->isMemberPointerType() && 636 Context.getTargetInfo().getCXXABI().isMicrosoft()) 637 (void)isCompleteType(E->getExprLoc(), T); 638 639 UpdateMarkingForLValueToRValue(E); 640 641 // Loading a __weak object implicitly retains the value, so we need a cleanup to 642 // balance that. 643 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 644 Cleanup.setExprNeedsCleanups(true); 645 646 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 647 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, 926 Name, true, false); 927 if (TrapFn.isInvalid()) 928 return ExprError(); 929 930 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 931 None, E->getEndLoc()); 932 if (Call.isInvalid()) 933 return ExprError(); 934 935 ExprResult Comma = 936 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 937 if (Comma.isInvalid()) 938 return ExprError(); 939 return Comma.get(); 940 } 941 942 if (!getLangOpts().CPlusPlus && 943 RequireCompleteType(E->getExprLoc(), E->getType(), 944 diag::err_call_incomplete_argument)) 945 return ExprError(); 946 947 return E; 948 } 949 950 /// Converts an integer to complex float type. Helper function of 951 /// UsualArithmeticConversions() 952 /// 953 /// \return false if the integer expression is an integer type and is 954 /// successfully converted to the complex type. 955 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 956 ExprResult &ComplexExpr, 957 QualType IntTy, 958 QualType ComplexTy, 959 bool SkipCast) { 960 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 961 if (SkipCast) return false; 962 if (IntTy->isIntegerType()) { 963 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 964 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 965 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 966 CK_FloatingRealToComplex); 967 } else { 968 assert(IntTy->isComplexIntegerType()); 969 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 970 CK_IntegralComplexToFloatingComplex); 971 } 972 return false; 973 } 974 975 /// Handle arithmetic conversion with complex types. Helper function of 976 /// UsualArithmeticConversions() 977 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 978 ExprResult &RHS, QualType LHSType, 979 QualType RHSType, 980 bool IsCompAssign) { 981 // if we have an integer operand, the result is the complex type. 982 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 983 /*skipCast*/false)) 984 return LHSType; 985 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 986 /*skipCast*/IsCompAssign)) 987 return RHSType; 988 989 // This handles complex/complex, complex/float, or float/complex. 990 // When both operands are complex, the shorter operand is converted to the 991 // type of the longer, and that is the type of the result. This corresponds 992 // to what is done when combining two real floating-point operands. 993 // The fun begins when size promotion occur across type domains. 994 // From H&S 6.3.4: When one operand is complex and the other is a real 995 // floating-point type, the less precise type is converted, within it's 996 // real or complex domain, to the precision of the other type. For example, 997 // when combining a "long double" with a "double _Complex", the 998 // "double _Complex" is promoted to "long double _Complex". 999 1000 // Compute the rank of the two types, regardless of whether they are complex. 1001 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1002 1003 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1004 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1005 QualType LHSElementType = 1006 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1007 QualType RHSElementType = 1008 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1009 1010 QualType ResultType = S.Context.getComplexType(LHSElementType); 1011 if (Order < 0) { 1012 // Promote the precision of the LHS if not an assignment. 1013 ResultType = S.Context.getComplexType(RHSElementType); 1014 if (!IsCompAssign) { 1015 if (LHSComplexType) 1016 LHS = 1017 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1018 else 1019 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1020 } 1021 } else if (Order > 0) { 1022 // Promote the precision of the RHS. 1023 if (RHSComplexType) 1024 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1025 else 1026 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1027 } 1028 return ResultType; 1029 } 1030 1031 /// Handle arithmetic conversion from integer to float. Helper function 1032 /// of UsualArithmeticConversions() 1033 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1034 ExprResult &IntExpr, 1035 QualType FloatTy, QualType IntTy, 1036 bool ConvertFloat, bool ConvertInt) { 1037 if (IntTy->isIntegerType()) { 1038 if (ConvertInt) 1039 // Convert intExpr to the lhs floating point type. 1040 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1041 CK_IntegralToFloating); 1042 return FloatTy; 1043 } 1044 1045 // Convert both sides to the appropriate complex float. 1046 assert(IntTy->isComplexIntegerType()); 1047 QualType result = S.Context.getComplexType(FloatTy); 1048 1049 // _Complex int -> _Complex float 1050 if (ConvertInt) 1051 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1052 CK_IntegralComplexToFloatingComplex); 1053 1054 // float -> _Complex float 1055 if (ConvertFloat) 1056 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1057 CK_FloatingRealToComplex); 1058 1059 return result; 1060 } 1061 1062 /// Handle arithmethic conversion with floating point types. Helper 1063 /// function of UsualArithmeticConversions() 1064 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1065 ExprResult &RHS, QualType LHSType, 1066 QualType RHSType, bool IsCompAssign) { 1067 bool LHSFloat = LHSType->isRealFloatingType(); 1068 bool RHSFloat = RHSType->isRealFloatingType(); 1069 1070 // If we have two real floating types, convert the smaller operand 1071 // to the bigger result. 1072 if (LHSFloat && RHSFloat) { 1073 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1074 if (order > 0) { 1075 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1076 return LHSType; 1077 } 1078 1079 assert(order < 0 && "illegal float comparison"); 1080 if (!IsCompAssign) 1081 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1082 return RHSType; 1083 } 1084 1085 if (LHSFloat) { 1086 // Half FP has to be promoted to float unless it is natively supported 1087 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1088 LHSType = S.Context.FloatTy; 1089 1090 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1091 /*convertFloat=*/!IsCompAssign, 1092 /*convertInt=*/ true); 1093 } 1094 assert(RHSFloat); 1095 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1096 /*convertInt=*/ true, 1097 /*convertFloat=*/!IsCompAssign); 1098 } 1099 1100 /// Diagnose attempts to convert between __float128 and long double if 1101 /// there is no support for such conversion. Helper function of 1102 /// UsualArithmeticConversions(). 1103 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1104 QualType RHSType) { 1105 /* No issue converting if at least one of the types is not a floating point 1106 type or the two types have the same rank. 1107 */ 1108 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1109 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1110 return false; 1111 1112 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1113 "The remaining types must be floating point types."); 1114 1115 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1116 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1117 1118 QualType LHSElemType = LHSComplex ? 1119 LHSComplex->getElementType() : LHSType; 1120 QualType RHSElemType = RHSComplex ? 1121 RHSComplex->getElementType() : RHSType; 1122 1123 // No issue if the two types have the same representation 1124 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1125 &S.Context.getFloatTypeSemantics(RHSElemType)) 1126 return false; 1127 1128 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1129 RHSElemType == S.Context.LongDoubleTy); 1130 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1131 RHSElemType == S.Context.Float128Ty); 1132 1133 // We've handled the situation where __float128 and long double have the same 1134 // representation. We allow all conversions for all possible long double types 1135 // except PPC's double double. 1136 return Float128AndLongDouble && 1137 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1138 &llvm::APFloat::PPCDoubleDouble()); 1139 } 1140 1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1142 1143 namespace { 1144 /// These helper callbacks are placed in an anonymous namespace to 1145 /// permit their use as function template parameters. 1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1147 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1148 } 1149 1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1151 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1152 CK_IntegralComplexCast); 1153 } 1154 } 1155 1156 /// Handle integer arithmetic conversions. Helper function of 1157 /// UsualArithmeticConversions() 1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1160 ExprResult &RHS, QualType LHSType, 1161 QualType RHSType, bool IsCompAssign) { 1162 // The rules for this case are in C99 6.3.1.8 1163 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1164 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1165 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1166 if (LHSSigned == RHSSigned) { 1167 // Same signedness; use the higher-ranked type 1168 if (order >= 0) { 1169 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1170 return LHSType; 1171 } else if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1173 return RHSType; 1174 } else if (order != (LHSSigned ? 1 : -1)) { 1175 // The unsigned type has greater than or equal rank to the 1176 // signed type, so use the unsigned type 1177 if (RHSSigned) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1184 // The two types are different widths; if we are here, that 1185 // means the signed type is larger than the unsigned type, so 1186 // use the signed type. 1187 if (LHSSigned) { 1188 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1189 return LHSType; 1190 } else if (!IsCompAssign) 1191 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1192 return RHSType; 1193 } else { 1194 // The signed type is higher-ranked than the unsigned type, 1195 // but isn't actually any bigger (like unsigned int and long 1196 // on most 32-bit systems). Use the unsigned type corresponding 1197 // to the signed type. 1198 QualType result = 1199 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1200 RHS = (*doRHSCast)(S, RHS.get(), result); 1201 if (!IsCompAssign) 1202 LHS = (*doLHSCast)(S, LHS.get(), result); 1203 return result; 1204 } 1205 } 1206 1207 /// Handle conversions with GCC complex int extension. Helper function 1208 /// of UsualArithmeticConversions() 1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1210 ExprResult &RHS, QualType LHSType, 1211 QualType RHSType, 1212 bool IsCompAssign) { 1213 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1214 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1215 1216 if (LHSComplexInt && RHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType RHSEltType = RHSComplexInt->getElementType(); 1219 QualType ScalarType = 1220 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1221 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1222 1223 return S.Context.getComplexType(ScalarType); 1224 } 1225 1226 if (LHSComplexInt) { 1227 QualType LHSEltType = LHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1231 QualType ComplexType = S.Context.getComplexType(ScalarType); 1232 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1233 CK_IntegralRealToComplex); 1234 1235 return ComplexType; 1236 } 1237 1238 assert(RHSComplexInt); 1239 1240 QualType RHSEltType = RHSComplexInt->getElementType(); 1241 QualType ScalarType = 1242 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1243 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1244 QualType ComplexType = S.Context.getComplexType(ScalarType); 1245 1246 if (!IsCompAssign) 1247 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1248 CK_IntegralRealToComplex); 1249 return ComplexType; 1250 } 1251 1252 /// Return the rank of a given fixed point or integer type. The value itself 1253 /// doesn't matter, but the values must be increasing with proper increasing 1254 /// rank as described in N1169 4.1.1. 1255 static unsigned GetFixedPointRank(QualType Ty) { 1256 const auto *BTy = Ty->getAs<BuiltinType>(); 1257 assert(BTy && "Expected a builtin type."); 1258 1259 switch (BTy->getKind()) { 1260 case BuiltinType::ShortFract: 1261 case BuiltinType::UShortFract: 1262 case BuiltinType::SatShortFract: 1263 case BuiltinType::SatUShortFract: 1264 return 1; 1265 case BuiltinType::Fract: 1266 case BuiltinType::UFract: 1267 case BuiltinType::SatFract: 1268 case BuiltinType::SatUFract: 1269 return 2; 1270 case BuiltinType::LongFract: 1271 case BuiltinType::ULongFract: 1272 case BuiltinType::SatLongFract: 1273 case BuiltinType::SatULongFract: 1274 return 3; 1275 case BuiltinType::ShortAccum: 1276 case BuiltinType::UShortAccum: 1277 case BuiltinType::SatShortAccum: 1278 case BuiltinType::SatUShortAccum: 1279 return 4; 1280 case BuiltinType::Accum: 1281 case BuiltinType::UAccum: 1282 case BuiltinType::SatAccum: 1283 case BuiltinType::SatUAccum: 1284 return 5; 1285 case BuiltinType::LongAccum: 1286 case BuiltinType::ULongAccum: 1287 case BuiltinType::SatLongAccum: 1288 case BuiltinType::SatULongAccum: 1289 return 6; 1290 default: 1291 if (BTy->isInteger()) 1292 return 0; 1293 llvm_unreachable("Unexpected fixed point or integer type"); 1294 } 1295 } 1296 1297 /// handleFixedPointConversion - Fixed point operations between fixed 1298 /// point types and integers or other fixed point types do not fall under 1299 /// usual arithmetic conversion since these conversions could result in loss 1300 /// of precsision (N1169 4.1.4). These operations should be calculated with 1301 /// the full precision of their result type (N1169 4.1.6.2.1). 1302 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1303 QualType RHSTy) { 1304 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1305 "Expected at least one of the operands to be a fixed point type"); 1306 assert((LHSTy->isFixedPointOrIntegerType() || 1307 RHSTy->isFixedPointOrIntegerType()) && 1308 "Special fixed point arithmetic operation conversions are only " 1309 "applied to ints or other fixed point types"); 1310 1311 // If one operand has signed fixed-point type and the other operand has 1312 // unsigned fixed-point type, then the unsigned fixed-point operand is 1313 // converted to its corresponding signed fixed-point type and the resulting 1314 // type is the type of the converted operand. 1315 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1316 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1317 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1318 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1319 1320 // The result type is the type with the highest rank, whereby a fixed-point 1321 // conversion rank is always greater than an integer conversion rank; if the 1322 // type of either of the operands is a saturating fixedpoint type, the result 1323 // type shall be the saturating fixed-point type corresponding to the type 1324 // with the highest rank; the resulting value is converted (taking into 1325 // account rounding and overflow) to the precision of the resulting type. 1326 // Same ranks between signed and unsigned types are resolved earlier, so both 1327 // types are either signed or both unsigned at this point. 1328 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1329 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1330 1331 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1332 1333 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1334 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1335 1336 return ResultTy; 1337 } 1338 1339 /// UsualArithmeticConversions - Performs various conversions that are common to 1340 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1341 /// routine returns the first non-arithmetic type found. The client is 1342 /// responsible for emitting appropriate error diagnostics. 1343 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1344 bool IsCompAssign) { 1345 if (!IsCompAssign) { 1346 LHS = UsualUnaryConversions(LHS.get()); 1347 if (LHS.isInvalid()) 1348 return QualType(); 1349 } 1350 1351 RHS = UsualUnaryConversions(RHS.get()); 1352 if (RHS.isInvalid()) 1353 return QualType(); 1354 1355 // For conversion purposes, we ignore any qualifiers. 1356 // For example, "const float" and "float" are equivalent. 1357 QualType LHSType = 1358 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1359 QualType RHSType = 1360 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1361 1362 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1363 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1364 LHSType = AtomicLHS->getValueType(); 1365 1366 // If both types are identical, no conversion is needed. 1367 if (LHSType == RHSType) 1368 return LHSType; 1369 1370 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1371 // The caller can deal with this (e.g. pointer + int). 1372 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1373 return QualType(); 1374 1375 // Apply unary and bitfield promotions to the LHS's type. 1376 QualType LHSUnpromotedType = LHSType; 1377 if (LHSType->isPromotableIntegerType()) 1378 LHSType = Context.getPromotedIntegerType(LHSType); 1379 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1380 if (!LHSBitfieldPromoteTy.isNull()) 1381 LHSType = LHSBitfieldPromoteTy; 1382 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1383 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1384 1385 // If both types are identical, no conversion is needed. 1386 if (LHSType == RHSType) 1387 return LHSType; 1388 1389 // At this point, we have two different arithmetic types. 1390 1391 // Diagnose attempts to convert between __float128 and long double where 1392 // such conversions currently can't be handled. 1393 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1394 return QualType(); 1395 1396 // Handle complex types first (C99 6.3.1.8p1). 1397 if (LHSType->isComplexType() || RHSType->isComplexType()) 1398 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1399 IsCompAssign); 1400 1401 // Now handle "real" floating types (i.e. float, double, long double). 1402 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1403 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1404 IsCompAssign); 1405 1406 // Handle GCC complex int extension. 1407 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1408 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1409 IsCompAssign); 1410 1411 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1412 return handleFixedPointConversion(*this, LHSType, RHSType); 1413 1414 // Finally, we have two differing integer types. 1415 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1416 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1417 } 1418 1419 //===----------------------------------------------------------------------===// 1420 // Semantic Analysis for various Expression Types 1421 //===----------------------------------------------------------------------===// 1422 1423 1424 ExprResult 1425 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1426 SourceLocation DefaultLoc, 1427 SourceLocation RParenLoc, 1428 Expr *ControllingExpr, 1429 ArrayRef<ParsedType> ArgTypes, 1430 ArrayRef<Expr *> ArgExprs) { 1431 unsigned NumAssocs = ArgTypes.size(); 1432 assert(NumAssocs == ArgExprs.size()); 1433 1434 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1435 for (unsigned i = 0; i < NumAssocs; ++i) { 1436 if (ArgTypes[i]) 1437 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1438 else 1439 Types[i] = nullptr; 1440 } 1441 1442 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1443 ControllingExpr, 1444 llvm::makeArrayRef(Types, NumAssocs), 1445 ArgExprs); 1446 delete [] Types; 1447 return ER; 1448 } 1449 1450 ExprResult 1451 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1452 SourceLocation DefaultLoc, 1453 SourceLocation RParenLoc, 1454 Expr *ControllingExpr, 1455 ArrayRef<TypeSourceInfo *> Types, 1456 ArrayRef<Expr *> Exprs) { 1457 unsigned NumAssocs = Types.size(); 1458 assert(NumAssocs == Exprs.size()); 1459 1460 // Decay and strip qualifiers for the controlling expression type, and handle 1461 // placeholder type replacement. See committee discussion from WG14 DR423. 1462 { 1463 EnterExpressionEvaluationContext Unevaluated( 1464 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1465 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1466 if (R.isInvalid()) 1467 return ExprError(); 1468 ControllingExpr = R.get(); 1469 } 1470 1471 // The controlling expression is an unevaluated operand, so side effects are 1472 // likely unintended. 1473 if (!inTemplateInstantiation() && 1474 ControllingExpr->HasSideEffects(Context, false)) 1475 Diag(ControllingExpr->getExprLoc(), 1476 diag::warn_side_effects_unevaluated_context); 1477 1478 bool TypeErrorFound = false, 1479 IsResultDependent = ControllingExpr->isTypeDependent(), 1480 ContainsUnexpandedParameterPack 1481 = ControllingExpr->containsUnexpandedParameterPack(); 1482 1483 for (unsigned i = 0; i < NumAssocs; ++i) { 1484 if (Exprs[i]->containsUnexpandedParameterPack()) 1485 ContainsUnexpandedParameterPack = true; 1486 1487 if (Types[i]) { 1488 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1489 ContainsUnexpandedParameterPack = true; 1490 1491 if (Types[i]->getType()->isDependentType()) { 1492 IsResultDependent = true; 1493 } else { 1494 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1495 // complete object type other than a variably modified type." 1496 unsigned D = 0; 1497 if (Types[i]->getType()->isIncompleteType()) 1498 D = diag::err_assoc_type_incomplete; 1499 else if (!Types[i]->getType()->isObjectType()) 1500 D = diag::err_assoc_type_nonobject; 1501 else if (Types[i]->getType()->isVariablyModifiedType()) 1502 D = diag::err_assoc_type_variably_modified; 1503 1504 if (D != 0) { 1505 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1506 << Types[i]->getTypeLoc().getSourceRange() 1507 << Types[i]->getType(); 1508 TypeErrorFound = true; 1509 } 1510 1511 // C11 6.5.1.1p2 "No two generic associations in the same generic 1512 // selection shall specify compatible types." 1513 for (unsigned j = i+1; j < NumAssocs; ++j) 1514 if (Types[j] && !Types[j]->getType()->isDependentType() && 1515 Context.typesAreCompatible(Types[i]->getType(), 1516 Types[j]->getType())) { 1517 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1518 diag::err_assoc_compatible_types) 1519 << Types[j]->getTypeLoc().getSourceRange() 1520 << Types[j]->getType() 1521 << Types[i]->getType(); 1522 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1523 diag::note_compat_assoc) 1524 << Types[i]->getTypeLoc().getSourceRange() 1525 << Types[i]->getType(); 1526 TypeErrorFound = true; 1527 } 1528 } 1529 } 1530 } 1531 if (TypeErrorFound) 1532 return ExprError(); 1533 1534 // If we determined that the generic selection is result-dependent, don't 1535 // try to compute the result expression. 1536 if (IsResultDependent) 1537 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1538 Exprs, DefaultLoc, RParenLoc, 1539 ContainsUnexpandedParameterPack); 1540 1541 SmallVector<unsigned, 1> CompatIndices; 1542 unsigned DefaultIndex = -1U; 1543 for (unsigned i = 0; i < NumAssocs; ++i) { 1544 if (!Types[i]) 1545 DefaultIndex = i; 1546 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1547 Types[i]->getType())) 1548 CompatIndices.push_back(i); 1549 } 1550 1551 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1552 // type compatible with at most one of the types named in its generic 1553 // association list." 1554 if (CompatIndices.size() > 1) { 1555 // We strip parens here because the controlling expression is typically 1556 // parenthesized in macro definitions. 1557 ControllingExpr = ControllingExpr->IgnoreParens(); 1558 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1559 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1560 << (unsigned)CompatIndices.size(); 1561 for (unsigned I : CompatIndices) { 1562 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1563 diag::note_compat_assoc) 1564 << Types[I]->getTypeLoc().getSourceRange() 1565 << Types[I]->getType(); 1566 } 1567 return ExprError(); 1568 } 1569 1570 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1571 // its controlling expression shall have type compatible with exactly one of 1572 // the types named in its generic association list." 1573 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1574 // We strip parens here because the controlling expression is typically 1575 // parenthesized in macro definitions. 1576 ControllingExpr = ControllingExpr->IgnoreParens(); 1577 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1578 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1579 return ExprError(); 1580 } 1581 1582 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1583 // type name that is compatible with the type of the controlling expression, 1584 // then the result expression of the generic selection is the expression 1585 // in that generic association. Otherwise, the result expression of the 1586 // generic selection is the expression in the default generic association." 1587 unsigned ResultIndex = 1588 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1589 1590 return GenericSelectionExpr::Create( 1591 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1592 ContainsUnexpandedParameterPack, ResultIndex); 1593 } 1594 1595 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1596 /// location of the token and the offset of the ud-suffix within it. 1597 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1598 unsigned Offset) { 1599 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1600 S.getLangOpts()); 1601 } 1602 1603 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1604 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1605 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1606 IdentifierInfo *UDSuffix, 1607 SourceLocation UDSuffixLoc, 1608 ArrayRef<Expr*> Args, 1609 SourceLocation LitEndLoc) { 1610 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1611 1612 QualType ArgTy[2]; 1613 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1614 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1615 if (ArgTy[ArgIdx]->isArrayType()) 1616 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1617 } 1618 1619 DeclarationName OpName = 1620 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1621 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1622 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1623 1624 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1625 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1626 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1627 /*AllowStringTemplate*/ false, 1628 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1629 return ExprError(); 1630 1631 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1632 } 1633 1634 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1635 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1636 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1637 /// multiple tokens. However, the common case is that StringToks points to one 1638 /// string. 1639 /// 1640 ExprResult 1641 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1642 assert(!StringToks.empty() && "Must have at least one string!"); 1643 1644 StringLiteralParser Literal(StringToks, PP); 1645 if (Literal.hadError) 1646 return ExprError(); 1647 1648 SmallVector<SourceLocation, 4> StringTokLocs; 1649 for (const Token &Tok : StringToks) 1650 StringTokLocs.push_back(Tok.getLocation()); 1651 1652 QualType CharTy = Context.CharTy; 1653 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1654 if (Literal.isWide()) { 1655 CharTy = Context.getWideCharType(); 1656 Kind = StringLiteral::Wide; 1657 } else if (Literal.isUTF8()) { 1658 if (getLangOpts().Char8) 1659 CharTy = Context.Char8Ty; 1660 Kind = StringLiteral::UTF8; 1661 } else if (Literal.isUTF16()) { 1662 CharTy = Context.Char16Ty; 1663 Kind = StringLiteral::UTF16; 1664 } else if (Literal.isUTF32()) { 1665 CharTy = Context.Char32Ty; 1666 Kind = StringLiteral::UTF32; 1667 } else if (Literal.isPascal()) { 1668 CharTy = Context.UnsignedCharTy; 1669 } 1670 1671 // Warn on initializing an array of char from a u8 string literal; this 1672 // becomes ill-formed in C++2a. 1673 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1674 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1675 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1676 1677 // Create removals for all 'u8' prefixes in the string literal(s). This 1678 // ensures C++2a compatibility (but may change the program behavior when 1679 // built by non-Clang compilers for which the execution character set is 1680 // not always UTF-8). 1681 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1682 SourceLocation RemovalDiagLoc; 1683 for (const Token &Tok : StringToks) { 1684 if (Tok.getKind() == tok::utf8_string_literal) { 1685 if (RemovalDiagLoc.isInvalid()) 1686 RemovalDiagLoc = Tok.getLocation(); 1687 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1688 Tok.getLocation(), 1689 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1690 getSourceManager(), getLangOpts()))); 1691 } 1692 } 1693 Diag(RemovalDiagLoc, RemovalDiag); 1694 } 1695 1696 1697 QualType CharTyConst = CharTy; 1698 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1699 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1700 CharTyConst.addConst(); 1701 1702 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1703 1704 // Get an array type for the string, according to C99 6.4.5. This includes 1705 // the nul terminator character as well as the string length for pascal 1706 // strings. 1707 QualType StrTy = Context.getConstantArrayType( 1708 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1709 ArrayType::Normal, 0); 1710 1711 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1712 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1713 Kind, Literal.Pascal, StrTy, 1714 &StringTokLocs[0], 1715 StringTokLocs.size()); 1716 if (Literal.getUDSuffix().empty()) 1717 return Lit; 1718 1719 // We're building a user-defined literal. 1720 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1721 SourceLocation UDSuffixLoc = 1722 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1723 Literal.getUDSuffixOffset()); 1724 1725 // Make sure we're allowed user-defined literals here. 1726 if (!UDLScope) 1727 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1728 1729 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1730 // operator "" X (str, len) 1731 QualType SizeType = Context.getSizeType(); 1732 1733 DeclarationName OpName = 1734 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1735 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1736 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1737 1738 QualType ArgTy[] = { 1739 Context.getArrayDecayedType(StrTy), SizeType 1740 }; 1741 1742 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1743 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1744 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1745 /*AllowStringTemplate*/ true, 1746 /*DiagnoseMissing*/ true)) { 1747 1748 case LOLR_Cooked: { 1749 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1750 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1751 StringTokLocs[0]); 1752 Expr *Args[] = { Lit, LenArg }; 1753 1754 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1755 } 1756 1757 case LOLR_StringTemplate: { 1758 TemplateArgumentListInfo ExplicitArgs; 1759 1760 unsigned CharBits = Context.getIntWidth(CharTy); 1761 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1762 llvm::APSInt Value(CharBits, CharIsUnsigned); 1763 1764 TemplateArgument TypeArg(CharTy); 1765 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1766 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1767 1768 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1769 Value = Lit->getCodeUnit(I); 1770 TemplateArgument Arg(Context, Value, CharTy); 1771 TemplateArgumentLocInfo ArgInfo; 1772 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1773 } 1774 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1775 &ExplicitArgs); 1776 } 1777 case LOLR_Raw: 1778 case LOLR_Template: 1779 case LOLR_ErrorNoDiagnostic: 1780 llvm_unreachable("unexpected literal operator lookup result"); 1781 case LOLR_Error: 1782 return ExprError(); 1783 } 1784 llvm_unreachable("unexpected literal operator lookup result"); 1785 } 1786 1787 ExprResult 1788 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1789 SourceLocation Loc, 1790 const CXXScopeSpec *SS) { 1791 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1792 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1793 } 1794 1795 /// BuildDeclRefExpr - Build an expression that references a 1796 /// declaration that does not require a closure capture. 1797 ExprResult 1798 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1799 const DeclarationNameInfo &NameInfo, 1800 const CXXScopeSpec *SS, NamedDecl *FoundD, 1801 const TemplateArgumentListInfo *TemplateArgs) { 1802 bool RefersToCapturedVariable = 1803 isa<VarDecl>(D) && 1804 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1805 1806 DeclRefExpr *E; 1807 if (isa<VarTemplateSpecializationDecl>(D)) { 1808 VarTemplateSpecializationDecl *VarSpec = 1809 cast<VarTemplateSpecializationDecl>(D); 1810 1811 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1812 : NestedNameSpecifierLoc(), 1813 VarSpec->getTemplateKeywordLoc(), D, 1814 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1815 FoundD, TemplateArgs); 1816 } else { 1817 assert(!TemplateArgs && "No template arguments for non-variable" 1818 " template specialization references"); 1819 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1820 : NestedNameSpecifierLoc(), 1821 SourceLocation(), D, RefersToCapturedVariable, 1822 NameInfo, Ty, VK, FoundD); 1823 } 1824 1825 MarkDeclRefReferenced(E); 1826 1827 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1828 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1829 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1830 getCurFunction()->recordUseOfWeak(E); 1831 1832 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1833 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1834 FD = IFD->getAnonField(); 1835 if (FD) { 1836 UnusedPrivateFields.remove(FD); 1837 // Just in case we're building an illegal pointer-to-member. 1838 if (FD->isBitField()) 1839 E->setObjectKind(OK_BitField); 1840 } 1841 1842 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1843 // designates a bit-field. 1844 if (auto *BD = dyn_cast<BindingDecl>(D)) 1845 if (auto *BE = BD->getBinding()) 1846 E->setObjectKind(BE->getObjectKind()); 1847 1848 return E; 1849 } 1850 1851 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1852 /// possibly a list of template arguments. 1853 /// 1854 /// If this produces template arguments, it is permitted to call 1855 /// DecomposeTemplateName. 1856 /// 1857 /// This actually loses a lot of source location information for 1858 /// non-standard name kinds; we should consider preserving that in 1859 /// some way. 1860 void 1861 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1862 TemplateArgumentListInfo &Buffer, 1863 DeclarationNameInfo &NameInfo, 1864 const TemplateArgumentListInfo *&TemplateArgs) { 1865 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1866 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1867 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1868 1869 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1870 Id.TemplateId->NumArgs); 1871 translateTemplateArguments(TemplateArgsPtr, Buffer); 1872 1873 TemplateName TName = Id.TemplateId->Template.get(); 1874 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1875 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1876 TemplateArgs = &Buffer; 1877 } else { 1878 NameInfo = GetNameFromUnqualifiedId(Id); 1879 TemplateArgs = nullptr; 1880 } 1881 } 1882 1883 static void emitEmptyLookupTypoDiagnostic( 1884 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1885 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1886 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1887 DeclContext *Ctx = 1888 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1889 if (!TC) { 1890 // Emit a special diagnostic for failed member lookups. 1891 // FIXME: computing the declaration context might fail here (?) 1892 if (Ctx) 1893 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1894 << SS.getRange(); 1895 else 1896 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1897 return; 1898 } 1899 1900 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1901 bool DroppedSpecifier = 1902 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1903 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1904 ? diag::note_implicit_param_decl 1905 : diag::note_previous_decl; 1906 if (!Ctx) 1907 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1908 SemaRef.PDiag(NoteID)); 1909 else 1910 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1911 << Typo << Ctx << DroppedSpecifier 1912 << SS.getRange(), 1913 SemaRef.PDiag(NoteID)); 1914 } 1915 1916 /// Diagnose an empty lookup. 1917 /// 1918 /// \return false if new lookup candidates were found 1919 bool 1920 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1921 std::unique_ptr<CorrectionCandidateCallback> CCC, 1922 TemplateArgumentListInfo *ExplicitTemplateArgs, 1923 ArrayRef<Expr *> Args, TypoExpr **Out) { 1924 DeclarationName Name = R.getLookupName(); 1925 1926 unsigned diagnostic = diag::err_undeclared_var_use; 1927 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1928 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1929 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1930 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1931 diagnostic = diag::err_undeclared_use; 1932 diagnostic_suggest = diag::err_undeclared_use_suggest; 1933 } 1934 1935 // If the original lookup was an unqualified lookup, fake an 1936 // unqualified lookup. This is useful when (for example) the 1937 // original lookup would not have found something because it was a 1938 // dependent name. 1939 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1940 while (DC) { 1941 if (isa<CXXRecordDecl>(DC)) { 1942 LookupQualifiedName(R, DC); 1943 1944 if (!R.empty()) { 1945 // Don't give errors about ambiguities in this lookup. 1946 R.suppressDiagnostics(); 1947 1948 // During a default argument instantiation the CurContext points 1949 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1950 // function parameter list, hence add an explicit check. 1951 bool isDefaultArgument = 1952 !CodeSynthesisContexts.empty() && 1953 CodeSynthesisContexts.back().Kind == 1954 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1955 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1956 bool isInstance = CurMethod && 1957 CurMethod->isInstance() && 1958 DC == CurMethod->getParent() && !isDefaultArgument; 1959 1960 // Give a code modification hint to insert 'this->'. 1961 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1962 // Actually quite difficult! 1963 if (getLangOpts().MSVCCompat) 1964 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1965 if (isInstance) { 1966 Diag(R.getNameLoc(), diagnostic) << Name 1967 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1968 CheckCXXThisCapture(R.getNameLoc()); 1969 } else { 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 } 1972 1973 // Do we really want to note all of these? 1974 for (NamedDecl *D : R) 1975 Diag(D->getLocation(), diag::note_dependent_var_use); 1976 1977 // Return true if we are inside a default argument instantiation 1978 // and the found name refers to an instance member function, otherwise 1979 // the function calling DiagnoseEmptyLookup will try to create an 1980 // implicit member call and this is wrong for default argument. 1981 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1982 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1983 return true; 1984 } 1985 1986 // Tell the callee to try to recover. 1987 return false; 1988 } 1989 1990 R.clear(); 1991 } 1992 1993 // In Microsoft mode, if we are performing lookup from within a friend 1994 // function definition declared at class scope then we must set 1995 // DC to the lexical parent to be able to search into the parent 1996 // class. 1997 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1998 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1999 DC->getLexicalParent()->isRecord()) 2000 DC = DC->getLexicalParent(); 2001 else 2002 DC = DC->getParent(); 2003 } 2004 2005 // We didn't find anything, so try to correct for a typo. 2006 TypoCorrection Corrected; 2007 if (S && Out) { 2008 SourceLocation TypoLoc = R.getNameLoc(); 2009 assert(!ExplicitTemplateArgs && 2010 "Diagnosing an empty lookup with explicit template args!"); 2011 *Out = CorrectTypoDelayed( 2012 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 2013 [=](const TypoCorrection &TC) { 2014 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2015 diagnostic, diagnostic_suggest); 2016 }, 2017 nullptr, CTK_ErrorRecovery); 2018 if (*Out) 2019 return true; 2020 } else if (S && (Corrected = 2021 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 2022 &SS, std::move(CCC), CTK_ErrorRecovery))) { 2023 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2024 bool DroppedSpecifier = 2025 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2026 R.setLookupName(Corrected.getCorrection()); 2027 2028 bool AcceptableWithRecovery = false; 2029 bool AcceptableWithoutRecovery = false; 2030 NamedDecl *ND = Corrected.getFoundDecl(); 2031 if (ND) { 2032 if (Corrected.isOverloaded()) { 2033 OverloadCandidateSet OCS(R.getNameLoc(), 2034 OverloadCandidateSet::CSK_Normal); 2035 OverloadCandidateSet::iterator Best; 2036 for (NamedDecl *CD : Corrected) { 2037 if (FunctionTemplateDecl *FTD = 2038 dyn_cast<FunctionTemplateDecl>(CD)) 2039 AddTemplateOverloadCandidate( 2040 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2041 Args, OCS); 2042 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2043 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2044 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2045 Args, OCS); 2046 } 2047 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2048 case OR_Success: 2049 ND = Best->FoundDecl; 2050 Corrected.setCorrectionDecl(ND); 2051 break; 2052 default: 2053 // FIXME: Arbitrarily pick the first declaration for the note. 2054 Corrected.setCorrectionDecl(ND); 2055 break; 2056 } 2057 } 2058 R.addDecl(ND); 2059 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2060 CXXRecordDecl *Record = nullptr; 2061 if (Corrected.getCorrectionSpecifier()) { 2062 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2063 Record = Ty->getAsCXXRecordDecl(); 2064 } 2065 if (!Record) 2066 Record = cast<CXXRecordDecl>( 2067 ND->getDeclContext()->getRedeclContext()); 2068 R.setNamingClass(Record); 2069 } 2070 2071 auto *UnderlyingND = ND->getUnderlyingDecl(); 2072 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2073 isa<FunctionTemplateDecl>(UnderlyingND); 2074 // FIXME: If we ended up with a typo for a type name or 2075 // Objective-C class name, we're in trouble because the parser 2076 // is in the wrong place to recover. Suggest the typo 2077 // correction, but don't make it a fix-it since we're not going 2078 // to recover well anyway. 2079 AcceptableWithoutRecovery = 2080 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 2081 } else { 2082 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2083 // because we aren't able to recover. 2084 AcceptableWithoutRecovery = true; 2085 } 2086 2087 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2088 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2089 ? diag::note_implicit_param_decl 2090 : diag::note_previous_decl; 2091 if (SS.isEmpty()) 2092 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2093 PDiag(NoteID), AcceptableWithRecovery); 2094 else 2095 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2096 << Name << computeDeclContext(SS, false) 2097 << DroppedSpecifier << SS.getRange(), 2098 PDiag(NoteID), AcceptableWithRecovery); 2099 2100 // Tell the callee whether to try to recover. 2101 return !AcceptableWithRecovery; 2102 } 2103 } 2104 R.clear(); 2105 2106 // Emit a special diagnostic for failed member lookups. 2107 // FIXME: computing the declaration context might fail here (?) 2108 if (!SS.isEmpty()) { 2109 Diag(R.getNameLoc(), diag::err_no_member) 2110 << Name << computeDeclContext(SS, false) 2111 << SS.getRange(); 2112 return true; 2113 } 2114 2115 // Give up, we can't recover. 2116 Diag(R.getNameLoc(), diagnostic) << Name; 2117 return true; 2118 } 2119 2120 /// In Microsoft mode, if we are inside a template class whose parent class has 2121 /// dependent base classes, and we can't resolve an unqualified identifier, then 2122 /// assume the identifier is a member of a dependent base class. We can only 2123 /// recover successfully in static methods, instance methods, and other contexts 2124 /// where 'this' is available. This doesn't precisely match MSVC's 2125 /// instantiation model, but it's close enough. 2126 static Expr * 2127 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2128 DeclarationNameInfo &NameInfo, 2129 SourceLocation TemplateKWLoc, 2130 const TemplateArgumentListInfo *TemplateArgs) { 2131 // Only try to recover from lookup into dependent bases in static methods or 2132 // contexts where 'this' is available. 2133 QualType ThisType = S.getCurrentThisType(); 2134 const CXXRecordDecl *RD = nullptr; 2135 if (!ThisType.isNull()) 2136 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2137 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2138 RD = MD->getParent(); 2139 if (!RD || !RD->hasAnyDependentBases()) 2140 return nullptr; 2141 2142 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2143 // is available, suggest inserting 'this->' as a fixit. 2144 SourceLocation Loc = NameInfo.getLoc(); 2145 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2146 DB << NameInfo.getName() << RD; 2147 2148 if (!ThisType.isNull()) { 2149 DB << FixItHint::CreateInsertion(Loc, "this->"); 2150 return CXXDependentScopeMemberExpr::Create( 2151 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2152 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2153 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2154 } 2155 2156 // Synthesize a fake NNS that points to the derived class. This will 2157 // perform name lookup during template instantiation. 2158 CXXScopeSpec SS; 2159 auto *NNS = 2160 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2161 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2162 return DependentScopeDeclRefExpr::Create( 2163 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2164 TemplateArgs); 2165 } 2166 2167 ExprResult 2168 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2169 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2170 bool HasTrailingLParen, bool IsAddressOfOperand, 2171 std::unique_ptr<CorrectionCandidateCallback> CCC, 2172 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2173 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2174 "cannot be direct & operand and have a trailing lparen"); 2175 if (SS.isInvalid()) 2176 return ExprError(); 2177 2178 TemplateArgumentListInfo TemplateArgsBuffer; 2179 2180 // Decompose the UnqualifiedId into the following data. 2181 DeclarationNameInfo NameInfo; 2182 const TemplateArgumentListInfo *TemplateArgs; 2183 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2184 2185 DeclarationName Name = NameInfo.getName(); 2186 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2187 SourceLocation NameLoc = NameInfo.getLoc(); 2188 2189 if (II && II->isEditorPlaceholder()) { 2190 // FIXME: When typed placeholders are supported we can create a typed 2191 // placeholder expression node. 2192 return ExprError(); 2193 } 2194 2195 // C++ [temp.dep.expr]p3: 2196 // An id-expression is type-dependent if it contains: 2197 // -- an identifier that was declared with a dependent type, 2198 // (note: handled after lookup) 2199 // -- a template-id that is dependent, 2200 // (note: handled in BuildTemplateIdExpr) 2201 // -- a conversion-function-id that specifies a dependent type, 2202 // -- a nested-name-specifier that contains a class-name that 2203 // names a dependent type. 2204 // Determine whether this is a member of an unknown specialization; 2205 // we need to handle these differently. 2206 bool DependentID = false; 2207 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2208 Name.getCXXNameType()->isDependentType()) { 2209 DependentID = true; 2210 } else if (SS.isSet()) { 2211 if (DeclContext *DC = computeDeclContext(SS, false)) { 2212 if (RequireCompleteDeclContext(SS, DC)) 2213 return ExprError(); 2214 } else { 2215 DependentID = true; 2216 } 2217 } 2218 2219 if (DependentID) 2220 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2221 IsAddressOfOperand, TemplateArgs); 2222 2223 // Perform the required lookup. 2224 LookupResult R(*this, NameInfo, 2225 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2226 ? LookupObjCImplicitSelfParam 2227 : LookupOrdinaryName); 2228 if (TemplateKWLoc.isValid() || TemplateArgs) { 2229 // Lookup the template name again to correctly establish the context in 2230 // which it was found. This is really unfortunate as we already did the 2231 // lookup to determine that it was a template name in the first place. If 2232 // this becomes a performance hit, we can work harder to preserve those 2233 // results until we get here but it's likely not worth it. 2234 bool MemberOfUnknownSpecialization; 2235 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2236 MemberOfUnknownSpecialization, TemplateKWLoc)) 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 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2294 II, SS.isValid() ? SS.getScopeRep() : 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, 2308 CCC ? std::move(CCC) : std::move(DefaultValidator), 2309 nullptr, None, &TE)) { 2310 if (TE && KeywordReplacement) { 2311 auto &State = getTypoExprState(TE); 2312 auto BestTC = State.Consumer->getNextCorrection(); 2313 if (BestTC.isKeyword()) { 2314 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2315 if (State.DiagHandler) 2316 State.DiagHandler(BestTC); 2317 KeywordReplacement->startToken(); 2318 KeywordReplacement->setKind(II->getTokenID()); 2319 KeywordReplacement->setIdentifierInfo(II); 2320 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2321 // Clean up the state associated with the TypoExpr, since it has 2322 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2323 clearDelayedTypo(TE); 2324 // Signal that a correction to a keyword was performed by returning a 2325 // valid-but-null ExprResult. 2326 return (Expr*)nullptr; 2327 } 2328 State.Consumer->resetCorrectionStream(); 2329 } 2330 return TE ? TE : ExprError(); 2331 } 2332 2333 assert(!R.empty() && 2334 "DiagnoseEmptyLookup returned false but added no results"); 2335 2336 // If we found an Objective-C instance variable, let 2337 // LookupInObjCMethod build the appropriate expression to 2338 // reference the ivar. 2339 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2340 R.clear(); 2341 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2342 // In a hopelessly buggy code, Objective-C instance variable 2343 // lookup fails and no expression will be built to reference it. 2344 if (!E.isInvalid() && !E.get()) 2345 return ExprError(); 2346 return E; 2347 } 2348 } 2349 2350 // This is guaranteed from this point on. 2351 assert(!R.empty() || ADL); 2352 2353 // Check whether this might be a C++ implicit instance member access. 2354 // C++ [class.mfct.non-static]p3: 2355 // When an id-expression that is not part of a class member access 2356 // syntax and not used to form a pointer to member is used in the 2357 // body of a non-static member function of class X, if name lookup 2358 // resolves the name in the id-expression to a non-static non-type 2359 // member of some class C, the id-expression is transformed into a 2360 // class member access expression using (*this) as the 2361 // postfix-expression to the left of the . operator. 2362 // 2363 // But we don't actually need to do this for '&' operands if R 2364 // resolved to a function or overloaded function set, because the 2365 // expression is ill-formed if it actually works out to be a 2366 // non-static member function: 2367 // 2368 // C++ [expr.ref]p4: 2369 // Otherwise, if E1.E2 refers to a non-static member function. . . 2370 // [t]he expression can be used only as the left-hand operand of a 2371 // member function call. 2372 // 2373 // There are other safeguards against such uses, but it's important 2374 // to get this right here so that we don't end up making a 2375 // spuriously dependent expression if we're inside a dependent 2376 // instance method. 2377 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2378 bool MightBeImplicitMember; 2379 if (!IsAddressOfOperand) 2380 MightBeImplicitMember = true; 2381 else if (!SS.isEmpty()) 2382 MightBeImplicitMember = false; 2383 else if (R.isOverloadedResult()) 2384 MightBeImplicitMember = false; 2385 else if (R.isUnresolvableResult()) 2386 MightBeImplicitMember = true; 2387 else 2388 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2389 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2390 isa<MSPropertyDecl>(R.getFoundDecl()); 2391 2392 if (MightBeImplicitMember) 2393 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2394 R, TemplateArgs, S); 2395 } 2396 2397 if (TemplateArgs || TemplateKWLoc.isValid()) { 2398 2399 // In C++1y, if this is a variable template id, then check it 2400 // in BuildTemplateIdExpr(). 2401 // The single lookup result must be a variable template declaration. 2402 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2403 Id.TemplateId->Kind == TNK_Var_template) { 2404 assert(R.getAsSingle<VarTemplateDecl>() && 2405 "There should only be one declaration found."); 2406 } 2407 2408 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2409 } 2410 2411 return BuildDeclarationNameExpr(SS, R, ADL); 2412 } 2413 2414 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2415 /// declaration name, generally during template instantiation. 2416 /// There's a large number of things which don't need to be done along 2417 /// this path. 2418 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2419 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2420 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2421 DeclContext *DC = computeDeclContext(SS, false); 2422 if (!DC) 2423 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2424 NameInfo, /*TemplateArgs=*/nullptr); 2425 2426 if (RequireCompleteDeclContext(SS, DC)) 2427 return ExprError(); 2428 2429 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2430 LookupQualifiedName(R, DC); 2431 2432 if (R.isAmbiguous()) 2433 return ExprError(); 2434 2435 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2436 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2437 NameInfo, /*TemplateArgs=*/nullptr); 2438 2439 if (R.empty()) { 2440 Diag(NameInfo.getLoc(), diag::err_no_member) 2441 << NameInfo.getName() << DC << SS.getRange(); 2442 return ExprError(); 2443 } 2444 2445 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2446 // Diagnose a missing typename if this resolved unambiguously to a type in 2447 // a dependent context. If we can recover with a type, downgrade this to 2448 // a warning in Microsoft compatibility mode. 2449 unsigned DiagID = diag::err_typename_missing; 2450 if (RecoveryTSI && getLangOpts().MSVCCompat) 2451 DiagID = diag::ext_typename_missing; 2452 SourceLocation Loc = SS.getBeginLoc(); 2453 auto D = Diag(Loc, DiagID); 2454 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2455 << SourceRange(Loc, NameInfo.getEndLoc()); 2456 2457 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2458 // context. 2459 if (!RecoveryTSI) 2460 return ExprError(); 2461 2462 // Only issue the fixit if we're prepared to recover. 2463 D << FixItHint::CreateInsertion(Loc, "typename "); 2464 2465 // Recover by pretending this was an elaborated type. 2466 QualType Ty = Context.getTypeDeclType(TD); 2467 TypeLocBuilder TLB; 2468 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2469 2470 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2471 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2472 QTL.setElaboratedKeywordLoc(SourceLocation()); 2473 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2474 2475 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2476 2477 return ExprEmpty(); 2478 } 2479 2480 // Defend against this resolving to an implicit member access. We usually 2481 // won't get here if this might be a legitimate a class member (we end up in 2482 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2483 // a pointer-to-member or in an unevaluated context in C++11. 2484 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2485 return BuildPossibleImplicitMemberExpr(SS, 2486 /*TemplateKWLoc=*/SourceLocation(), 2487 R, /*TemplateArgs=*/nullptr, S); 2488 2489 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2490 } 2491 2492 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2493 /// detected that we're currently inside an ObjC method. Perform some 2494 /// additional lookup. 2495 /// 2496 /// Ideally, most of this would be done by lookup, but there's 2497 /// actually quite a lot of extra work involved. 2498 /// 2499 /// Returns a null sentinel to indicate trivial success. 2500 ExprResult 2501 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2502 IdentifierInfo *II, bool AllowBuiltinCreation) { 2503 SourceLocation Loc = Lookup.getNameLoc(); 2504 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2505 2506 // Check for error condition which is already reported. 2507 if (!CurMethod) 2508 return ExprError(); 2509 2510 // There are two cases to handle here. 1) scoped lookup could have failed, 2511 // in which case we should look for an ivar. 2) scoped lookup could have 2512 // found a decl, but that decl is outside the current instance method (i.e. 2513 // a global variable). In these two cases, we do a lookup for an ivar with 2514 // this name, if the lookup sucedes, we replace it our current decl. 2515 2516 // If we're in a class method, we don't normally want to look for 2517 // ivars. But if we don't find anything else, and there's an 2518 // ivar, that's an error. 2519 bool IsClassMethod = CurMethod->isClassMethod(); 2520 2521 bool LookForIvars; 2522 if (Lookup.empty()) 2523 LookForIvars = true; 2524 else if (IsClassMethod) 2525 LookForIvars = false; 2526 else 2527 LookForIvars = (Lookup.isSingleResult() && 2528 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2529 ObjCInterfaceDecl *IFace = nullptr; 2530 if (LookForIvars) { 2531 IFace = CurMethod->getClassInterface(); 2532 ObjCInterfaceDecl *ClassDeclared; 2533 ObjCIvarDecl *IV = nullptr; 2534 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2535 // Diagnose using an ivar in a class method. 2536 if (IsClassMethod) 2537 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2538 << IV->getDeclName()); 2539 2540 // If we're referencing an invalid decl, just return this as a silent 2541 // error node. The error diagnostic was already emitted on the decl. 2542 if (IV->isInvalidDecl()) 2543 return ExprError(); 2544 2545 // Check if referencing a field with __attribute__((deprecated)). 2546 if (DiagnoseUseOfDecl(IV, Loc)) 2547 return ExprError(); 2548 2549 // Diagnose the use of an ivar outside of the declaring class. 2550 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2551 !declaresSameEntity(ClassDeclared, IFace) && 2552 !getLangOpts().DebuggerSupport) 2553 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2554 2555 // FIXME: This should use a new expr for a direct reference, don't 2556 // turn this into Self->ivar, just return a BareIVarExpr or something. 2557 IdentifierInfo &II = Context.Idents.get("self"); 2558 UnqualifiedId SelfName; 2559 SelfName.setIdentifier(&II, SourceLocation()); 2560 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2561 CXXScopeSpec SelfScopeSpec; 2562 SourceLocation TemplateKWLoc; 2563 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2564 SelfName, false, false); 2565 if (SelfExpr.isInvalid()) 2566 return ExprError(); 2567 2568 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2569 if (SelfExpr.isInvalid()) 2570 return ExprError(); 2571 2572 MarkAnyDeclReferenced(Loc, IV, true); 2573 2574 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2575 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2576 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2577 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2578 2579 ObjCIvarRefExpr *Result = new (Context) 2580 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2581 IV->getLocation(), SelfExpr.get(), true, true); 2582 2583 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2584 if (!isUnevaluatedContext() && 2585 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2586 getCurFunction()->recordUseOfWeak(Result); 2587 } 2588 if (getLangOpts().ObjCAutoRefCount) { 2589 if (CurContext->isClosure()) 2590 Diag(Loc, diag::warn_implicitly_retains_self) 2591 << FixItHint::CreateInsertion(Loc, "self->"); 2592 } 2593 2594 return Result; 2595 } 2596 } else if (CurMethod->isInstanceMethod()) { 2597 // We should warn if a local variable hides an ivar. 2598 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2599 ObjCInterfaceDecl *ClassDeclared; 2600 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2601 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2602 declaresSameEntity(IFace, ClassDeclared)) 2603 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2604 } 2605 } 2606 } else if (Lookup.isSingleResult() && 2607 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2608 // If accessing a stand-alone ivar in a class method, this is an error. 2609 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2610 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2611 << IV->getDeclName()); 2612 } 2613 2614 if (Lookup.empty() && II && AllowBuiltinCreation) { 2615 // FIXME. Consolidate this with similar code in LookupName. 2616 if (unsigned BuiltinID = II->getBuiltinID()) { 2617 if (!(getLangOpts().CPlusPlus && 2618 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2619 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2620 S, Lookup.isForRedeclaration(), 2621 Lookup.getNameLoc()); 2622 if (D) Lookup.addDecl(D); 2623 } 2624 } 2625 } 2626 // Sentinel value saying that we didn't do anything special. 2627 return ExprResult((Expr *)nullptr); 2628 } 2629 2630 /// Cast a base object to a member's actual type. 2631 /// 2632 /// Logically this happens in three phases: 2633 /// 2634 /// * First we cast from the base type to the naming class. 2635 /// The naming class is the class into which we were looking 2636 /// when we found the member; it's the qualifier type if a 2637 /// qualifier was provided, and otherwise it's the base type. 2638 /// 2639 /// * Next we cast from the naming class to the declaring class. 2640 /// If the member we found was brought into a class's scope by 2641 /// a using declaration, this is that class; otherwise it's 2642 /// the class declaring the member. 2643 /// 2644 /// * Finally we cast from the declaring class to the "true" 2645 /// declaring class of the member. This conversion does not 2646 /// obey access control. 2647 ExprResult 2648 Sema::PerformObjectMemberConversion(Expr *From, 2649 NestedNameSpecifier *Qualifier, 2650 NamedDecl *FoundDecl, 2651 NamedDecl *Member) { 2652 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2653 if (!RD) 2654 return From; 2655 2656 QualType DestRecordType; 2657 QualType DestType; 2658 QualType FromRecordType; 2659 QualType FromType = From->getType(); 2660 bool PointerConversions = false; 2661 if (isa<FieldDecl>(Member)) { 2662 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2663 auto FromPtrType = FromType->getAs<PointerType>(); 2664 DestRecordType = Context.getAddrSpaceQualType( 2665 DestRecordType, FromPtrType 2666 ? FromType->getPointeeType().getAddressSpace() 2667 : FromType.getAddressSpace()); 2668 2669 if (FromPtrType) { 2670 DestType = Context.getPointerType(DestRecordType); 2671 FromRecordType = FromPtrType->getPointeeType(); 2672 PointerConversions = true; 2673 } else { 2674 DestType = DestRecordType; 2675 FromRecordType = FromType; 2676 } 2677 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2678 if (Method->isStatic()) 2679 return From; 2680 2681 DestType = Method->getThisType(); 2682 DestRecordType = DestType->getPointeeType(); 2683 2684 if (FromType->getAs<PointerType>()) { 2685 FromRecordType = FromType->getPointeeType(); 2686 PointerConversions = true; 2687 } else { 2688 FromRecordType = FromType; 2689 DestType = DestRecordType; 2690 } 2691 } else { 2692 // No conversion necessary. 2693 return From; 2694 } 2695 2696 if (DestType->isDependentType() || FromType->isDependentType()) 2697 return From; 2698 2699 // If the unqualified types are the same, no conversion is necessary. 2700 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2701 return From; 2702 2703 SourceRange FromRange = From->getSourceRange(); 2704 SourceLocation FromLoc = FromRange.getBegin(); 2705 2706 ExprValueKind VK = From->getValueKind(); 2707 2708 // C++ [class.member.lookup]p8: 2709 // [...] Ambiguities can often be resolved by qualifying a name with its 2710 // class name. 2711 // 2712 // If the member was a qualified name and the qualified referred to a 2713 // specific base subobject type, we'll cast to that intermediate type 2714 // first and then to the object in which the member is declared. That allows 2715 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2716 // 2717 // class Base { public: int x; }; 2718 // class Derived1 : public Base { }; 2719 // class Derived2 : public Base { }; 2720 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2721 // 2722 // void VeryDerived::f() { 2723 // x = 17; // error: ambiguous base subobjects 2724 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2725 // } 2726 if (Qualifier && Qualifier->getAsType()) { 2727 QualType QType = QualType(Qualifier->getAsType(), 0); 2728 assert(QType->isRecordType() && "lookup done with non-record type"); 2729 2730 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2731 2732 // In C++98, the qualifier type doesn't actually have to be a base 2733 // type of the object type, in which case we just ignore it. 2734 // Otherwise build the appropriate casts. 2735 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2736 CXXCastPath BasePath; 2737 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2738 FromLoc, FromRange, &BasePath)) 2739 return ExprError(); 2740 2741 if (PointerConversions) 2742 QType = Context.getPointerType(QType); 2743 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2744 VK, &BasePath).get(); 2745 2746 FromType = QType; 2747 FromRecordType = QRecordType; 2748 2749 // If the qualifier type was the same as the destination type, 2750 // we're done. 2751 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2752 return From; 2753 } 2754 } 2755 2756 bool IgnoreAccess = false; 2757 2758 // If we actually found the member through a using declaration, cast 2759 // down to the using declaration's type. 2760 // 2761 // Pointer equality is fine here because only one declaration of a 2762 // class ever has member declarations. 2763 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2764 assert(isa<UsingShadowDecl>(FoundDecl)); 2765 QualType URecordType = Context.getTypeDeclType( 2766 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2767 2768 // We only need to do this if the naming-class to declaring-class 2769 // conversion is non-trivial. 2770 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2771 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2772 CXXCastPath BasePath; 2773 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2774 FromLoc, FromRange, &BasePath)) 2775 return ExprError(); 2776 2777 QualType UType = URecordType; 2778 if (PointerConversions) 2779 UType = Context.getPointerType(UType); 2780 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2781 VK, &BasePath).get(); 2782 FromType = UType; 2783 FromRecordType = URecordType; 2784 } 2785 2786 // We don't do access control for the conversion from the 2787 // declaring class to the true declaring class. 2788 IgnoreAccess = true; 2789 } 2790 2791 CXXCastPath BasePath; 2792 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2793 FromLoc, FromRange, &BasePath, 2794 IgnoreAccess)) 2795 return ExprError(); 2796 2797 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2798 VK, &BasePath); 2799 } 2800 2801 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2802 const LookupResult &R, 2803 bool HasTrailingLParen) { 2804 // Only when used directly as the postfix-expression of a call. 2805 if (!HasTrailingLParen) 2806 return false; 2807 2808 // Never if a scope specifier was provided. 2809 if (SS.isSet()) 2810 return false; 2811 2812 // Only in C++ or ObjC++. 2813 if (!getLangOpts().CPlusPlus) 2814 return false; 2815 2816 // Turn off ADL when we find certain kinds of declarations during 2817 // normal lookup: 2818 for (NamedDecl *D : R) { 2819 // C++0x [basic.lookup.argdep]p3: 2820 // -- a declaration of a class member 2821 // Since using decls preserve this property, we check this on the 2822 // original decl. 2823 if (D->isCXXClassMember()) 2824 return false; 2825 2826 // C++0x [basic.lookup.argdep]p3: 2827 // -- a block-scope function declaration that is not a 2828 // using-declaration 2829 // NOTE: we also trigger this for function templates (in fact, we 2830 // don't check the decl type at all, since all other decl types 2831 // turn off ADL anyway). 2832 if (isa<UsingShadowDecl>(D)) 2833 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2834 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2835 return false; 2836 2837 // C++0x [basic.lookup.argdep]p3: 2838 // -- a declaration that is neither a function or a function 2839 // template 2840 // And also for builtin functions. 2841 if (isa<FunctionDecl>(D)) { 2842 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2843 2844 // But also builtin functions. 2845 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2846 return false; 2847 } else if (!isa<FunctionTemplateDecl>(D)) 2848 return false; 2849 } 2850 2851 return true; 2852 } 2853 2854 2855 /// Diagnoses obvious problems with the use of the given declaration 2856 /// as an expression. This is only actually called for lookups that 2857 /// were not overloaded, and it doesn't promise that the declaration 2858 /// will in fact be used. 2859 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2860 if (D->isInvalidDecl()) 2861 return true; 2862 2863 if (isa<TypedefNameDecl>(D)) { 2864 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2865 return true; 2866 } 2867 2868 if (isa<ObjCInterfaceDecl>(D)) { 2869 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2870 return true; 2871 } 2872 2873 if (isa<NamespaceDecl>(D)) { 2874 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2875 return true; 2876 } 2877 2878 return false; 2879 } 2880 2881 // Certain multiversion types should be treated as overloaded even when there is 2882 // only one result. 2883 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2884 assert(R.isSingleResult() && "Expected only a single result"); 2885 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2886 return FD && 2887 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2888 } 2889 2890 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2891 LookupResult &R, bool NeedsADL, 2892 bool AcceptInvalidDecl) { 2893 // If this is a single, fully-resolved result and we don't need ADL, 2894 // just build an ordinary singleton decl ref. 2895 if (!NeedsADL && R.isSingleResult() && 2896 !R.getAsSingle<FunctionTemplateDecl>() && 2897 !ShouldLookupResultBeMultiVersionOverload(R)) 2898 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2899 R.getRepresentativeDecl(), nullptr, 2900 AcceptInvalidDecl); 2901 2902 // We only need to check the declaration if there's exactly one 2903 // result, because in the overloaded case the results can only be 2904 // functions and function templates. 2905 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2906 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2907 return ExprError(); 2908 2909 // Otherwise, just build an unresolved lookup expression. Suppress 2910 // any lookup-related diagnostics; we'll hash these out later, when 2911 // we've picked a target. 2912 R.suppressDiagnostics(); 2913 2914 UnresolvedLookupExpr *ULE 2915 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2916 SS.getWithLocInContext(Context), 2917 R.getLookupNameInfo(), 2918 NeedsADL, R.isOverloadedResult(), 2919 R.begin(), R.end()); 2920 2921 return ULE; 2922 } 2923 2924 static void 2925 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2926 ValueDecl *var, DeclContext *DC); 2927 2928 /// Complete semantic analysis for a reference to the given declaration. 2929 ExprResult Sema::BuildDeclarationNameExpr( 2930 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2931 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2932 bool AcceptInvalidDecl) { 2933 assert(D && "Cannot refer to a NULL declaration"); 2934 assert(!isa<FunctionTemplateDecl>(D) && 2935 "Cannot refer unambiguously to a function template"); 2936 2937 SourceLocation Loc = NameInfo.getLoc(); 2938 if (CheckDeclInExpr(*this, Loc, D)) 2939 return ExprError(); 2940 2941 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2942 // Specifically diagnose references to class templates that are missing 2943 // a template argument list. 2944 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2945 return ExprError(); 2946 } 2947 2948 // Make sure that we're referring to a value. 2949 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2950 if (!VD) { 2951 Diag(Loc, diag::err_ref_non_value) 2952 << D << SS.getRange(); 2953 Diag(D->getLocation(), diag::note_declared_at); 2954 return ExprError(); 2955 } 2956 2957 // Check whether this declaration can be used. Note that we suppress 2958 // this check when we're going to perform argument-dependent lookup 2959 // on this function name, because this might not be the function 2960 // that overload resolution actually selects. 2961 if (DiagnoseUseOfDecl(VD, Loc)) 2962 return ExprError(); 2963 2964 // Only create DeclRefExpr's for valid Decl's. 2965 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2966 return ExprError(); 2967 2968 // Handle members of anonymous structs and unions. If we got here, 2969 // and the reference is to a class member indirect field, then this 2970 // must be the subject of a pointer-to-member expression. 2971 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2972 if (!indirectField->isCXXClassMember()) 2973 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2974 indirectField); 2975 2976 { 2977 QualType type = VD->getType(); 2978 if (type.isNull()) 2979 return ExprError(); 2980 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2981 // C++ [except.spec]p17: 2982 // An exception-specification is considered to be needed when: 2983 // - in an expression, the function is the unique lookup result or 2984 // the selected member of a set of overloaded functions. 2985 ResolveExceptionSpec(Loc, FPT); 2986 type = VD->getType(); 2987 } 2988 ExprValueKind valueKind = VK_RValue; 2989 2990 switch (D->getKind()) { 2991 // Ignore all the non-ValueDecl kinds. 2992 #define ABSTRACT_DECL(kind) 2993 #define VALUE(type, base) 2994 #define DECL(type, base) \ 2995 case Decl::type: 2996 #include "clang/AST/DeclNodes.inc" 2997 llvm_unreachable("invalid value decl kind"); 2998 2999 // These shouldn't make it here. 3000 case Decl::ObjCAtDefsField: 3001 llvm_unreachable("forming non-member reference to ivar?"); 3002 3003 // Enum constants are always r-values and never references. 3004 // Unresolved using declarations are dependent. 3005 case Decl::EnumConstant: 3006 case Decl::UnresolvedUsingValue: 3007 case Decl::OMPDeclareReduction: 3008 case Decl::OMPDeclareMapper: 3009 valueKind = VK_RValue; 3010 break; 3011 3012 // Fields and indirect fields that got here must be for 3013 // pointer-to-member expressions; we just call them l-values for 3014 // internal consistency, because this subexpression doesn't really 3015 // exist in the high-level semantics. 3016 case Decl::Field: 3017 case Decl::IndirectField: 3018 case Decl::ObjCIvar: 3019 assert(getLangOpts().CPlusPlus && 3020 "building reference to field in C?"); 3021 3022 // These can't have reference type in well-formed programs, but 3023 // for internal consistency we do this anyway. 3024 type = type.getNonReferenceType(); 3025 valueKind = VK_LValue; 3026 break; 3027 3028 // Non-type template parameters are either l-values or r-values 3029 // depending on the type. 3030 case Decl::NonTypeTemplateParm: { 3031 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3032 type = reftype->getPointeeType(); 3033 valueKind = VK_LValue; // even if the parameter is an r-value reference 3034 break; 3035 } 3036 3037 // For non-references, we need to strip qualifiers just in case 3038 // the template parameter was declared as 'const int' or whatever. 3039 valueKind = VK_RValue; 3040 type = type.getUnqualifiedType(); 3041 break; 3042 } 3043 3044 case Decl::Var: 3045 case Decl::VarTemplateSpecialization: 3046 case Decl::VarTemplatePartialSpecialization: 3047 case Decl::Decomposition: 3048 case Decl::OMPCapturedExpr: 3049 // In C, "extern void blah;" is valid and is an r-value. 3050 if (!getLangOpts().CPlusPlus && 3051 !type.hasQualifiers() && 3052 type->isVoidType()) { 3053 valueKind = VK_RValue; 3054 break; 3055 } 3056 LLVM_FALLTHROUGH; 3057 3058 case Decl::ImplicitParam: 3059 case Decl::ParmVar: { 3060 // These are always l-values. 3061 valueKind = VK_LValue; 3062 type = type.getNonReferenceType(); 3063 3064 // FIXME: Does the addition of const really only apply in 3065 // potentially-evaluated contexts? Since the variable isn't actually 3066 // captured in an unevaluated context, it seems that the answer is no. 3067 if (!isUnevaluatedContext()) { 3068 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3069 if (!CapturedType.isNull()) 3070 type = CapturedType; 3071 } 3072 3073 break; 3074 } 3075 3076 case Decl::Binding: { 3077 // These are always lvalues. 3078 valueKind = VK_LValue; 3079 type = type.getNonReferenceType(); 3080 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3081 // decides how that's supposed to work. 3082 auto *BD = cast<BindingDecl>(VD); 3083 if (BD->getDeclContext()->isFunctionOrMethod() && 3084 BD->getDeclContext() != CurContext) 3085 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3086 break; 3087 } 3088 3089 case Decl::Function: { 3090 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3091 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3092 type = Context.BuiltinFnTy; 3093 valueKind = VK_RValue; 3094 break; 3095 } 3096 } 3097 3098 const FunctionType *fty = type->castAs<FunctionType>(); 3099 3100 // If we're referring to a function with an __unknown_anytype 3101 // result type, make the entire expression __unknown_anytype. 3102 if (fty->getReturnType() == Context.UnknownAnyTy) { 3103 type = Context.UnknownAnyTy; 3104 valueKind = VK_RValue; 3105 break; 3106 } 3107 3108 // Functions are l-values in C++. 3109 if (getLangOpts().CPlusPlus) { 3110 valueKind = VK_LValue; 3111 break; 3112 } 3113 3114 // C99 DR 316 says that, if a function type comes from a 3115 // function definition (without a prototype), that type is only 3116 // used for checking compatibility. Therefore, when referencing 3117 // the function, we pretend that we don't have the full function 3118 // type. 3119 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3120 isa<FunctionProtoType>(fty)) 3121 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3122 fty->getExtInfo()); 3123 3124 // Functions are r-values in C. 3125 valueKind = VK_RValue; 3126 break; 3127 } 3128 3129 case Decl::CXXDeductionGuide: 3130 llvm_unreachable("building reference to deduction guide"); 3131 3132 case Decl::MSProperty: 3133 valueKind = VK_LValue; 3134 break; 3135 3136 case Decl::CXXMethod: 3137 // If we're referring to a method with an __unknown_anytype 3138 // result type, make the entire expression __unknown_anytype. 3139 // This should only be possible with a type written directly. 3140 if (const FunctionProtoType *proto 3141 = dyn_cast<FunctionProtoType>(VD->getType())) 3142 if (proto->getReturnType() == Context.UnknownAnyTy) { 3143 type = Context.UnknownAnyTy; 3144 valueKind = VK_RValue; 3145 break; 3146 } 3147 3148 // C++ methods are l-values if static, r-values if non-static. 3149 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3150 valueKind = VK_LValue; 3151 break; 3152 } 3153 LLVM_FALLTHROUGH; 3154 3155 case Decl::CXXConversion: 3156 case Decl::CXXDestructor: 3157 case Decl::CXXConstructor: 3158 valueKind = VK_RValue; 3159 break; 3160 } 3161 3162 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3163 TemplateArgs); 3164 } 3165 } 3166 3167 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3168 SmallString<32> &Target) { 3169 Target.resize(CharByteWidth * (Source.size() + 1)); 3170 char *ResultPtr = &Target[0]; 3171 const llvm::UTF8 *ErrorPtr; 3172 bool success = 3173 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3174 (void)success; 3175 assert(success); 3176 Target.resize(ResultPtr - &Target[0]); 3177 } 3178 3179 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3180 PredefinedExpr::IdentKind IK) { 3181 // Pick the current block, lambda, captured statement or function. 3182 Decl *currentDecl = nullptr; 3183 if (const BlockScopeInfo *BSI = getCurBlock()) 3184 currentDecl = BSI->TheDecl; 3185 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3186 currentDecl = LSI->CallOperator; 3187 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3188 currentDecl = CSI->TheCapturedDecl; 3189 else 3190 currentDecl = getCurFunctionOrMethodDecl(); 3191 3192 if (!currentDecl) { 3193 Diag(Loc, diag::ext_predef_outside_function); 3194 currentDecl = Context.getTranslationUnitDecl(); 3195 } 3196 3197 QualType ResTy; 3198 StringLiteral *SL = nullptr; 3199 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3200 ResTy = Context.DependentTy; 3201 else { 3202 // Pre-defined identifiers are of type char[x], where x is the length of 3203 // the string. 3204 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3205 unsigned Length = Str.length(); 3206 3207 llvm::APInt LengthI(32, Length + 1); 3208 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3209 ResTy = 3210 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3211 SmallString<32> RawChars; 3212 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3213 Str, RawChars); 3214 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3215 /*IndexTypeQuals*/ 0); 3216 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3217 /*Pascal*/ false, ResTy, Loc); 3218 } else { 3219 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3220 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3221 /*IndexTypeQuals*/ 0); 3222 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3223 /*Pascal*/ false, ResTy, Loc); 3224 } 3225 } 3226 3227 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3228 } 3229 3230 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3231 PredefinedExpr::IdentKind IK; 3232 3233 switch (Kind) { 3234 default: llvm_unreachable("Unknown simple primary expr!"); 3235 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3236 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3237 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3238 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3239 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3240 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3241 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3242 } 3243 3244 return BuildPredefinedExpr(Loc, IK); 3245 } 3246 3247 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3248 SmallString<16> CharBuffer; 3249 bool Invalid = false; 3250 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3251 if (Invalid) 3252 return ExprError(); 3253 3254 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3255 PP, Tok.getKind()); 3256 if (Literal.hadError()) 3257 return ExprError(); 3258 3259 QualType Ty; 3260 if (Literal.isWide()) 3261 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3262 else if (Literal.isUTF8() && getLangOpts().Char8) 3263 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3264 else if (Literal.isUTF16()) 3265 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3266 else if (Literal.isUTF32()) 3267 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3268 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3269 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3270 else 3271 Ty = Context.CharTy; // 'x' -> char in C++ 3272 3273 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3274 if (Literal.isWide()) 3275 Kind = CharacterLiteral::Wide; 3276 else if (Literal.isUTF16()) 3277 Kind = CharacterLiteral::UTF16; 3278 else if (Literal.isUTF32()) 3279 Kind = CharacterLiteral::UTF32; 3280 else if (Literal.isUTF8()) 3281 Kind = CharacterLiteral::UTF8; 3282 3283 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3284 Tok.getLocation()); 3285 3286 if (Literal.getUDSuffix().empty()) 3287 return Lit; 3288 3289 // We're building a user-defined literal. 3290 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3291 SourceLocation UDSuffixLoc = 3292 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3293 3294 // Make sure we're allowed user-defined literals here. 3295 if (!UDLScope) 3296 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3297 3298 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3299 // operator "" X (ch) 3300 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3301 Lit, Tok.getLocation()); 3302 } 3303 3304 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3305 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3306 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3307 Context.IntTy, Loc); 3308 } 3309 3310 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3311 QualType Ty, SourceLocation Loc) { 3312 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3313 3314 using llvm::APFloat; 3315 APFloat Val(Format); 3316 3317 APFloat::opStatus result = Literal.GetFloatValue(Val); 3318 3319 // Overflow is always an error, but underflow is only an error if 3320 // we underflowed to zero (APFloat reports denormals as underflow). 3321 if ((result & APFloat::opOverflow) || 3322 ((result & APFloat::opUnderflow) && Val.isZero())) { 3323 unsigned diagnostic; 3324 SmallString<20> buffer; 3325 if (result & APFloat::opOverflow) { 3326 diagnostic = diag::warn_float_overflow; 3327 APFloat::getLargest(Format).toString(buffer); 3328 } else { 3329 diagnostic = diag::warn_float_underflow; 3330 APFloat::getSmallest(Format).toString(buffer); 3331 } 3332 3333 S.Diag(Loc, diagnostic) 3334 << Ty 3335 << StringRef(buffer.data(), buffer.size()); 3336 } 3337 3338 bool isExact = (result == APFloat::opOK); 3339 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3340 } 3341 3342 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3343 assert(E && "Invalid expression"); 3344 3345 if (E->isValueDependent()) 3346 return false; 3347 3348 QualType QT = E->getType(); 3349 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3350 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3351 return true; 3352 } 3353 3354 llvm::APSInt ValueAPS; 3355 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3356 3357 if (R.isInvalid()) 3358 return true; 3359 3360 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3361 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3362 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3363 << ValueAPS.toString(10) << ValueIsPositive; 3364 return true; 3365 } 3366 3367 return false; 3368 } 3369 3370 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3371 // Fast path for a single digit (which is quite common). A single digit 3372 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3373 if (Tok.getLength() == 1) { 3374 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3375 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3376 } 3377 3378 SmallString<128> SpellingBuffer; 3379 // NumericLiteralParser wants to overread by one character. Add padding to 3380 // the buffer in case the token is copied to the buffer. If getSpelling() 3381 // returns a StringRef to the memory buffer, it should have a null char at 3382 // the EOF, so it is also safe. 3383 SpellingBuffer.resize(Tok.getLength() + 1); 3384 3385 // Get the spelling of the token, which eliminates trigraphs, etc. 3386 bool Invalid = false; 3387 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3388 if (Invalid) 3389 return ExprError(); 3390 3391 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3392 if (Literal.hadError) 3393 return ExprError(); 3394 3395 if (Literal.hasUDSuffix()) { 3396 // We're building a user-defined literal. 3397 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3398 SourceLocation UDSuffixLoc = 3399 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3400 3401 // Make sure we're allowed user-defined literals here. 3402 if (!UDLScope) 3403 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3404 3405 QualType CookedTy; 3406 if (Literal.isFloatingLiteral()) { 3407 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3408 // long double, the literal is treated as a call of the form 3409 // operator "" X (f L) 3410 CookedTy = Context.LongDoubleTy; 3411 } else { 3412 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3413 // unsigned long long, the literal is treated as a call of the form 3414 // operator "" X (n ULL) 3415 CookedTy = Context.UnsignedLongLongTy; 3416 } 3417 3418 DeclarationName OpName = 3419 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3420 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3421 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3422 3423 SourceLocation TokLoc = Tok.getLocation(); 3424 3425 // Perform literal operator lookup to determine if we're building a raw 3426 // literal or a cooked one. 3427 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3428 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3429 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3430 /*AllowStringTemplate*/ false, 3431 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3432 case LOLR_ErrorNoDiagnostic: 3433 // Lookup failure for imaginary constants isn't fatal, there's still the 3434 // GNU extension producing _Complex types. 3435 break; 3436 case LOLR_Error: 3437 return ExprError(); 3438 case LOLR_Cooked: { 3439 Expr *Lit; 3440 if (Literal.isFloatingLiteral()) { 3441 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3442 } else { 3443 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3444 if (Literal.GetIntegerValue(ResultVal)) 3445 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3446 << /* Unsigned */ 1; 3447 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3448 Tok.getLocation()); 3449 } 3450 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3451 } 3452 3453 case LOLR_Raw: { 3454 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3455 // literal is treated as a call of the form 3456 // operator "" X ("n") 3457 unsigned Length = Literal.getUDSuffixOffset(); 3458 QualType StrTy = Context.getConstantArrayType( 3459 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3460 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3461 Expr *Lit = StringLiteral::Create( 3462 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3463 /*Pascal*/false, StrTy, &TokLoc, 1); 3464 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3465 } 3466 3467 case LOLR_Template: { 3468 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3469 // template), L is treated as a call fo the form 3470 // operator "" X <'c1', 'c2', ... 'ck'>() 3471 // where n is the source character sequence c1 c2 ... ck. 3472 TemplateArgumentListInfo ExplicitArgs; 3473 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3474 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3475 llvm::APSInt Value(CharBits, CharIsUnsigned); 3476 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3477 Value = TokSpelling[I]; 3478 TemplateArgument Arg(Context, Value, Context.CharTy); 3479 TemplateArgumentLocInfo ArgInfo; 3480 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3481 } 3482 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3483 &ExplicitArgs); 3484 } 3485 case LOLR_StringTemplate: 3486 llvm_unreachable("unexpected literal operator lookup result"); 3487 } 3488 } 3489 3490 Expr *Res; 3491 3492 if (Literal.isFixedPointLiteral()) { 3493 QualType Ty; 3494 3495 if (Literal.isAccum) { 3496 if (Literal.isHalf) { 3497 Ty = Context.ShortAccumTy; 3498 } else if (Literal.isLong) { 3499 Ty = Context.LongAccumTy; 3500 } else { 3501 Ty = Context.AccumTy; 3502 } 3503 } else if (Literal.isFract) { 3504 if (Literal.isHalf) { 3505 Ty = Context.ShortFractTy; 3506 } else if (Literal.isLong) { 3507 Ty = Context.LongFractTy; 3508 } else { 3509 Ty = Context.FractTy; 3510 } 3511 } 3512 3513 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3514 3515 bool isSigned = !Literal.isUnsigned; 3516 unsigned scale = Context.getFixedPointScale(Ty); 3517 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3518 3519 llvm::APInt Val(bit_width, 0, isSigned); 3520 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3521 bool ValIsZero = Val.isNullValue() && !Overflowed; 3522 3523 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3524 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3525 // Clause 6.4.4 - The value of a constant shall be in the range of 3526 // representable values for its type, with exception for constants of a 3527 // fract type with a value of exactly 1; such a constant shall denote 3528 // the maximal value for the type. 3529 --Val; 3530 else if (Val.ugt(MaxVal) || Overflowed) 3531 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3532 3533 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3534 Tok.getLocation(), scale); 3535 } else if (Literal.isFloatingLiteral()) { 3536 QualType Ty; 3537 if (Literal.isHalf){ 3538 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3539 Ty = Context.HalfTy; 3540 else { 3541 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3542 return ExprError(); 3543 } 3544 } else if (Literal.isFloat) 3545 Ty = Context.FloatTy; 3546 else if (Literal.isLong) 3547 Ty = Context.LongDoubleTy; 3548 else if (Literal.isFloat16) 3549 Ty = Context.Float16Ty; 3550 else if (Literal.isFloat128) 3551 Ty = Context.Float128Ty; 3552 else 3553 Ty = Context.DoubleTy; 3554 3555 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3556 3557 if (Ty == Context.DoubleTy) { 3558 if (getLangOpts().SinglePrecisionConstants) { 3559 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3560 if (BTy->getKind() != BuiltinType::Float) { 3561 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3562 } 3563 } else if (getLangOpts().OpenCL && 3564 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3565 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3566 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3567 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3568 } 3569 } 3570 } else if (!Literal.isIntegerLiteral()) { 3571 return ExprError(); 3572 } else { 3573 QualType Ty; 3574 3575 // 'long long' is a C99 or C++11 feature. 3576 if (!getLangOpts().C99 && Literal.isLongLong) { 3577 if (getLangOpts().CPlusPlus) 3578 Diag(Tok.getLocation(), 3579 getLangOpts().CPlusPlus11 ? 3580 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3581 else 3582 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3583 } 3584 3585 // Get the value in the widest-possible width. 3586 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3587 llvm::APInt ResultVal(MaxWidth, 0); 3588 3589 if (Literal.GetIntegerValue(ResultVal)) { 3590 // If this value didn't fit into uintmax_t, error and force to ull. 3591 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3592 << /* Unsigned */ 1; 3593 Ty = Context.UnsignedLongLongTy; 3594 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3595 "long long is not intmax_t?"); 3596 } else { 3597 // If this value fits into a ULL, try to figure out what else it fits into 3598 // according to the rules of C99 6.4.4.1p5. 3599 3600 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3601 // be an unsigned int. 3602 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3603 3604 // Check from smallest to largest, picking the smallest type we can. 3605 unsigned Width = 0; 3606 3607 // Microsoft specific integer suffixes are explicitly sized. 3608 if (Literal.MicrosoftInteger) { 3609 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3610 Width = 8; 3611 Ty = Context.CharTy; 3612 } else { 3613 Width = Literal.MicrosoftInteger; 3614 Ty = Context.getIntTypeForBitwidth(Width, 3615 /*Signed=*/!Literal.isUnsigned); 3616 } 3617 } 3618 3619 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3620 // Are int/unsigned possibilities? 3621 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3622 3623 // Does it fit in a unsigned int? 3624 if (ResultVal.isIntN(IntSize)) { 3625 // Does it fit in a signed int? 3626 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3627 Ty = Context.IntTy; 3628 else if (AllowUnsigned) 3629 Ty = Context.UnsignedIntTy; 3630 Width = IntSize; 3631 } 3632 } 3633 3634 // Are long/unsigned long possibilities? 3635 if (Ty.isNull() && !Literal.isLongLong) { 3636 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3637 3638 // Does it fit in a unsigned long? 3639 if (ResultVal.isIntN(LongSize)) { 3640 // Does it fit in a signed long? 3641 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3642 Ty = Context.LongTy; 3643 else if (AllowUnsigned) 3644 Ty = Context.UnsignedLongTy; 3645 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3646 // is compatible. 3647 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3648 const unsigned LongLongSize = 3649 Context.getTargetInfo().getLongLongWidth(); 3650 Diag(Tok.getLocation(), 3651 getLangOpts().CPlusPlus 3652 ? Literal.isLong 3653 ? diag::warn_old_implicitly_unsigned_long_cxx 3654 : /*C++98 UB*/ diag:: 3655 ext_old_implicitly_unsigned_long_cxx 3656 : diag::warn_old_implicitly_unsigned_long) 3657 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3658 : /*will be ill-formed*/ 1); 3659 Ty = Context.UnsignedLongTy; 3660 } 3661 Width = LongSize; 3662 } 3663 } 3664 3665 // Check long long if needed. 3666 if (Ty.isNull()) { 3667 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3668 3669 // Does it fit in a unsigned long long? 3670 if (ResultVal.isIntN(LongLongSize)) { 3671 // Does it fit in a signed long long? 3672 // To be compatible with MSVC, hex integer literals ending with the 3673 // LL or i64 suffix are always signed in Microsoft mode. 3674 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3675 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3676 Ty = Context.LongLongTy; 3677 else if (AllowUnsigned) 3678 Ty = Context.UnsignedLongLongTy; 3679 Width = LongLongSize; 3680 } 3681 } 3682 3683 // If we still couldn't decide a type, we probably have something that 3684 // does not fit in a signed long long, but has no U suffix. 3685 if (Ty.isNull()) { 3686 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3687 Ty = Context.UnsignedLongLongTy; 3688 Width = Context.getTargetInfo().getLongLongWidth(); 3689 } 3690 3691 if (ResultVal.getBitWidth() != Width) 3692 ResultVal = ResultVal.trunc(Width); 3693 } 3694 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3695 } 3696 3697 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3698 if (Literal.isImaginary) { 3699 Res = new (Context) ImaginaryLiteral(Res, 3700 Context.getComplexType(Res->getType())); 3701 3702 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3703 } 3704 return Res; 3705 } 3706 3707 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3708 assert(E && "ActOnParenExpr() missing expr"); 3709 return new (Context) ParenExpr(L, R, E); 3710 } 3711 3712 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3713 SourceLocation Loc, 3714 SourceRange ArgRange) { 3715 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3716 // scalar or vector data type argument..." 3717 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3718 // type (C99 6.2.5p18) or void. 3719 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3720 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3721 << T << ArgRange; 3722 return true; 3723 } 3724 3725 assert((T->isVoidType() || !T->isIncompleteType()) && 3726 "Scalar types should always be complete"); 3727 return false; 3728 } 3729 3730 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3731 SourceLocation Loc, 3732 SourceRange ArgRange, 3733 UnaryExprOrTypeTrait TraitKind) { 3734 // Invalid types must be hard errors for SFINAE in C++. 3735 if (S.LangOpts.CPlusPlus) 3736 return true; 3737 3738 // C99 6.5.3.4p1: 3739 if (T->isFunctionType() && 3740 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3741 TraitKind == UETT_PreferredAlignOf)) { 3742 // sizeof(function)/alignof(function) is allowed as an extension. 3743 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3744 << TraitKind << ArgRange; 3745 return false; 3746 } 3747 3748 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3749 // this is an error (OpenCL v1.1 s6.3.k) 3750 if (T->isVoidType()) { 3751 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3752 : diag::ext_sizeof_alignof_void_type; 3753 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3754 return false; 3755 } 3756 3757 return true; 3758 } 3759 3760 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3761 SourceLocation Loc, 3762 SourceRange ArgRange, 3763 UnaryExprOrTypeTrait TraitKind) { 3764 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3765 // runtime doesn't allow it. 3766 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3767 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3768 << T << (TraitKind == UETT_SizeOf) 3769 << ArgRange; 3770 return true; 3771 } 3772 3773 return false; 3774 } 3775 3776 /// Check whether E is a pointer from a decayed array type (the decayed 3777 /// pointer type is equal to T) and emit a warning if it is. 3778 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3779 Expr *E) { 3780 // Don't warn if the operation changed the type. 3781 if (T != E->getType()) 3782 return; 3783 3784 // Now look for array decays. 3785 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3786 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3787 return; 3788 3789 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3790 << ICE->getType() 3791 << ICE->getSubExpr()->getType(); 3792 } 3793 3794 /// Check the constraints on expression operands to unary type expression 3795 /// and type traits. 3796 /// 3797 /// Completes any types necessary and validates the constraints on the operand 3798 /// expression. The logic mostly mirrors the type-based overload, but may modify 3799 /// the expression as it completes the type for that expression through template 3800 /// instantiation, etc. 3801 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3802 UnaryExprOrTypeTrait ExprKind) { 3803 QualType ExprTy = E->getType(); 3804 assert(!ExprTy->isReferenceType()); 3805 3806 if (ExprKind == UETT_VecStep) 3807 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3808 E->getSourceRange()); 3809 3810 // Whitelist some types as extensions 3811 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3812 E->getSourceRange(), ExprKind)) 3813 return false; 3814 3815 // 'alignof' applied to an expression only requires the base element type of 3816 // the expression to be complete. 'sizeof' requires the expression's type to 3817 // be complete (and will attempt to complete it if it's an array of unknown 3818 // bound). 3819 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3820 if (RequireCompleteType(E->getExprLoc(), 3821 Context.getBaseElementType(E->getType()), 3822 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3823 E->getSourceRange())) 3824 return true; 3825 } else { 3826 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3827 ExprKind, E->getSourceRange())) 3828 return true; 3829 } 3830 3831 // Completing the expression's type may have changed it. 3832 ExprTy = E->getType(); 3833 assert(!ExprTy->isReferenceType()); 3834 3835 if (ExprTy->isFunctionType()) { 3836 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3837 << ExprKind << E->getSourceRange(); 3838 return true; 3839 } 3840 3841 // The operand for sizeof and alignof is in an unevaluated expression context, 3842 // so side effects could result in unintended consequences. 3843 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3844 ExprKind == UETT_PreferredAlignOf) && 3845 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3846 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3847 3848 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3849 E->getSourceRange(), ExprKind)) 3850 return true; 3851 3852 if (ExprKind == UETT_SizeOf) { 3853 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3854 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3855 QualType OType = PVD->getOriginalType(); 3856 QualType Type = PVD->getType(); 3857 if (Type->isPointerType() && OType->isArrayType()) { 3858 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3859 << Type << OType; 3860 Diag(PVD->getLocation(), diag::note_declared_at); 3861 } 3862 } 3863 } 3864 3865 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3866 // decays into a pointer and returns an unintended result. This is most 3867 // likely a typo for "sizeof(array) op x". 3868 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3869 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3870 BO->getLHS()); 3871 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3872 BO->getRHS()); 3873 } 3874 } 3875 3876 return false; 3877 } 3878 3879 /// Check the constraints on operands to unary expression and type 3880 /// traits. 3881 /// 3882 /// This will complete any types necessary, and validate the various constraints 3883 /// on those operands. 3884 /// 3885 /// The UsualUnaryConversions() function is *not* called by this routine. 3886 /// C99 6.3.2.1p[2-4] all state: 3887 /// Except when it is the operand of the sizeof operator ... 3888 /// 3889 /// C++ [expr.sizeof]p4 3890 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3891 /// standard conversions are not applied to the operand of sizeof. 3892 /// 3893 /// This policy is followed for all of the unary trait expressions. 3894 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3895 SourceLocation OpLoc, 3896 SourceRange ExprRange, 3897 UnaryExprOrTypeTrait ExprKind) { 3898 if (ExprType->isDependentType()) 3899 return false; 3900 3901 // C++ [expr.sizeof]p2: 3902 // When applied to a reference or a reference type, the result 3903 // is the size of the referenced type. 3904 // C++11 [expr.alignof]p3: 3905 // When alignof is applied to a reference type, the result 3906 // shall be the alignment of the referenced type. 3907 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3908 ExprType = Ref->getPointeeType(); 3909 3910 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3911 // When alignof or _Alignof is applied to an array type, the result 3912 // is the alignment of the element type. 3913 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3914 ExprKind == UETT_OpenMPRequiredSimdAlign) 3915 ExprType = Context.getBaseElementType(ExprType); 3916 3917 if (ExprKind == UETT_VecStep) 3918 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3919 3920 // Whitelist some types as extensions 3921 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3922 ExprKind)) 3923 return false; 3924 3925 if (RequireCompleteType(OpLoc, ExprType, 3926 diag::err_sizeof_alignof_incomplete_type, 3927 ExprKind, ExprRange)) 3928 return true; 3929 3930 if (ExprType->isFunctionType()) { 3931 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3932 << ExprKind << ExprRange; 3933 return true; 3934 } 3935 3936 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3937 ExprKind)) 3938 return true; 3939 3940 return false; 3941 } 3942 3943 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3944 E = E->IgnoreParens(); 3945 3946 // Cannot know anything else if the expression is dependent. 3947 if (E->isTypeDependent()) 3948 return false; 3949 3950 if (E->getObjectKind() == OK_BitField) { 3951 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3952 << 1 << E->getSourceRange(); 3953 return true; 3954 } 3955 3956 ValueDecl *D = nullptr; 3957 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3958 D = DRE->getDecl(); 3959 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3960 D = ME->getMemberDecl(); 3961 } 3962 3963 // If it's a field, require the containing struct to have a 3964 // complete definition so that we can compute the layout. 3965 // 3966 // This can happen in C++11 onwards, either by naming the member 3967 // in a way that is not transformed into a member access expression 3968 // (in an unevaluated operand, for instance), or by naming the member 3969 // in a trailing-return-type. 3970 // 3971 // For the record, since __alignof__ on expressions is a GCC 3972 // extension, GCC seems to permit this but always gives the 3973 // nonsensical answer 0. 3974 // 3975 // We don't really need the layout here --- we could instead just 3976 // directly check for all the appropriate alignment-lowing 3977 // attributes --- but that would require duplicating a lot of 3978 // logic that just isn't worth duplicating for such a marginal 3979 // use-case. 3980 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3981 // Fast path this check, since we at least know the record has a 3982 // definition if we can find a member of it. 3983 if (!FD->getParent()->isCompleteDefinition()) { 3984 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3985 << E->getSourceRange(); 3986 return true; 3987 } 3988 3989 // Otherwise, if it's a field, and the field doesn't have 3990 // reference type, then it must have a complete type (or be a 3991 // flexible array member, which we explicitly want to 3992 // white-list anyway), which makes the following checks trivial. 3993 if (!FD->getType()->isReferenceType()) 3994 return false; 3995 } 3996 3997 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3998 } 3999 4000 bool Sema::CheckVecStepExpr(Expr *E) { 4001 E = E->IgnoreParens(); 4002 4003 // Cannot know anything else if the expression is dependent. 4004 if (E->isTypeDependent()) 4005 return false; 4006 4007 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4008 } 4009 4010 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4011 CapturingScopeInfo *CSI) { 4012 assert(T->isVariablyModifiedType()); 4013 assert(CSI != nullptr); 4014 4015 // We're going to walk down into the type and look for VLA expressions. 4016 do { 4017 const Type *Ty = T.getTypePtr(); 4018 switch (Ty->getTypeClass()) { 4019 #define TYPE(Class, Base) 4020 #define ABSTRACT_TYPE(Class, Base) 4021 #define NON_CANONICAL_TYPE(Class, Base) 4022 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4023 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4024 #include "clang/AST/TypeNodes.def" 4025 T = QualType(); 4026 break; 4027 // These types are never variably-modified. 4028 case Type::Builtin: 4029 case Type::Complex: 4030 case Type::Vector: 4031 case Type::ExtVector: 4032 case Type::Record: 4033 case Type::Enum: 4034 case Type::Elaborated: 4035 case Type::TemplateSpecialization: 4036 case Type::ObjCObject: 4037 case Type::ObjCInterface: 4038 case Type::ObjCObjectPointer: 4039 case Type::ObjCTypeParam: 4040 case Type::Pipe: 4041 llvm_unreachable("type class is never variably-modified!"); 4042 case Type::Adjusted: 4043 T = cast<AdjustedType>(Ty)->getOriginalType(); 4044 break; 4045 case Type::Decayed: 4046 T = cast<DecayedType>(Ty)->getPointeeType(); 4047 break; 4048 case Type::Pointer: 4049 T = cast<PointerType>(Ty)->getPointeeType(); 4050 break; 4051 case Type::BlockPointer: 4052 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4053 break; 4054 case Type::LValueReference: 4055 case Type::RValueReference: 4056 T = cast<ReferenceType>(Ty)->getPointeeType(); 4057 break; 4058 case Type::MemberPointer: 4059 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4060 break; 4061 case Type::ConstantArray: 4062 case Type::IncompleteArray: 4063 // Losing element qualification here is fine. 4064 T = cast<ArrayType>(Ty)->getElementType(); 4065 break; 4066 case Type::VariableArray: { 4067 // Losing element qualification here is fine. 4068 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4069 4070 // Unknown size indication requires no size computation. 4071 // Otherwise, evaluate and record it. 4072 if (auto Size = VAT->getSizeExpr()) { 4073 if (!CSI->isVLATypeCaptured(VAT)) { 4074 RecordDecl *CapRecord = nullptr; 4075 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 4076 CapRecord = LSI->Lambda; 4077 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 4078 CapRecord = CRSI->TheRecordDecl; 4079 } 4080 if (CapRecord) { 4081 auto ExprLoc = Size->getExprLoc(); 4082 auto SizeType = Context.getSizeType(); 4083 // Build the non-static data member. 4084 auto Field = 4085 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 4086 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 4087 /*BW*/ nullptr, /*Mutable*/ false, 4088 /*InitStyle*/ ICIS_NoInit); 4089 Field->setImplicit(true); 4090 Field->setAccess(AS_private); 4091 Field->setCapturedVLAType(VAT); 4092 CapRecord->addDecl(Field); 4093 4094 CSI->addVLATypeCapture(ExprLoc, SizeType); 4095 } 4096 } 4097 } 4098 T = VAT->getElementType(); 4099 break; 4100 } 4101 case Type::FunctionProto: 4102 case Type::FunctionNoProto: 4103 T = cast<FunctionType>(Ty)->getReturnType(); 4104 break; 4105 case Type::Paren: 4106 case Type::TypeOf: 4107 case Type::UnaryTransform: 4108 case Type::Attributed: 4109 case Type::SubstTemplateTypeParm: 4110 case Type::PackExpansion: 4111 // Keep walking after single level desugaring. 4112 T = T.getSingleStepDesugaredType(Context); 4113 break; 4114 case Type::Typedef: 4115 T = cast<TypedefType>(Ty)->desugar(); 4116 break; 4117 case Type::Decltype: 4118 T = cast<DecltypeType>(Ty)->desugar(); 4119 break; 4120 case Type::Auto: 4121 case Type::DeducedTemplateSpecialization: 4122 T = cast<DeducedType>(Ty)->getDeducedType(); 4123 break; 4124 case Type::TypeOfExpr: 4125 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4126 break; 4127 case Type::Atomic: 4128 T = cast<AtomicType>(Ty)->getValueType(); 4129 break; 4130 } 4131 } while (!T.isNull() && T->isVariablyModifiedType()); 4132 } 4133 4134 /// Build a sizeof or alignof expression given a type operand. 4135 ExprResult 4136 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4137 SourceLocation OpLoc, 4138 UnaryExprOrTypeTrait ExprKind, 4139 SourceRange R) { 4140 if (!TInfo) 4141 return ExprError(); 4142 4143 QualType T = TInfo->getType(); 4144 4145 if (!T->isDependentType() && 4146 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4147 return ExprError(); 4148 4149 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4150 if (auto *TT = T->getAs<TypedefType>()) { 4151 for (auto I = FunctionScopes.rbegin(), 4152 E = std::prev(FunctionScopes.rend()); 4153 I != E; ++I) { 4154 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4155 if (CSI == nullptr) 4156 break; 4157 DeclContext *DC = nullptr; 4158 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4159 DC = LSI->CallOperator; 4160 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4161 DC = CRSI->TheCapturedDecl; 4162 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4163 DC = BSI->TheDecl; 4164 if (DC) { 4165 if (DC->containsDecl(TT->getDecl())) 4166 break; 4167 captureVariablyModifiedType(Context, T, CSI); 4168 } 4169 } 4170 } 4171 } 4172 4173 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4174 return new (Context) UnaryExprOrTypeTraitExpr( 4175 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4176 } 4177 4178 /// Build a sizeof or alignof expression given an expression 4179 /// operand. 4180 ExprResult 4181 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4182 UnaryExprOrTypeTrait ExprKind) { 4183 ExprResult PE = CheckPlaceholderExpr(E); 4184 if (PE.isInvalid()) 4185 return ExprError(); 4186 4187 E = PE.get(); 4188 4189 // Verify that the operand is valid. 4190 bool isInvalid = false; 4191 if (E->isTypeDependent()) { 4192 // Delay type-checking for type-dependent expressions. 4193 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4194 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4195 } else if (ExprKind == UETT_VecStep) { 4196 isInvalid = CheckVecStepExpr(E); 4197 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4198 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4199 isInvalid = true; 4200 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4201 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4202 isInvalid = true; 4203 } else { 4204 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4205 } 4206 4207 if (isInvalid) 4208 return ExprError(); 4209 4210 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4211 PE = TransformToPotentiallyEvaluated(E); 4212 if (PE.isInvalid()) return ExprError(); 4213 E = PE.get(); 4214 } 4215 4216 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4217 return new (Context) UnaryExprOrTypeTraitExpr( 4218 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4219 } 4220 4221 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4222 /// expr and the same for @c alignof and @c __alignof 4223 /// Note that the ArgRange is invalid if isType is false. 4224 ExprResult 4225 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4226 UnaryExprOrTypeTrait ExprKind, bool IsType, 4227 void *TyOrEx, SourceRange ArgRange) { 4228 // If error parsing type, ignore. 4229 if (!TyOrEx) return ExprError(); 4230 4231 if (IsType) { 4232 TypeSourceInfo *TInfo; 4233 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4234 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4235 } 4236 4237 Expr *ArgEx = (Expr *)TyOrEx; 4238 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4239 return Result; 4240 } 4241 4242 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4243 bool IsReal) { 4244 if (V.get()->isTypeDependent()) 4245 return S.Context.DependentTy; 4246 4247 // _Real and _Imag are only l-values for normal l-values. 4248 if (V.get()->getObjectKind() != OK_Ordinary) { 4249 V = S.DefaultLvalueConversion(V.get()); 4250 if (V.isInvalid()) 4251 return QualType(); 4252 } 4253 4254 // These operators return the element type of a complex type. 4255 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4256 return CT->getElementType(); 4257 4258 // Otherwise they pass through real integer and floating point types here. 4259 if (V.get()->getType()->isArithmeticType()) 4260 return V.get()->getType(); 4261 4262 // Test for placeholders. 4263 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4264 if (PR.isInvalid()) return QualType(); 4265 if (PR.get() != V.get()) { 4266 V = PR; 4267 return CheckRealImagOperand(S, V, Loc, IsReal); 4268 } 4269 4270 // Reject anything else. 4271 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4272 << (IsReal ? "__real" : "__imag"); 4273 return QualType(); 4274 } 4275 4276 4277 4278 ExprResult 4279 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4280 tok::TokenKind Kind, Expr *Input) { 4281 UnaryOperatorKind Opc; 4282 switch (Kind) { 4283 default: llvm_unreachable("Unknown unary op!"); 4284 case tok::plusplus: Opc = UO_PostInc; break; 4285 case tok::minusminus: Opc = UO_PostDec; break; 4286 } 4287 4288 // Since this might is a postfix expression, get rid of ParenListExprs. 4289 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4290 if (Result.isInvalid()) return ExprError(); 4291 Input = Result.get(); 4292 4293 return BuildUnaryOp(S, OpLoc, Opc, Input); 4294 } 4295 4296 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4297 /// 4298 /// \return true on error 4299 static bool checkArithmeticOnObjCPointer(Sema &S, 4300 SourceLocation opLoc, 4301 Expr *op) { 4302 assert(op->getType()->isObjCObjectPointerType()); 4303 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4304 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4305 return false; 4306 4307 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4308 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4309 << op->getSourceRange(); 4310 return true; 4311 } 4312 4313 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4314 auto *BaseNoParens = Base->IgnoreParens(); 4315 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4316 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4317 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4318 } 4319 4320 ExprResult 4321 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4322 Expr *idx, SourceLocation rbLoc) { 4323 if (base && !base->getType().isNull() && 4324 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4325 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4326 /*Length=*/nullptr, rbLoc); 4327 4328 // Since this might be a postfix expression, get rid of ParenListExprs. 4329 if (isa<ParenListExpr>(base)) { 4330 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4331 if (result.isInvalid()) return ExprError(); 4332 base = result.get(); 4333 } 4334 4335 // Handle any non-overload placeholder types in the base and index 4336 // expressions. We can't handle overloads here because the other 4337 // operand might be an overloadable type, in which case the overload 4338 // resolution for the operator overload should get the first crack 4339 // at the overload. 4340 bool IsMSPropertySubscript = false; 4341 if (base->getType()->isNonOverloadPlaceholderType()) { 4342 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4343 if (!IsMSPropertySubscript) { 4344 ExprResult result = CheckPlaceholderExpr(base); 4345 if (result.isInvalid()) 4346 return ExprError(); 4347 base = result.get(); 4348 } 4349 } 4350 if (idx->getType()->isNonOverloadPlaceholderType()) { 4351 ExprResult result = CheckPlaceholderExpr(idx); 4352 if (result.isInvalid()) return ExprError(); 4353 idx = result.get(); 4354 } 4355 4356 // Build an unanalyzed expression if either operand is type-dependent. 4357 if (getLangOpts().CPlusPlus && 4358 (base->isTypeDependent() || idx->isTypeDependent())) { 4359 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4360 VK_LValue, OK_Ordinary, rbLoc); 4361 } 4362 4363 // MSDN, property (C++) 4364 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4365 // This attribute can also be used in the declaration of an empty array in a 4366 // class or structure definition. For example: 4367 // __declspec(property(get=GetX, put=PutX)) int x[]; 4368 // The above statement indicates that x[] can be used with one or more array 4369 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4370 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4371 if (IsMSPropertySubscript) { 4372 // Build MS property subscript expression if base is MS property reference 4373 // or MS property subscript. 4374 return new (Context) MSPropertySubscriptExpr( 4375 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4376 } 4377 4378 // Use C++ overloaded-operator rules if either operand has record 4379 // type. The spec says to do this if either type is *overloadable*, 4380 // but enum types can't declare subscript operators or conversion 4381 // operators, so there's nothing interesting for overload resolution 4382 // to do if there aren't any record types involved. 4383 // 4384 // ObjC pointers have their own subscripting logic that is not tied 4385 // to overload resolution and so should not take this path. 4386 if (getLangOpts().CPlusPlus && 4387 (base->getType()->isRecordType() || 4388 (!base->getType()->isObjCObjectPointerType() && 4389 idx->getType()->isRecordType()))) { 4390 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4391 } 4392 4393 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4394 4395 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4396 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4397 4398 return Res; 4399 } 4400 4401 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4402 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4403 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4404 4405 // For expressions like `&(*s).b`, the base is recorded and what should be 4406 // checked. 4407 const MemberExpr *Member = nullptr; 4408 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4409 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4410 4411 LastRecord.PossibleDerefs.erase(StrippedExpr); 4412 } 4413 4414 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4415 QualType ResultTy = E->getType(); 4416 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4417 4418 // Bail if the element is an array since it is not memory access. 4419 if (isa<ArrayType>(ResultTy)) 4420 return; 4421 4422 if (ResultTy->hasAttr(attr::NoDeref)) { 4423 LastRecord.PossibleDerefs.insert(E); 4424 return; 4425 } 4426 4427 // Check if the base type is a pointer to a member access of a struct 4428 // marked with noderef. 4429 const Expr *Base = E->getBase(); 4430 QualType BaseTy = Base->getType(); 4431 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4432 // Not a pointer access 4433 return; 4434 4435 const MemberExpr *Member = nullptr; 4436 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4437 Member->isArrow()) 4438 Base = Member->getBase(); 4439 4440 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4441 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4442 LastRecord.PossibleDerefs.insert(E); 4443 } 4444 } 4445 4446 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4447 Expr *LowerBound, 4448 SourceLocation ColonLoc, Expr *Length, 4449 SourceLocation RBLoc) { 4450 if (Base->getType()->isPlaceholderType() && 4451 !Base->getType()->isSpecificPlaceholderType( 4452 BuiltinType::OMPArraySection)) { 4453 ExprResult Result = CheckPlaceholderExpr(Base); 4454 if (Result.isInvalid()) 4455 return ExprError(); 4456 Base = Result.get(); 4457 } 4458 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4459 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4460 if (Result.isInvalid()) 4461 return ExprError(); 4462 Result = DefaultLvalueConversion(Result.get()); 4463 if (Result.isInvalid()) 4464 return ExprError(); 4465 LowerBound = Result.get(); 4466 } 4467 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4468 ExprResult Result = CheckPlaceholderExpr(Length); 4469 if (Result.isInvalid()) 4470 return ExprError(); 4471 Result = DefaultLvalueConversion(Result.get()); 4472 if (Result.isInvalid()) 4473 return ExprError(); 4474 Length = Result.get(); 4475 } 4476 4477 // Build an unanalyzed expression if either operand is type-dependent. 4478 if (Base->isTypeDependent() || 4479 (LowerBound && 4480 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4481 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4482 return new (Context) 4483 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4484 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4485 } 4486 4487 // Perform default conversions. 4488 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4489 QualType ResultTy; 4490 if (OriginalTy->isAnyPointerType()) { 4491 ResultTy = OriginalTy->getPointeeType(); 4492 } else if (OriginalTy->isArrayType()) { 4493 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4494 } else { 4495 return ExprError( 4496 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4497 << Base->getSourceRange()); 4498 } 4499 // C99 6.5.2.1p1 4500 if (LowerBound) { 4501 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4502 LowerBound); 4503 if (Res.isInvalid()) 4504 return ExprError(Diag(LowerBound->getExprLoc(), 4505 diag::err_omp_typecheck_section_not_integer) 4506 << 0 << LowerBound->getSourceRange()); 4507 LowerBound = Res.get(); 4508 4509 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4510 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4511 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4512 << 0 << LowerBound->getSourceRange(); 4513 } 4514 if (Length) { 4515 auto Res = 4516 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4517 if (Res.isInvalid()) 4518 return ExprError(Diag(Length->getExprLoc(), 4519 diag::err_omp_typecheck_section_not_integer) 4520 << 1 << Length->getSourceRange()); 4521 Length = Res.get(); 4522 4523 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4524 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4525 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4526 << 1 << Length->getSourceRange(); 4527 } 4528 4529 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4530 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4531 // type. Note that functions are not objects, and that (in C99 parlance) 4532 // incomplete types are not object types. 4533 if (ResultTy->isFunctionType()) { 4534 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4535 << ResultTy << Base->getSourceRange(); 4536 return ExprError(); 4537 } 4538 4539 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4540 diag::err_omp_section_incomplete_type, Base)) 4541 return ExprError(); 4542 4543 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4544 Expr::EvalResult Result; 4545 if (LowerBound->EvaluateAsInt(Result, Context)) { 4546 // OpenMP 4.5, [2.4 Array Sections] 4547 // The array section must be a subset of the original array. 4548 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4549 if (LowerBoundValue.isNegative()) { 4550 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4551 << LowerBound->getSourceRange(); 4552 return ExprError(); 4553 } 4554 } 4555 } 4556 4557 if (Length) { 4558 Expr::EvalResult Result; 4559 if (Length->EvaluateAsInt(Result, Context)) { 4560 // OpenMP 4.5, [2.4 Array Sections] 4561 // The length must evaluate to non-negative integers. 4562 llvm::APSInt LengthValue = Result.Val.getInt(); 4563 if (LengthValue.isNegative()) { 4564 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4565 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4566 << Length->getSourceRange(); 4567 return ExprError(); 4568 } 4569 } 4570 } else if (ColonLoc.isValid() && 4571 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4572 !OriginalTy->isVariableArrayType()))) { 4573 // OpenMP 4.5, [2.4 Array Sections] 4574 // When the size of the array dimension is not known, the length must be 4575 // specified explicitly. 4576 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4577 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4578 return ExprError(); 4579 } 4580 4581 if (!Base->getType()->isSpecificPlaceholderType( 4582 BuiltinType::OMPArraySection)) { 4583 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4584 if (Result.isInvalid()) 4585 return ExprError(); 4586 Base = Result.get(); 4587 } 4588 return new (Context) 4589 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4590 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4591 } 4592 4593 ExprResult 4594 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4595 Expr *Idx, SourceLocation RLoc) { 4596 Expr *LHSExp = Base; 4597 Expr *RHSExp = Idx; 4598 4599 ExprValueKind VK = VK_LValue; 4600 ExprObjectKind OK = OK_Ordinary; 4601 4602 // Per C++ core issue 1213, the result is an xvalue if either operand is 4603 // a non-lvalue array, and an lvalue otherwise. 4604 if (getLangOpts().CPlusPlus11) { 4605 for (auto *Op : {LHSExp, RHSExp}) { 4606 Op = Op->IgnoreImplicit(); 4607 if (Op->getType()->isArrayType() && !Op->isLValue()) 4608 VK = VK_XValue; 4609 } 4610 } 4611 4612 // Perform default conversions. 4613 if (!LHSExp->getType()->getAs<VectorType>()) { 4614 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4615 if (Result.isInvalid()) 4616 return ExprError(); 4617 LHSExp = Result.get(); 4618 } 4619 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4620 if (Result.isInvalid()) 4621 return ExprError(); 4622 RHSExp = Result.get(); 4623 4624 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4625 4626 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4627 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4628 // in the subscript position. As a result, we need to derive the array base 4629 // and index from the expression types. 4630 Expr *BaseExpr, *IndexExpr; 4631 QualType ResultType; 4632 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4633 BaseExpr = LHSExp; 4634 IndexExpr = RHSExp; 4635 ResultType = Context.DependentTy; 4636 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4637 BaseExpr = LHSExp; 4638 IndexExpr = RHSExp; 4639 ResultType = PTy->getPointeeType(); 4640 } else if (const ObjCObjectPointerType *PTy = 4641 LHSTy->getAs<ObjCObjectPointerType>()) { 4642 BaseExpr = LHSExp; 4643 IndexExpr = RHSExp; 4644 4645 // Use custom logic if this should be the pseudo-object subscript 4646 // expression. 4647 if (!LangOpts.isSubscriptPointerArithmetic()) 4648 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4649 nullptr); 4650 4651 ResultType = PTy->getPointeeType(); 4652 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4653 // Handle the uncommon case of "123[Ptr]". 4654 BaseExpr = RHSExp; 4655 IndexExpr = LHSExp; 4656 ResultType = PTy->getPointeeType(); 4657 } else if (const ObjCObjectPointerType *PTy = 4658 RHSTy->getAs<ObjCObjectPointerType>()) { 4659 // Handle the uncommon case of "123[Ptr]". 4660 BaseExpr = RHSExp; 4661 IndexExpr = LHSExp; 4662 ResultType = PTy->getPointeeType(); 4663 if (!LangOpts.isSubscriptPointerArithmetic()) { 4664 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4665 << ResultType << BaseExpr->getSourceRange(); 4666 return ExprError(); 4667 } 4668 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4669 BaseExpr = LHSExp; // vectors: V[123] 4670 IndexExpr = RHSExp; 4671 // We apply C++ DR1213 to vector subscripting too. 4672 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4673 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4674 if (Materialized.isInvalid()) 4675 return ExprError(); 4676 LHSExp = Materialized.get(); 4677 } 4678 VK = LHSExp->getValueKind(); 4679 if (VK != VK_RValue) 4680 OK = OK_VectorComponent; 4681 4682 ResultType = VTy->getElementType(); 4683 QualType BaseType = BaseExpr->getType(); 4684 Qualifiers BaseQuals = BaseType.getQualifiers(); 4685 Qualifiers MemberQuals = ResultType.getQualifiers(); 4686 Qualifiers Combined = BaseQuals + MemberQuals; 4687 if (Combined != MemberQuals) 4688 ResultType = Context.getQualifiedType(ResultType, Combined); 4689 } else if (LHSTy->isArrayType()) { 4690 // If we see an array that wasn't promoted by 4691 // DefaultFunctionArrayLvalueConversion, it must be an array that 4692 // wasn't promoted because of the C90 rule that doesn't 4693 // allow promoting non-lvalue arrays. Warn, then 4694 // force the promotion here. 4695 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4696 << LHSExp->getSourceRange(); 4697 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4698 CK_ArrayToPointerDecay).get(); 4699 LHSTy = LHSExp->getType(); 4700 4701 BaseExpr = LHSExp; 4702 IndexExpr = RHSExp; 4703 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4704 } else if (RHSTy->isArrayType()) { 4705 // Same as previous, except for 123[f().a] case 4706 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4707 << RHSExp->getSourceRange(); 4708 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4709 CK_ArrayToPointerDecay).get(); 4710 RHSTy = RHSExp->getType(); 4711 4712 BaseExpr = RHSExp; 4713 IndexExpr = LHSExp; 4714 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4715 } else { 4716 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4717 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4718 } 4719 // C99 6.5.2.1p1 4720 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4721 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4722 << IndexExpr->getSourceRange()); 4723 4724 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4725 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4726 && !IndexExpr->isTypeDependent()) 4727 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4728 4729 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4730 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4731 // type. Note that Functions are not objects, and that (in C99 parlance) 4732 // incomplete types are not object types. 4733 if (ResultType->isFunctionType()) { 4734 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4735 << ResultType << BaseExpr->getSourceRange(); 4736 return ExprError(); 4737 } 4738 4739 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4740 // GNU extension: subscripting on pointer to void 4741 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4742 << BaseExpr->getSourceRange(); 4743 4744 // C forbids expressions of unqualified void type from being l-values. 4745 // See IsCForbiddenLValueType. 4746 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4747 } else if (!ResultType->isDependentType() && 4748 RequireCompleteType(LLoc, ResultType, 4749 diag::err_subscript_incomplete_type, BaseExpr)) 4750 return ExprError(); 4751 4752 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4753 !ResultType.isCForbiddenLValueType()); 4754 4755 return new (Context) 4756 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4757 } 4758 4759 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4760 ParmVarDecl *Param) { 4761 if (Param->hasUnparsedDefaultArg()) { 4762 Diag(CallLoc, 4763 diag::err_use_of_default_argument_to_function_declared_later) << 4764 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4765 Diag(UnparsedDefaultArgLocs[Param], 4766 diag::note_default_argument_declared_here); 4767 return true; 4768 } 4769 4770 if (Param->hasUninstantiatedDefaultArg()) { 4771 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4772 4773 EnterExpressionEvaluationContext EvalContext( 4774 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4775 4776 // Instantiate the expression. 4777 // 4778 // FIXME: Pass in a correct Pattern argument, otherwise 4779 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4780 // 4781 // template<typename T> 4782 // struct A { 4783 // static int FooImpl(); 4784 // 4785 // template<typename Tp> 4786 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4787 // // template argument list [[T], [Tp]], should be [[Tp]]. 4788 // friend A<Tp> Foo(int a); 4789 // }; 4790 // 4791 // template<typename T> 4792 // A<T> Foo(int a = A<T>::FooImpl()); 4793 MultiLevelTemplateArgumentList MutiLevelArgList 4794 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4795 4796 InstantiatingTemplate Inst(*this, CallLoc, Param, 4797 MutiLevelArgList.getInnermost()); 4798 if (Inst.isInvalid()) 4799 return true; 4800 if (Inst.isAlreadyInstantiating()) { 4801 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4802 Param->setInvalidDecl(); 4803 return true; 4804 } 4805 4806 ExprResult Result; 4807 { 4808 // C++ [dcl.fct.default]p5: 4809 // The names in the [default argument] expression are bound, and 4810 // the semantic constraints are checked, at the point where the 4811 // default argument expression appears. 4812 ContextRAII SavedContext(*this, FD); 4813 LocalInstantiationScope Local(*this); 4814 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4815 /*DirectInit*/false); 4816 } 4817 if (Result.isInvalid()) 4818 return true; 4819 4820 // Check the expression as an initializer for the parameter. 4821 InitializedEntity Entity 4822 = InitializedEntity::InitializeParameter(Context, Param); 4823 InitializationKind Kind = InitializationKind::CreateCopy( 4824 Param->getLocation(), 4825 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4826 Expr *ResultE = Result.getAs<Expr>(); 4827 4828 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4829 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4830 if (Result.isInvalid()) 4831 return true; 4832 4833 Result = 4834 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4835 /*DiscardedValue*/ false); 4836 if (Result.isInvalid()) 4837 return true; 4838 4839 // Remember the instantiated default argument. 4840 Param->setDefaultArg(Result.getAs<Expr>()); 4841 if (ASTMutationListener *L = getASTMutationListener()) { 4842 L->DefaultArgumentInstantiated(Param); 4843 } 4844 } 4845 4846 // If the default argument expression is not set yet, we are building it now. 4847 if (!Param->hasInit()) { 4848 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4849 Param->setInvalidDecl(); 4850 return true; 4851 } 4852 4853 // If the default expression creates temporaries, we need to 4854 // push them to the current stack of expression temporaries so they'll 4855 // be properly destroyed. 4856 // FIXME: We should really be rebuilding the default argument with new 4857 // bound temporaries; see the comment in PR5810. 4858 // We don't need to do that with block decls, though, because 4859 // blocks in default argument expression can never capture anything. 4860 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4861 // Set the "needs cleanups" bit regardless of whether there are 4862 // any explicit objects. 4863 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4864 4865 // Append all the objects to the cleanup list. Right now, this 4866 // should always be a no-op, because blocks in default argument 4867 // expressions should never be able to capture anything. 4868 assert(!Init->getNumObjects() && 4869 "default argument expression has capturing blocks?"); 4870 } 4871 4872 // We already type-checked the argument, so we know it works. 4873 // Just mark all of the declarations in this potentially-evaluated expression 4874 // as being "referenced". 4875 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4876 /*SkipLocalVariables=*/true); 4877 return false; 4878 } 4879 4880 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4881 FunctionDecl *FD, ParmVarDecl *Param) { 4882 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4883 return ExprError(); 4884 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4885 } 4886 4887 Sema::VariadicCallType 4888 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4889 Expr *Fn) { 4890 if (Proto && Proto->isVariadic()) { 4891 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4892 return VariadicConstructor; 4893 else if (Fn && Fn->getType()->isBlockPointerType()) 4894 return VariadicBlock; 4895 else if (FDecl) { 4896 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4897 if (Method->isInstance()) 4898 return VariadicMethod; 4899 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4900 return VariadicMethod; 4901 return VariadicFunction; 4902 } 4903 return VariadicDoesNotApply; 4904 } 4905 4906 namespace { 4907 class FunctionCallCCC : public FunctionCallFilterCCC { 4908 public: 4909 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4910 unsigned NumArgs, MemberExpr *ME) 4911 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4912 FunctionName(FuncName) {} 4913 4914 bool ValidateCandidate(const TypoCorrection &candidate) override { 4915 if (!candidate.getCorrectionSpecifier() || 4916 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4917 return false; 4918 } 4919 4920 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4921 } 4922 4923 private: 4924 const IdentifierInfo *const FunctionName; 4925 }; 4926 } 4927 4928 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4929 FunctionDecl *FDecl, 4930 ArrayRef<Expr *> Args) { 4931 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4932 DeclarationName FuncName = FDecl->getDeclName(); 4933 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4934 4935 if (TypoCorrection Corrected = S.CorrectTypo( 4936 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4937 S.getScopeForContext(S.CurContext), nullptr, 4938 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4939 Args.size(), ME), 4940 Sema::CTK_ErrorRecovery)) { 4941 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4942 if (Corrected.isOverloaded()) { 4943 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4944 OverloadCandidateSet::iterator Best; 4945 for (NamedDecl *CD : Corrected) { 4946 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4947 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4948 OCS); 4949 } 4950 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4951 case OR_Success: 4952 ND = Best->FoundDecl; 4953 Corrected.setCorrectionDecl(ND); 4954 break; 4955 default: 4956 break; 4957 } 4958 } 4959 ND = ND->getUnderlyingDecl(); 4960 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4961 return Corrected; 4962 } 4963 } 4964 return TypoCorrection(); 4965 } 4966 4967 /// ConvertArgumentsForCall - Converts the arguments specified in 4968 /// Args/NumArgs to the parameter types of the function FDecl with 4969 /// function prototype Proto. Call is the call expression itself, and 4970 /// Fn is the function expression. For a C++ member function, this 4971 /// routine does not attempt to convert the object argument. Returns 4972 /// true if the call is ill-formed. 4973 bool 4974 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4975 FunctionDecl *FDecl, 4976 const FunctionProtoType *Proto, 4977 ArrayRef<Expr *> Args, 4978 SourceLocation RParenLoc, 4979 bool IsExecConfig) { 4980 // Bail out early if calling a builtin with custom typechecking. 4981 if (FDecl) 4982 if (unsigned ID = FDecl->getBuiltinID()) 4983 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4984 return false; 4985 4986 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4987 // assignment, to the types of the corresponding parameter, ... 4988 unsigned NumParams = Proto->getNumParams(); 4989 bool Invalid = false; 4990 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4991 unsigned FnKind = Fn->getType()->isBlockPointerType() 4992 ? 1 /* block */ 4993 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4994 : 0 /* function */); 4995 4996 // If too few arguments are available (and we don't have default 4997 // arguments for the remaining parameters), don't make the call. 4998 if (Args.size() < NumParams) { 4999 if (Args.size() < MinArgs) { 5000 TypoCorrection TC; 5001 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5002 unsigned diag_id = 5003 MinArgs == NumParams && !Proto->isVariadic() 5004 ? diag::err_typecheck_call_too_few_args_suggest 5005 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5006 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5007 << static_cast<unsigned>(Args.size()) 5008 << TC.getCorrectionRange()); 5009 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5010 Diag(RParenLoc, 5011 MinArgs == NumParams && !Proto->isVariadic() 5012 ? diag::err_typecheck_call_too_few_args_one 5013 : diag::err_typecheck_call_too_few_args_at_least_one) 5014 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5015 else 5016 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5017 ? diag::err_typecheck_call_too_few_args 5018 : diag::err_typecheck_call_too_few_args_at_least) 5019 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5020 << Fn->getSourceRange(); 5021 5022 // Emit the location of the prototype. 5023 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5024 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5025 5026 return true; 5027 } 5028 // We reserve space for the default arguments when we create 5029 // the call expression, before calling ConvertArgumentsForCall. 5030 assert((Call->getNumArgs() == NumParams) && 5031 "We should have reserved space for the default arguments before!"); 5032 } 5033 5034 // If too many are passed and not variadic, error on the extras and drop 5035 // them. 5036 if (Args.size() > NumParams) { 5037 if (!Proto->isVariadic()) { 5038 TypoCorrection TC; 5039 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5040 unsigned diag_id = 5041 MinArgs == NumParams && !Proto->isVariadic() 5042 ? diag::err_typecheck_call_too_many_args_suggest 5043 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5044 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5045 << static_cast<unsigned>(Args.size()) 5046 << TC.getCorrectionRange()); 5047 } else if (NumParams == 1 && FDecl && 5048 FDecl->getParamDecl(0)->getDeclName()) 5049 Diag(Args[NumParams]->getBeginLoc(), 5050 MinArgs == NumParams 5051 ? diag::err_typecheck_call_too_many_args_one 5052 : diag::err_typecheck_call_too_many_args_at_most_one) 5053 << FnKind << FDecl->getParamDecl(0) 5054 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5055 << SourceRange(Args[NumParams]->getBeginLoc(), 5056 Args.back()->getEndLoc()); 5057 else 5058 Diag(Args[NumParams]->getBeginLoc(), 5059 MinArgs == NumParams 5060 ? diag::err_typecheck_call_too_many_args 5061 : diag::err_typecheck_call_too_many_args_at_most) 5062 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5063 << Fn->getSourceRange() 5064 << SourceRange(Args[NumParams]->getBeginLoc(), 5065 Args.back()->getEndLoc()); 5066 5067 // Emit the location of the prototype. 5068 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5069 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5070 5071 // This deletes the extra arguments. 5072 Call->shrinkNumArgs(NumParams); 5073 return true; 5074 } 5075 } 5076 SmallVector<Expr *, 8> AllArgs; 5077 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5078 5079 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5080 AllArgs, CallType); 5081 if (Invalid) 5082 return true; 5083 unsigned TotalNumArgs = AllArgs.size(); 5084 for (unsigned i = 0; i < TotalNumArgs; ++i) 5085 Call->setArg(i, AllArgs[i]); 5086 5087 return false; 5088 } 5089 5090 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5091 const FunctionProtoType *Proto, 5092 unsigned FirstParam, ArrayRef<Expr *> Args, 5093 SmallVectorImpl<Expr *> &AllArgs, 5094 VariadicCallType CallType, bool AllowExplicit, 5095 bool IsListInitialization) { 5096 unsigned NumParams = Proto->getNumParams(); 5097 bool Invalid = false; 5098 size_t ArgIx = 0; 5099 // Continue to check argument types (even if we have too few/many args). 5100 for (unsigned i = FirstParam; i < NumParams; i++) { 5101 QualType ProtoArgType = Proto->getParamType(i); 5102 5103 Expr *Arg; 5104 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5105 if (ArgIx < Args.size()) { 5106 Arg = Args[ArgIx++]; 5107 5108 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5109 diag::err_call_incomplete_argument, Arg)) 5110 return true; 5111 5112 // Strip the unbridged-cast placeholder expression off, if applicable. 5113 bool CFAudited = false; 5114 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5115 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5116 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5117 Arg = stripARCUnbridgedCast(Arg); 5118 else if (getLangOpts().ObjCAutoRefCount && 5119 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5120 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5121 CFAudited = true; 5122 5123 if (Proto->getExtParameterInfo(i).isNoEscape()) 5124 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5125 BE->getBlockDecl()->setDoesNotEscape(); 5126 5127 InitializedEntity Entity = 5128 Param ? InitializedEntity::InitializeParameter(Context, Param, 5129 ProtoArgType) 5130 : InitializedEntity::InitializeParameter( 5131 Context, ProtoArgType, Proto->isParamConsumed(i)); 5132 5133 // Remember that parameter belongs to a CF audited API. 5134 if (CFAudited) 5135 Entity.setParameterCFAudited(); 5136 5137 ExprResult ArgE = PerformCopyInitialization( 5138 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5139 if (ArgE.isInvalid()) 5140 return true; 5141 5142 Arg = ArgE.getAs<Expr>(); 5143 } else { 5144 assert(Param && "can't use default arguments without a known callee"); 5145 5146 ExprResult ArgExpr = 5147 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5148 if (ArgExpr.isInvalid()) 5149 return true; 5150 5151 Arg = ArgExpr.getAs<Expr>(); 5152 } 5153 5154 // Check for array bounds violations for each argument to the call. This 5155 // check only triggers warnings when the argument isn't a more complex Expr 5156 // with its own checking, such as a BinaryOperator. 5157 CheckArrayAccess(Arg); 5158 5159 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5160 CheckStaticArrayArgument(CallLoc, Param, Arg); 5161 5162 AllArgs.push_back(Arg); 5163 } 5164 5165 // If this is a variadic call, handle args passed through "...". 5166 if (CallType != VariadicDoesNotApply) { 5167 // Assume that extern "C" functions with variadic arguments that 5168 // return __unknown_anytype aren't *really* variadic. 5169 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5170 FDecl->isExternC()) { 5171 for (Expr *A : Args.slice(ArgIx)) { 5172 QualType paramType; // ignored 5173 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5174 Invalid |= arg.isInvalid(); 5175 AllArgs.push_back(arg.get()); 5176 } 5177 5178 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5179 } else { 5180 for (Expr *A : Args.slice(ArgIx)) { 5181 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5182 Invalid |= Arg.isInvalid(); 5183 AllArgs.push_back(Arg.get()); 5184 } 5185 } 5186 5187 // Check for array bounds violations. 5188 for (Expr *A : Args.slice(ArgIx)) 5189 CheckArrayAccess(A); 5190 } 5191 return Invalid; 5192 } 5193 5194 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5195 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5196 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5197 TL = DTL.getOriginalLoc(); 5198 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5199 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5200 << ATL.getLocalSourceRange(); 5201 } 5202 5203 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5204 /// array parameter, check that it is non-null, and that if it is formed by 5205 /// array-to-pointer decay, the underlying array is sufficiently large. 5206 /// 5207 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5208 /// array type derivation, then for each call to the function, the value of the 5209 /// corresponding actual argument shall provide access to the first element of 5210 /// an array with at least as many elements as specified by the size expression. 5211 void 5212 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5213 ParmVarDecl *Param, 5214 const Expr *ArgExpr) { 5215 // Static array parameters are not supported in C++. 5216 if (!Param || getLangOpts().CPlusPlus) 5217 return; 5218 5219 QualType OrigTy = Param->getOriginalType(); 5220 5221 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5222 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5223 return; 5224 5225 if (ArgExpr->isNullPointerConstant(Context, 5226 Expr::NPC_NeverValueDependent)) { 5227 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5228 DiagnoseCalleeStaticArrayParam(*this, Param); 5229 return; 5230 } 5231 5232 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5233 if (!CAT) 5234 return; 5235 5236 const ConstantArrayType *ArgCAT = 5237 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5238 if (!ArgCAT) 5239 return; 5240 5241 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5242 ArgCAT->getElementType())) { 5243 if (ArgCAT->getSize().ult(CAT->getSize())) { 5244 Diag(CallLoc, diag::warn_static_array_too_small) 5245 << ArgExpr->getSourceRange() 5246 << (unsigned)ArgCAT->getSize().getZExtValue() 5247 << (unsigned)CAT->getSize().getZExtValue() << 0; 5248 DiagnoseCalleeStaticArrayParam(*this, Param); 5249 } 5250 return; 5251 } 5252 5253 Optional<CharUnits> ArgSize = 5254 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5255 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5256 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5257 Diag(CallLoc, diag::warn_static_array_too_small) 5258 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5259 << (unsigned)ParmSize->getQuantity() << 1; 5260 DiagnoseCalleeStaticArrayParam(*this, Param); 5261 } 5262 } 5263 5264 /// Given a function expression of unknown-any type, try to rebuild it 5265 /// to have a function type. 5266 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5267 5268 /// Is the given type a placeholder that we need to lower out 5269 /// immediately during argument processing? 5270 static bool isPlaceholderToRemoveAsArg(QualType type) { 5271 // Placeholders are never sugared. 5272 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5273 if (!placeholder) return false; 5274 5275 switch (placeholder->getKind()) { 5276 // Ignore all the non-placeholder types. 5277 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5278 case BuiltinType::Id: 5279 #include "clang/Basic/OpenCLImageTypes.def" 5280 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5281 case BuiltinType::Id: 5282 #include "clang/Basic/OpenCLExtensionTypes.def" 5283 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5284 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5285 #include "clang/AST/BuiltinTypes.def" 5286 return false; 5287 5288 // We cannot lower out overload sets; they might validly be resolved 5289 // by the call machinery. 5290 case BuiltinType::Overload: 5291 return false; 5292 5293 // Unbridged casts in ARC can be handled in some call positions and 5294 // should be left in place. 5295 case BuiltinType::ARCUnbridgedCast: 5296 return false; 5297 5298 // Pseudo-objects should be converted as soon as possible. 5299 case BuiltinType::PseudoObject: 5300 return true; 5301 5302 // The debugger mode could theoretically but currently does not try 5303 // to resolve unknown-typed arguments based on known parameter types. 5304 case BuiltinType::UnknownAny: 5305 return true; 5306 5307 // These are always invalid as call arguments and should be reported. 5308 case BuiltinType::BoundMember: 5309 case BuiltinType::BuiltinFn: 5310 case BuiltinType::OMPArraySection: 5311 return true; 5312 5313 } 5314 llvm_unreachable("bad builtin type kind"); 5315 } 5316 5317 /// Check an argument list for placeholders that we won't try to 5318 /// handle later. 5319 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5320 // Apply this processing to all the arguments at once instead of 5321 // dying at the first failure. 5322 bool hasInvalid = false; 5323 for (size_t i = 0, e = args.size(); i != e; i++) { 5324 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5325 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5326 if (result.isInvalid()) hasInvalid = true; 5327 else args[i] = result.get(); 5328 } else if (hasInvalid) { 5329 (void)S.CorrectDelayedTyposInExpr(args[i]); 5330 } 5331 } 5332 return hasInvalid; 5333 } 5334 5335 /// If a builtin function has a pointer argument with no explicit address 5336 /// space, then it should be able to accept a pointer to any address 5337 /// space as input. In order to do this, we need to replace the 5338 /// standard builtin declaration with one that uses the same address space 5339 /// as the call. 5340 /// 5341 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5342 /// it does not contain any pointer arguments without 5343 /// an address space qualifer. Otherwise the rewritten 5344 /// FunctionDecl is returned. 5345 /// TODO: Handle pointer return types. 5346 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5347 const FunctionDecl *FDecl, 5348 MultiExprArg ArgExprs) { 5349 5350 QualType DeclType = FDecl->getType(); 5351 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5352 5353 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5354 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5355 return nullptr; 5356 5357 bool NeedsNewDecl = false; 5358 unsigned i = 0; 5359 SmallVector<QualType, 8> OverloadParams; 5360 5361 for (QualType ParamType : FT->param_types()) { 5362 5363 // Convert array arguments to pointer to simplify type lookup. 5364 ExprResult ArgRes = 5365 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5366 if (ArgRes.isInvalid()) 5367 return nullptr; 5368 Expr *Arg = ArgRes.get(); 5369 QualType ArgType = Arg->getType(); 5370 if (!ParamType->isPointerType() || 5371 ParamType.getQualifiers().hasAddressSpace() || 5372 !ArgType->isPointerType() || 5373 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5374 OverloadParams.push_back(ParamType); 5375 continue; 5376 } 5377 5378 QualType PointeeType = ParamType->getPointeeType(); 5379 if (PointeeType.getQualifiers().hasAddressSpace()) 5380 continue; 5381 5382 NeedsNewDecl = true; 5383 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5384 5385 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5386 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5387 } 5388 5389 if (!NeedsNewDecl) 5390 return nullptr; 5391 5392 FunctionProtoType::ExtProtoInfo EPI; 5393 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5394 OverloadParams, EPI); 5395 DeclContext *Parent = Context.getTranslationUnitDecl(); 5396 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5397 FDecl->getLocation(), 5398 FDecl->getLocation(), 5399 FDecl->getIdentifier(), 5400 OverloadTy, 5401 /*TInfo=*/nullptr, 5402 SC_Extern, false, 5403 /*hasPrototype=*/true); 5404 SmallVector<ParmVarDecl*, 16> Params; 5405 FT = cast<FunctionProtoType>(OverloadTy); 5406 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5407 QualType ParamType = FT->getParamType(i); 5408 ParmVarDecl *Parm = 5409 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5410 SourceLocation(), nullptr, ParamType, 5411 /*TInfo=*/nullptr, SC_None, nullptr); 5412 Parm->setScopeInfo(0, i); 5413 Params.push_back(Parm); 5414 } 5415 OverloadDecl->setParams(Params); 5416 return OverloadDecl; 5417 } 5418 5419 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5420 FunctionDecl *Callee, 5421 MultiExprArg ArgExprs) { 5422 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5423 // similar attributes) really don't like it when functions are called with an 5424 // invalid number of args. 5425 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5426 /*PartialOverloading=*/false) && 5427 !Callee->isVariadic()) 5428 return; 5429 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5430 return; 5431 5432 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5433 S.Diag(Fn->getBeginLoc(), 5434 isa<CXXMethodDecl>(Callee) 5435 ? diag::err_ovl_no_viable_member_function_in_call 5436 : diag::err_ovl_no_viable_function_in_call) 5437 << Callee << Callee->getSourceRange(); 5438 S.Diag(Callee->getLocation(), 5439 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5440 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5441 return; 5442 } 5443 } 5444 5445 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5446 const UnresolvedMemberExpr *const UME, Sema &S) { 5447 5448 const auto GetFunctionLevelDCIfCXXClass = 5449 [](Sema &S) -> const CXXRecordDecl * { 5450 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5451 if (!DC || !DC->getParent()) 5452 return nullptr; 5453 5454 // If the call to some member function was made from within a member 5455 // function body 'M' return return 'M's parent. 5456 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5457 return MD->getParent()->getCanonicalDecl(); 5458 // else the call was made from within a default member initializer of a 5459 // class, so return the class. 5460 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5461 return RD->getCanonicalDecl(); 5462 return nullptr; 5463 }; 5464 // If our DeclContext is neither a member function nor a class (in the 5465 // case of a lambda in a default member initializer), we can't have an 5466 // enclosing 'this'. 5467 5468 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5469 if (!CurParentClass) 5470 return false; 5471 5472 // The naming class for implicit member functions call is the class in which 5473 // name lookup starts. 5474 const CXXRecordDecl *const NamingClass = 5475 UME->getNamingClass()->getCanonicalDecl(); 5476 assert(NamingClass && "Must have naming class even for implicit access"); 5477 5478 // If the unresolved member functions were found in a 'naming class' that is 5479 // related (either the same or derived from) to the class that contains the 5480 // member function that itself contained the implicit member access. 5481 5482 return CurParentClass == NamingClass || 5483 CurParentClass->isDerivedFrom(NamingClass); 5484 } 5485 5486 static void 5487 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5488 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5489 5490 if (!UME) 5491 return; 5492 5493 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5494 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5495 // already been captured, or if this is an implicit member function call (if 5496 // it isn't, an attempt to capture 'this' should already have been made). 5497 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5498 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5499 return; 5500 5501 // Check if the naming class in which the unresolved members were found is 5502 // related (same as or is a base of) to the enclosing class. 5503 5504 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5505 return; 5506 5507 5508 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5509 // If the enclosing function is not dependent, then this lambda is 5510 // capture ready, so if we can capture this, do so. 5511 if (!EnclosingFunctionCtx->isDependentContext()) { 5512 // If the current lambda and all enclosing lambdas can capture 'this' - 5513 // then go ahead and capture 'this' (since our unresolved overload set 5514 // contains at least one non-static member function). 5515 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5516 S.CheckCXXThisCapture(CallLoc); 5517 } else if (S.CurContext->isDependentContext()) { 5518 // ... since this is an implicit member reference, that might potentially 5519 // involve a 'this' capture, mark 'this' for potential capture in 5520 // enclosing lambdas. 5521 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5522 CurLSI->addPotentialThisCapture(CallLoc); 5523 } 5524 } 5525 5526 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5527 /// This provides the location of the left/right parens and a list of comma 5528 /// locations. 5529 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5530 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5531 Expr *ExecConfig, bool IsExecConfig) { 5532 // Since this might be a postfix expression, get rid of ParenListExprs. 5533 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5534 if (Result.isInvalid()) return ExprError(); 5535 Fn = Result.get(); 5536 5537 if (checkArgsForPlaceholders(*this, ArgExprs)) 5538 return ExprError(); 5539 5540 if (getLangOpts().CPlusPlus) { 5541 // If this is a pseudo-destructor expression, build the call immediately. 5542 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5543 if (!ArgExprs.empty()) { 5544 // Pseudo-destructor calls should not have any arguments. 5545 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5546 << FixItHint::CreateRemoval( 5547 SourceRange(ArgExprs.front()->getBeginLoc(), 5548 ArgExprs.back()->getEndLoc())); 5549 } 5550 5551 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5552 VK_RValue, RParenLoc); 5553 } 5554 if (Fn->getType() == Context.PseudoObjectTy) { 5555 ExprResult result = CheckPlaceholderExpr(Fn); 5556 if (result.isInvalid()) return ExprError(); 5557 Fn = result.get(); 5558 } 5559 5560 // Determine whether this is a dependent call inside a C++ template, 5561 // in which case we won't do any semantic analysis now. 5562 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5563 if (ExecConfig) { 5564 return CUDAKernelCallExpr::Create( 5565 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5566 Context.DependentTy, VK_RValue, RParenLoc); 5567 } else { 5568 5569 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5570 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5571 Fn->getBeginLoc()); 5572 5573 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5574 VK_RValue, RParenLoc); 5575 } 5576 } 5577 5578 // Determine whether this is a call to an object (C++ [over.call.object]). 5579 if (Fn->getType()->isRecordType()) 5580 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5581 RParenLoc); 5582 5583 if (Fn->getType() == Context.UnknownAnyTy) { 5584 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5585 if (result.isInvalid()) return ExprError(); 5586 Fn = result.get(); 5587 } 5588 5589 if (Fn->getType() == Context.BoundMemberTy) { 5590 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5591 RParenLoc); 5592 } 5593 } 5594 5595 // Check for overloaded calls. This can happen even in C due to extensions. 5596 if (Fn->getType() == Context.OverloadTy) { 5597 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5598 5599 // We aren't supposed to apply this logic if there's an '&' involved. 5600 if (!find.HasFormOfMemberPointer) { 5601 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5602 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5603 VK_RValue, RParenLoc); 5604 OverloadExpr *ovl = find.Expression; 5605 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5606 return BuildOverloadedCallExpr( 5607 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5608 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5609 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5610 RParenLoc); 5611 } 5612 } 5613 5614 // If we're directly calling a function, get the appropriate declaration. 5615 if (Fn->getType() == Context.UnknownAnyTy) { 5616 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5617 if (result.isInvalid()) return ExprError(); 5618 Fn = result.get(); 5619 } 5620 5621 Expr *NakedFn = Fn->IgnoreParens(); 5622 5623 bool CallingNDeclIndirectly = false; 5624 NamedDecl *NDecl = nullptr; 5625 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5626 if (UnOp->getOpcode() == UO_AddrOf) { 5627 CallingNDeclIndirectly = true; 5628 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5629 } 5630 } 5631 5632 if (isa<DeclRefExpr>(NakedFn)) { 5633 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5634 5635 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5636 if (FDecl && FDecl->getBuiltinID()) { 5637 // Rewrite the function decl for this builtin by replacing parameters 5638 // with no explicit address space with the address space of the arguments 5639 // in ArgExprs. 5640 if ((FDecl = 5641 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5642 NDecl = FDecl; 5643 Fn = DeclRefExpr::Create( 5644 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5645 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5646 } 5647 } 5648 } else if (isa<MemberExpr>(NakedFn)) 5649 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5650 5651 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5652 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5653 FD, /*Complain=*/true, Fn->getBeginLoc())) 5654 return ExprError(); 5655 5656 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5657 return ExprError(); 5658 5659 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5660 } 5661 5662 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5663 ExecConfig, IsExecConfig); 5664 } 5665 5666 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5667 /// 5668 /// __builtin_astype( value, dst type ) 5669 /// 5670 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5671 SourceLocation BuiltinLoc, 5672 SourceLocation RParenLoc) { 5673 ExprValueKind VK = VK_RValue; 5674 ExprObjectKind OK = OK_Ordinary; 5675 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5676 QualType SrcTy = E->getType(); 5677 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5678 return ExprError(Diag(BuiltinLoc, 5679 diag::err_invalid_astype_of_different_size) 5680 << DstTy 5681 << SrcTy 5682 << E->getSourceRange()); 5683 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5684 } 5685 5686 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5687 /// provided arguments. 5688 /// 5689 /// __builtin_convertvector( value, dst type ) 5690 /// 5691 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5692 SourceLocation BuiltinLoc, 5693 SourceLocation RParenLoc) { 5694 TypeSourceInfo *TInfo; 5695 GetTypeFromParser(ParsedDestTy, &TInfo); 5696 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5697 } 5698 5699 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5700 /// i.e. an expression not of \p OverloadTy. The expression should 5701 /// unary-convert to an expression of function-pointer or 5702 /// block-pointer type. 5703 /// 5704 /// \param NDecl the declaration being called, if available 5705 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5706 SourceLocation LParenLoc, 5707 ArrayRef<Expr *> Args, 5708 SourceLocation RParenLoc, Expr *Config, 5709 bool IsExecConfig, ADLCallKind UsesADL) { 5710 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5711 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5712 5713 // Functions with 'interrupt' attribute cannot be called directly. 5714 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5715 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5716 return ExprError(); 5717 } 5718 5719 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5720 // so there's some risk when calling out to non-interrupt handler functions 5721 // that the callee might not preserve them. This is easy to diagnose here, 5722 // but can be very challenging to debug. 5723 if (auto *Caller = getCurFunctionDecl()) 5724 if (Caller->hasAttr<ARMInterruptAttr>()) { 5725 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5726 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5727 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5728 } 5729 5730 // Promote the function operand. 5731 // We special-case function promotion here because we only allow promoting 5732 // builtin functions to function pointers in the callee of a call. 5733 ExprResult Result; 5734 QualType ResultTy; 5735 if (BuiltinID && 5736 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5737 // Extract the return type from the (builtin) function pointer type. 5738 // FIXME Several builtins still have setType in 5739 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5740 // Builtins.def to ensure they are correct before removing setType calls. 5741 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5742 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5743 ResultTy = FDecl->getCallResultType(); 5744 } else { 5745 Result = CallExprUnaryConversions(Fn); 5746 ResultTy = Context.BoolTy; 5747 } 5748 if (Result.isInvalid()) 5749 return ExprError(); 5750 Fn = Result.get(); 5751 5752 // Check for a valid function type, but only if it is not a builtin which 5753 // requires custom type checking. These will be handled by 5754 // CheckBuiltinFunctionCall below just after creation of the call expression. 5755 const FunctionType *FuncT = nullptr; 5756 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5757 retry: 5758 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5759 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5760 // have type pointer to function". 5761 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5762 if (!FuncT) 5763 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5764 << Fn->getType() << Fn->getSourceRange()); 5765 } else if (const BlockPointerType *BPT = 5766 Fn->getType()->getAs<BlockPointerType>()) { 5767 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5768 } else { 5769 // Handle calls to expressions of unknown-any type. 5770 if (Fn->getType() == Context.UnknownAnyTy) { 5771 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5772 if (rewrite.isInvalid()) return ExprError(); 5773 Fn = rewrite.get(); 5774 goto retry; 5775 } 5776 5777 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5778 << Fn->getType() << Fn->getSourceRange()); 5779 } 5780 } 5781 5782 // Get the number of parameters in the function prototype, if any. 5783 // We will allocate space for max(Args.size(), NumParams) arguments 5784 // in the call expression. 5785 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5786 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5787 5788 CallExpr *TheCall; 5789 if (Config) { 5790 assert(UsesADL == ADLCallKind::NotADL && 5791 "CUDAKernelCallExpr should not use ADL"); 5792 TheCall = 5793 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5794 ResultTy, VK_RValue, RParenLoc, NumParams); 5795 } else { 5796 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5797 RParenLoc, NumParams, UsesADL); 5798 } 5799 5800 if (!getLangOpts().CPlusPlus) { 5801 // Forget about the nulled arguments since typo correction 5802 // do not handle them well. 5803 TheCall->shrinkNumArgs(Args.size()); 5804 // C cannot always handle TypoExpr nodes in builtin calls and direct 5805 // function calls as their argument checking don't necessarily handle 5806 // dependent types properly, so make sure any TypoExprs have been 5807 // dealt with. 5808 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5809 if (!Result.isUsable()) return ExprError(); 5810 CallExpr *TheOldCall = TheCall; 5811 TheCall = dyn_cast<CallExpr>(Result.get()); 5812 bool CorrectedTypos = TheCall != TheOldCall; 5813 if (!TheCall) return Result; 5814 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5815 5816 // A new call expression node was created if some typos were corrected. 5817 // However it may not have been constructed with enough storage. In this 5818 // case, rebuild the node with enough storage. The waste of space is 5819 // immaterial since this only happens when some typos were corrected. 5820 if (CorrectedTypos && Args.size() < NumParams) { 5821 if (Config) 5822 TheCall = CUDAKernelCallExpr::Create( 5823 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5824 RParenLoc, NumParams); 5825 else 5826 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5827 RParenLoc, NumParams, UsesADL); 5828 } 5829 // We can now handle the nulled arguments for the default arguments. 5830 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5831 } 5832 5833 // Bail out early if calling a builtin with custom type checking. 5834 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5835 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5836 5837 if (getLangOpts().CUDA) { 5838 if (Config) { 5839 // CUDA: Kernel calls must be to global functions 5840 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5841 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5842 << FDecl << Fn->getSourceRange()); 5843 5844 // CUDA: Kernel function must have 'void' return type 5845 if (!FuncT->getReturnType()->isVoidType()) 5846 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5847 << Fn->getType() << Fn->getSourceRange()); 5848 } else { 5849 // CUDA: Calls to global functions must be configured 5850 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5851 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5852 << FDecl << Fn->getSourceRange()); 5853 } 5854 } 5855 5856 // Check for a valid return type 5857 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5858 FDecl)) 5859 return ExprError(); 5860 5861 // We know the result type of the call, set it. 5862 TheCall->setType(FuncT->getCallResultType(Context)); 5863 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5864 5865 if (Proto) { 5866 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5867 IsExecConfig)) 5868 return ExprError(); 5869 } else { 5870 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5871 5872 if (FDecl) { 5873 // Check if we have too few/too many template arguments, based 5874 // on our knowledge of the function definition. 5875 const FunctionDecl *Def = nullptr; 5876 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5877 Proto = Def->getType()->getAs<FunctionProtoType>(); 5878 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5879 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5880 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5881 } 5882 5883 // If the function we're calling isn't a function prototype, but we have 5884 // a function prototype from a prior declaratiom, use that prototype. 5885 if (!FDecl->hasPrototype()) 5886 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5887 } 5888 5889 // Promote the arguments (C99 6.5.2.2p6). 5890 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5891 Expr *Arg = Args[i]; 5892 5893 if (Proto && i < Proto->getNumParams()) { 5894 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5895 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5896 ExprResult ArgE = 5897 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5898 if (ArgE.isInvalid()) 5899 return true; 5900 5901 Arg = ArgE.getAs<Expr>(); 5902 5903 } else { 5904 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5905 5906 if (ArgE.isInvalid()) 5907 return true; 5908 5909 Arg = ArgE.getAs<Expr>(); 5910 } 5911 5912 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5913 diag::err_call_incomplete_argument, Arg)) 5914 return ExprError(); 5915 5916 TheCall->setArg(i, Arg); 5917 } 5918 } 5919 5920 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5921 if (!Method->isStatic()) 5922 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5923 << Fn->getSourceRange()); 5924 5925 // Check for sentinels 5926 if (NDecl) 5927 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5928 5929 // Do special checking on direct calls to functions. 5930 if (FDecl) { 5931 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5932 return ExprError(); 5933 5934 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 5935 5936 if (BuiltinID) 5937 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5938 } else if (NDecl) { 5939 if (CheckPointerCall(NDecl, TheCall, Proto)) 5940 return ExprError(); 5941 } else { 5942 if (CheckOtherCall(TheCall, Proto)) 5943 return ExprError(); 5944 } 5945 5946 return MaybeBindToTemporary(TheCall); 5947 } 5948 5949 ExprResult 5950 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5951 SourceLocation RParenLoc, Expr *InitExpr) { 5952 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5953 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5954 5955 TypeSourceInfo *TInfo; 5956 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5957 if (!TInfo) 5958 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5959 5960 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5961 } 5962 5963 ExprResult 5964 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5965 SourceLocation RParenLoc, Expr *LiteralExpr) { 5966 QualType literalType = TInfo->getType(); 5967 5968 if (literalType->isArrayType()) { 5969 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5970 diag::err_illegal_decl_array_incomplete_type, 5971 SourceRange(LParenLoc, 5972 LiteralExpr->getSourceRange().getEnd()))) 5973 return ExprError(); 5974 if (literalType->isVariableArrayType()) 5975 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5976 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5977 } else if (!literalType->isDependentType() && 5978 RequireCompleteType(LParenLoc, literalType, 5979 diag::err_typecheck_decl_incomplete_type, 5980 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5981 return ExprError(); 5982 5983 InitializedEntity Entity 5984 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5985 InitializationKind Kind 5986 = InitializationKind::CreateCStyleCast(LParenLoc, 5987 SourceRange(LParenLoc, RParenLoc), 5988 /*InitList=*/true); 5989 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5990 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5991 &literalType); 5992 if (Result.isInvalid()) 5993 return ExprError(); 5994 LiteralExpr = Result.get(); 5995 5996 bool isFileScope = !CurContext->isFunctionOrMethod(); 5997 5998 // In C, compound literals are l-values for some reason. 5999 // For GCC compatibility, in C++, file-scope array compound literals with 6000 // constant initializers are also l-values, and compound literals are 6001 // otherwise prvalues. 6002 // 6003 // (GCC also treats C++ list-initialized file-scope array prvalues with 6004 // constant initializers as l-values, but that's non-conforming, so we don't 6005 // follow it there.) 6006 // 6007 // FIXME: It would be better to handle the lvalue cases as materializing and 6008 // lifetime-extending a temporary object, but our materialized temporaries 6009 // representation only supports lifetime extension from a variable, not "out 6010 // of thin air". 6011 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6012 // is bound to the result of applying array-to-pointer decay to the compound 6013 // literal. 6014 // FIXME: GCC supports compound literals of reference type, which should 6015 // obviously have a value kind derived from the kind of reference involved. 6016 ExprValueKind VK = 6017 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6018 ? VK_RValue 6019 : VK_LValue; 6020 6021 if (isFileScope) 6022 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6023 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6024 Expr *Init = ILE->getInit(i); 6025 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6026 } 6027 6028 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6029 VK, LiteralExpr, isFileScope); 6030 if (isFileScope) { 6031 if (!LiteralExpr->isTypeDependent() && 6032 !LiteralExpr->isValueDependent() && 6033 !literalType->isDependentType()) // C99 6.5.2.5p3 6034 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6035 return ExprError(); 6036 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6037 literalType.getAddressSpace() != LangAS::Default) { 6038 // Embedded-C extensions to C99 6.5.2.5: 6039 // "If the compound literal occurs inside the body of a function, the 6040 // type name shall not be qualified by an address-space qualifier." 6041 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6042 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6043 return ExprError(); 6044 } 6045 6046 return MaybeBindToTemporary(E); 6047 } 6048 6049 ExprResult 6050 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6051 SourceLocation RBraceLoc) { 6052 // Immediately handle non-overload placeholders. Overloads can be 6053 // resolved contextually, but everything else here can't. 6054 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6055 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6056 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6057 6058 // Ignore failures; dropping the entire initializer list because 6059 // of one failure would be terrible for indexing/etc. 6060 if (result.isInvalid()) continue; 6061 6062 InitArgList[I] = result.get(); 6063 } 6064 } 6065 6066 // Semantic analysis for initializers is done by ActOnDeclarator() and 6067 // CheckInitializer() - it requires knowledge of the object being initialized. 6068 6069 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6070 RBraceLoc); 6071 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6072 return E; 6073 } 6074 6075 /// Do an explicit extend of the given block pointer if we're in ARC. 6076 void Sema::maybeExtendBlockObject(ExprResult &E) { 6077 assert(E.get()->getType()->isBlockPointerType()); 6078 assert(E.get()->isRValue()); 6079 6080 // Only do this in an r-value context. 6081 if (!getLangOpts().ObjCAutoRefCount) return; 6082 6083 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6084 CK_ARCExtendBlockObject, E.get(), 6085 /*base path*/ nullptr, VK_RValue); 6086 Cleanup.setExprNeedsCleanups(true); 6087 } 6088 6089 /// Prepare a conversion of the given expression to an ObjC object 6090 /// pointer type. 6091 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6092 QualType type = E.get()->getType(); 6093 if (type->isObjCObjectPointerType()) { 6094 return CK_BitCast; 6095 } else if (type->isBlockPointerType()) { 6096 maybeExtendBlockObject(E); 6097 return CK_BlockPointerToObjCPointerCast; 6098 } else { 6099 assert(type->isPointerType()); 6100 return CK_CPointerToObjCPointerCast; 6101 } 6102 } 6103 6104 /// Prepares for a scalar cast, performing all the necessary stages 6105 /// except the final cast and returning the kind required. 6106 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6107 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6108 // Also, callers should have filtered out the invalid cases with 6109 // pointers. Everything else should be possible. 6110 6111 QualType SrcTy = Src.get()->getType(); 6112 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6113 return CK_NoOp; 6114 6115 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6116 case Type::STK_MemberPointer: 6117 llvm_unreachable("member pointer type in C"); 6118 6119 case Type::STK_CPointer: 6120 case Type::STK_BlockPointer: 6121 case Type::STK_ObjCObjectPointer: 6122 switch (DestTy->getScalarTypeKind()) { 6123 case Type::STK_CPointer: { 6124 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6125 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6126 if (SrcAS != DestAS) 6127 return CK_AddressSpaceConversion; 6128 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6129 return CK_NoOp; 6130 return CK_BitCast; 6131 } 6132 case Type::STK_BlockPointer: 6133 return (SrcKind == Type::STK_BlockPointer 6134 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6135 case Type::STK_ObjCObjectPointer: 6136 if (SrcKind == Type::STK_ObjCObjectPointer) 6137 return CK_BitCast; 6138 if (SrcKind == Type::STK_CPointer) 6139 return CK_CPointerToObjCPointerCast; 6140 maybeExtendBlockObject(Src); 6141 return CK_BlockPointerToObjCPointerCast; 6142 case Type::STK_Bool: 6143 return CK_PointerToBoolean; 6144 case Type::STK_Integral: 6145 return CK_PointerToIntegral; 6146 case Type::STK_Floating: 6147 case Type::STK_FloatingComplex: 6148 case Type::STK_IntegralComplex: 6149 case Type::STK_MemberPointer: 6150 case Type::STK_FixedPoint: 6151 llvm_unreachable("illegal cast from pointer"); 6152 } 6153 llvm_unreachable("Should have returned before this"); 6154 6155 case Type::STK_FixedPoint: 6156 switch (DestTy->getScalarTypeKind()) { 6157 case Type::STK_FixedPoint: 6158 return CK_FixedPointCast; 6159 case Type::STK_Bool: 6160 return CK_FixedPointToBoolean; 6161 case Type::STK_Integral: 6162 return CK_FixedPointToIntegral; 6163 case Type::STK_Floating: 6164 case Type::STK_IntegralComplex: 6165 case Type::STK_FloatingComplex: 6166 Diag(Src.get()->getExprLoc(), 6167 diag::err_unimplemented_conversion_with_fixed_point_type) 6168 << DestTy; 6169 return CK_IntegralCast; 6170 case Type::STK_CPointer: 6171 case Type::STK_ObjCObjectPointer: 6172 case Type::STK_BlockPointer: 6173 case Type::STK_MemberPointer: 6174 llvm_unreachable("illegal cast to pointer type"); 6175 } 6176 llvm_unreachable("Should have returned before this"); 6177 6178 case Type::STK_Bool: // casting from bool is like casting from an integer 6179 case Type::STK_Integral: 6180 switch (DestTy->getScalarTypeKind()) { 6181 case Type::STK_CPointer: 6182 case Type::STK_ObjCObjectPointer: 6183 case Type::STK_BlockPointer: 6184 if (Src.get()->isNullPointerConstant(Context, 6185 Expr::NPC_ValueDependentIsNull)) 6186 return CK_NullToPointer; 6187 return CK_IntegralToPointer; 6188 case Type::STK_Bool: 6189 return CK_IntegralToBoolean; 6190 case Type::STK_Integral: 6191 return CK_IntegralCast; 6192 case Type::STK_Floating: 6193 return CK_IntegralToFloating; 6194 case Type::STK_IntegralComplex: 6195 Src = ImpCastExprToType(Src.get(), 6196 DestTy->castAs<ComplexType>()->getElementType(), 6197 CK_IntegralCast); 6198 return CK_IntegralRealToComplex; 6199 case Type::STK_FloatingComplex: 6200 Src = ImpCastExprToType(Src.get(), 6201 DestTy->castAs<ComplexType>()->getElementType(), 6202 CK_IntegralToFloating); 6203 return CK_FloatingRealToComplex; 6204 case Type::STK_MemberPointer: 6205 llvm_unreachable("member pointer type in C"); 6206 case Type::STK_FixedPoint: 6207 return CK_IntegralToFixedPoint; 6208 } 6209 llvm_unreachable("Should have returned before this"); 6210 6211 case Type::STK_Floating: 6212 switch (DestTy->getScalarTypeKind()) { 6213 case Type::STK_Floating: 6214 return CK_FloatingCast; 6215 case Type::STK_Bool: 6216 return CK_FloatingToBoolean; 6217 case Type::STK_Integral: 6218 return CK_FloatingToIntegral; 6219 case Type::STK_FloatingComplex: 6220 Src = ImpCastExprToType(Src.get(), 6221 DestTy->castAs<ComplexType>()->getElementType(), 6222 CK_FloatingCast); 6223 return CK_FloatingRealToComplex; 6224 case Type::STK_IntegralComplex: 6225 Src = ImpCastExprToType(Src.get(), 6226 DestTy->castAs<ComplexType>()->getElementType(), 6227 CK_FloatingToIntegral); 6228 return CK_IntegralRealToComplex; 6229 case Type::STK_CPointer: 6230 case Type::STK_ObjCObjectPointer: 6231 case Type::STK_BlockPointer: 6232 llvm_unreachable("valid float->pointer cast?"); 6233 case Type::STK_MemberPointer: 6234 llvm_unreachable("member pointer type in C"); 6235 case Type::STK_FixedPoint: 6236 Diag(Src.get()->getExprLoc(), 6237 diag::err_unimplemented_conversion_with_fixed_point_type) 6238 << SrcTy; 6239 return CK_IntegralCast; 6240 } 6241 llvm_unreachable("Should have returned before this"); 6242 6243 case Type::STK_FloatingComplex: 6244 switch (DestTy->getScalarTypeKind()) { 6245 case Type::STK_FloatingComplex: 6246 return CK_FloatingComplexCast; 6247 case Type::STK_IntegralComplex: 6248 return CK_FloatingComplexToIntegralComplex; 6249 case Type::STK_Floating: { 6250 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6251 if (Context.hasSameType(ET, DestTy)) 6252 return CK_FloatingComplexToReal; 6253 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6254 return CK_FloatingCast; 6255 } 6256 case Type::STK_Bool: 6257 return CK_FloatingComplexToBoolean; 6258 case Type::STK_Integral: 6259 Src = ImpCastExprToType(Src.get(), 6260 SrcTy->castAs<ComplexType>()->getElementType(), 6261 CK_FloatingComplexToReal); 6262 return CK_FloatingToIntegral; 6263 case Type::STK_CPointer: 6264 case Type::STK_ObjCObjectPointer: 6265 case Type::STK_BlockPointer: 6266 llvm_unreachable("valid complex float->pointer cast?"); 6267 case Type::STK_MemberPointer: 6268 llvm_unreachable("member pointer type in C"); 6269 case Type::STK_FixedPoint: 6270 Diag(Src.get()->getExprLoc(), 6271 diag::err_unimplemented_conversion_with_fixed_point_type) 6272 << SrcTy; 6273 return CK_IntegralCast; 6274 } 6275 llvm_unreachable("Should have returned before this"); 6276 6277 case Type::STK_IntegralComplex: 6278 switch (DestTy->getScalarTypeKind()) { 6279 case Type::STK_FloatingComplex: 6280 return CK_IntegralComplexToFloatingComplex; 6281 case Type::STK_IntegralComplex: 6282 return CK_IntegralComplexCast; 6283 case Type::STK_Integral: { 6284 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6285 if (Context.hasSameType(ET, DestTy)) 6286 return CK_IntegralComplexToReal; 6287 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6288 return CK_IntegralCast; 6289 } 6290 case Type::STK_Bool: 6291 return CK_IntegralComplexToBoolean; 6292 case Type::STK_Floating: 6293 Src = ImpCastExprToType(Src.get(), 6294 SrcTy->castAs<ComplexType>()->getElementType(), 6295 CK_IntegralComplexToReal); 6296 return CK_IntegralToFloating; 6297 case Type::STK_CPointer: 6298 case Type::STK_ObjCObjectPointer: 6299 case Type::STK_BlockPointer: 6300 llvm_unreachable("valid complex int->pointer cast?"); 6301 case Type::STK_MemberPointer: 6302 llvm_unreachable("member pointer type in C"); 6303 case Type::STK_FixedPoint: 6304 Diag(Src.get()->getExprLoc(), 6305 diag::err_unimplemented_conversion_with_fixed_point_type) 6306 << SrcTy; 6307 return CK_IntegralCast; 6308 } 6309 llvm_unreachable("Should have returned before this"); 6310 } 6311 6312 llvm_unreachable("Unhandled scalar cast"); 6313 } 6314 6315 static bool breakDownVectorType(QualType type, uint64_t &len, 6316 QualType &eltType) { 6317 // Vectors are simple. 6318 if (const VectorType *vecType = type->getAs<VectorType>()) { 6319 len = vecType->getNumElements(); 6320 eltType = vecType->getElementType(); 6321 assert(eltType->isScalarType()); 6322 return true; 6323 } 6324 6325 // We allow lax conversion to and from non-vector types, but only if 6326 // they're real types (i.e. non-complex, non-pointer scalar types). 6327 if (!type->isRealType()) return false; 6328 6329 len = 1; 6330 eltType = type; 6331 return true; 6332 } 6333 6334 /// Are the two types lax-compatible vector types? That is, given 6335 /// that one of them is a vector, do they have equal storage sizes, 6336 /// where the storage size is the number of elements times the element 6337 /// size? 6338 /// 6339 /// This will also return false if either of the types is neither a 6340 /// vector nor a real type. 6341 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6342 assert(destTy->isVectorType() || srcTy->isVectorType()); 6343 6344 // Disallow lax conversions between scalars and ExtVectors (these 6345 // conversions are allowed for other vector types because common headers 6346 // depend on them). Most scalar OP ExtVector cases are handled by the 6347 // splat path anyway, which does what we want (convert, not bitcast). 6348 // What this rules out for ExtVectors is crazy things like char4*float. 6349 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6350 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6351 6352 uint64_t srcLen, destLen; 6353 QualType srcEltTy, destEltTy; 6354 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6355 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6356 6357 // ASTContext::getTypeSize will return the size rounded up to a 6358 // power of 2, so instead of using that, we need to use the raw 6359 // element size multiplied by the element count. 6360 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6361 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6362 6363 return (srcLen * srcEltSize == destLen * destEltSize); 6364 } 6365 6366 /// Is this a legal conversion between two types, one of which is 6367 /// known to be a vector type? 6368 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6369 assert(destTy->isVectorType() || srcTy->isVectorType()); 6370 6371 if (!Context.getLangOpts().LaxVectorConversions) 6372 return false; 6373 return areLaxCompatibleVectorTypes(srcTy, destTy); 6374 } 6375 6376 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6377 CastKind &Kind) { 6378 assert(VectorTy->isVectorType() && "Not a vector type!"); 6379 6380 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6381 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6382 return Diag(R.getBegin(), 6383 Ty->isVectorType() ? 6384 diag::err_invalid_conversion_between_vectors : 6385 diag::err_invalid_conversion_between_vector_and_integer) 6386 << VectorTy << Ty << R; 6387 } else 6388 return Diag(R.getBegin(), 6389 diag::err_invalid_conversion_between_vector_and_scalar) 6390 << VectorTy << Ty << R; 6391 6392 Kind = CK_BitCast; 6393 return false; 6394 } 6395 6396 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6397 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6398 6399 if (DestElemTy == SplattedExpr->getType()) 6400 return SplattedExpr; 6401 6402 assert(DestElemTy->isFloatingType() || 6403 DestElemTy->isIntegralOrEnumerationType()); 6404 6405 CastKind CK; 6406 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6407 // OpenCL requires that we convert `true` boolean expressions to -1, but 6408 // only when splatting vectors. 6409 if (DestElemTy->isFloatingType()) { 6410 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6411 // in two steps: boolean to signed integral, then to floating. 6412 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6413 CK_BooleanToSignedIntegral); 6414 SplattedExpr = CastExprRes.get(); 6415 CK = CK_IntegralToFloating; 6416 } else { 6417 CK = CK_BooleanToSignedIntegral; 6418 } 6419 } else { 6420 ExprResult CastExprRes = SplattedExpr; 6421 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6422 if (CastExprRes.isInvalid()) 6423 return ExprError(); 6424 SplattedExpr = CastExprRes.get(); 6425 } 6426 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6427 } 6428 6429 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6430 Expr *CastExpr, CastKind &Kind) { 6431 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6432 6433 QualType SrcTy = CastExpr->getType(); 6434 6435 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6436 // an ExtVectorType. 6437 // In OpenCL, casts between vectors of different types are not allowed. 6438 // (See OpenCL 6.2). 6439 if (SrcTy->isVectorType()) { 6440 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6441 (getLangOpts().OpenCL && 6442 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6443 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6444 << DestTy << SrcTy << R; 6445 return ExprError(); 6446 } 6447 Kind = CK_BitCast; 6448 return CastExpr; 6449 } 6450 6451 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6452 // conversion will take place first from scalar to elt type, and then 6453 // splat from elt type to vector. 6454 if (SrcTy->isPointerType()) 6455 return Diag(R.getBegin(), 6456 diag::err_invalid_conversion_between_vector_and_scalar) 6457 << DestTy << SrcTy << R; 6458 6459 Kind = CK_VectorSplat; 6460 return prepareVectorSplat(DestTy, CastExpr); 6461 } 6462 6463 ExprResult 6464 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6465 Declarator &D, ParsedType &Ty, 6466 SourceLocation RParenLoc, Expr *CastExpr) { 6467 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6468 "ActOnCastExpr(): missing type or expr"); 6469 6470 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6471 if (D.isInvalidType()) 6472 return ExprError(); 6473 6474 if (getLangOpts().CPlusPlus) { 6475 // Check that there are no default arguments (C++ only). 6476 CheckExtraCXXDefaultArguments(D); 6477 } else { 6478 // Make sure any TypoExprs have been dealt with. 6479 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6480 if (!Res.isUsable()) 6481 return ExprError(); 6482 CastExpr = Res.get(); 6483 } 6484 6485 checkUnusedDeclAttributes(D); 6486 6487 QualType castType = castTInfo->getType(); 6488 Ty = CreateParsedType(castType, castTInfo); 6489 6490 bool isVectorLiteral = false; 6491 6492 // Check for an altivec or OpenCL literal, 6493 // i.e. all the elements are integer constants. 6494 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6495 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6496 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6497 && castType->isVectorType() && (PE || PLE)) { 6498 if (PLE && PLE->getNumExprs() == 0) { 6499 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6500 return ExprError(); 6501 } 6502 if (PE || PLE->getNumExprs() == 1) { 6503 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6504 if (!E->getType()->isVectorType()) 6505 isVectorLiteral = true; 6506 } 6507 else 6508 isVectorLiteral = true; 6509 } 6510 6511 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6512 // then handle it as such. 6513 if (isVectorLiteral) 6514 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6515 6516 // If the Expr being casted is a ParenListExpr, handle it specially. 6517 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6518 // sequence of BinOp comma operators. 6519 if (isa<ParenListExpr>(CastExpr)) { 6520 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6521 if (Result.isInvalid()) return ExprError(); 6522 CastExpr = Result.get(); 6523 } 6524 6525 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6526 !getSourceManager().isInSystemMacro(LParenLoc)) 6527 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6528 6529 CheckTollFreeBridgeCast(castType, CastExpr); 6530 6531 CheckObjCBridgeRelatedCast(castType, CastExpr); 6532 6533 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6534 6535 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6536 } 6537 6538 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6539 SourceLocation RParenLoc, Expr *E, 6540 TypeSourceInfo *TInfo) { 6541 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6542 "Expected paren or paren list expression"); 6543 6544 Expr **exprs; 6545 unsigned numExprs; 6546 Expr *subExpr; 6547 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6548 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6549 LiteralLParenLoc = PE->getLParenLoc(); 6550 LiteralRParenLoc = PE->getRParenLoc(); 6551 exprs = PE->getExprs(); 6552 numExprs = PE->getNumExprs(); 6553 } else { // isa<ParenExpr> by assertion at function entrance 6554 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6555 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6556 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6557 exprs = &subExpr; 6558 numExprs = 1; 6559 } 6560 6561 QualType Ty = TInfo->getType(); 6562 assert(Ty->isVectorType() && "Expected vector type"); 6563 6564 SmallVector<Expr *, 8> initExprs; 6565 const VectorType *VTy = Ty->getAs<VectorType>(); 6566 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6567 6568 // '(...)' form of vector initialization in AltiVec: the number of 6569 // initializers must be one or must match the size of the vector. 6570 // If a single value is specified in the initializer then it will be 6571 // replicated to all the components of the vector 6572 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6573 // The number of initializers must be one or must match the size of the 6574 // vector. If a single value is specified in the initializer then it will 6575 // be replicated to all the components of the vector 6576 if (numExprs == 1) { 6577 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6578 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6579 if (Literal.isInvalid()) 6580 return ExprError(); 6581 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6582 PrepareScalarCast(Literal, ElemTy)); 6583 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6584 } 6585 else if (numExprs < numElems) { 6586 Diag(E->getExprLoc(), 6587 diag::err_incorrect_number_of_vector_initializers); 6588 return ExprError(); 6589 } 6590 else 6591 initExprs.append(exprs, exprs + numExprs); 6592 } 6593 else { 6594 // For OpenCL, when the number of initializers is a single value, 6595 // it will be replicated to all components of the vector. 6596 if (getLangOpts().OpenCL && 6597 VTy->getVectorKind() == VectorType::GenericVector && 6598 numExprs == 1) { 6599 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6600 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6601 if (Literal.isInvalid()) 6602 return ExprError(); 6603 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6604 PrepareScalarCast(Literal, ElemTy)); 6605 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6606 } 6607 6608 initExprs.append(exprs, exprs + numExprs); 6609 } 6610 // FIXME: This means that pretty-printing the final AST will produce curly 6611 // braces instead of the original commas. 6612 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6613 initExprs, LiteralRParenLoc); 6614 initE->setType(Ty); 6615 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6616 } 6617 6618 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6619 /// the ParenListExpr into a sequence of comma binary operators. 6620 ExprResult 6621 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6622 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6623 if (!E) 6624 return OrigExpr; 6625 6626 ExprResult Result(E->getExpr(0)); 6627 6628 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6629 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6630 E->getExpr(i)); 6631 6632 if (Result.isInvalid()) return ExprError(); 6633 6634 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6635 } 6636 6637 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6638 SourceLocation R, 6639 MultiExprArg Val) { 6640 return ParenListExpr::Create(Context, L, Val, R); 6641 } 6642 6643 /// Emit a specialized diagnostic when one expression is a null pointer 6644 /// constant and the other is not a pointer. Returns true if a diagnostic is 6645 /// emitted. 6646 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6647 SourceLocation QuestionLoc) { 6648 Expr *NullExpr = LHSExpr; 6649 Expr *NonPointerExpr = RHSExpr; 6650 Expr::NullPointerConstantKind NullKind = 6651 NullExpr->isNullPointerConstant(Context, 6652 Expr::NPC_ValueDependentIsNotNull); 6653 6654 if (NullKind == Expr::NPCK_NotNull) { 6655 NullExpr = RHSExpr; 6656 NonPointerExpr = LHSExpr; 6657 NullKind = 6658 NullExpr->isNullPointerConstant(Context, 6659 Expr::NPC_ValueDependentIsNotNull); 6660 } 6661 6662 if (NullKind == Expr::NPCK_NotNull) 6663 return false; 6664 6665 if (NullKind == Expr::NPCK_ZeroExpression) 6666 return false; 6667 6668 if (NullKind == Expr::NPCK_ZeroLiteral) { 6669 // In this case, check to make sure that we got here from a "NULL" 6670 // string in the source code. 6671 NullExpr = NullExpr->IgnoreParenImpCasts(); 6672 SourceLocation loc = NullExpr->getExprLoc(); 6673 if (!findMacroSpelling(loc, "NULL")) 6674 return false; 6675 } 6676 6677 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6678 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6679 << NonPointerExpr->getType() << DiagType 6680 << NonPointerExpr->getSourceRange(); 6681 return true; 6682 } 6683 6684 /// Return false if the condition expression is valid, true otherwise. 6685 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6686 QualType CondTy = Cond->getType(); 6687 6688 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6689 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6690 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6691 << CondTy << Cond->getSourceRange(); 6692 return true; 6693 } 6694 6695 // C99 6.5.15p2 6696 if (CondTy->isScalarType()) return false; 6697 6698 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6699 << CondTy << Cond->getSourceRange(); 6700 return true; 6701 } 6702 6703 /// Handle when one or both operands are void type. 6704 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6705 ExprResult &RHS) { 6706 Expr *LHSExpr = LHS.get(); 6707 Expr *RHSExpr = RHS.get(); 6708 6709 if (!LHSExpr->getType()->isVoidType()) 6710 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6711 << RHSExpr->getSourceRange(); 6712 if (!RHSExpr->getType()->isVoidType()) 6713 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6714 << LHSExpr->getSourceRange(); 6715 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6716 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6717 return S.Context.VoidTy; 6718 } 6719 6720 /// Return false if the NullExpr can be promoted to PointerTy, 6721 /// true otherwise. 6722 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6723 QualType PointerTy) { 6724 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6725 !NullExpr.get()->isNullPointerConstant(S.Context, 6726 Expr::NPC_ValueDependentIsNull)) 6727 return true; 6728 6729 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6730 return false; 6731 } 6732 6733 /// Checks compatibility between two pointers and return the resulting 6734 /// type. 6735 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6736 ExprResult &RHS, 6737 SourceLocation Loc) { 6738 QualType LHSTy = LHS.get()->getType(); 6739 QualType RHSTy = RHS.get()->getType(); 6740 6741 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6742 // Two identical pointers types are always compatible. 6743 return LHSTy; 6744 } 6745 6746 QualType lhptee, rhptee; 6747 6748 // Get the pointee types. 6749 bool IsBlockPointer = false; 6750 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6751 lhptee = LHSBTy->getPointeeType(); 6752 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6753 IsBlockPointer = true; 6754 } else { 6755 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6756 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6757 } 6758 6759 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6760 // differently qualified versions of compatible types, the result type is 6761 // a pointer to an appropriately qualified version of the composite 6762 // type. 6763 6764 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6765 // clause doesn't make sense for our extensions. E.g. address space 2 should 6766 // be incompatible with address space 3: they may live on different devices or 6767 // anything. 6768 Qualifiers lhQual = lhptee.getQualifiers(); 6769 Qualifiers rhQual = rhptee.getQualifiers(); 6770 6771 LangAS ResultAddrSpace = LangAS::Default; 6772 LangAS LAddrSpace = lhQual.getAddressSpace(); 6773 LangAS RAddrSpace = rhQual.getAddressSpace(); 6774 6775 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6776 // spaces is disallowed. 6777 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6778 ResultAddrSpace = LAddrSpace; 6779 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6780 ResultAddrSpace = RAddrSpace; 6781 else { 6782 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6783 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6784 << RHS.get()->getSourceRange(); 6785 return QualType(); 6786 } 6787 6788 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6789 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6790 lhQual.removeCVRQualifiers(); 6791 rhQual.removeCVRQualifiers(); 6792 6793 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6794 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6795 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6796 // qual types are compatible iff 6797 // * corresponded types are compatible 6798 // * CVR qualifiers are equal 6799 // * address spaces are equal 6800 // Thus for conditional operator we merge CVR and address space unqualified 6801 // pointees and if there is a composite type we return a pointer to it with 6802 // merged qualifiers. 6803 LHSCastKind = 6804 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6805 RHSCastKind = 6806 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6807 lhQual.removeAddressSpace(); 6808 rhQual.removeAddressSpace(); 6809 6810 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6811 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6812 6813 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6814 6815 if (CompositeTy.isNull()) { 6816 // In this situation, we assume void* type. No especially good 6817 // reason, but this is what gcc does, and we do have to pick 6818 // to get a consistent AST. 6819 QualType incompatTy; 6820 incompatTy = S.Context.getPointerType( 6821 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6822 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6823 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6824 6825 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6826 // for casts between types with incompatible address space qualifiers. 6827 // For the following code the compiler produces casts between global and 6828 // local address spaces of the corresponded innermost pointees: 6829 // local int *global *a; 6830 // global int *global *b; 6831 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6832 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6833 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6834 << RHS.get()->getSourceRange(); 6835 6836 return incompatTy; 6837 } 6838 6839 // The pointer types are compatible. 6840 // In case of OpenCL ResultTy should have the address space qualifier 6841 // which is a superset of address spaces of both the 2nd and the 3rd 6842 // operands of the conditional operator. 6843 QualType ResultTy = [&, ResultAddrSpace]() { 6844 if (S.getLangOpts().OpenCL) { 6845 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6846 CompositeQuals.setAddressSpace(ResultAddrSpace); 6847 return S.Context 6848 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6849 .withCVRQualifiers(MergedCVRQual); 6850 } 6851 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6852 }(); 6853 if (IsBlockPointer) 6854 ResultTy = S.Context.getBlockPointerType(ResultTy); 6855 else 6856 ResultTy = S.Context.getPointerType(ResultTy); 6857 6858 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6859 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6860 return ResultTy; 6861 } 6862 6863 /// Return the resulting type when the operands are both block pointers. 6864 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6865 ExprResult &LHS, 6866 ExprResult &RHS, 6867 SourceLocation Loc) { 6868 QualType LHSTy = LHS.get()->getType(); 6869 QualType RHSTy = RHS.get()->getType(); 6870 6871 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6872 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6873 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6874 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6875 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6876 return destType; 6877 } 6878 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6879 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6880 << RHS.get()->getSourceRange(); 6881 return QualType(); 6882 } 6883 6884 // We have 2 block pointer types. 6885 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6886 } 6887 6888 /// Return the resulting type when the operands are both pointers. 6889 static QualType 6890 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6891 ExprResult &RHS, 6892 SourceLocation Loc) { 6893 // get the pointer types 6894 QualType LHSTy = LHS.get()->getType(); 6895 QualType RHSTy = RHS.get()->getType(); 6896 6897 // get the "pointed to" types 6898 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6899 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6900 6901 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6902 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6903 // Figure out necessary qualifiers (C99 6.5.15p6) 6904 QualType destPointee 6905 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6906 QualType destType = S.Context.getPointerType(destPointee); 6907 // Add qualifiers if necessary. 6908 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6909 // Promote to void*. 6910 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6911 return destType; 6912 } 6913 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6914 QualType destPointee 6915 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6916 QualType destType = S.Context.getPointerType(destPointee); 6917 // Add qualifiers if necessary. 6918 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6919 // Promote to void*. 6920 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6921 return destType; 6922 } 6923 6924 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6925 } 6926 6927 /// Return false if the first expression is not an integer and the second 6928 /// expression is not a pointer, true otherwise. 6929 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6930 Expr* PointerExpr, SourceLocation Loc, 6931 bool IsIntFirstExpr) { 6932 if (!PointerExpr->getType()->isPointerType() || 6933 !Int.get()->getType()->isIntegerType()) 6934 return false; 6935 6936 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6937 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6938 6939 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6940 << Expr1->getType() << Expr2->getType() 6941 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6942 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6943 CK_IntegralToPointer); 6944 return true; 6945 } 6946 6947 /// Simple conversion between integer and floating point types. 6948 /// 6949 /// Used when handling the OpenCL conditional operator where the 6950 /// condition is a vector while the other operands are scalar. 6951 /// 6952 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6953 /// types are either integer or floating type. Between the two 6954 /// operands, the type with the higher rank is defined as the "result 6955 /// type". The other operand needs to be promoted to the same type. No 6956 /// other type promotion is allowed. We cannot use 6957 /// UsualArithmeticConversions() for this purpose, since it always 6958 /// promotes promotable types. 6959 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6960 ExprResult &RHS, 6961 SourceLocation QuestionLoc) { 6962 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6963 if (LHS.isInvalid()) 6964 return QualType(); 6965 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6966 if (RHS.isInvalid()) 6967 return QualType(); 6968 6969 // For conversion purposes, we ignore any qualifiers. 6970 // For example, "const float" and "float" are equivalent. 6971 QualType LHSType = 6972 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6973 QualType RHSType = 6974 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6975 6976 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6977 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6978 << LHSType << LHS.get()->getSourceRange(); 6979 return QualType(); 6980 } 6981 6982 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6983 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6984 << RHSType << RHS.get()->getSourceRange(); 6985 return QualType(); 6986 } 6987 6988 // If both types are identical, no conversion is needed. 6989 if (LHSType == RHSType) 6990 return LHSType; 6991 6992 // Now handle "real" floating types (i.e. float, double, long double). 6993 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6994 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6995 /*IsCompAssign = */ false); 6996 6997 // Finally, we have two differing integer types. 6998 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6999 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7000 } 7001 7002 /// Convert scalar operands to a vector that matches the 7003 /// condition in length. 7004 /// 7005 /// Used when handling the OpenCL conditional operator where the 7006 /// condition is a vector while the other operands are scalar. 7007 /// 7008 /// We first compute the "result type" for the scalar operands 7009 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7010 /// into a vector of that type where the length matches the condition 7011 /// vector type. s6.11.6 requires that the element types of the result 7012 /// and the condition must have the same number of bits. 7013 static QualType 7014 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7015 QualType CondTy, SourceLocation QuestionLoc) { 7016 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7017 if (ResTy.isNull()) return QualType(); 7018 7019 const VectorType *CV = CondTy->getAs<VectorType>(); 7020 assert(CV); 7021 7022 // Determine the vector result type 7023 unsigned NumElements = CV->getNumElements(); 7024 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7025 7026 // Ensure that all types have the same number of bits 7027 if (S.Context.getTypeSize(CV->getElementType()) 7028 != S.Context.getTypeSize(ResTy)) { 7029 // Since VectorTy is created internally, it does not pretty print 7030 // with an OpenCL name. Instead, we just print a description. 7031 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7032 SmallString<64> Str; 7033 llvm::raw_svector_ostream OS(Str); 7034 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7035 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7036 << CondTy << OS.str(); 7037 return QualType(); 7038 } 7039 7040 // Convert operands to the vector result type 7041 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7042 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7043 7044 return VectorTy; 7045 } 7046 7047 /// Return false if this is a valid OpenCL condition vector 7048 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7049 SourceLocation QuestionLoc) { 7050 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7051 // integral type. 7052 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7053 assert(CondTy); 7054 QualType EleTy = CondTy->getElementType(); 7055 if (EleTy->isIntegerType()) return false; 7056 7057 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7058 << Cond->getType() << Cond->getSourceRange(); 7059 return true; 7060 } 7061 7062 /// Return false if the vector condition type and the vector 7063 /// result type are compatible. 7064 /// 7065 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7066 /// number of elements, and their element types have the same number 7067 /// of bits. 7068 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7069 SourceLocation QuestionLoc) { 7070 const VectorType *CV = CondTy->getAs<VectorType>(); 7071 const VectorType *RV = VecResTy->getAs<VectorType>(); 7072 assert(CV && RV); 7073 7074 if (CV->getNumElements() != RV->getNumElements()) { 7075 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7076 << CondTy << VecResTy; 7077 return true; 7078 } 7079 7080 QualType CVE = CV->getElementType(); 7081 QualType RVE = RV->getElementType(); 7082 7083 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7084 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7085 << CondTy << VecResTy; 7086 return true; 7087 } 7088 7089 return false; 7090 } 7091 7092 /// Return the resulting type for the conditional operator in 7093 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7094 /// s6.3.i) when the condition is a vector type. 7095 static QualType 7096 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7097 ExprResult &LHS, ExprResult &RHS, 7098 SourceLocation QuestionLoc) { 7099 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7100 if (Cond.isInvalid()) 7101 return QualType(); 7102 QualType CondTy = Cond.get()->getType(); 7103 7104 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7105 return QualType(); 7106 7107 // If either operand is a vector then find the vector type of the 7108 // result as specified in OpenCL v1.1 s6.3.i. 7109 if (LHS.get()->getType()->isVectorType() || 7110 RHS.get()->getType()->isVectorType()) { 7111 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7112 /*isCompAssign*/false, 7113 /*AllowBothBool*/true, 7114 /*AllowBoolConversions*/false); 7115 if (VecResTy.isNull()) return QualType(); 7116 // The result type must match the condition type as specified in 7117 // OpenCL v1.1 s6.11.6. 7118 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7119 return QualType(); 7120 return VecResTy; 7121 } 7122 7123 // Both operands are scalar. 7124 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7125 } 7126 7127 /// Return true if the Expr is block type 7128 static bool checkBlockType(Sema &S, const Expr *E) { 7129 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7130 QualType Ty = CE->getCallee()->getType(); 7131 if (Ty->isBlockPointerType()) { 7132 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7133 return true; 7134 } 7135 } 7136 return false; 7137 } 7138 7139 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7140 /// In that case, LHS = cond. 7141 /// C99 6.5.15 7142 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7143 ExprResult &RHS, ExprValueKind &VK, 7144 ExprObjectKind &OK, 7145 SourceLocation QuestionLoc) { 7146 7147 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7148 if (!LHSResult.isUsable()) return QualType(); 7149 LHS = LHSResult; 7150 7151 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7152 if (!RHSResult.isUsable()) return QualType(); 7153 RHS = RHSResult; 7154 7155 // C++ is sufficiently different to merit its own checker. 7156 if (getLangOpts().CPlusPlus) 7157 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7158 7159 VK = VK_RValue; 7160 OK = OK_Ordinary; 7161 7162 // The OpenCL operator with a vector condition is sufficiently 7163 // different to merit its own checker. 7164 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7165 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7166 7167 // First, check the condition. 7168 Cond = UsualUnaryConversions(Cond.get()); 7169 if (Cond.isInvalid()) 7170 return QualType(); 7171 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7172 return QualType(); 7173 7174 // Now check the two expressions. 7175 if (LHS.get()->getType()->isVectorType() || 7176 RHS.get()->getType()->isVectorType()) 7177 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7178 /*AllowBothBool*/true, 7179 /*AllowBoolConversions*/false); 7180 7181 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7182 if (LHS.isInvalid() || RHS.isInvalid()) 7183 return QualType(); 7184 7185 QualType LHSTy = LHS.get()->getType(); 7186 QualType RHSTy = RHS.get()->getType(); 7187 7188 // Diagnose attempts to convert between __float128 and long double where 7189 // such conversions currently can't be handled. 7190 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7191 Diag(QuestionLoc, 7192 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7194 return QualType(); 7195 } 7196 7197 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7198 // selection operator (?:). 7199 if (getLangOpts().OpenCL && 7200 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7201 return QualType(); 7202 } 7203 7204 // If both operands have arithmetic type, do the usual arithmetic conversions 7205 // to find a common type: C99 6.5.15p3,5. 7206 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7207 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7208 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7209 7210 return ResTy; 7211 } 7212 7213 // If both operands are the same structure or union type, the result is that 7214 // type. 7215 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7216 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7217 if (LHSRT->getDecl() == RHSRT->getDecl()) 7218 // "If both the operands have structure or union type, the result has 7219 // that type." This implies that CV qualifiers are dropped. 7220 return LHSTy.getUnqualifiedType(); 7221 // FIXME: Type of conditional expression must be complete in C mode. 7222 } 7223 7224 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7225 // The following || allows only one side to be void (a GCC-ism). 7226 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7227 return checkConditionalVoidType(*this, LHS, RHS); 7228 } 7229 7230 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7231 // the type of the other operand." 7232 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7233 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7234 7235 // All objective-c pointer type analysis is done here. 7236 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7237 QuestionLoc); 7238 if (LHS.isInvalid() || RHS.isInvalid()) 7239 return QualType(); 7240 if (!compositeType.isNull()) 7241 return compositeType; 7242 7243 7244 // Handle block pointer types. 7245 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7246 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7247 QuestionLoc); 7248 7249 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7250 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7251 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7252 QuestionLoc); 7253 7254 // GCC compatibility: soften pointer/integer mismatch. Note that 7255 // null pointers have been filtered out by this point. 7256 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7257 /*isIntFirstExpr=*/true)) 7258 return RHSTy; 7259 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7260 /*isIntFirstExpr=*/false)) 7261 return LHSTy; 7262 7263 // Emit a better diagnostic if one of the expressions is a null pointer 7264 // constant and the other is not a pointer type. In this case, the user most 7265 // likely forgot to take the address of the other expression. 7266 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7267 return QualType(); 7268 7269 // Otherwise, the operands are not compatible. 7270 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7271 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7272 << RHS.get()->getSourceRange(); 7273 return QualType(); 7274 } 7275 7276 /// FindCompositeObjCPointerType - Helper method to find composite type of 7277 /// two objective-c pointer types of the two input expressions. 7278 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7279 SourceLocation QuestionLoc) { 7280 QualType LHSTy = LHS.get()->getType(); 7281 QualType RHSTy = RHS.get()->getType(); 7282 7283 // Handle things like Class and struct objc_class*. Here we case the result 7284 // to the pseudo-builtin, because that will be implicitly cast back to the 7285 // redefinition type if an attempt is made to access its fields. 7286 if (LHSTy->isObjCClassType() && 7287 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7288 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7289 return LHSTy; 7290 } 7291 if (RHSTy->isObjCClassType() && 7292 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7293 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7294 return RHSTy; 7295 } 7296 // And the same for struct objc_object* / id 7297 if (LHSTy->isObjCIdType() && 7298 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7299 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7300 return LHSTy; 7301 } 7302 if (RHSTy->isObjCIdType() && 7303 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7304 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7305 return RHSTy; 7306 } 7307 // And the same for struct objc_selector* / SEL 7308 if (Context.isObjCSelType(LHSTy) && 7309 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7310 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7311 return LHSTy; 7312 } 7313 if (Context.isObjCSelType(RHSTy) && 7314 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7315 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7316 return RHSTy; 7317 } 7318 // Check constraints for Objective-C object pointers types. 7319 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7320 7321 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7322 // Two identical object pointer types are always compatible. 7323 return LHSTy; 7324 } 7325 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7326 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7327 QualType compositeType = LHSTy; 7328 7329 // If both operands are interfaces and either operand can be 7330 // assigned to the other, use that type as the composite 7331 // type. This allows 7332 // xxx ? (A*) a : (B*) b 7333 // where B is a subclass of A. 7334 // 7335 // Additionally, as for assignment, if either type is 'id' 7336 // allow silent coercion. Finally, if the types are 7337 // incompatible then make sure to use 'id' as the composite 7338 // type so the result is acceptable for sending messages to. 7339 7340 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7341 // It could return the composite type. 7342 if (!(compositeType = 7343 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7344 // Nothing more to do. 7345 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7346 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7347 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7348 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7349 } else if ((LHSTy->isObjCQualifiedIdType() || 7350 RHSTy->isObjCQualifiedIdType()) && 7351 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7352 // Need to handle "id<xx>" explicitly. 7353 // GCC allows qualified id and any Objective-C type to devolve to 7354 // id. Currently localizing to here until clear this should be 7355 // part of ObjCQualifiedIdTypesAreCompatible. 7356 compositeType = Context.getObjCIdType(); 7357 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7358 compositeType = Context.getObjCIdType(); 7359 } else { 7360 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7361 << LHSTy << RHSTy 7362 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7363 QualType incompatTy = Context.getObjCIdType(); 7364 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7365 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7366 return incompatTy; 7367 } 7368 // The object pointer types are compatible. 7369 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7370 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7371 return compositeType; 7372 } 7373 // Check Objective-C object pointer types and 'void *' 7374 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7375 if (getLangOpts().ObjCAutoRefCount) { 7376 // ARC forbids the implicit conversion of object pointers to 'void *', 7377 // so these types are not compatible. 7378 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7380 LHS = RHS = true; 7381 return QualType(); 7382 } 7383 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7384 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7385 QualType destPointee 7386 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7387 QualType destType = Context.getPointerType(destPointee); 7388 // Add qualifiers if necessary. 7389 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7390 // Promote to void*. 7391 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7392 return destType; 7393 } 7394 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7395 if (getLangOpts().ObjCAutoRefCount) { 7396 // ARC forbids the implicit conversion of object pointers to 'void *', 7397 // so these types are not compatible. 7398 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7399 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7400 LHS = RHS = true; 7401 return QualType(); 7402 } 7403 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7404 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7405 QualType destPointee 7406 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7407 QualType destType = Context.getPointerType(destPointee); 7408 // Add qualifiers if necessary. 7409 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7410 // Promote to void*. 7411 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7412 return destType; 7413 } 7414 return QualType(); 7415 } 7416 7417 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7418 /// ParenRange in parentheses. 7419 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7420 const PartialDiagnostic &Note, 7421 SourceRange ParenRange) { 7422 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7423 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7424 EndLoc.isValid()) { 7425 Self.Diag(Loc, Note) 7426 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7427 << FixItHint::CreateInsertion(EndLoc, ")"); 7428 } else { 7429 // We can't display the parentheses, so just show the bare note. 7430 Self.Diag(Loc, Note) << ParenRange; 7431 } 7432 } 7433 7434 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7435 return BinaryOperator::isAdditiveOp(Opc) || 7436 BinaryOperator::isMultiplicativeOp(Opc) || 7437 BinaryOperator::isShiftOp(Opc); 7438 } 7439 7440 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7441 /// expression, either using a built-in or overloaded operator, 7442 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7443 /// expression. 7444 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7445 Expr **RHSExprs) { 7446 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7447 E = E->IgnoreImpCasts(); 7448 E = E->IgnoreConversionOperator(); 7449 E = E->IgnoreImpCasts(); 7450 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7451 E = MTE->GetTemporaryExpr(); 7452 E = E->IgnoreImpCasts(); 7453 } 7454 7455 // Built-in binary operator. 7456 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7457 if (IsArithmeticOp(OP->getOpcode())) { 7458 *Opcode = OP->getOpcode(); 7459 *RHSExprs = OP->getRHS(); 7460 return true; 7461 } 7462 } 7463 7464 // Overloaded operator. 7465 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7466 if (Call->getNumArgs() != 2) 7467 return false; 7468 7469 // Make sure this is really a binary operator that is safe to pass into 7470 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7471 OverloadedOperatorKind OO = Call->getOperator(); 7472 if (OO < OO_Plus || OO > OO_Arrow || 7473 OO == OO_PlusPlus || OO == OO_MinusMinus) 7474 return false; 7475 7476 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7477 if (IsArithmeticOp(OpKind)) { 7478 *Opcode = OpKind; 7479 *RHSExprs = Call->getArg(1); 7480 return true; 7481 } 7482 } 7483 7484 return false; 7485 } 7486 7487 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7488 /// or is a logical expression such as (x==y) which has int type, but is 7489 /// commonly interpreted as boolean. 7490 static bool ExprLooksBoolean(Expr *E) { 7491 E = E->IgnoreParenImpCasts(); 7492 7493 if (E->getType()->isBooleanType()) 7494 return true; 7495 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7496 return OP->isComparisonOp() || OP->isLogicalOp(); 7497 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7498 return OP->getOpcode() == UO_LNot; 7499 if (E->getType()->isPointerType()) 7500 return true; 7501 // FIXME: What about overloaded operator calls returning "unspecified boolean 7502 // type"s (commonly pointer-to-members)? 7503 7504 return false; 7505 } 7506 7507 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7508 /// and binary operator are mixed in a way that suggests the programmer assumed 7509 /// the conditional operator has higher precedence, for example: 7510 /// "int x = a + someBinaryCondition ? 1 : 2". 7511 static void DiagnoseConditionalPrecedence(Sema &Self, 7512 SourceLocation OpLoc, 7513 Expr *Condition, 7514 Expr *LHSExpr, 7515 Expr *RHSExpr) { 7516 BinaryOperatorKind CondOpcode; 7517 Expr *CondRHS; 7518 7519 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7520 return; 7521 if (!ExprLooksBoolean(CondRHS)) 7522 return; 7523 7524 // The condition is an arithmetic binary expression, with a right- 7525 // hand side that looks boolean, so warn. 7526 7527 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7528 << Condition->getSourceRange() 7529 << BinaryOperator::getOpcodeStr(CondOpcode); 7530 7531 SuggestParentheses( 7532 Self, OpLoc, 7533 Self.PDiag(diag::note_precedence_silence) 7534 << BinaryOperator::getOpcodeStr(CondOpcode), 7535 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7536 7537 SuggestParentheses(Self, OpLoc, 7538 Self.PDiag(diag::note_precedence_conditional_first), 7539 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7540 } 7541 7542 /// Compute the nullability of a conditional expression. 7543 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7544 QualType LHSTy, QualType RHSTy, 7545 ASTContext &Ctx) { 7546 if (!ResTy->isAnyPointerType()) 7547 return ResTy; 7548 7549 auto GetNullability = [&Ctx](QualType Ty) { 7550 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7551 if (Kind) 7552 return *Kind; 7553 return NullabilityKind::Unspecified; 7554 }; 7555 7556 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7557 NullabilityKind MergedKind; 7558 7559 // Compute nullability of a binary conditional expression. 7560 if (IsBin) { 7561 if (LHSKind == NullabilityKind::NonNull) 7562 MergedKind = NullabilityKind::NonNull; 7563 else 7564 MergedKind = RHSKind; 7565 // Compute nullability of a normal conditional expression. 7566 } else { 7567 if (LHSKind == NullabilityKind::Nullable || 7568 RHSKind == NullabilityKind::Nullable) 7569 MergedKind = NullabilityKind::Nullable; 7570 else if (LHSKind == NullabilityKind::NonNull) 7571 MergedKind = RHSKind; 7572 else if (RHSKind == NullabilityKind::NonNull) 7573 MergedKind = LHSKind; 7574 else 7575 MergedKind = NullabilityKind::Unspecified; 7576 } 7577 7578 // Return if ResTy already has the correct nullability. 7579 if (GetNullability(ResTy) == MergedKind) 7580 return ResTy; 7581 7582 // Strip all nullability from ResTy. 7583 while (ResTy->getNullability(Ctx)) 7584 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7585 7586 // Create a new AttributedType with the new nullability kind. 7587 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7588 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7589 } 7590 7591 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7592 /// in the case of a the GNU conditional expr extension. 7593 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7594 SourceLocation ColonLoc, 7595 Expr *CondExpr, Expr *LHSExpr, 7596 Expr *RHSExpr) { 7597 if (!getLangOpts().CPlusPlus) { 7598 // C cannot handle TypoExpr nodes in the condition because it 7599 // doesn't handle dependent types properly, so make sure any TypoExprs have 7600 // been dealt with before checking the operands. 7601 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7602 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7603 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7604 7605 if (!CondResult.isUsable()) 7606 return ExprError(); 7607 7608 if (LHSExpr) { 7609 if (!LHSResult.isUsable()) 7610 return ExprError(); 7611 } 7612 7613 if (!RHSResult.isUsable()) 7614 return ExprError(); 7615 7616 CondExpr = CondResult.get(); 7617 LHSExpr = LHSResult.get(); 7618 RHSExpr = RHSResult.get(); 7619 } 7620 7621 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7622 // was the condition. 7623 OpaqueValueExpr *opaqueValue = nullptr; 7624 Expr *commonExpr = nullptr; 7625 if (!LHSExpr) { 7626 commonExpr = CondExpr; 7627 // Lower out placeholder types first. This is important so that we don't 7628 // try to capture a placeholder. This happens in few cases in C++; such 7629 // as Objective-C++'s dictionary subscripting syntax. 7630 if (commonExpr->hasPlaceholderType()) { 7631 ExprResult result = CheckPlaceholderExpr(commonExpr); 7632 if (!result.isUsable()) return ExprError(); 7633 commonExpr = result.get(); 7634 } 7635 // We usually want to apply unary conversions *before* saving, except 7636 // in the special case of a C++ l-value conditional. 7637 if (!(getLangOpts().CPlusPlus 7638 && !commonExpr->isTypeDependent() 7639 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7640 && commonExpr->isGLValue() 7641 && commonExpr->isOrdinaryOrBitFieldObject() 7642 && RHSExpr->isOrdinaryOrBitFieldObject() 7643 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7644 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7645 if (commonRes.isInvalid()) 7646 return ExprError(); 7647 commonExpr = commonRes.get(); 7648 } 7649 7650 // If the common expression is a class or array prvalue, materialize it 7651 // so that we can safely refer to it multiple times. 7652 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7653 commonExpr->getType()->isArrayType())) { 7654 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7655 if (MatExpr.isInvalid()) 7656 return ExprError(); 7657 commonExpr = MatExpr.get(); 7658 } 7659 7660 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7661 commonExpr->getType(), 7662 commonExpr->getValueKind(), 7663 commonExpr->getObjectKind(), 7664 commonExpr); 7665 LHSExpr = CondExpr = opaqueValue; 7666 } 7667 7668 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7669 ExprValueKind VK = VK_RValue; 7670 ExprObjectKind OK = OK_Ordinary; 7671 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7672 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7673 VK, OK, QuestionLoc); 7674 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7675 RHS.isInvalid()) 7676 return ExprError(); 7677 7678 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7679 RHS.get()); 7680 7681 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7682 7683 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7684 Context); 7685 7686 if (!commonExpr) 7687 return new (Context) 7688 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7689 RHS.get(), result, VK, OK); 7690 7691 return new (Context) BinaryConditionalOperator( 7692 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7693 ColonLoc, result, VK, OK); 7694 } 7695 7696 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7697 // being closely modeled after the C99 spec:-). The odd characteristic of this 7698 // routine is it effectively iqnores the qualifiers on the top level pointee. 7699 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7700 // FIXME: add a couple examples in this comment. 7701 static Sema::AssignConvertType 7702 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7703 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7704 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7705 7706 // get the "pointed to" type (ignoring qualifiers at the top level) 7707 const Type *lhptee, *rhptee; 7708 Qualifiers lhq, rhq; 7709 std::tie(lhptee, lhq) = 7710 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7711 std::tie(rhptee, rhq) = 7712 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7713 7714 Sema::AssignConvertType ConvTy = Sema::Compatible; 7715 7716 // C99 6.5.16.1p1: This following citation is common to constraints 7717 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7718 // qualifiers of the type *pointed to* by the right; 7719 7720 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7721 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7722 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7723 // Ignore lifetime for further calculation. 7724 lhq.removeObjCLifetime(); 7725 rhq.removeObjCLifetime(); 7726 } 7727 7728 if (!lhq.compatiblyIncludes(rhq)) { 7729 // Treat address-space mismatches as fatal. TODO: address subspaces 7730 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7731 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7732 7733 // It's okay to add or remove GC or lifetime qualifiers when converting to 7734 // and from void*. 7735 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7736 .compatiblyIncludes( 7737 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7738 && (lhptee->isVoidType() || rhptee->isVoidType())) 7739 ; // keep old 7740 7741 // Treat lifetime mismatches as fatal. 7742 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7743 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7744 7745 // For GCC/MS compatibility, other qualifier mismatches are treated 7746 // as still compatible in C. 7747 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7748 } 7749 7750 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7751 // incomplete type and the other is a pointer to a qualified or unqualified 7752 // version of void... 7753 if (lhptee->isVoidType()) { 7754 if (rhptee->isIncompleteOrObjectType()) 7755 return ConvTy; 7756 7757 // As an extension, we allow cast to/from void* to function pointer. 7758 assert(rhptee->isFunctionType()); 7759 return Sema::FunctionVoidPointer; 7760 } 7761 7762 if (rhptee->isVoidType()) { 7763 if (lhptee->isIncompleteOrObjectType()) 7764 return ConvTy; 7765 7766 // As an extension, we allow cast to/from void* to function pointer. 7767 assert(lhptee->isFunctionType()); 7768 return Sema::FunctionVoidPointer; 7769 } 7770 7771 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7772 // unqualified versions of compatible types, ... 7773 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7774 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7775 // Check if the pointee types are compatible ignoring the sign. 7776 // We explicitly check for char so that we catch "char" vs 7777 // "unsigned char" on systems where "char" is unsigned. 7778 if (lhptee->isCharType()) 7779 ltrans = S.Context.UnsignedCharTy; 7780 else if (lhptee->hasSignedIntegerRepresentation()) 7781 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7782 7783 if (rhptee->isCharType()) 7784 rtrans = S.Context.UnsignedCharTy; 7785 else if (rhptee->hasSignedIntegerRepresentation()) 7786 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7787 7788 if (ltrans == rtrans) { 7789 // Types are compatible ignoring the sign. Qualifier incompatibility 7790 // takes priority over sign incompatibility because the sign 7791 // warning can be disabled. 7792 if (ConvTy != Sema::Compatible) 7793 return ConvTy; 7794 7795 return Sema::IncompatiblePointerSign; 7796 } 7797 7798 // If we are a multi-level pointer, it's possible that our issue is simply 7799 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7800 // the eventual target type is the same and the pointers have the same 7801 // level of indirection, this must be the issue. 7802 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7803 do { 7804 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7805 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7806 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7807 7808 if (lhptee == rhptee) 7809 return Sema::IncompatibleNestedPointerQualifiers; 7810 } 7811 7812 // General pointer incompatibility takes priority over qualifiers. 7813 return Sema::IncompatiblePointer; 7814 } 7815 if (!S.getLangOpts().CPlusPlus && 7816 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7817 return Sema::IncompatiblePointer; 7818 return ConvTy; 7819 } 7820 7821 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7822 /// block pointer types are compatible or whether a block and normal pointer 7823 /// are compatible. It is more restrict than comparing two function pointer 7824 // types. 7825 static Sema::AssignConvertType 7826 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7827 QualType RHSType) { 7828 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7829 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7830 7831 QualType lhptee, rhptee; 7832 7833 // get the "pointed to" type (ignoring qualifiers at the top level) 7834 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7835 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7836 7837 // In C++, the types have to match exactly. 7838 if (S.getLangOpts().CPlusPlus) 7839 return Sema::IncompatibleBlockPointer; 7840 7841 Sema::AssignConvertType ConvTy = Sema::Compatible; 7842 7843 // For blocks we enforce that qualifiers are identical. 7844 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7845 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7846 if (S.getLangOpts().OpenCL) { 7847 LQuals.removeAddressSpace(); 7848 RQuals.removeAddressSpace(); 7849 } 7850 if (LQuals != RQuals) 7851 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7852 7853 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7854 // assignment. 7855 // The current behavior is similar to C++ lambdas. A block might be 7856 // assigned to a variable iff its return type and parameters are compatible 7857 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7858 // an assignment. Presumably it should behave in way that a function pointer 7859 // assignment does in C, so for each parameter and return type: 7860 // * CVR and address space of LHS should be a superset of CVR and address 7861 // space of RHS. 7862 // * unqualified types should be compatible. 7863 if (S.getLangOpts().OpenCL) { 7864 if (!S.Context.typesAreBlockPointerCompatible( 7865 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7866 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7867 return Sema::IncompatibleBlockPointer; 7868 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7869 return Sema::IncompatibleBlockPointer; 7870 7871 return ConvTy; 7872 } 7873 7874 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7875 /// for assignment compatibility. 7876 static Sema::AssignConvertType 7877 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7878 QualType RHSType) { 7879 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7880 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7881 7882 if (LHSType->isObjCBuiltinType()) { 7883 // Class is not compatible with ObjC object pointers. 7884 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7885 !RHSType->isObjCQualifiedClassType()) 7886 return Sema::IncompatiblePointer; 7887 return Sema::Compatible; 7888 } 7889 if (RHSType->isObjCBuiltinType()) { 7890 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7891 !LHSType->isObjCQualifiedClassType()) 7892 return Sema::IncompatiblePointer; 7893 return Sema::Compatible; 7894 } 7895 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7896 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7897 7898 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7899 // make an exception for id<P> 7900 !LHSType->isObjCQualifiedIdType()) 7901 return Sema::CompatiblePointerDiscardsQualifiers; 7902 7903 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7904 return Sema::Compatible; 7905 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7906 return Sema::IncompatibleObjCQualifiedId; 7907 return Sema::IncompatiblePointer; 7908 } 7909 7910 Sema::AssignConvertType 7911 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7912 QualType LHSType, QualType RHSType) { 7913 // Fake up an opaque expression. We don't actually care about what 7914 // cast operations are required, so if CheckAssignmentConstraints 7915 // adds casts to this they'll be wasted, but fortunately that doesn't 7916 // usually happen on valid code. 7917 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7918 ExprResult RHSPtr = &RHSExpr; 7919 CastKind K; 7920 7921 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7922 } 7923 7924 /// This helper function returns true if QT is a vector type that has element 7925 /// type ElementType. 7926 static bool isVector(QualType QT, QualType ElementType) { 7927 if (const VectorType *VT = QT->getAs<VectorType>()) 7928 return VT->getElementType() == ElementType; 7929 return false; 7930 } 7931 7932 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7933 /// has code to accommodate several GCC extensions when type checking 7934 /// pointers. Here are some objectionable examples that GCC considers warnings: 7935 /// 7936 /// int a, *pint; 7937 /// short *pshort; 7938 /// struct foo *pfoo; 7939 /// 7940 /// pint = pshort; // warning: assignment from incompatible pointer type 7941 /// a = pint; // warning: assignment makes integer from pointer without a cast 7942 /// pint = a; // warning: assignment makes pointer from integer without a cast 7943 /// pint = pfoo; // warning: assignment from incompatible pointer type 7944 /// 7945 /// As a result, the code for dealing with pointers is more complex than the 7946 /// C99 spec dictates. 7947 /// 7948 /// Sets 'Kind' for any result kind except Incompatible. 7949 Sema::AssignConvertType 7950 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7951 CastKind &Kind, bool ConvertRHS) { 7952 QualType RHSType = RHS.get()->getType(); 7953 QualType OrigLHSType = LHSType; 7954 7955 // Get canonical types. We're not formatting these types, just comparing 7956 // them. 7957 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7958 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7959 7960 // Common case: no conversion required. 7961 if (LHSType == RHSType) { 7962 Kind = CK_NoOp; 7963 return Compatible; 7964 } 7965 7966 // If we have an atomic type, try a non-atomic assignment, then just add an 7967 // atomic qualification step. 7968 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7969 Sema::AssignConvertType result = 7970 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7971 if (result != Compatible) 7972 return result; 7973 if (Kind != CK_NoOp && ConvertRHS) 7974 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7975 Kind = CK_NonAtomicToAtomic; 7976 return Compatible; 7977 } 7978 7979 // If the left-hand side is a reference type, then we are in a 7980 // (rare!) case where we've allowed the use of references in C, 7981 // e.g., as a parameter type in a built-in function. In this case, 7982 // just make sure that the type referenced is compatible with the 7983 // right-hand side type. The caller is responsible for adjusting 7984 // LHSType so that the resulting expression does not have reference 7985 // type. 7986 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7987 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7988 Kind = CK_LValueBitCast; 7989 return Compatible; 7990 } 7991 return Incompatible; 7992 } 7993 7994 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7995 // to the same ExtVector type. 7996 if (LHSType->isExtVectorType()) { 7997 if (RHSType->isExtVectorType()) 7998 return Incompatible; 7999 if (RHSType->isArithmeticType()) { 8000 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8001 if (ConvertRHS) 8002 RHS = prepareVectorSplat(LHSType, RHS.get()); 8003 Kind = CK_VectorSplat; 8004 return Compatible; 8005 } 8006 } 8007 8008 // Conversions to or from vector type. 8009 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8010 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8011 // Allow assignments of an AltiVec vector type to an equivalent GCC 8012 // vector type and vice versa 8013 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8014 Kind = CK_BitCast; 8015 return Compatible; 8016 } 8017 8018 // If we are allowing lax vector conversions, and LHS and RHS are both 8019 // vectors, the total size only needs to be the same. This is a bitcast; 8020 // no bits are changed but the result type is different. 8021 if (isLaxVectorConversion(RHSType, LHSType)) { 8022 Kind = CK_BitCast; 8023 return IncompatibleVectors; 8024 } 8025 } 8026 8027 // When the RHS comes from another lax conversion (e.g. binops between 8028 // scalars and vectors) the result is canonicalized as a vector. When the 8029 // LHS is also a vector, the lax is allowed by the condition above. Handle 8030 // the case where LHS is a scalar. 8031 if (LHSType->isScalarType()) { 8032 const VectorType *VecType = RHSType->getAs<VectorType>(); 8033 if (VecType && VecType->getNumElements() == 1 && 8034 isLaxVectorConversion(RHSType, LHSType)) { 8035 ExprResult *VecExpr = &RHS; 8036 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8037 Kind = CK_BitCast; 8038 return Compatible; 8039 } 8040 } 8041 8042 return Incompatible; 8043 } 8044 8045 // Diagnose attempts to convert between __float128 and long double where 8046 // such conversions currently can't be handled. 8047 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8048 return Incompatible; 8049 8050 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8051 // discards the imaginary part. 8052 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8053 !LHSType->getAs<ComplexType>()) 8054 return Incompatible; 8055 8056 // Arithmetic conversions. 8057 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8058 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8059 if (ConvertRHS) 8060 Kind = PrepareScalarCast(RHS, LHSType); 8061 return Compatible; 8062 } 8063 8064 // Conversions to normal pointers. 8065 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8066 // U* -> T* 8067 if (isa<PointerType>(RHSType)) { 8068 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8069 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8070 if (AddrSpaceL != AddrSpaceR) 8071 Kind = CK_AddressSpaceConversion; 8072 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8073 Kind = CK_NoOp; 8074 else 8075 Kind = CK_BitCast; 8076 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8077 } 8078 8079 // int -> T* 8080 if (RHSType->isIntegerType()) { 8081 Kind = CK_IntegralToPointer; // FIXME: null? 8082 return IntToPointer; 8083 } 8084 8085 // C pointers are not compatible with ObjC object pointers, 8086 // with two exceptions: 8087 if (isa<ObjCObjectPointerType>(RHSType)) { 8088 // - conversions to void* 8089 if (LHSPointer->getPointeeType()->isVoidType()) { 8090 Kind = CK_BitCast; 8091 return Compatible; 8092 } 8093 8094 // - conversions from 'Class' to the redefinition type 8095 if (RHSType->isObjCClassType() && 8096 Context.hasSameType(LHSType, 8097 Context.getObjCClassRedefinitionType())) { 8098 Kind = CK_BitCast; 8099 return Compatible; 8100 } 8101 8102 Kind = CK_BitCast; 8103 return IncompatiblePointer; 8104 } 8105 8106 // U^ -> void* 8107 if (RHSType->getAs<BlockPointerType>()) { 8108 if (LHSPointer->getPointeeType()->isVoidType()) { 8109 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8110 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8111 ->getPointeeType() 8112 .getAddressSpace(); 8113 Kind = 8114 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8115 return Compatible; 8116 } 8117 } 8118 8119 return Incompatible; 8120 } 8121 8122 // Conversions to block pointers. 8123 if (isa<BlockPointerType>(LHSType)) { 8124 // U^ -> T^ 8125 if (RHSType->isBlockPointerType()) { 8126 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8127 ->getPointeeType() 8128 .getAddressSpace(); 8129 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8130 ->getPointeeType() 8131 .getAddressSpace(); 8132 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8133 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8134 } 8135 8136 // int or null -> T^ 8137 if (RHSType->isIntegerType()) { 8138 Kind = CK_IntegralToPointer; // FIXME: null 8139 return IntToBlockPointer; 8140 } 8141 8142 // id -> T^ 8143 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8144 Kind = CK_AnyPointerToBlockPointerCast; 8145 return Compatible; 8146 } 8147 8148 // void* -> T^ 8149 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8150 if (RHSPT->getPointeeType()->isVoidType()) { 8151 Kind = CK_AnyPointerToBlockPointerCast; 8152 return Compatible; 8153 } 8154 8155 return Incompatible; 8156 } 8157 8158 // Conversions to Objective-C pointers. 8159 if (isa<ObjCObjectPointerType>(LHSType)) { 8160 // A* -> B* 8161 if (RHSType->isObjCObjectPointerType()) { 8162 Kind = CK_BitCast; 8163 Sema::AssignConvertType result = 8164 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8165 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8166 result == Compatible && 8167 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8168 result = IncompatibleObjCWeakRef; 8169 return result; 8170 } 8171 8172 // int or null -> A* 8173 if (RHSType->isIntegerType()) { 8174 Kind = CK_IntegralToPointer; // FIXME: null 8175 return IntToPointer; 8176 } 8177 8178 // In general, C pointers are not compatible with ObjC object pointers, 8179 // with two exceptions: 8180 if (isa<PointerType>(RHSType)) { 8181 Kind = CK_CPointerToObjCPointerCast; 8182 8183 // - conversions from 'void*' 8184 if (RHSType->isVoidPointerType()) { 8185 return Compatible; 8186 } 8187 8188 // - conversions to 'Class' from its redefinition type 8189 if (LHSType->isObjCClassType() && 8190 Context.hasSameType(RHSType, 8191 Context.getObjCClassRedefinitionType())) { 8192 return Compatible; 8193 } 8194 8195 return IncompatiblePointer; 8196 } 8197 8198 // Only under strict condition T^ is compatible with an Objective-C pointer. 8199 if (RHSType->isBlockPointerType() && 8200 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8201 if (ConvertRHS) 8202 maybeExtendBlockObject(RHS); 8203 Kind = CK_BlockPointerToObjCPointerCast; 8204 return Compatible; 8205 } 8206 8207 return Incompatible; 8208 } 8209 8210 // Conversions from pointers that are not covered by the above. 8211 if (isa<PointerType>(RHSType)) { 8212 // T* -> _Bool 8213 if (LHSType == Context.BoolTy) { 8214 Kind = CK_PointerToBoolean; 8215 return Compatible; 8216 } 8217 8218 // T* -> int 8219 if (LHSType->isIntegerType()) { 8220 Kind = CK_PointerToIntegral; 8221 return PointerToInt; 8222 } 8223 8224 return Incompatible; 8225 } 8226 8227 // Conversions from Objective-C pointers that are not covered by the above. 8228 if (isa<ObjCObjectPointerType>(RHSType)) { 8229 // T* -> _Bool 8230 if (LHSType == Context.BoolTy) { 8231 Kind = CK_PointerToBoolean; 8232 return Compatible; 8233 } 8234 8235 // T* -> int 8236 if (LHSType->isIntegerType()) { 8237 Kind = CK_PointerToIntegral; 8238 return PointerToInt; 8239 } 8240 8241 return Incompatible; 8242 } 8243 8244 // struct A -> struct B 8245 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8246 if (Context.typesAreCompatible(LHSType, RHSType)) { 8247 Kind = CK_NoOp; 8248 return Compatible; 8249 } 8250 } 8251 8252 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8253 Kind = CK_IntToOCLSampler; 8254 return Compatible; 8255 } 8256 8257 return Incompatible; 8258 } 8259 8260 /// Constructs a transparent union from an expression that is 8261 /// used to initialize the transparent union. 8262 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8263 ExprResult &EResult, QualType UnionType, 8264 FieldDecl *Field) { 8265 // Build an initializer list that designates the appropriate member 8266 // of the transparent union. 8267 Expr *E = EResult.get(); 8268 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8269 E, SourceLocation()); 8270 Initializer->setType(UnionType); 8271 Initializer->setInitializedFieldInUnion(Field); 8272 8273 // Build a compound literal constructing a value of the transparent 8274 // union type from this initializer list. 8275 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8276 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8277 VK_RValue, Initializer, false); 8278 } 8279 8280 Sema::AssignConvertType 8281 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8282 ExprResult &RHS) { 8283 QualType RHSType = RHS.get()->getType(); 8284 8285 // If the ArgType is a Union type, we want to handle a potential 8286 // transparent_union GCC extension. 8287 const RecordType *UT = ArgType->getAsUnionType(); 8288 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8289 return Incompatible; 8290 8291 // The field to initialize within the transparent union. 8292 RecordDecl *UD = UT->getDecl(); 8293 FieldDecl *InitField = nullptr; 8294 // It's compatible if the expression matches any of the fields. 8295 for (auto *it : UD->fields()) { 8296 if (it->getType()->isPointerType()) { 8297 // If the transparent union contains a pointer type, we allow: 8298 // 1) void pointer 8299 // 2) null pointer constant 8300 if (RHSType->isPointerType()) 8301 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8302 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8303 InitField = it; 8304 break; 8305 } 8306 8307 if (RHS.get()->isNullPointerConstant(Context, 8308 Expr::NPC_ValueDependentIsNull)) { 8309 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8310 CK_NullToPointer); 8311 InitField = it; 8312 break; 8313 } 8314 } 8315 8316 CastKind Kind; 8317 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8318 == Compatible) { 8319 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8320 InitField = it; 8321 break; 8322 } 8323 } 8324 8325 if (!InitField) 8326 return Incompatible; 8327 8328 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8329 return Compatible; 8330 } 8331 8332 Sema::AssignConvertType 8333 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8334 bool Diagnose, 8335 bool DiagnoseCFAudited, 8336 bool ConvertRHS) { 8337 // We need to be able to tell the caller whether we diagnosed a problem, if 8338 // they ask us to issue diagnostics. 8339 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8340 8341 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8342 // we can't avoid *all* modifications at the moment, so we need some somewhere 8343 // to put the updated value. 8344 ExprResult LocalRHS = CallerRHS; 8345 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8346 8347 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8348 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8349 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8350 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8351 Diag(RHS.get()->getExprLoc(), 8352 diag::warn_noderef_to_dereferenceable_pointer) 8353 << RHS.get()->getSourceRange(); 8354 } 8355 } 8356 } 8357 8358 if (getLangOpts().CPlusPlus) { 8359 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8360 // C++ 5.17p3: If the left operand is not of class type, the 8361 // expression is implicitly converted (C++ 4) to the 8362 // cv-unqualified type of the left operand. 8363 QualType RHSType = RHS.get()->getType(); 8364 if (Diagnose) { 8365 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8366 AA_Assigning); 8367 } else { 8368 ImplicitConversionSequence ICS = 8369 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8370 /*SuppressUserConversions=*/false, 8371 /*AllowExplicit=*/false, 8372 /*InOverloadResolution=*/false, 8373 /*CStyle=*/false, 8374 /*AllowObjCWritebackConversion=*/false); 8375 if (ICS.isFailure()) 8376 return Incompatible; 8377 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8378 ICS, AA_Assigning); 8379 } 8380 if (RHS.isInvalid()) 8381 return Incompatible; 8382 Sema::AssignConvertType result = Compatible; 8383 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8384 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8385 result = IncompatibleObjCWeakRef; 8386 return result; 8387 } 8388 8389 // FIXME: Currently, we fall through and treat C++ classes like C 8390 // structures. 8391 // FIXME: We also fall through for atomics; not sure what should 8392 // happen there, though. 8393 } else if (RHS.get()->getType() == Context.OverloadTy) { 8394 // As a set of extensions to C, we support overloading on functions. These 8395 // functions need to be resolved here. 8396 DeclAccessPair DAP; 8397 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8398 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8399 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8400 else 8401 return Incompatible; 8402 } 8403 8404 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8405 // a null pointer constant. 8406 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8407 LHSType->isBlockPointerType()) && 8408 RHS.get()->isNullPointerConstant(Context, 8409 Expr::NPC_ValueDependentIsNull)) { 8410 if (Diagnose || ConvertRHS) { 8411 CastKind Kind; 8412 CXXCastPath Path; 8413 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8414 /*IgnoreBaseAccess=*/false, Diagnose); 8415 if (ConvertRHS) 8416 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8417 } 8418 return Compatible; 8419 } 8420 8421 // OpenCL queue_t type assignment. 8422 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8423 Context, Expr::NPC_ValueDependentIsNull)) { 8424 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8425 return Compatible; 8426 } 8427 8428 // This check seems unnatural, however it is necessary to ensure the proper 8429 // conversion of functions/arrays. If the conversion were done for all 8430 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8431 // expressions that suppress this implicit conversion (&, sizeof). 8432 // 8433 // Suppress this for references: C++ 8.5.3p5. 8434 if (!LHSType->isReferenceType()) { 8435 // FIXME: We potentially allocate here even if ConvertRHS is false. 8436 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8437 if (RHS.isInvalid()) 8438 return Incompatible; 8439 } 8440 CastKind Kind; 8441 Sema::AssignConvertType result = 8442 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8443 8444 // C99 6.5.16.1p2: The value of the right operand is converted to the 8445 // type of the assignment expression. 8446 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8447 // so that we can use references in built-in functions even in C. 8448 // The getNonReferenceType() call makes sure that the resulting expression 8449 // does not have reference type. 8450 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8451 QualType Ty = LHSType.getNonLValueExprType(Context); 8452 Expr *E = RHS.get(); 8453 8454 // Check for various Objective-C errors. If we are not reporting 8455 // diagnostics and just checking for errors, e.g., during overload 8456 // resolution, return Incompatible to indicate the failure. 8457 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8458 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8459 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8460 if (!Diagnose) 8461 return Incompatible; 8462 } 8463 if (getLangOpts().ObjC && 8464 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8465 E->getType(), E, Diagnose) || 8466 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8467 if (!Diagnose) 8468 return Incompatible; 8469 // Replace the expression with a corrected version and continue so we 8470 // can find further errors. 8471 RHS = E; 8472 return Compatible; 8473 } 8474 8475 if (ConvertRHS) 8476 RHS = ImpCastExprToType(E, Ty, Kind); 8477 } 8478 8479 return result; 8480 } 8481 8482 namespace { 8483 /// The original operand to an operator, prior to the application of the usual 8484 /// arithmetic conversions and converting the arguments of a builtin operator 8485 /// candidate. 8486 struct OriginalOperand { 8487 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8488 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8489 Op = MTE->GetTemporaryExpr(); 8490 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8491 Op = BTE->getSubExpr(); 8492 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8493 Orig = ICE->getSubExprAsWritten(); 8494 Conversion = ICE->getConversionFunction(); 8495 } 8496 } 8497 8498 QualType getType() const { return Orig->getType(); } 8499 8500 Expr *Orig; 8501 NamedDecl *Conversion; 8502 }; 8503 } 8504 8505 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8506 ExprResult &RHS) { 8507 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8508 8509 Diag(Loc, diag::err_typecheck_invalid_operands) 8510 << OrigLHS.getType() << OrigRHS.getType() 8511 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8512 8513 // If a user-defined conversion was applied to either of the operands prior 8514 // to applying the built-in operator rules, tell the user about it. 8515 if (OrigLHS.Conversion) { 8516 Diag(OrigLHS.Conversion->getLocation(), 8517 diag::note_typecheck_invalid_operands_converted) 8518 << 0 << LHS.get()->getType(); 8519 } 8520 if (OrigRHS.Conversion) { 8521 Diag(OrigRHS.Conversion->getLocation(), 8522 diag::note_typecheck_invalid_operands_converted) 8523 << 1 << RHS.get()->getType(); 8524 } 8525 8526 return QualType(); 8527 } 8528 8529 // Diagnose cases where a scalar was implicitly converted to a vector and 8530 // diagnose the underlying types. Otherwise, diagnose the error 8531 // as invalid vector logical operands for non-C++ cases. 8532 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8533 ExprResult &RHS) { 8534 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8535 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8536 8537 bool LHSNatVec = LHSType->isVectorType(); 8538 bool RHSNatVec = RHSType->isVectorType(); 8539 8540 if (!(LHSNatVec && RHSNatVec)) { 8541 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8542 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8543 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8544 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8545 << Vector->getSourceRange(); 8546 return QualType(); 8547 } 8548 8549 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8550 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8551 << RHS.get()->getSourceRange(); 8552 8553 return QualType(); 8554 } 8555 8556 /// Try to convert a value of non-vector type to a vector type by converting 8557 /// the type to the element type of the vector and then performing a splat. 8558 /// If the language is OpenCL, we only use conversions that promote scalar 8559 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8560 /// for float->int. 8561 /// 8562 /// OpenCL V2.0 6.2.6.p2: 8563 /// An error shall occur if any scalar operand type has greater rank 8564 /// than the type of the vector element. 8565 /// 8566 /// \param scalar - if non-null, actually perform the conversions 8567 /// \return true if the operation fails (but without diagnosing the failure) 8568 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8569 QualType scalarTy, 8570 QualType vectorEltTy, 8571 QualType vectorTy, 8572 unsigned &DiagID) { 8573 // The conversion to apply to the scalar before splatting it, 8574 // if necessary. 8575 CastKind scalarCast = CK_NoOp; 8576 8577 if (vectorEltTy->isIntegralType(S.Context)) { 8578 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8579 (scalarTy->isIntegerType() && 8580 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8581 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8582 return true; 8583 } 8584 if (!scalarTy->isIntegralType(S.Context)) 8585 return true; 8586 scalarCast = CK_IntegralCast; 8587 } else if (vectorEltTy->isRealFloatingType()) { 8588 if (scalarTy->isRealFloatingType()) { 8589 if (S.getLangOpts().OpenCL && 8590 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8591 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8592 return true; 8593 } 8594 scalarCast = CK_FloatingCast; 8595 } 8596 else if (scalarTy->isIntegralType(S.Context)) 8597 scalarCast = CK_IntegralToFloating; 8598 else 8599 return true; 8600 } else { 8601 return true; 8602 } 8603 8604 // Adjust scalar if desired. 8605 if (scalar) { 8606 if (scalarCast != CK_NoOp) 8607 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8608 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8609 } 8610 return false; 8611 } 8612 8613 /// Convert vector E to a vector with the same number of elements but different 8614 /// element type. 8615 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8616 const auto *VecTy = E->getType()->getAs<VectorType>(); 8617 assert(VecTy && "Expression E must be a vector"); 8618 QualType NewVecTy = S.Context.getVectorType(ElementType, 8619 VecTy->getNumElements(), 8620 VecTy->getVectorKind()); 8621 8622 // Look through the implicit cast. Return the subexpression if its type is 8623 // NewVecTy. 8624 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8625 if (ICE->getSubExpr()->getType() == NewVecTy) 8626 return ICE->getSubExpr(); 8627 8628 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8629 return S.ImpCastExprToType(E, NewVecTy, Cast); 8630 } 8631 8632 /// Test if a (constant) integer Int can be casted to another integer type 8633 /// IntTy without losing precision. 8634 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8635 QualType OtherIntTy) { 8636 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8637 8638 // Reject cases where the value of the Int is unknown as that would 8639 // possibly cause truncation, but accept cases where the scalar can be 8640 // demoted without loss of precision. 8641 Expr::EvalResult EVResult; 8642 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8643 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8644 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8645 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8646 8647 if (CstInt) { 8648 // If the scalar is constant and is of a higher order and has more active 8649 // bits that the vector element type, reject it. 8650 llvm::APSInt Result = EVResult.Val.getInt(); 8651 unsigned NumBits = IntSigned 8652 ? (Result.isNegative() ? Result.getMinSignedBits() 8653 : Result.getActiveBits()) 8654 : Result.getActiveBits(); 8655 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8656 return true; 8657 8658 // If the signedness of the scalar type and the vector element type 8659 // differs and the number of bits is greater than that of the vector 8660 // element reject it. 8661 return (IntSigned != OtherIntSigned && 8662 NumBits > S.Context.getIntWidth(OtherIntTy)); 8663 } 8664 8665 // Reject cases where the value of the scalar is not constant and it's 8666 // order is greater than that of the vector element type. 8667 return (Order < 0); 8668 } 8669 8670 /// Test if a (constant) integer Int can be casted to floating point type 8671 /// FloatTy without losing precision. 8672 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8673 QualType FloatTy) { 8674 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8675 8676 // Determine if the integer constant can be expressed as a floating point 8677 // number of the appropriate type. 8678 Expr::EvalResult EVResult; 8679 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8680 8681 uint64_t Bits = 0; 8682 if (CstInt) { 8683 // Reject constants that would be truncated if they were converted to 8684 // the floating point type. Test by simple to/from conversion. 8685 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8686 // could be avoided if there was a convertFromAPInt method 8687 // which could signal back if implicit truncation occurred. 8688 llvm::APSInt Result = EVResult.Val.getInt(); 8689 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8690 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8691 llvm::APFloat::rmTowardZero); 8692 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8693 !IntTy->hasSignedIntegerRepresentation()); 8694 bool Ignored = false; 8695 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8696 &Ignored); 8697 if (Result != ConvertBack) 8698 return true; 8699 } else { 8700 // Reject types that cannot be fully encoded into the mantissa of 8701 // the float. 8702 Bits = S.Context.getTypeSize(IntTy); 8703 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8704 S.Context.getFloatTypeSemantics(FloatTy)); 8705 if (Bits > FloatPrec) 8706 return true; 8707 } 8708 8709 return false; 8710 } 8711 8712 /// Attempt to convert and splat Scalar into a vector whose types matches 8713 /// Vector following GCC conversion rules. The rule is that implicit 8714 /// conversion can occur when Scalar can be casted to match Vector's element 8715 /// type without causing truncation of Scalar. 8716 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8717 ExprResult *Vector) { 8718 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8719 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8720 const VectorType *VT = VectorTy->getAs<VectorType>(); 8721 8722 assert(!isa<ExtVectorType>(VT) && 8723 "ExtVectorTypes should not be handled here!"); 8724 8725 QualType VectorEltTy = VT->getElementType(); 8726 8727 // Reject cases where the vector element type or the scalar element type are 8728 // not integral or floating point types. 8729 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8730 return true; 8731 8732 // The conversion to apply to the scalar before splatting it, 8733 // if necessary. 8734 CastKind ScalarCast = CK_NoOp; 8735 8736 // Accept cases where the vector elements are integers and the scalar is 8737 // an integer. 8738 // FIXME: Notionally if the scalar was a floating point value with a precise 8739 // integral representation, we could cast it to an appropriate integer 8740 // type and then perform the rest of the checks here. GCC will perform 8741 // this conversion in some cases as determined by the input language. 8742 // We should accept it on a language independent basis. 8743 if (VectorEltTy->isIntegralType(S.Context) && 8744 ScalarTy->isIntegralType(S.Context) && 8745 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8746 8747 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8748 return true; 8749 8750 ScalarCast = CK_IntegralCast; 8751 } else if (VectorEltTy->isRealFloatingType()) { 8752 if (ScalarTy->isRealFloatingType()) { 8753 8754 // Reject cases where the scalar type is not a constant and has a higher 8755 // Order than the vector element type. 8756 llvm::APFloat Result(0.0); 8757 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8758 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8759 if (!CstScalar && Order < 0) 8760 return true; 8761 8762 // If the scalar cannot be safely casted to the vector element type, 8763 // reject it. 8764 if (CstScalar) { 8765 bool Truncated = false; 8766 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8767 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8768 if (Truncated) 8769 return true; 8770 } 8771 8772 ScalarCast = CK_FloatingCast; 8773 } else if (ScalarTy->isIntegralType(S.Context)) { 8774 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8775 return true; 8776 8777 ScalarCast = CK_IntegralToFloating; 8778 } else 8779 return true; 8780 } 8781 8782 // Adjust scalar if desired. 8783 if (Scalar) { 8784 if (ScalarCast != CK_NoOp) 8785 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8786 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8787 } 8788 return false; 8789 } 8790 8791 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8792 SourceLocation Loc, bool IsCompAssign, 8793 bool AllowBothBool, 8794 bool AllowBoolConversions) { 8795 if (!IsCompAssign) { 8796 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8797 if (LHS.isInvalid()) 8798 return QualType(); 8799 } 8800 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8801 if (RHS.isInvalid()) 8802 return QualType(); 8803 8804 // For conversion purposes, we ignore any qualifiers. 8805 // For example, "const float" and "float" are equivalent. 8806 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8807 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8808 8809 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8810 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8811 assert(LHSVecType || RHSVecType); 8812 8813 // AltiVec-style "vector bool op vector bool" combinations are allowed 8814 // for some operators but not others. 8815 if (!AllowBothBool && 8816 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8817 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8818 return InvalidOperands(Loc, LHS, RHS); 8819 8820 // If the vector types are identical, return. 8821 if (Context.hasSameType(LHSType, RHSType)) 8822 return LHSType; 8823 8824 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8825 if (LHSVecType && RHSVecType && 8826 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8827 if (isa<ExtVectorType>(LHSVecType)) { 8828 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8829 return LHSType; 8830 } 8831 8832 if (!IsCompAssign) 8833 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8834 return RHSType; 8835 } 8836 8837 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8838 // can be mixed, with the result being the non-bool type. The non-bool 8839 // operand must have integer element type. 8840 if (AllowBoolConversions && LHSVecType && RHSVecType && 8841 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8842 (Context.getTypeSize(LHSVecType->getElementType()) == 8843 Context.getTypeSize(RHSVecType->getElementType()))) { 8844 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8845 LHSVecType->getElementType()->isIntegerType() && 8846 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8847 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8848 return LHSType; 8849 } 8850 if (!IsCompAssign && 8851 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8852 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8853 RHSVecType->getElementType()->isIntegerType()) { 8854 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8855 return RHSType; 8856 } 8857 } 8858 8859 // If there's a vector type and a scalar, try to convert the scalar to 8860 // the vector element type and splat. 8861 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8862 if (!RHSVecType) { 8863 if (isa<ExtVectorType>(LHSVecType)) { 8864 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8865 LHSVecType->getElementType(), LHSType, 8866 DiagID)) 8867 return LHSType; 8868 } else { 8869 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8870 return LHSType; 8871 } 8872 } 8873 if (!LHSVecType) { 8874 if (isa<ExtVectorType>(RHSVecType)) { 8875 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8876 LHSType, RHSVecType->getElementType(), 8877 RHSType, DiagID)) 8878 return RHSType; 8879 } else { 8880 if (LHS.get()->getValueKind() == VK_LValue || 8881 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8882 return RHSType; 8883 } 8884 } 8885 8886 // FIXME: The code below also handles conversion between vectors and 8887 // non-scalars, we should break this down into fine grained specific checks 8888 // and emit proper diagnostics. 8889 QualType VecType = LHSVecType ? LHSType : RHSType; 8890 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8891 QualType OtherType = LHSVecType ? RHSType : LHSType; 8892 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8893 if (isLaxVectorConversion(OtherType, VecType)) { 8894 // If we're allowing lax vector conversions, only the total (data) size 8895 // needs to be the same. For non compound assignment, if one of the types is 8896 // scalar, the result is always the vector type. 8897 if (!IsCompAssign) { 8898 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8899 return VecType; 8900 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8901 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8902 // type. Note that this is already done by non-compound assignments in 8903 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8904 // <1 x T> -> T. The result is also a vector type. 8905 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8906 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8907 ExprResult *RHSExpr = &RHS; 8908 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8909 return VecType; 8910 } 8911 } 8912 8913 // Okay, the expression is invalid. 8914 8915 // If there's a non-vector, non-real operand, diagnose that. 8916 if ((!RHSVecType && !RHSType->isRealType()) || 8917 (!LHSVecType && !LHSType->isRealType())) { 8918 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8919 << LHSType << RHSType 8920 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8921 return QualType(); 8922 } 8923 8924 // OpenCL V1.1 6.2.6.p1: 8925 // If the operands are of more than one vector type, then an error shall 8926 // occur. Implicit conversions between vector types are not permitted, per 8927 // section 6.2.1. 8928 if (getLangOpts().OpenCL && 8929 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8930 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8931 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8932 << RHSType; 8933 return QualType(); 8934 } 8935 8936 8937 // If there is a vector type that is not a ExtVector and a scalar, we reach 8938 // this point if scalar could not be converted to the vector's element type 8939 // without truncation. 8940 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8941 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8942 QualType Scalar = LHSVecType ? RHSType : LHSType; 8943 QualType Vector = LHSVecType ? LHSType : RHSType; 8944 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8945 Diag(Loc, 8946 diag::err_typecheck_vector_not_convertable_implict_truncation) 8947 << ScalarOrVector << Scalar << Vector; 8948 8949 return QualType(); 8950 } 8951 8952 // Otherwise, use the generic diagnostic. 8953 Diag(Loc, DiagID) 8954 << LHSType << RHSType 8955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8956 return QualType(); 8957 } 8958 8959 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8960 // expression. These are mainly cases where the null pointer is used as an 8961 // integer instead of a pointer. 8962 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8963 SourceLocation Loc, bool IsCompare) { 8964 // The canonical way to check for a GNU null is with isNullPointerConstant, 8965 // but we use a bit of a hack here for speed; this is a relatively 8966 // hot path, and isNullPointerConstant is slow. 8967 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8968 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8969 8970 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8971 8972 // Avoid analyzing cases where the result will either be invalid (and 8973 // diagnosed as such) or entirely valid and not something to warn about. 8974 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8975 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8976 return; 8977 8978 // Comparison operations would not make sense with a null pointer no matter 8979 // what the other expression is. 8980 if (!IsCompare) { 8981 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8982 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8983 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8984 return; 8985 } 8986 8987 // The rest of the operations only make sense with a null pointer 8988 // if the other expression is a pointer. 8989 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8990 NonNullType->canDecayToPointerType()) 8991 return; 8992 8993 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8994 << LHSNull /* LHS is NULL */ << NonNullType 8995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8996 } 8997 8998 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8999 SourceLocation Loc) { 9000 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9001 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9002 if (!LUE || !RUE) 9003 return; 9004 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9005 RUE->getKind() != UETT_SizeOf) 9006 return; 9007 9008 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 9009 QualType RHSTy; 9010 9011 if (RUE->isArgumentType()) 9012 RHSTy = RUE->getArgumentType(); 9013 else 9014 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9015 9016 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 9017 return; 9018 if (LHSTy->getPointeeType() != RHSTy) 9019 return; 9020 9021 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9022 } 9023 9024 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9025 ExprResult &RHS, 9026 SourceLocation Loc, bool IsDiv) { 9027 // Check for division/remainder by zero. 9028 Expr::EvalResult RHSValue; 9029 if (!RHS.get()->isValueDependent() && 9030 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9031 RHSValue.Val.getInt() == 0) 9032 S.DiagRuntimeBehavior(Loc, RHS.get(), 9033 S.PDiag(diag::warn_remainder_division_by_zero) 9034 << IsDiv << RHS.get()->getSourceRange()); 9035 } 9036 9037 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9038 SourceLocation Loc, 9039 bool IsCompAssign, bool IsDiv) { 9040 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9041 9042 if (LHS.get()->getType()->isVectorType() || 9043 RHS.get()->getType()->isVectorType()) 9044 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9045 /*AllowBothBool*/getLangOpts().AltiVec, 9046 /*AllowBoolConversions*/false); 9047 9048 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9049 if (LHS.isInvalid() || RHS.isInvalid()) 9050 return QualType(); 9051 9052 9053 if (compType.isNull() || !compType->isArithmeticType()) 9054 return InvalidOperands(Loc, LHS, RHS); 9055 if (IsDiv) { 9056 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9057 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 9058 } 9059 return compType; 9060 } 9061 9062 QualType Sema::CheckRemainderOperands( 9063 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9064 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9065 9066 if (LHS.get()->getType()->isVectorType() || 9067 RHS.get()->getType()->isVectorType()) { 9068 if (LHS.get()->getType()->hasIntegerRepresentation() && 9069 RHS.get()->getType()->hasIntegerRepresentation()) 9070 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9071 /*AllowBothBool*/getLangOpts().AltiVec, 9072 /*AllowBoolConversions*/false); 9073 return InvalidOperands(Loc, LHS, RHS); 9074 } 9075 9076 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 9077 if (LHS.isInvalid() || RHS.isInvalid()) 9078 return QualType(); 9079 9080 if (compType.isNull() || !compType->isIntegerType()) 9081 return InvalidOperands(Loc, LHS, RHS); 9082 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9083 return compType; 9084 } 9085 9086 /// Diagnose invalid arithmetic on two void pointers. 9087 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9088 Expr *LHSExpr, Expr *RHSExpr) { 9089 S.Diag(Loc, S.getLangOpts().CPlusPlus 9090 ? diag::err_typecheck_pointer_arith_void_type 9091 : diag::ext_gnu_void_ptr) 9092 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9093 << RHSExpr->getSourceRange(); 9094 } 9095 9096 /// Diagnose invalid arithmetic on a void pointer. 9097 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9098 Expr *Pointer) { 9099 S.Diag(Loc, S.getLangOpts().CPlusPlus 9100 ? diag::err_typecheck_pointer_arith_void_type 9101 : diag::ext_gnu_void_ptr) 9102 << 0 /* one pointer */ << Pointer->getSourceRange(); 9103 } 9104 9105 /// Diagnose invalid arithmetic on a null pointer. 9106 /// 9107 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9108 /// idiom, which we recognize as a GNU extension. 9109 /// 9110 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9111 Expr *Pointer, bool IsGNUIdiom) { 9112 if (IsGNUIdiom) 9113 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9114 << Pointer->getSourceRange(); 9115 else 9116 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9117 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9118 } 9119 9120 /// Diagnose invalid arithmetic on two function pointers. 9121 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9122 Expr *LHS, Expr *RHS) { 9123 assert(LHS->getType()->isAnyPointerType()); 9124 assert(RHS->getType()->isAnyPointerType()); 9125 S.Diag(Loc, S.getLangOpts().CPlusPlus 9126 ? diag::err_typecheck_pointer_arith_function_type 9127 : diag::ext_gnu_ptr_func_arith) 9128 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9129 // We only show the second type if it differs from the first. 9130 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9131 RHS->getType()) 9132 << RHS->getType()->getPointeeType() 9133 << LHS->getSourceRange() << RHS->getSourceRange(); 9134 } 9135 9136 /// Diagnose invalid arithmetic on a function pointer. 9137 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9138 Expr *Pointer) { 9139 assert(Pointer->getType()->isAnyPointerType()); 9140 S.Diag(Loc, S.getLangOpts().CPlusPlus 9141 ? diag::err_typecheck_pointer_arith_function_type 9142 : diag::ext_gnu_ptr_func_arith) 9143 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9144 << 0 /* one pointer, so only one type */ 9145 << Pointer->getSourceRange(); 9146 } 9147 9148 /// Emit error if Operand is incomplete pointer type 9149 /// 9150 /// \returns True if pointer has incomplete type 9151 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9152 Expr *Operand) { 9153 QualType ResType = Operand->getType(); 9154 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9155 ResType = ResAtomicType->getValueType(); 9156 9157 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9158 QualType PointeeTy = ResType->getPointeeType(); 9159 return S.RequireCompleteType(Loc, PointeeTy, 9160 diag::err_typecheck_arithmetic_incomplete_type, 9161 PointeeTy, Operand->getSourceRange()); 9162 } 9163 9164 /// Check the validity of an arithmetic pointer operand. 9165 /// 9166 /// If the operand has pointer type, this code will check for pointer types 9167 /// which are invalid in arithmetic operations. These will be diagnosed 9168 /// appropriately, including whether or not the use is supported as an 9169 /// extension. 9170 /// 9171 /// \returns True when the operand is valid to use (even if as an extension). 9172 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9173 Expr *Operand) { 9174 QualType ResType = Operand->getType(); 9175 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9176 ResType = ResAtomicType->getValueType(); 9177 9178 if (!ResType->isAnyPointerType()) return true; 9179 9180 QualType PointeeTy = ResType->getPointeeType(); 9181 if (PointeeTy->isVoidType()) { 9182 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9183 return !S.getLangOpts().CPlusPlus; 9184 } 9185 if (PointeeTy->isFunctionType()) { 9186 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9187 return !S.getLangOpts().CPlusPlus; 9188 } 9189 9190 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9191 9192 return true; 9193 } 9194 9195 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9196 /// operands. 9197 /// 9198 /// This routine will diagnose any invalid arithmetic on pointer operands much 9199 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9200 /// for emitting a single diagnostic even for operations where both LHS and RHS 9201 /// are (potentially problematic) pointers. 9202 /// 9203 /// \returns True when the operand is valid to use (even if as an extension). 9204 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9205 Expr *LHSExpr, Expr *RHSExpr) { 9206 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9207 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9208 if (!isLHSPointer && !isRHSPointer) return true; 9209 9210 QualType LHSPointeeTy, RHSPointeeTy; 9211 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9212 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9213 9214 // if both are pointers check if operation is valid wrt address spaces 9215 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9216 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9217 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9218 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9219 S.Diag(Loc, 9220 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9221 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9222 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9223 return false; 9224 } 9225 } 9226 9227 // Check for arithmetic on pointers to incomplete types. 9228 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9229 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9230 if (isLHSVoidPtr || isRHSVoidPtr) { 9231 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9232 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9233 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9234 9235 return !S.getLangOpts().CPlusPlus; 9236 } 9237 9238 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9239 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9240 if (isLHSFuncPtr || isRHSFuncPtr) { 9241 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9242 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9243 RHSExpr); 9244 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9245 9246 return !S.getLangOpts().CPlusPlus; 9247 } 9248 9249 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9250 return false; 9251 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9252 return false; 9253 9254 return true; 9255 } 9256 9257 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9258 /// literal. 9259 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9260 Expr *LHSExpr, Expr *RHSExpr) { 9261 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9262 Expr* IndexExpr = RHSExpr; 9263 if (!StrExpr) { 9264 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9265 IndexExpr = LHSExpr; 9266 } 9267 9268 bool IsStringPlusInt = StrExpr && 9269 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9270 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9271 return; 9272 9273 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9274 Self.Diag(OpLoc, diag::warn_string_plus_int) 9275 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9276 9277 // Only print a fixit for "str" + int, not for int + "str". 9278 if (IndexExpr == RHSExpr) { 9279 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9280 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9281 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9282 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9283 << FixItHint::CreateInsertion(EndLoc, "]"); 9284 } else 9285 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9286 } 9287 9288 /// Emit a warning when adding a char literal to a string. 9289 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9290 Expr *LHSExpr, Expr *RHSExpr) { 9291 const Expr *StringRefExpr = LHSExpr; 9292 const CharacterLiteral *CharExpr = 9293 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9294 9295 if (!CharExpr) { 9296 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9297 StringRefExpr = RHSExpr; 9298 } 9299 9300 if (!CharExpr || !StringRefExpr) 9301 return; 9302 9303 const QualType StringType = StringRefExpr->getType(); 9304 9305 // Return if not a PointerType. 9306 if (!StringType->isAnyPointerType()) 9307 return; 9308 9309 // Return if not a CharacterType. 9310 if (!StringType->getPointeeType()->isAnyCharacterType()) 9311 return; 9312 9313 ASTContext &Ctx = Self.getASTContext(); 9314 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9315 9316 const QualType CharType = CharExpr->getType(); 9317 if (!CharType->isAnyCharacterType() && 9318 CharType->isIntegerType() && 9319 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9320 Self.Diag(OpLoc, diag::warn_string_plus_char) 9321 << DiagRange << Ctx.CharTy; 9322 } else { 9323 Self.Diag(OpLoc, diag::warn_string_plus_char) 9324 << DiagRange << CharExpr->getType(); 9325 } 9326 9327 // Only print a fixit for str + char, not for char + str. 9328 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9329 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9330 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9331 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9332 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9333 << FixItHint::CreateInsertion(EndLoc, "]"); 9334 } else { 9335 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9336 } 9337 } 9338 9339 /// Emit error when two pointers are incompatible. 9340 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9341 Expr *LHSExpr, Expr *RHSExpr) { 9342 assert(LHSExpr->getType()->isAnyPointerType()); 9343 assert(RHSExpr->getType()->isAnyPointerType()); 9344 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9345 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9346 << RHSExpr->getSourceRange(); 9347 } 9348 9349 // C99 6.5.6 9350 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9351 SourceLocation Loc, BinaryOperatorKind Opc, 9352 QualType* CompLHSTy) { 9353 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9354 9355 if (LHS.get()->getType()->isVectorType() || 9356 RHS.get()->getType()->isVectorType()) { 9357 QualType compType = CheckVectorOperands( 9358 LHS, RHS, Loc, CompLHSTy, 9359 /*AllowBothBool*/getLangOpts().AltiVec, 9360 /*AllowBoolConversions*/getLangOpts().ZVector); 9361 if (CompLHSTy) *CompLHSTy = compType; 9362 return compType; 9363 } 9364 9365 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9366 if (LHS.isInvalid() || RHS.isInvalid()) 9367 return QualType(); 9368 9369 // Diagnose "string literal" '+' int and string '+' "char literal". 9370 if (Opc == BO_Add) { 9371 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9372 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9373 } 9374 9375 // handle the common case first (both operands are arithmetic). 9376 if (!compType.isNull() && compType->isArithmeticType()) { 9377 if (CompLHSTy) *CompLHSTy = compType; 9378 return compType; 9379 } 9380 9381 // Type-checking. Ultimately the pointer's going to be in PExp; 9382 // note that we bias towards the LHS being the pointer. 9383 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9384 9385 bool isObjCPointer; 9386 if (PExp->getType()->isPointerType()) { 9387 isObjCPointer = false; 9388 } else if (PExp->getType()->isObjCObjectPointerType()) { 9389 isObjCPointer = true; 9390 } else { 9391 std::swap(PExp, IExp); 9392 if (PExp->getType()->isPointerType()) { 9393 isObjCPointer = false; 9394 } else if (PExp->getType()->isObjCObjectPointerType()) { 9395 isObjCPointer = true; 9396 } else { 9397 return InvalidOperands(Loc, LHS, RHS); 9398 } 9399 } 9400 assert(PExp->getType()->isAnyPointerType()); 9401 9402 if (!IExp->getType()->isIntegerType()) 9403 return InvalidOperands(Loc, LHS, RHS); 9404 9405 // Adding to a null pointer results in undefined behavior. 9406 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9407 Context, Expr::NPC_ValueDependentIsNotNull)) { 9408 // In C++ adding zero to a null pointer is defined. 9409 Expr::EvalResult KnownVal; 9410 if (!getLangOpts().CPlusPlus || 9411 (!IExp->isValueDependent() && 9412 (!IExp->EvaluateAsInt(KnownVal, Context) || 9413 KnownVal.Val.getInt() != 0))) { 9414 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9415 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9416 Context, BO_Add, PExp, IExp); 9417 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9418 } 9419 } 9420 9421 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9422 return QualType(); 9423 9424 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9425 return QualType(); 9426 9427 // Check array bounds for pointer arithemtic 9428 CheckArrayAccess(PExp, IExp); 9429 9430 if (CompLHSTy) { 9431 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9432 if (LHSTy.isNull()) { 9433 LHSTy = LHS.get()->getType(); 9434 if (LHSTy->isPromotableIntegerType()) 9435 LHSTy = Context.getPromotedIntegerType(LHSTy); 9436 } 9437 *CompLHSTy = LHSTy; 9438 } 9439 9440 return PExp->getType(); 9441 } 9442 9443 // C99 6.5.6 9444 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9445 SourceLocation Loc, 9446 QualType* CompLHSTy) { 9447 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9448 9449 if (LHS.get()->getType()->isVectorType() || 9450 RHS.get()->getType()->isVectorType()) { 9451 QualType compType = CheckVectorOperands( 9452 LHS, RHS, Loc, CompLHSTy, 9453 /*AllowBothBool*/getLangOpts().AltiVec, 9454 /*AllowBoolConversions*/getLangOpts().ZVector); 9455 if (CompLHSTy) *CompLHSTy = compType; 9456 return compType; 9457 } 9458 9459 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9460 if (LHS.isInvalid() || RHS.isInvalid()) 9461 return QualType(); 9462 9463 // Enforce type constraints: C99 6.5.6p3. 9464 9465 // Handle the common case first (both operands are arithmetic). 9466 if (!compType.isNull() && compType->isArithmeticType()) { 9467 if (CompLHSTy) *CompLHSTy = compType; 9468 return compType; 9469 } 9470 9471 // Either ptr - int or ptr - ptr. 9472 if (LHS.get()->getType()->isAnyPointerType()) { 9473 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9474 9475 // Diagnose bad cases where we step over interface counts. 9476 if (LHS.get()->getType()->isObjCObjectPointerType() && 9477 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9478 return QualType(); 9479 9480 // The result type of a pointer-int computation is the pointer type. 9481 if (RHS.get()->getType()->isIntegerType()) { 9482 // Subtracting from a null pointer should produce a warning. 9483 // The last argument to the diagnose call says this doesn't match the 9484 // GNU int-to-pointer idiom. 9485 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9486 Expr::NPC_ValueDependentIsNotNull)) { 9487 // In C++ adding zero to a null pointer is defined. 9488 Expr::EvalResult KnownVal; 9489 if (!getLangOpts().CPlusPlus || 9490 (!RHS.get()->isValueDependent() && 9491 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9492 KnownVal.Val.getInt() != 0))) { 9493 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9494 } 9495 } 9496 9497 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9498 return QualType(); 9499 9500 // Check array bounds for pointer arithemtic 9501 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9502 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9503 9504 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9505 return LHS.get()->getType(); 9506 } 9507 9508 // Handle pointer-pointer subtractions. 9509 if (const PointerType *RHSPTy 9510 = RHS.get()->getType()->getAs<PointerType>()) { 9511 QualType rpointee = RHSPTy->getPointeeType(); 9512 9513 if (getLangOpts().CPlusPlus) { 9514 // Pointee types must be the same: C++ [expr.add] 9515 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9516 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9517 } 9518 } else { 9519 // Pointee types must be compatible C99 6.5.6p3 9520 if (!Context.typesAreCompatible( 9521 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9522 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9523 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9524 return QualType(); 9525 } 9526 } 9527 9528 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9529 LHS.get(), RHS.get())) 9530 return QualType(); 9531 9532 // FIXME: Add warnings for nullptr - ptr. 9533 9534 // The pointee type may have zero size. As an extension, a structure or 9535 // union may have zero size or an array may have zero length. In this 9536 // case subtraction does not make sense. 9537 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9538 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9539 if (ElementSize.isZero()) { 9540 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9541 << rpointee.getUnqualifiedType() 9542 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9543 } 9544 } 9545 9546 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9547 return Context.getPointerDiffType(); 9548 } 9549 } 9550 9551 return InvalidOperands(Loc, LHS, RHS); 9552 } 9553 9554 static bool isScopedEnumerationType(QualType T) { 9555 if (const EnumType *ET = T->getAs<EnumType>()) 9556 return ET->getDecl()->isScoped(); 9557 return false; 9558 } 9559 9560 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9561 SourceLocation Loc, BinaryOperatorKind Opc, 9562 QualType LHSType) { 9563 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9564 // so skip remaining warnings as we don't want to modify values within Sema. 9565 if (S.getLangOpts().OpenCL) 9566 return; 9567 9568 // Check right/shifter operand 9569 Expr::EvalResult RHSResult; 9570 if (RHS.get()->isValueDependent() || 9571 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9572 return; 9573 llvm::APSInt Right = RHSResult.Val.getInt(); 9574 9575 if (Right.isNegative()) { 9576 S.DiagRuntimeBehavior(Loc, RHS.get(), 9577 S.PDiag(diag::warn_shift_negative) 9578 << RHS.get()->getSourceRange()); 9579 return; 9580 } 9581 llvm::APInt LeftBits(Right.getBitWidth(), 9582 S.Context.getTypeSize(LHS.get()->getType())); 9583 if (Right.uge(LeftBits)) { 9584 S.DiagRuntimeBehavior(Loc, RHS.get(), 9585 S.PDiag(diag::warn_shift_gt_typewidth) 9586 << RHS.get()->getSourceRange()); 9587 return; 9588 } 9589 if (Opc != BO_Shl) 9590 return; 9591 9592 // When left shifting an ICE which is signed, we can check for overflow which 9593 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9594 // integers have defined behavior modulo one more than the maximum value 9595 // representable in the result type, so never warn for those. 9596 Expr::EvalResult LHSResult; 9597 if (LHS.get()->isValueDependent() || 9598 LHSType->hasUnsignedIntegerRepresentation() || 9599 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9600 return; 9601 llvm::APSInt Left = LHSResult.Val.getInt(); 9602 9603 // If LHS does not have a signed type and non-negative value 9604 // then, the behavior is undefined. Warn about it. 9605 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9606 S.DiagRuntimeBehavior(Loc, LHS.get(), 9607 S.PDiag(diag::warn_shift_lhs_negative) 9608 << LHS.get()->getSourceRange()); 9609 return; 9610 } 9611 9612 llvm::APInt ResultBits = 9613 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9614 if (LeftBits.uge(ResultBits)) 9615 return; 9616 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9617 Result = Result.shl(Right); 9618 9619 // Print the bit representation of the signed integer as an unsigned 9620 // hexadecimal number. 9621 SmallString<40> HexResult; 9622 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9623 9624 // If we are only missing a sign bit, this is less likely to result in actual 9625 // bugs -- if the result is cast back to an unsigned type, it will have the 9626 // expected value. Thus we place this behind a different warning that can be 9627 // turned off separately if needed. 9628 if (LeftBits == ResultBits - 1) { 9629 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9630 << HexResult << LHSType 9631 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9632 return; 9633 } 9634 9635 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9636 << HexResult.str() << Result.getMinSignedBits() << LHSType 9637 << Left.getBitWidth() << LHS.get()->getSourceRange() 9638 << RHS.get()->getSourceRange(); 9639 } 9640 9641 /// Return the resulting type when a vector is shifted 9642 /// by a scalar or vector shift amount. 9643 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9644 SourceLocation Loc, bool IsCompAssign) { 9645 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9646 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9647 !LHS.get()->getType()->isVectorType()) { 9648 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9649 << RHS.get()->getType() << LHS.get()->getType() 9650 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9651 return QualType(); 9652 } 9653 9654 if (!IsCompAssign) { 9655 LHS = S.UsualUnaryConversions(LHS.get()); 9656 if (LHS.isInvalid()) return QualType(); 9657 } 9658 9659 RHS = S.UsualUnaryConversions(RHS.get()); 9660 if (RHS.isInvalid()) return QualType(); 9661 9662 QualType LHSType = LHS.get()->getType(); 9663 // Note that LHS might be a scalar because the routine calls not only in 9664 // OpenCL case. 9665 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9666 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9667 9668 // Note that RHS might not be a vector. 9669 QualType RHSType = RHS.get()->getType(); 9670 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9671 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9672 9673 // The operands need to be integers. 9674 if (!LHSEleType->isIntegerType()) { 9675 S.Diag(Loc, diag::err_typecheck_expect_int) 9676 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9677 return QualType(); 9678 } 9679 9680 if (!RHSEleType->isIntegerType()) { 9681 S.Diag(Loc, diag::err_typecheck_expect_int) 9682 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9683 return QualType(); 9684 } 9685 9686 if (!LHSVecTy) { 9687 assert(RHSVecTy); 9688 if (IsCompAssign) 9689 return RHSType; 9690 if (LHSEleType != RHSEleType) { 9691 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9692 LHSEleType = RHSEleType; 9693 } 9694 QualType VecTy = 9695 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9696 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9697 LHSType = VecTy; 9698 } else if (RHSVecTy) { 9699 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9700 // are applied component-wise. So if RHS is a vector, then ensure 9701 // that the number of elements is the same as LHS... 9702 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9703 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9704 << LHS.get()->getType() << RHS.get()->getType() 9705 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9706 return QualType(); 9707 } 9708 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9709 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9710 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9711 if (LHSBT != RHSBT && 9712 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9713 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9714 << LHS.get()->getType() << RHS.get()->getType() 9715 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9716 } 9717 } 9718 } else { 9719 // ...else expand RHS to match the number of elements in LHS. 9720 QualType VecTy = 9721 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9722 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9723 } 9724 9725 return LHSType; 9726 } 9727 9728 // C99 6.5.7 9729 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9730 SourceLocation Loc, BinaryOperatorKind Opc, 9731 bool IsCompAssign) { 9732 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9733 9734 // Vector shifts promote their scalar inputs to vector type. 9735 if (LHS.get()->getType()->isVectorType() || 9736 RHS.get()->getType()->isVectorType()) { 9737 if (LangOpts.ZVector) { 9738 // The shift operators for the z vector extensions work basically 9739 // like general shifts, except that neither the LHS nor the RHS is 9740 // allowed to be a "vector bool". 9741 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9742 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9743 return InvalidOperands(Loc, LHS, RHS); 9744 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9745 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9746 return InvalidOperands(Loc, LHS, RHS); 9747 } 9748 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9749 } 9750 9751 // Shifts don't perform usual arithmetic conversions, they just do integer 9752 // promotions on each operand. C99 6.5.7p3 9753 9754 // For the LHS, do usual unary conversions, but then reset them away 9755 // if this is a compound assignment. 9756 ExprResult OldLHS = LHS; 9757 LHS = UsualUnaryConversions(LHS.get()); 9758 if (LHS.isInvalid()) 9759 return QualType(); 9760 QualType LHSType = LHS.get()->getType(); 9761 if (IsCompAssign) LHS = OldLHS; 9762 9763 // The RHS is simpler. 9764 RHS = UsualUnaryConversions(RHS.get()); 9765 if (RHS.isInvalid()) 9766 return QualType(); 9767 QualType RHSType = RHS.get()->getType(); 9768 9769 // C99 6.5.7p2: Each of the operands shall have integer type. 9770 if (!LHSType->hasIntegerRepresentation() || 9771 !RHSType->hasIntegerRepresentation()) 9772 return InvalidOperands(Loc, LHS, RHS); 9773 9774 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9775 // hasIntegerRepresentation() above instead of this. 9776 if (isScopedEnumerationType(LHSType) || 9777 isScopedEnumerationType(RHSType)) { 9778 return InvalidOperands(Loc, LHS, RHS); 9779 } 9780 // Sanity-check shift operands 9781 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9782 9783 // "The type of the result is that of the promoted left operand." 9784 return LHSType; 9785 } 9786 9787 /// If two different enums are compared, raise a warning. 9788 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9789 Expr *RHS) { 9790 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9791 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9792 9793 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9794 if (!LHSEnumType) 9795 return; 9796 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9797 if (!RHSEnumType) 9798 return; 9799 9800 // Ignore anonymous enums. 9801 if (!LHSEnumType->getDecl()->getIdentifier() && 9802 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9803 return; 9804 if (!RHSEnumType->getDecl()->getIdentifier() && 9805 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9806 return; 9807 9808 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9809 return; 9810 9811 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9812 << LHSStrippedType << RHSStrippedType 9813 << LHS->getSourceRange() << RHS->getSourceRange(); 9814 } 9815 9816 /// Diagnose bad pointer comparisons. 9817 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9818 ExprResult &LHS, ExprResult &RHS, 9819 bool IsError) { 9820 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9821 : diag::ext_typecheck_comparison_of_distinct_pointers) 9822 << LHS.get()->getType() << RHS.get()->getType() 9823 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9824 } 9825 9826 /// Returns false if the pointers are converted to a composite type, 9827 /// true otherwise. 9828 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9829 ExprResult &LHS, ExprResult &RHS) { 9830 // C++ [expr.rel]p2: 9831 // [...] Pointer conversions (4.10) and qualification 9832 // conversions (4.4) are performed on pointer operands (or on 9833 // a pointer operand and a null pointer constant) to bring 9834 // them to their composite pointer type. [...] 9835 // 9836 // C++ [expr.eq]p1 uses the same notion for (in)equality 9837 // comparisons of pointers. 9838 9839 QualType LHSType = LHS.get()->getType(); 9840 QualType RHSType = RHS.get()->getType(); 9841 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9842 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9843 9844 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9845 if (T.isNull()) { 9846 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9847 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9848 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9849 else 9850 S.InvalidOperands(Loc, LHS, RHS); 9851 return true; 9852 } 9853 9854 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9855 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9856 return false; 9857 } 9858 9859 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9860 ExprResult &LHS, 9861 ExprResult &RHS, 9862 bool IsError) { 9863 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9864 : diag::ext_typecheck_comparison_of_fptr_to_void) 9865 << LHS.get()->getType() << RHS.get()->getType() 9866 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9867 } 9868 9869 static bool isObjCObjectLiteral(ExprResult &E) { 9870 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9871 case Stmt::ObjCArrayLiteralClass: 9872 case Stmt::ObjCDictionaryLiteralClass: 9873 case Stmt::ObjCStringLiteralClass: 9874 case Stmt::ObjCBoxedExprClass: 9875 return true; 9876 default: 9877 // Note that ObjCBoolLiteral is NOT an object literal! 9878 return false; 9879 } 9880 } 9881 9882 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9883 const ObjCObjectPointerType *Type = 9884 LHS->getType()->getAs<ObjCObjectPointerType>(); 9885 9886 // If this is not actually an Objective-C object, bail out. 9887 if (!Type) 9888 return false; 9889 9890 // Get the LHS object's interface type. 9891 QualType InterfaceType = Type->getPointeeType(); 9892 9893 // If the RHS isn't an Objective-C object, bail out. 9894 if (!RHS->getType()->isObjCObjectPointerType()) 9895 return false; 9896 9897 // Try to find the -isEqual: method. 9898 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9899 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9900 InterfaceType, 9901 /*instance=*/true); 9902 if (!Method) { 9903 if (Type->isObjCIdType()) { 9904 // For 'id', just check the global pool. 9905 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9906 /*receiverId=*/true); 9907 } else { 9908 // Check protocols. 9909 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9910 /*instance=*/true); 9911 } 9912 } 9913 9914 if (!Method) 9915 return false; 9916 9917 QualType T = Method->parameters()[0]->getType(); 9918 if (!T->isObjCObjectPointerType()) 9919 return false; 9920 9921 QualType R = Method->getReturnType(); 9922 if (!R->isScalarType()) 9923 return false; 9924 9925 return true; 9926 } 9927 9928 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9929 FromE = FromE->IgnoreParenImpCasts(); 9930 switch (FromE->getStmtClass()) { 9931 default: 9932 break; 9933 case Stmt::ObjCStringLiteralClass: 9934 // "string literal" 9935 return LK_String; 9936 case Stmt::ObjCArrayLiteralClass: 9937 // "array literal" 9938 return LK_Array; 9939 case Stmt::ObjCDictionaryLiteralClass: 9940 // "dictionary literal" 9941 return LK_Dictionary; 9942 case Stmt::BlockExprClass: 9943 return LK_Block; 9944 case Stmt::ObjCBoxedExprClass: { 9945 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9946 switch (Inner->getStmtClass()) { 9947 case Stmt::IntegerLiteralClass: 9948 case Stmt::FloatingLiteralClass: 9949 case Stmt::CharacterLiteralClass: 9950 case Stmt::ObjCBoolLiteralExprClass: 9951 case Stmt::CXXBoolLiteralExprClass: 9952 // "numeric literal" 9953 return LK_Numeric; 9954 case Stmt::ImplicitCastExprClass: { 9955 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9956 // Boolean literals can be represented by implicit casts. 9957 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9958 return LK_Numeric; 9959 break; 9960 } 9961 default: 9962 break; 9963 } 9964 return LK_Boxed; 9965 } 9966 } 9967 return LK_None; 9968 } 9969 9970 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9971 ExprResult &LHS, ExprResult &RHS, 9972 BinaryOperator::Opcode Opc){ 9973 Expr *Literal; 9974 Expr *Other; 9975 if (isObjCObjectLiteral(LHS)) { 9976 Literal = LHS.get(); 9977 Other = RHS.get(); 9978 } else { 9979 Literal = RHS.get(); 9980 Other = LHS.get(); 9981 } 9982 9983 // Don't warn on comparisons against nil. 9984 Other = Other->IgnoreParenCasts(); 9985 if (Other->isNullPointerConstant(S.getASTContext(), 9986 Expr::NPC_ValueDependentIsNotNull)) 9987 return; 9988 9989 // This should be kept in sync with warn_objc_literal_comparison. 9990 // LK_String should always be after the other literals, since it has its own 9991 // warning flag. 9992 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9993 assert(LiteralKind != Sema::LK_Block); 9994 if (LiteralKind == Sema::LK_None) { 9995 llvm_unreachable("Unknown Objective-C object literal kind"); 9996 } 9997 9998 if (LiteralKind == Sema::LK_String) 9999 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10000 << Literal->getSourceRange(); 10001 else 10002 S.Diag(Loc, diag::warn_objc_literal_comparison) 10003 << LiteralKind << Literal->getSourceRange(); 10004 10005 if (BinaryOperator::isEqualityOp(Opc) && 10006 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10007 SourceLocation Start = LHS.get()->getBeginLoc(); 10008 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10009 CharSourceRange OpRange = 10010 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10011 10012 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10013 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10014 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10015 << FixItHint::CreateInsertion(End, "]"); 10016 } 10017 } 10018 10019 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10020 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10021 ExprResult &RHS, SourceLocation Loc, 10022 BinaryOperatorKind Opc) { 10023 // Check that left hand side is !something. 10024 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10025 if (!UO || UO->getOpcode() != UO_LNot) return; 10026 10027 // Only check if the right hand side is non-bool arithmetic type. 10028 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10029 10030 // Make sure that the something in !something is not bool. 10031 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10032 if (SubExpr->isKnownToHaveBooleanValue()) return; 10033 10034 // Emit warning. 10035 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10036 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10037 << Loc << IsBitwiseOp; 10038 10039 // First note suggest !(x < y) 10040 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10041 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10042 FirstClose = S.getLocForEndOfToken(FirstClose); 10043 if (FirstClose.isInvalid()) 10044 FirstOpen = SourceLocation(); 10045 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10046 << IsBitwiseOp 10047 << FixItHint::CreateInsertion(FirstOpen, "(") 10048 << FixItHint::CreateInsertion(FirstClose, ")"); 10049 10050 // Second note suggests (!x) < y 10051 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10052 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10053 SecondClose = S.getLocForEndOfToken(SecondClose); 10054 if (SecondClose.isInvalid()) 10055 SecondOpen = SourceLocation(); 10056 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10057 << FixItHint::CreateInsertion(SecondOpen, "(") 10058 << FixItHint::CreateInsertion(SecondClose, ")"); 10059 } 10060 10061 // Get the decl for a simple expression: a reference to a variable, 10062 // an implicit C++ field reference, or an implicit ObjC ivar reference. 10063 static ValueDecl *getCompareDecl(Expr *E) { 10064 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 10065 return DR->getDecl(); 10066 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 10067 if (Ivar->isFreeIvar()) 10068 return Ivar->getDecl(); 10069 } 10070 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10071 if (Mem->isImplicitAccess()) 10072 return Mem->getMemberDecl(); 10073 } 10074 return nullptr; 10075 } 10076 10077 /// Diagnose some forms of syntactically-obvious tautological comparison. 10078 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10079 Expr *LHS, Expr *RHS, 10080 BinaryOperatorKind Opc) { 10081 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10082 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10083 10084 QualType LHSType = LHS->getType(); 10085 QualType RHSType = RHS->getType(); 10086 if (LHSType->hasFloatingRepresentation() || 10087 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10088 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 10089 S.inTemplateInstantiation()) 10090 return; 10091 10092 // Comparisons between two array types are ill-formed for operator<=>, so 10093 // we shouldn't emit any additional warnings about it. 10094 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10095 return; 10096 10097 // For non-floating point types, check for self-comparisons of the form 10098 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10099 // often indicate logic errors in the program. 10100 // 10101 // NOTE: Don't warn about comparison expressions resulting from macro 10102 // expansion. Also don't warn about comparisons which are only self 10103 // comparisons within a template instantiation. The warnings should catch 10104 // obvious cases in the definition of the template anyways. The idea is to 10105 // warn when the typed comparison operator will always evaluate to the same 10106 // result. 10107 ValueDecl *DL = getCompareDecl(LHSStripped); 10108 ValueDecl *DR = getCompareDecl(RHSStripped); 10109 if (DL && DR && declaresSameEntity(DL, DR)) { 10110 StringRef Result; 10111 switch (Opc) { 10112 case BO_EQ: case BO_LE: case BO_GE: 10113 Result = "true"; 10114 break; 10115 case BO_NE: case BO_LT: case BO_GT: 10116 Result = "false"; 10117 break; 10118 case BO_Cmp: 10119 Result = "'std::strong_ordering::equal'"; 10120 break; 10121 default: 10122 break; 10123 } 10124 S.DiagRuntimeBehavior(Loc, nullptr, 10125 S.PDiag(diag::warn_comparison_always) 10126 << 0 /*self-comparison*/ << !Result.empty() 10127 << Result); 10128 } else if (DL && DR && 10129 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10130 !DL->isWeak() && !DR->isWeak()) { 10131 // What is it always going to evaluate to? 10132 StringRef Result; 10133 switch(Opc) { 10134 case BO_EQ: // e.g. array1 == array2 10135 Result = "false"; 10136 break; 10137 case BO_NE: // e.g. array1 != array2 10138 Result = "true"; 10139 break; 10140 default: // e.g. array1 <= array2 10141 // The best we can say is 'a constant' 10142 break; 10143 } 10144 S.DiagRuntimeBehavior(Loc, nullptr, 10145 S.PDiag(diag::warn_comparison_always) 10146 << 1 /*array comparison*/ 10147 << !Result.empty() << Result); 10148 } 10149 10150 if (isa<CastExpr>(LHSStripped)) 10151 LHSStripped = LHSStripped->IgnoreParenCasts(); 10152 if (isa<CastExpr>(RHSStripped)) 10153 RHSStripped = RHSStripped->IgnoreParenCasts(); 10154 10155 // Warn about comparisons against a string constant (unless the other 10156 // operand is null); the user probably wants strcmp. 10157 Expr *LiteralString = nullptr; 10158 Expr *LiteralStringStripped = nullptr; 10159 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10160 !RHSStripped->isNullPointerConstant(S.Context, 10161 Expr::NPC_ValueDependentIsNull)) { 10162 LiteralString = LHS; 10163 LiteralStringStripped = LHSStripped; 10164 } else if ((isa<StringLiteral>(RHSStripped) || 10165 isa<ObjCEncodeExpr>(RHSStripped)) && 10166 !LHSStripped->isNullPointerConstant(S.Context, 10167 Expr::NPC_ValueDependentIsNull)) { 10168 LiteralString = RHS; 10169 LiteralStringStripped = RHSStripped; 10170 } 10171 10172 if (LiteralString) { 10173 S.DiagRuntimeBehavior(Loc, nullptr, 10174 S.PDiag(diag::warn_stringcompare) 10175 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10176 << LiteralString->getSourceRange()); 10177 } 10178 } 10179 10180 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10181 switch (CK) { 10182 default: { 10183 #ifndef NDEBUG 10184 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10185 << "\n"; 10186 #endif 10187 llvm_unreachable("unhandled cast kind"); 10188 } 10189 case CK_UserDefinedConversion: 10190 return ICK_Identity; 10191 case CK_LValueToRValue: 10192 return ICK_Lvalue_To_Rvalue; 10193 case CK_ArrayToPointerDecay: 10194 return ICK_Array_To_Pointer; 10195 case CK_FunctionToPointerDecay: 10196 return ICK_Function_To_Pointer; 10197 case CK_IntegralCast: 10198 return ICK_Integral_Conversion; 10199 case CK_FloatingCast: 10200 return ICK_Floating_Conversion; 10201 case CK_IntegralToFloating: 10202 case CK_FloatingToIntegral: 10203 return ICK_Floating_Integral; 10204 case CK_IntegralComplexCast: 10205 case CK_FloatingComplexCast: 10206 case CK_FloatingComplexToIntegralComplex: 10207 case CK_IntegralComplexToFloatingComplex: 10208 return ICK_Complex_Conversion; 10209 case CK_FloatingComplexToReal: 10210 case CK_FloatingRealToComplex: 10211 case CK_IntegralComplexToReal: 10212 case CK_IntegralRealToComplex: 10213 return ICK_Complex_Real; 10214 } 10215 } 10216 10217 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10218 QualType FromType, 10219 SourceLocation Loc) { 10220 // Check for a narrowing implicit conversion. 10221 StandardConversionSequence SCS; 10222 SCS.setAsIdentityConversion(); 10223 SCS.setToType(0, FromType); 10224 SCS.setToType(1, ToType); 10225 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10226 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10227 10228 APValue PreNarrowingValue; 10229 QualType PreNarrowingType; 10230 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10231 PreNarrowingType, 10232 /*IgnoreFloatToIntegralConversion*/ true)) { 10233 case NK_Dependent_Narrowing: 10234 // Implicit conversion to a narrower type, but the expression is 10235 // value-dependent so we can't tell whether it's actually narrowing. 10236 case NK_Not_Narrowing: 10237 return false; 10238 10239 case NK_Constant_Narrowing: 10240 // Implicit conversion to a narrower type, and the value is not a constant 10241 // expression. 10242 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10243 << /*Constant*/ 1 10244 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10245 return true; 10246 10247 case NK_Variable_Narrowing: 10248 // Implicit conversion to a narrower type, and the value is not a constant 10249 // expression. 10250 case NK_Type_Narrowing: 10251 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10252 << /*Constant*/ 0 << FromType << ToType; 10253 // TODO: It's not a constant expression, but what if the user intended it 10254 // to be? Can we produce notes to help them figure out why it isn't? 10255 return true; 10256 } 10257 llvm_unreachable("unhandled case in switch"); 10258 } 10259 10260 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10261 ExprResult &LHS, 10262 ExprResult &RHS, 10263 SourceLocation Loc) { 10264 using CCT = ComparisonCategoryType; 10265 10266 QualType LHSType = LHS.get()->getType(); 10267 QualType RHSType = RHS.get()->getType(); 10268 // Dig out the original argument type and expression before implicit casts 10269 // were applied. These are the types/expressions we need to check the 10270 // [expr.spaceship] requirements against. 10271 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10272 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10273 QualType LHSStrippedType = LHSStripped.get()->getType(); 10274 QualType RHSStrippedType = RHSStripped.get()->getType(); 10275 10276 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10277 // other is not, the program is ill-formed. 10278 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10279 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10280 return QualType(); 10281 } 10282 10283 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10284 RHSStrippedType->isEnumeralType(); 10285 if (NumEnumArgs == 1) { 10286 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10287 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10288 if (OtherTy->hasFloatingRepresentation()) { 10289 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10290 return QualType(); 10291 } 10292 } 10293 if (NumEnumArgs == 2) { 10294 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10295 // type E, the operator yields the result of converting the operands 10296 // to the underlying type of E and applying <=> to the converted operands. 10297 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10298 S.InvalidOperands(Loc, LHS, RHS); 10299 return QualType(); 10300 } 10301 QualType IntType = 10302 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10303 assert(IntType->isArithmeticType()); 10304 10305 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10306 // promote the boolean type, and all other promotable integer types, to 10307 // avoid this. 10308 if (IntType->isPromotableIntegerType()) 10309 IntType = S.Context.getPromotedIntegerType(IntType); 10310 10311 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10312 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10313 LHSType = RHSType = IntType; 10314 } 10315 10316 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10317 // usual arithmetic conversions are applied to the operands. 10318 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10319 if (LHS.isInvalid() || RHS.isInvalid()) 10320 return QualType(); 10321 if (Type.isNull()) 10322 return S.InvalidOperands(Loc, LHS, RHS); 10323 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10324 10325 bool HasNarrowing = checkThreeWayNarrowingConversion( 10326 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10327 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10328 RHS.get()->getBeginLoc()); 10329 if (HasNarrowing) 10330 return QualType(); 10331 10332 assert(!Type.isNull() && "composite type for <=> has not been set"); 10333 10334 auto TypeKind = [&]() { 10335 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10336 if (CT->getElementType()->hasFloatingRepresentation()) 10337 return CCT::WeakEquality; 10338 return CCT::StrongEquality; 10339 } 10340 if (Type->isIntegralOrEnumerationType()) 10341 return CCT::StrongOrdering; 10342 if (Type->hasFloatingRepresentation()) 10343 return CCT::PartialOrdering; 10344 llvm_unreachable("other types are unimplemented"); 10345 }(); 10346 10347 return S.CheckComparisonCategoryType(TypeKind, Loc); 10348 } 10349 10350 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10351 ExprResult &RHS, 10352 SourceLocation Loc, 10353 BinaryOperatorKind Opc) { 10354 if (Opc == BO_Cmp) 10355 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10356 10357 // C99 6.5.8p3 / C99 6.5.9p4 10358 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10359 if (LHS.isInvalid() || RHS.isInvalid()) 10360 return QualType(); 10361 if (Type.isNull()) 10362 return S.InvalidOperands(Loc, LHS, RHS); 10363 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10364 10365 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10366 10367 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10368 return S.InvalidOperands(Loc, LHS, RHS); 10369 10370 // Check for comparisons of floating point operands using != and ==. 10371 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10372 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10373 10374 // The result of comparisons is 'bool' in C++, 'int' in C. 10375 return S.Context.getLogicalOperationType(); 10376 } 10377 10378 // C99 6.5.8, C++ [expr.rel] 10379 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10380 SourceLocation Loc, 10381 BinaryOperatorKind Opc) { 10382 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10383 bool IsThreeWay = Opc == BO_Cmp; 10384 auto IsAnyPointerType = [](ExprResult E) { 10385 QualType Ty = E.get()->getType(); 10386 return Ty->isPointerType() || Ty->isMemberPointerType(); 10387 }; 10388 10389 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10390 // type, array-to-pointer, ..., conversions are performed on both operands to 10391 // bring them to their composite type. 10392 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10393 // any type-related checks. 10394 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10395 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10396 if (LHS.isInvalid()) 10397 return QualType(); 10398 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10399 if (RHS.isInvalid()) 10400 return QualType(); 10401 } else { 10402 LHS = DefaultLvalueConversion(LHS.get()); 10403 if (LHS.isInvalid()) 10404 return QualType(); 10405 RHS = DefaultLvalueConversion(RHS.get()); 10406 if (RHS.isInvalid()) 10407 return QualType(); 10408 } 10409 10410 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10411 10412 // Handle vector comparisons separately. 10413 if (LHS.get()->getType()->isVectorType() || 10414 RHS.get()->getType()->isVectorType()) 10415 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10416 10417 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10418 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10419 10420 QualType LHSType = LHS.get()->getType(); 10421 QualType RHSType = RHS.get()->getType(); 10422 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10423 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10424 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10425 10426 const Expr::NullPointerConstantKind LHSNullKind = 10427 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10428 const Expr::NullPointerConstantKind RHSNullKind = 10429 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10430 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10431 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10432 10433 auto computeResultTy = [&]() { 10434 if (Opc != BO_Cmp) 10435 return Context.getLogicalOperationType(); 10436 assert(getLangOpts().CPlusPlus); 10437 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10438 10439 QualType CompositeTy = LHS.get()->getType(); 10440 assert(!CompositeTy->isReferenceType()); 10441 10442 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10443 return CheckComparisonCategoryType(Kind, Loc); 10444 }; 10445 10446 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10447 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10448 // result is of type std::strong_equality 10449 if (CompositeTy->isFunctionPointerType() || 10450 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10451 // FIXME: consider making the function pointer case produce 10452 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10453 // and direction polls 10454 return buildResultTy(ComparisonCategoryType::StrongEquality); 10455 10456 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10457 // pointer type, p <=> q is of type std::strong_ordering. 10458 if (CompositeTy->isPointerType()) { 10459 // P0946R0: Comparisons between a null pointer constant and an object 10460 // pointer result in std::strong_equality 10461 if (LHSIsNull != RHSIsNull) 10462 return buildResultTy(ComparisonCategoryType::StrongEquality); 10463 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10464 } 10465 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10466 // TODO: Extend support for operator<=> to ObjC types. 10467 return InvalidOperands(Loc, LHS, RHS); 10468 }; 10469 10470 10471 if (!IsRelational && LHSIsNull != RHSIsNull) { 10472 bool IsEquality = Opc == BO_EQ; 10473 if (RHSIsNull) 10474 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10475 RHS.get()->getSourceRange()); 10476 else 10477 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10478 LHS.get()->getSourceRange()); 10479 } 10480 10481 if ((LHSType->isIntegerType() && !LHSIsNull) || 10482 (RHSType->isIntegerType() && !RHSIsNull)) { 10483 // Skip normal pointer conversion checks in this case; we have better 10484 // diagnostics for this below. 10485 } else if (getLangOpts().CPlusPlus) { 10486 // Equality comparison of a function pointer to a void pointer is invalid, 10487 // but we allow it as an extension. 10488 // FIXME: If we really want to allow this, should it be part of composite 10489 // pointer type computation so it works in conditionals too? 10490 if (!IsRelational && 10491 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10492 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10493 // This is a gcc extension compatibility comparison. 10494 // In a SFINAE context, we treat this as a hard error to maintain 10495 // conformance with the C++ standard. 10496 diagnoseFunctionPointerToVoidComparison( 10497 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10498 10499 if (isSFINAEContext()) 10500 return QualType(); 10501 10502 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10503 return computeResultTy(); 10504 } 10505 10506 // C++ [expr.eq]p2: 10507 // If at least one operand is a pointer [...] bring them to their 10508 // composite pointer type. 10509 // C++ [expr.spaceship]p6 10510 // If at least one of the operands is of pointer type, [...] bring them 10511 // to their composite pointer type. 10512 // C++ [expr.rel]p2: 10513 // If both operands are pointers, [...] bring them to their composite 10514 // pointer type. 10515 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10516 (IsRelational ? 2 : 1) && 10517 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10518 RHSType->isObjCObjectPointerType()))) { 10519 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10520 return QualType(); 10521 return computeResultTy(); 10522 } 10523 } else if (LHSType->isPointerType() && 10524 RHSType->isPointerType()) { // C99 6.5.8p2 10525 // All of the following pointer-related warnings are GCC extensions, except 10526 // when handling null pointer constants. 10527 QualType LCanPointeeTy = 10528 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10529 QualType RCanPointeeTy = 10530 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10531 10532 // C99 6.5.9p2 and C99 6.5.8p2 10533 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10534 RCanPointeeTy.getUnqualifiedType())) { 10535 // Valid unless a relational comparison of function pointers 10536 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10537 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10538 << LHSType << RHSType << LHS.get()->getSourceRange() 10539 << RHS.get()->getSourceRange(); 10540 } 10541 } else if (!IsRelational && 10542 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10543 // Valid unless comparison between non-null pointer and function pointer 10544 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10545 && !LHSIsNull && !RHSIsNull) 10546 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10547 /*isError*/false); 10548 } else { 10549 // Invalid 10550 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10551 } 10552 if (LCanPointeeTy != RCanPointeeTy) { 10553 // Treat NULL constant as a special case in OpenCL. 10554 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10555 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10556 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10557 Diag(Loc, 10558 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10559 << LHSType << RHSType << 0 /* comparison */ 10560 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10561 } 10562 } 10563 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10564 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10565 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10566 : CK_BitCast; 10567 if (LHSIsNull && !RHSIsNull) 10568 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10569 else 10570 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10571 } 10572 return computeResultTy(); 10573 } 10574 10575 if (getLangOpts().CPlusPlus) { 10576 // C++ [expr.eq]p4: 10577 // Two operands of type std::nullptr_t or one operand of type 10578 // std::nullptr_t and the other a null pointer constant compare equal. 10579 if (!IsRelational && LHSIsNull && RHSIsNull) { 10580 if (LHSType->isNullPtrType()) { 10581 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10582 return computeResultTy(); 10583 } 10584 if (RHSType->isNullPtrType()) { 10585 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10586 return computeResultTy(); 10587 } 10588 } 10589 10590 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10591 // These aren't covered by the composite pointer type rules. 10592 if (!IsRelational && RHSType->isNullPtrType() && 10593 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10594 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10595 return computeResultTy(); 10596 } 10597 if (!IsRelational && LHSType->isNullPtrType() && 10598 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10599 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10600 return computeResultTy(); 10601 } 10602 10603 if (IsRelational && 10604 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10605 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10606 // HACK: Relational comparison of nullptr_t against a pointer type is 10607 // invalid per DR583, but we allow it within std::less<> and friends, 10608 // since otherwise common uses of it break. 10609 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10610 // friends to have std::nullptr_t overload candidates. 10611 DeclContext *DC = CurContext; 10612 if (isa<FunctionDecl>(DC)) 10613 DC = DC->getParent(); 10614 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10615 if (CTSD->isInStdNamespace() && 10616 llvm::StringSwitch<bool>(CTSD->getName()) 10617 .Cases("less", "less_equal", "greater", "greater_equal", true) 10618 .Default(false)) { 10619 if (RHSType->isNullPtrType()) 10620 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10621 else 10622 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10623 return computeResultTy(); 10624 } 10625 } 10626 } 10627 10628 // C++ [expr.eq]p2: 10629 // If at least one operand is a pointer to member, [...] bring them to 10630 // their composite pointer type. 10631 if (!IsRelational && 10632 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10633 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10634 return QualType(); 10635 else 10636 return computeResultTy(); 10637 } 10638 } 10639 10640 // Handle block pointer types. 10641 if (!IsRelational && LHSType->isBlockPointerType() && 10642 RHSType->isBlockPointerType()) { 10643 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10644 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10645 10646 if (!LHSIsNull && !RHSIsNull && 10647 !Context.typesAreCompatible(lpointee, rpointee)) { 10648 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10649 << LHSType << RHSType << LHS.get()->getSourceRange() 10650 << RHS.get()->getSourceRange(); 10651 } 10652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10653 return computeResultTy(); 10654 } 10655 10656 // Allow block pointers to be compared with null pointer constants. 10657 if (!IsRelational 10658 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10659 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10660 if (!LHSIsNull && !RHSIsNull) { 10661 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10662 ->getPointeeType()->isVoidType()) 10663 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10664 ->getPointeeType()->isVoidType()))) 10665 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10666 << LHSType << RHSType << LHS.get()->getSourceRange() 10667 << RHS.get()->getSourceRange(); 10668 } 10669 if (LHSIsNull && !RHSIsNull) 10670 LHS = ImpCastExprToType(LHS.get(), RHSType, 10671 RHSType->isPointerType() ? CK_BitCast 10672 : CK_AnyPointerToBlockPointerCast); 10673 else 10674 RHS = ImpCastExprToType(RHS.get(), LHSType, 10675 LHSType->isPointerType() ? CK_BitCast 10676 : CK_AnyPointerToBlockPointerCast); 10677 return computeResultTy(); 10678 } 10679 10680 if (LHSType->isObjCObjectPointerType() || 10681 RHSType->isObjCObjectPointerType()) { 10682 const PointerType *LPT = LHSType->getAs<PointerType>(); 10683 const PointerType *RPT = RHSType->getAs<PointerType>(); 10684 if (LPT || RPT) { 10685 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10686 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10687 10688 if (!LPtrToVoid && !RPtrToVoid && 10689 !Context.typesAreCompatible(LHSType, RHSType)) { 10690 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10691 /*isError*/false); 10692 } 10693 if (LHSIsNull && !RHSIsNull) { 10694 Expr *E = LHS.get(); 10695 if (getLangOpts().ObjCAutoRefCount) 10696 CheckObjCConversion(SourceRange(), RHSType, E, 10697 CCK_ImplicitConversion); 10698 LHS = ImpCastExprToType(E, RHSType, 10699 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10700 } 10701 else { 10702 Expr *E = RHS.get(); 10703 if (getLangOpts().ObjCAutoRefCount) 10704 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10705 /*Diagnose=*/true, 10706 /*DiagnoseCFAudited=*/false, Opc); 10707 RHS = ImpCastExprToType(E, LHSType, 10708 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10709 } 10710 return computeResultTy(); 10711 } 10712 if (LHSType->isObjCObjectPointerType() && 10713 RHSType->isObjCObjectPointerType()) { 10714 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10715 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10716 /*isError*/false); 10717 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10718 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10719 10720 if (LHSIsNull && !RHSIsNull) 10721 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10722 else 10723 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10724 return computeResultTy(); 10725 } 10726 10727 if (!IsRelational && LHSType->isBlockPointerType() && 10728 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10729 LHS = ImpCastExprToType(LHS.get(), RHSType, 10730 CK_BlockPointerToObjCPointerCast); 10731 return computeResultTy(); 10732 } else if (!IsRelational && 10733 LHSType->isBlockCompatibleObjCPointerType(Context) && 10734 RHSType->isBlockPointerType()) { 10735 RHS = ImpCastExprToType(RHS.get(), LHSType, 10736 CK_BlockPointerToObjCPointerCast); 10737 return computeResultTy(); 10738 } 10739 } 10740 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10741 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10742 unsigned DiagID = 0; 10743 bool isError = false; 10744 if (LangOpts.DebuggerSupport) { 10745 // Under a debugger, allow the comparison of pointers to integers, 10746 // since users tend to want to compare addresses. 10747 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10748 (RHSIsNull && RHSType->isIntegerType())) { 10749 if (IsRelational) { 10750 isError = getLangOpts().CPlusPlus; 10751 DiagID = 10752 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10753 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10754 } 10755 } else if (getLangOpts().CPlusPlus) { 10756 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10757 isError = true; 10758 } else if (IsRelational) 10759 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10760 else 10761 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10762 10763 if (DiagID) { 10764 Diag(Loc, DiagID) 10765 << LHSType << RHSType << LHS.get()->getSourceRange() 10766 << RHS.get()->getSourceRange(); 10767 if (isError) 10768 return QualType(); 10769 } 10770 10771 if (LHSType->isIntegerType()) 10772 LHS = ImpCastExprToType(LHS.get(), RHSType, 10773 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10774 else 10775 RHS = ImpCastExprToType(RHS.get(), LHSType, 10776 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10777 return computeResultTy(); 10778 } 10779 10780 // Handle block pointers. 10781 if (!IsRelational && RHSIsNull 10782 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10783 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10784 return computeResultTy(); 10785 } 10786 if (!IsRelational && LHSIsNull 10787 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10788 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10789 return computeResultTy(); 10790 } 10791 10792 if (getLangOpts().OpenCLVersion >= 200) { 10793 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10794 return computeResultTy(); 10795 } 10796 10797 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10798 return computeResultTy(); 10799 } 10800 10801 if (LHSIsNull && RHSType->isQueueT()) { 10802 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10803 return computeResultTy(); 10804 } 10805 10806 if (LHSType->isQueueT() && RHSIsNull) { 10807 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10808 return computeResultTy(); 10809 } 10810 } 10811 10812 return InvalidOperands(Loc, LHS, RHS); 10813 } 10814 10815 // Return a signed ext_vector_type that is of identical size and number of 10816 // elements. For floating point vectors, return an integer type of identical 10817 // size and number of elements. In the non ext_vector_type case, search from 10818 // the largest type to the smallest type to avoid cases where long long == long, 10819 // where long gets picked over long long. 10820 QualType Sema::GetSignedVectorType(QualType V) { 10821 const VectorType *VTy = V->getAs<VectorType>(); 10822 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10823 10824 if (isa<ExtVectorType>(VTy)) { 10825 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10826 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10827 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10828 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10829 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10830 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10831 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10832 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10833 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10834 "Unhandled vector element size in vector compare"); 10835 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10836 } 10837 10838 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10839 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10840 VectorType::GenericVector); 10841 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10842 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10843 VectorType::GenericVector); 10844 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10845 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10846 VectorType::GenericVector); 10847 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10848 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10849 VectorType::GenericVector); 10850 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10851 "Unhandled vector element size in vector compare"); 10852 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10853 VectorType::GenericVector); 10854 } 10855 10856 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10857 /// operates on extended vector types. Instead of producing an IntTy result, 10858 /// like a scalar comparison, a vector comparison produces a vector of integer 10859 /// types. 10860 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10861 SourceLocation Loc, 10862 BinaryOperatorKind Opc) { 10863 // Check to make sure we're operating on vectors of the same type and width, 10864 // Allowing one side to be a scalar of element type. 10865 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10866 /*AllowBothBool*/true, 10867 /*AllowBoolConversions*/getLangOpts().ZVector); 10868 if (vType.isNull()) 10869 return vType; 10870 10871 QualType LHSType = LHS.get()->getType(); 10872 10873 // If AltiVec, the comparison results in a numeric type, i.e. 10874 // bool for C++, int for C 10875 if (getLangOpts().AltiVec && 10876 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10877 return Context.getLogicalOperationType(); 10878 10879 // For non-floating point types, check for self-comparisons of the form 10880 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10881 // often indicate logic errors in the program. 10882 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10883 10884 // Check for comparisons of floating point operands using != and ==. 10885 if (BinaryOperator::isEqualityOp(Opc) && 10886 LHSType->hasFloatingRepresentation()) { 10887 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10888 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10889 } 10890 10891 // Return a signed type for the vector. 10892 return GetSignedVectorType(vType); 10893 } 10894 10895 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10896 SourceLocation Loc) { 10897 // Ensure that either both operands are of the same vector type, or 10898 // one operand is of a vector type and the other is of its element type. 10899 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10900 /*AllowBothBool*/true, 10901 /*AllowBoolConversions*/false); 10902 if (vType.isNull()) 10903 return InvalidOperands(Loc, LHS, RHS); 10904 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10905 vType->hasFloatingRepresentation()) 10906 return InvalidOperands(Loc, LHS, RHS); 10907 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10908 // usage of the logical operators && and || with vectors in C. This 10909 // check could be notionally dropped. 10910 if (!getLangOpts().CPlusPlus && 10911 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10912 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10913 10914 return GetSignedVectorType(LHS.get()->getType()); 10915 } 10916 10917 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10918 SourceLocation Loc, 10919 BinaryOperatorKind Opc) { 10920 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10921 10922 bool IsCompAssign = 10923 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10924 10925 if (LHS.get()->getType()->isVectorType() || 10926 RHS.get()->getType()->isVectorType()) { 10927 if (LHS.get()->getType()->hasIntegerRepresentation() && 10928 RHS.get()->getType()->hasIntegerRepresentation()) 10929 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10930 /*AllowBothBool*/true, 10931 /*AllowBoolConversions*/getLangOpts().ZVector); 10932 return InvalidOperands(Loc, LHS, RHS); 10933 } 10934 10935 if (Opc == BO_And) 10936 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10937 10938 ExprResult LHSResult = LHS, RHSResult = RHS; 10939 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10940 IsCompAssign); 10941 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10942 return QualType(); 10943 LHS = LHSResult.get(); 10944 RHS = RHSResult.get(); 10945 10946 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10947 return compType; 10948 return InvalidOperands(Loc, LHS, RHS); 10949 } 10950 10951 // C99 6.5.[13,14] 10952 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10953 SourceLocation Loc, 10954 BinaryOperatorKind Opc) { 10955 // Check vector operands differently. 10956 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10957 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10958 10959 // Diagnose cases where the user write a logical and/or but probably meant a 10960 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10961 // is a constant. 10962 if (LHS.get()->getType()->isIntegerType() && 10963 !LHS.get()->getType()->isBooleanType() && 10964 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10965 // Don't warn in macros or template instantiations. 10966 !Loc.isMacroID() && !inTemplateInstantiation()) { 10967 // If the RHS can be constant folded, and if it constant folds to something 10968 // that isn't 0 or 1 (which indicate a potential logical operation that 10969 // happened to fold to true/false) then warn. 10970 // Parens on the RHS are ignored. 10971 Expr::EvalResult EVResult; 10972 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 10973 llvm::APSInt Result = EVResult.Val.getInt(); 10974 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10975 !RHS.get()->getExprLoc().isMacroID()) || 10976 (Result != 0 && Result != 1)) { 10977 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10978 << RHS.get()->getSourceRange() 10979 << (Opc == BO_LAnd ? "&&" : "||"); 10980 // Suggest replacing the logical operator with the bitwise version 10981 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10982 << (Opc == BO_LAnd ? "&" : "|") 10983 << FixItHint::CreateReplacement(SourceRange( 10984 Loc, getLocForEndOfToken(Loc)), 10985 Opc == BO_LAnd ? "&" : "|"); 10986 if (Opc == BO_LAnd) 10987 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10988 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10989 << FixItHint::CreateRemoval( 10990 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10991 RHS.get()->getEndLoc())); 10992 } 10993 } 10994 } 10995 10996 if (!Context.getLangOpts().CPlusPlus) { 10997 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10998 // not operate on the built-in scalar and vector float types. 10999 if (Context.getLangOpts().OpenCL && 11000 Context.getLangOpts().OpenCLVersion < 120) { 11001 if (LHS.get()->getType()->isFloatingType() || 11002 RHS.get()->getType()->isFloatingType()) 11003 return InvalidOperands(Loc, LHS, RHS); 11004 } 11005 11006 LHS = UsualUnaryConversions(LHS.get()); 11007 if (LHS.isInvalid()) 11008 return QualType(); 11009 11010 RHS = UsualUnaryConversions(RHS.get()); 11011 if (RHS.isInvalid()) 11012 return QualType(); 11013 11014 if (!LHS.get()->getType()->isScalarType() || 11015 !RHS.get()->getType()->isScalarType()) 11016 return InvalidOperands(Loc, LHS, RHS); 11017 11018 return Context.IntTy; 11019 } 11020 11021 // The following is safe because we only use this method for 11022 // non-overloadable operands. 11023 11024 // C++ [expr.log.and]p1 11025 // C++ [expr.log.or]p1 11026 // The operands are both contextually converted to type bool. 11027 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11028 if (LHSRes.isInvalid()) 11029 return InvalidOperands(Loc, LHS, RHS); 11030 LHS = LHSRes; 11031 11032 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11033 if (RHSRes.isInvalid()) 11034 return InvalidOperands(Loc, LHS, RHS); 11035 RHS = RHSRes; 11036 11037 // C++ [expr.log.and]p2 11038 // C++ [expr.log.or]p2 11039 // The result is a bool. 11040 return Context.BoolTy; 11041 } 11042 11043 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11044 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11045 if (!ME) return false; 11046 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11047 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11048 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11049 if (!Base) return false; 11050 return Base->getMethodDecl() != nullptr; 11051 } 11052 11053 /// Is the given expression (which must be 'const') a reference to a 11054 /// variable which was originally non-const, but which has become 11055 /// 'const' due to being captured within a block? 11056 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11057 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11058 assert(E->isLValue() && E->getType().isConstQualified()); 11059 E = E->IgnoreParens(); 11060 11061 // Must be a reference to a declaration from an enclosing scope. 11062 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11063 if (!DRE) return NCCK_None; 11064 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11065 11066 // The declaration must be a variable which is not declared 'const'. 11067 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11068 if (!var) return NCCK_None; 11069 if (var->getType().isConstQualified()) return NCCK_None; 11070 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11071 11072 // Decide whether the first capture was for a block or a lambda. 11073 DeclContext *DC = S.CurContext, *Prev = nullptr; 11074 // Decide whether the first capture was for a block or a lambda. 11075 while (DC) { 11076 // For init-capture, it is possible that the variable belongs to the 11077 // template pattern of the current context. 11078 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11079 if (var->isInitCapture() && 11080 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11081 break; 11082 if (DC == var->getDeclContext()) 11083 break; 11084 Prev = DC; 11085 DC = DC->getParent(); 11086 } 11087 // Unless we have an init-capture, we've gone one step too far. 11088 if (!var->isInitCapture()) 11089 DC = Prev; 11090 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11091 } 11092 11093 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11094 Ty = Ty.getNonReferenceType(); 11095 if (IsDereference && Ty->isPointerType()) 11096 Ty = Ty->getPointeeType(); 11097 return !Ty.isConstQualified(); 11098 } 11099 11100 // Update err_typecheck_assign_const and note_typecheck_assign_const 11101 // when this enum is changed. 11102 enum { 11103 ConstFunction, 11104 ConstVariable, 11105 ConstMember, 11106 ConstMethod, 11107 NestedConstMember, 11108 ConstUnknown, // Keep as last element 11109 }; 11110 11111 /// Emit the "read-only variable not assignable" error and print notes to give 11112 /// more information about why the variable is not assignable, such as pointing 11113 /// to the declaration of a const variable, showing that a method is const, or 11114 /// that the function is returning a const reference. 11115 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11116 SourceLocation Loc) { 11117 SourceRange ExprRange = E->getSourceRange(); 11118 11119 // Only emit one error on the first const found. All other consts will emit 11120 // a note to the error. 11121 bool DiagnosticEmitted = false; 11122 11123 // Track if the current expression is the result of a dereference, and if the 11124 // next checked expression is the result of a dereference. 11125 bool IsDereference = false; 11126 bool NextIsDereference = false; 11127 11128 // Loop to process MemberExpr chains. 11129 while (true) { 11130 IsDereference = NextIsDereference; 11131 11132 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11133 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11134 NextIsDereference = ME->isArrow(); 11135 const ValueDecl *VD = ME->getMemberDecl(); 11136 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11137 // Mutable fields can be modified even if the class is const. 11138 if (Field->isMutable()) { 11139 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11140 break; 11141 } 11142 11143 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11144 if (!DiagnosticEmitted) { 11145 S.Diag(Loc, diag::err_typecheck_assign_const) 11146 << ExprRange << ConstMember << false /*static*/ << Field 11147 << Field->getType(); 11148 DiagnosticEmitted = true; 11149 } 11150 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11151 << ConstMember << false /*static*/ << Field << Field->getType() 11152 << Field->getSourceRange(); 11153 } 11154 E = ME->getBase(); 11155 continue; 11156 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11157 if (VDecl->getType().isConstQualified()) { 11158 if (!DiagnosticEmitted) { 11159 S.Diag(Loc, diag::err_typecheck_assign_const) 11160 << ExprRange << ConstMember << true /*static*/ << VDecl 11161 << VDecl->getType(); 11162 DiagnosticEmitted = true; 11163 } 11164 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11165 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11166 << VDecl->getSourceRange(); 11167 } 11168 // Static fields do not inherit constness from parents. 11169 break; 11170 } 11171 break; // End MemberExpr 11172 } else if (const ArraySubscriptExpr *ASE = 11173 dyn_cast<ArraySubscriptExpr>(E)) { 11174 E = ASE->getBase()->IgnoreParenImpCasts(); 11175 continue; 11176 } else if (const ExtVectorElementExpr *EVE = 11177 dyn_cast<ExtVectorElementExpr>(E)) { 11178 E = EVE->getBase()->IgnoreParenImpCasts(); 11179 continue; 11180 } 11181 break; 11182 } 11183 11184 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11185 // Function calls 11186 const FunctionDecl *FD = CE->getDirectCallee(); 11187 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11188 if (!DiagnosticEmitted) { 11189 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11190 << ConstFunction << FD; 11191 DiagnosticEmitted = true; 11192 } 11193 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11194 diag::note_typecheck_assign_const) 11195 << ConstFunction << FD << FD->getReturnType() 11196 << FD->getReturnTypeSourceRange(); 11197 } 11198 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11199 // Point to variable declaration. 11200 if (const ValueDecl *VD = DRE->getDecl()) { 11201 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11202 if (!DiagnosticEmitted) { 11203 S.Diag(Loc, diag::err_typecheck_assign_const) 11204 << ExprRange << ConstVariable << VD << VD->getType(); 11205 DiagnosticEmitted = true; 11206 } 11207 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11208 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11209 } 11210 } 11211 } else if (isa<CXXThisExpr>(E)) { 11212 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11213 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11214 if (MD->isConst()) { 11215 if (!DiagnosticEmitted) { 11216 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11217 << ConstMethod << MD; 11218 DiagnosticEmitted = true; 11219 } 11220 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11221 << ConstMethod << MD << MD->getSourceRange(); 11222 } 11223 } 11224 } 11225 } 11226 11227 if (DiagnosticEmitted) 11228 return; 11229 11230 // Can't determine a more specific message, so display the generic error. 11231 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11232 } 11233 11234 enum OriginalExprKind { 11235 OEK_Variable, 11236 OEK_Member, 11237 OEK_LValue 11238 }; 11239 11240 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11241 const RecordType *Ty, 11242 SourceLocation Loc, SourceRange Range, 11243 OriginalExprKind OEK, 11244 bool &DiagnosticEmitted) { 11245 std::vector<const RecordType *> RecordTypeList; 11246 RecordTypeList.push_back(Ty); 11247 unsigned NextToCheckIndex = 0; 11248 // We walk the record hierarchy breadth-first to ensure that we print 11249 // diagnostics in field nesting order. 11250 while (RecordTypeList.size() > NextToCheckIndex) { 11251 bool IsNested = NextToCheckIndex > 0; 11252 for (const FieldDecl *Field : 11253 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11254 // First, check every field for constness. 11255 QualType FieldTy = Field->getType(); 11256 if (FieldTy.isConstQualified()) { 11257 if (!DiagnosticEmitted) { 11258 S.Diag(Loc, diag::err_typecheck_assign_const) 11259 << Range << NestedConstMember << OEK << VD 11260 << IsNested << Field; 11261 DiagnosticEmitted = true; 11262 } 11263 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11264 << NestedConstMember << IsNested << Field 11265 << FieldTy << Field->getSourceRange(); 11266 } 11267 11268 // Then we append it to the list to check next in order. 11269 FieldTy = FieldTy.getCanonicalType(); 11270 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11271 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11272 RecordTypeList.push_back(FieldRecTy); 11273 } 11274 } 11275 ++NextToCheckIndex; 11276 } 11277 } 11278 11279 /// Emit an error for the case where a record we are trying to assign to has a 11280 /// const-qualified field somewhere in its hierarchy. 11281 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11282 SourceLocation Loc) { 11283 QualType Ty = E->getType(); 11284 assert(Ty->isRecordType() && "lvalue was not record?"); 11285 SourceRange Range = E->getSourceRange(); 11286 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11287 bool DiagEmitted = false; 11288 11289 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11290 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11291 Range, OEK_Member, DiagEmitted); 11292 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11293 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11294 Range, OEK_Variable, DiagEmitted); 11295 else 11296 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11297 Range, OEK_LValue, DiagEmitted); 11298 if (!DiagEmitted) 11299 DiagnoseConstAssignment(S, E, Loc); 11300 } 11301 11302 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11303 /// emit an error and return true. If so, return false. 11304 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11305 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11306 11307 S.CheckShadowingDeclModification(E, Loc); 11308 11309 SourceLocation OrigLoc = Loc; 11310 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11311 &Loc); 11312 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11313 IsLV = Expr::MLV_InvalidMessageExpression; 11314 if (IsLV == Expr::MLV_Valid) 11315 return false; 11316 11317 unsigned DiagID = 0; 11318 bool NeedType = false; 11319 switch (IsLV) { // C99 6.5.16p2 11320 case Expr::MLV_ConstQualified: 11321 // Use a specialized diagnostic when we're assigning to an object 11322 // from an enclosing function or block. 11323 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11324 if (NCCK == NCCK_Block) 11325 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11326 else 11327 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11328 break; 11329 } 11330 11331 // In ARC, use some specialized diagnostics for occasions where we 11332 // infer 'const'. These are always pseudo-strong variables. 11333 if (S.getLangOpts().ObjCAutoRefCount) { 11334 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11335 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11336 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11337 11338 // Use the normal diagnostic if it's pseudo-__strong but the 11339 // user actually wrote 'const'. 11340 if (var->isARCPseudoStrong() && 11341 (!var->getTypeSourceInfo() || 11342 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11343 // There are three pseudo-strong cases: 11344 // - self 11345 ObjCMethodDecl *method = S.getCurMethodDecl(); 11346 if (method && var == method->getSelfDecl()) { 11347 DiagID = method->isClassMethod() 11348 ? diag::err_typecheck_arc_assign_self_class_method 11349 : diag::err_typecheck_arc_assign_self; 11350 11351 // - Objective-C externally_retained attribute. 11352 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11353 isa<ParmVarDecl>(var)) { 11354 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11355 11356 // - fast enumeration variables 11357 } else { 11358 DiagID = diag::err_typecheck_arr_assign_enumeration; 11359 } 11360 11361 SourceRange Assign; 11362 if (Loc != OrigLoc) 11363 Assign = SourceRange(OrigLoc, OrigLoc); 11364 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11365 // We need to preserve the AST regardless, so migration tool 11366 // can do its job. 11367 return false; 11368 } 11369 } 11370 } 11371 11372 // If none of the special cases above are triggered, then this is a 11373 // simple const assignment. 11374 if (DiagID == 0) { 11375 DiagnoseConstAssignment(S, E, Loc); 11376 return true; 11377 } 11378 11379 break; 11380 case Expr::MLV_ConstAddrSpace: 11381 DiagnoseConstAssignment(S, E, Loc); 11382 return true; 11383 case Expr::MLV_ConstQualifiedField: 11384 DiagnoseRecursiveConstFields(S, E, Loc); 11385 return true; 11386 case Expr::MLV_ArrayType: 11387 case Expr::MLV_ArrayTemporary: 11388 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11389 NeedType = true; 11390 break; 11391 case Expr::MLV_NotObjectType: 11392 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11393 NeedType = true; 11394 break; 11395 case Expr::MLV_LValueCast: 11396 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11397 break; 11398 case Expr::MLV_Valid: 11399 llvm_unreachable("did not take early return for MLV_Valid"); 11400 case Expr::MLV_InvalidExpression: 11401 case Expr::MLV_MemberFunction: 11402 case Expr::MLV_ClassTemporary: 11403 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11404 break; 11405 case Expr::MLV_IncompleteType: 11406 case Expr::MLV_IncompleteVoidType: 11407 return S.RequireCompleteType(Loc, E->getType(), 11408 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11409 case Expr::MLV_DuplicateVectorComponents: 11410 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11411 break; 11412 case Expr::MLV_NoSetterProperty: 11413 llvm_unreachable("readonly properties should be processed differently"); 11414 case Expr::MLV_InvalidMessageExpression: 11415 DiagID = diag::err_readonly_message_assignment; 11416 break; 11417 case Expr::MLV_SubObjCPropertySetting: 11418 DiagID = diag::err_no_subobject_property_setting; 11419 break; 11420 } 11421 11422 SourceRange Assign; 11423 if (Loc != OrigLoc) 11424 Assign = SourceRange(OrigLoc, OrigLoc); 11425 if (NeedType) 11426 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11427 else 11428 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11429 return true; 11430 } 11431 11432 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11433 SourceLocation Loc, 11434 Sema &Sema) { 11435 if (Sema.inTemplateInstantiation()) 11436 return; 11437 if (Sema.isUnevaluatedContext()) 11438 return; 11439 if (Loc.isInvalid() || Loc.isMacroID()) 11440 return; 11441 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11442 return; 11443 11444 // C / C++ fields 11445 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11446 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11447 if (ML && MR) { 11448 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11449 return; 11450 const ValueDecl *LHSDecl = 11451 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11452 const ValueDecl *RHSDecl = 11453 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11454 if (LHSDecl != RHSDecl) 11455 return; 11456 if (LHSDecl->getType().isVolatileQualified()) 11457 return; 11458 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11459 if (RefTy->getPointeeType().isVolatileQualified()) 11460 return; 11461 11462 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11463 } 11464 11465 // Objective-C instance variables 11466 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11467 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11468 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11469 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11470 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11471 if (RL && RR && RL->getDecl() == RR->getDecl()) 11472 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11473 } 11474 } 11475 11476 // C99 6.5.16.1 11477 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11478 SourceLocation Loc, 11479 QualType CompoundType) { 11480 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11481 11482 // Verify that LHS is a modifiable lvalue, and emit error if not. 11483 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11484 return QualType(); 11485 11486 QualType LHSType = LHSExpr->getType(); 11487 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11488 CompoundType; 11489 // OpenCL v1.2 s6.1.1.1 p2: 11490 // The half data type can only be used to declare a pointer to a buffer that 11491 // contains half values 11492 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11493 LHSType->isHalfType()) { 11494 Diag(Loc, diag::err_opencl_half_load_store) << 1 11495 << LHSType.getUnqualifiedType(); 11496 return QualType(); 11497 } 11498 11499 AssignConvertType ConvTy; 11500 if (CompoundType.isNull()) { 11501 Expr *RHSCheck = RHS.get(); 11502 11503 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11504 11505 QualType LHSTy(LHSType); 11506 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11507 if (RHS.isInvalid()) 11508 return QualType(); 11509 // Special case of NSObject attributes on c-style pointer types. 11510 if (ConvTy == IncompatiblePointer && 11511 ((Context.isObjCNSObjectType(LHSType) && 11512 RHSType->isObjCObjectPointerType()) || 11513 (Context.isObjCNSObjectType(RHSType) && 11514 LHSType->isObjCObjectPointerType()))) 11515 ConvTy = Compatible; 11516 11517 if (ConvTy == Compatible && 11518 LHSType->isObjCObjectType()) 11519 Diag(Loc, diag::err_objc_object_assignment) 11520 << LHSType; 11521 11522 // If the RHS is a unary plus or minus, check to see if they = and + are 11523 // right next to each other. If so, the user may have typo'd "x =+ 4" 11524 // instead of "x += 4". 11525 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11526 RHSCheck = ICE->getSubExpr(); 11527 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11528 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11529 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11530 // Only if the two operators are exactly adjacent. 11531 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11532 // And there is a space or other character before the subexpr of the 11533 // unary +/-. We don't want to warn on "x=-1". 11534 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11535 UO->getSubExpr()->getBeginLoc().isFileID()) { 11536 Diag(Loc, diag::warn_not_compound_assign) 11537 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11538 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11539 } 11540 } 11541 11542 if (ConvTy == Compatible) { 11543 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11544 // Warn about retain cycles where a block captures the LHS, but 11545 // not if the LHS is a simple variable into which the block is 11546 // being stored...unless that variable can be captured by reference! 11547 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11548 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11549 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11550 checkRetainCycles(LHSExpr, RHS.get()); 11551 } 11552 11553 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11554 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11555 // It is safe to assign a weak reference into a strong variable. 11556 // Although this code can still have problems: 11557 // id x = self.weakProp; 11558 // id y = self.weakProp; 11559 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11560 // paths through the function. This should be revisited if 11561 // -Wrepeated-use-of-weak is made flow-sensitive. 11562 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11563 // variable, which will be valid for the current autorelease scope. 11564 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11565 RHS.get()->getBeginLoc())) 11566 getCurFunction()->markSafeWeakUse(RHS.get()); 11567 11568 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11569 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11570 } 11571 } 11572 } else { 11573 // Compound assignment "x += y" 11574 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11575 } 11576 11577 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11578 RHS.get(), AA_Assigning)) 11579 return QualType(); 11580 11581 CheckForNullPointerDereference(*this, LHSExpr); 11582 11583 // C99 6.5.16p3: The type of an assignment expression is the type of the 11584 // left operand unless the left operand has qualified type, in which case 11585 // it is the unqualified version of the type of the left operand. 11586 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11587 // is converted to the type of the assignment expression (above). 11588 // C++ 5.17p1: the type of the assignment expression is that of its left 11589 // operand. 11590 return (getLangOpts().CPlusPlus 11591 ? LHSType : LHSType.getUnqualifiedType()); 11592 } 11593 11594 // Only ignore explicit casts to void. 11595 static bool IgnoreCommaOperand(const Expr *E) { 11596 E = E->IgnoreParens(); 11597 11598 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11599 if (CE->getCastKind() == CK_ToVoid) { 11600 return true; 11601 } 11602 11603 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11604 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11605 CE->getSubExpr()->getType()->isDependentType()) { 11606 return true; 11607 } 11608 } 11609 11610 return false; 11611 } 11612 11613 // Look for instances where it is likely the comma operator is confused with 11614 // another operator. There is a whitelist of acceptable expressions for the 11615 // left hand side of the comma operator, otherwise emit a warning. 11616 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11617 // No warnings in macros 11618 if (Loc.isMacroID()) 11619 return; 11620 11621 // Don't warn in template instantiations. 11622 if (inTemplateInstantiation()) 11623 return; 11624 11625 // Scope isn't fine-grained enough to whitelist the specific cases, so 11626 // instead, skip more than needed, then call back into here with the 11627 // CommaVisitor in SemaStmt.cpp. 11628 // The whitelisted locations are the initialization and increment portions 11629 // of a for loop. The additional checks are on the condition of 11630 // if statements, do/while loops, and for loops. 11631 // Differences in scope flags for C89 mode requires the extra logic. 11632 const unsigned ForIncrementFlags = 11633 getLangOpts().C99 || getLangOpts().CPlusPlus 11634 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11635 : Scope::ContinueScope | Scope::BreakScope; 11636 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11637 const unsigned ScopeFlags = getCurScope()->getFlags(); 11638 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11639 (ScopeFlags & ForInitFlags) == ForInitFlags) 11640 return; 11641 11642 // If there are multiple comma operators used together, get the RHS of the 11643 // of the comma operator as the LHS. 11644 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11645 if (BO->getOpcode() != BO_Comma) 11646 break; 11647 LHS = BO->getRHS(); 11648 } 11649 11650 // Only allow some expressions on LHS to not warn. 11651 if (IgnoreCommaOperand(LHS)) 11652 return; 11653 11654 Diag(Loc, diag::warn_comma_operator); 11655 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11656 << LHS->getSourceRange() 11657 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11658 LangOpts.CPlusPlus ? "static_cast<void>(" 11659 : "(void)(") 11660 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11661 ")"); 11662 } 11663 11664 // C99 6.5.17 11665 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11666 SourceLocation Loc) { 11667 LHS = S.CheckPlaceholderExpr(LHS.get()); 11668 RHS = S.CheckPlaceholderExpr(RHS.get()); 11669 if (LHS.isInvalid() || RHS.isInvalid()) 11670 return QualType(); 11671 11672 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11673 // operands, but not unary promotions. 11674 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11675 11676 // So we treat the LHS as a ignored value, and in C++ we allow the 11677 // containing site to determine what should be done with the RHS. 11678 LHS = S.IgnoredValueConversions(LHS.get()); 11679 if (LHS.isInvalid()) 11680 return QualType(); 11681 11682 S.DiagnoseUnusedExprResult(LHS.get()); 11683 11684 if (!S.getLangOpts().CPlusPlus) { 11685 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11686 if (RHS.isInvalid()) 11687 return QualType(); 11688 if (!RHS.get()->getType()->isVoidType()) 11689 S.RequireCompleteType(Loc, RHS.get()->getType(), 11690 diag::err_incomplete_type); 11691 } 11692 11693 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11694 S.DiagnoseCommaOperator(LHS.get(), Loc); 11695 11696 return RHS.get()->getType(); 11697 } 11698 11699 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11700 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11701 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11702 ExprValueKind &VK, 11703 ExprObjectKind &OK, 11704 SourceLocation OpLoc, 11705 bool IsInc, bool IsPrefix) { 11706 if (Op->isTypeDependent()) 11707 return S.Context.DependentTy; 11708 11709 QualType ResType = Op->getType(); 11710 // Atomic types can be used for increment / decrement where the non-atomic 11711 // versions can, so ignore the _Atomic() specifier for the purpose of 11712 // checking. 11713 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11714 ResType = ResAtomicType->getValueType(); 11715 11716 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11717 11718 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11719 // Decrement of bool is not allowed. 11720 if (!IsInc) { 11721 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11722 return QualType(); 11723 } 11724 // Increment of bool sets it to true, but is deprecated. 11725 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11726 : diag::warn_increment_bool) 11727 << Op->getSourceRange(); 11728 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11729 // Error on enum increments and decrements in C++ mode 11730 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11731 return QualType(); 11732 } else if (ResType->isRealType()) { 11733 // OK! 11734 } else if (ResType->isPointerType()) { 11735 // C99 6.5.2.4p2, 6.5.6p2 11736 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11737 return QualType(); 11738 } else if (ResType->isObjCObjectPointerType()) { 11739 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11740 // Otherwise, we just need a complete type. 11741 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11742 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11743 return QualType(); 11744 } else if (ResType->isAnyComplexType()) { 11745 // C99 does not support ++/-- on complex types, we allow as an extension. 11746 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11747 << ResType << Op->getSourceRange(); 11748 } else if (ResType->isPlaceholderType()) { 11749 ExprResult PR = S.CheckPlaceholderExpr(Op); 11750 if (PR.isInvalid()) return QualType(); 11751 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11752 IsInc, IsPrefix); 11753 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11754 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11755 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11756 (ResType->getAs<VectorType>()->getVectorKind() != 11757 VectorType::AltiVecBool)) { 11758 // The z vector extensions allow ++ and -- for non-bool vectors. 11759 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11760 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11761 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11762 } else { 11763 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11764 << ResType << int(IsInc) << Op->getSourceRange(); 11765 return QualType(); 11766 } 11767 // At this point, we know we have a real, complex or pointer type. 11768 // Now make sure the operand is a modifiable lvalue. 11769 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11770 return QualType(); 11771 // In C++, a prefix increment is the same type as the operand. Otherwise 11772 // (in C or with postfix), the increment is the unqualified type of the 11773 // operand. 11774 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11775 VK = VK_LValue; 11776 OK = Op->getObjectKind(); 11777 return ResType; 11778 } else { 11779 VK = VK_RValue; 11780 return ResType.getUnqualifiedType(); 11781 } 11782 } 11783 11784 11785 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11786 /// This routine allows us to typecheck complex/recursive expressions 11787 /// where the declaration is needed for type checking. We only need to 11788 /// handle cases when the expression references a function designator 11789 /// or is an lvalue. Here are some examples: 11790 /// - &(x) => x 11791 /// - &*****f => f for f a function designator. 11792 /// - &s.xx => s 11793 /// - &s.zz[1].yy -> s, if zz is an array 11794 /// - *(x + 1) -> x, if x is an array 11795 /// - &"123"[2] -> 0 11796 /// - & __real__ x -> x 11797 static ValueDecl *getPrimaryDecl(Expr *E) { 11798 switch (E->getStmtClass()) { 11799 case Stmt::DeclRefExprClass: 11800 return cast<DeclRefExpr>(E)->getDecl(); 11801 case Stmt::MemberExprClass: 11802 // If this is an arrow operator, the address is an offset from 11803 // the base's value, so the object the base refers to is 11804 // irrelevant. 11805 if (cast<MemberExpr>(E)->isArrow()) 11806 return nullptr; 11807 // Otherwise, the expression refers to a part of the base 11808 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11809 case Stmt::ArraySubscriptExprClass: { 11810 // FIXME: This code shouldn't be necessary! We should catch the implicit 11811 // promotion of register arrays earlier. 11812 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11813 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11814 if (ICE->getSubExpr()->getType()->isArrayType()) 11815 return getPrimaryDecl(ICE->getSubExpr()); 11816 } 11817 return nullptr; 11818 } 11819 case Stmt::UnaryOperatorClass: { 11820 UnaryOperator *UO = cast<UnaryOperator>(E); 11821 11822 switch(UO->getOpcode()) { 11823 case UO_Real: 11824 case UO_Imag: 11825 case UO_Extension: 11826 return getPrimaryDecl(UO->getSubExpr()); 11827 default: 11828 return nullptr; 11829 } 11830 } 11831 case Stmt::ParenExprClass: 11832 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11833 case Stmt::ImplicitCastExprClass: 11834 // If the result of an implicit cast is an l-value, we care about 11835 // the sub-expression; otherwise, the result here doesn't matter. 11836 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11837 default: 11838 return nullptr; 11839 } 11840 } 11841 11842 namespace { 11843 enum { 11844 AO_Bit_Field = 0, 11845 AO_Vector_Element = 1, 11846 AO_Property_Expansion = 2, 11847 AO_Register_Variable = 3, 11848 AO_No_Error = 4 11849 }; 11850 } 11851 /// Diagnose invalid operand for address of operations. 11852 /// 11853 /// \param Type The type of operand which cannot have its address taken. 11854 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11855 Expr *E, unsigned Type) { 11856 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11857 } 11858 11859 /// CheckAddressOfOperand - The operand of & must be either a function 11860 /// designator or an lvalue designating an object. If it is an lvalue, the 11861 /// object cannot be declared with storage class register or be a bit field. 11862 /// Note: The usual conversions are *not* applied to the operand of the & 11863 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11864 /// In C++, the operand might be an overloaded function name, in which case 11865 /// we allow the '&' but retain the overloaded-function type. 11866 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11867 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11868 if (PTy->getKind() == BuiltinType::Overload) { 11869 Expr *E = OrigOp.get()->IgnoreParens(); 11870 if (!isa<OverloadExpr>(E)) { 11871 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11872 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11873 << OrigOp.get()->getSourceRange(); 11874 return QualType(); 11875 } 11876 11877 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11878 if (isa<UnresolvedMemberExpr>(Ovl)) 11879 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11880 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11881 << OrigOp.get()->getSourceRange(); 11882 return QualType(); 11883 } 11884 11885 return Context.OverloadTy; 11886 } 11887 11888 if (PTy->getKind() == BuiltinType::UnknownAny) 11889 return Context.UnknownAnyTy; 11890 11891 if (PTy->getKind() == BuiltinType::BoundMember) { 11892 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11893 << OrigOp.get()->getSourceRange(); 11894 return QualType(); 11895 } 11896 11897 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11898 if (OrigOp.isInvalid()) return QualType(); 11899 } 11900 11901 if (OrigOp.get()->isTypeDependent()) 11902 return Context.DependentTy; 11903 11904 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11905 11906 // Make sure to ignore parentheses in subsequent checks 11907 Expr *op = OrigOp.get()->IgnoreParens(); 11908 11909 // In OpenCL captures for blocks called as lambda functions 11910 // are located in the private address space. Blocks used in 11911 // enqueue_kernel can be located in a different address space 11912 // depending on a vendor implementation. Thus preventing 11913 // taking an address of the capture to avoid invalid AS casts. 11914 if (LangOpts.OpenCL) { 11915 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11916 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11917 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11918 return QualType(); 11919 } 11920 } 11921 11922 if (getLangOpts().C99) { 11923 // Implement C99-only parts of addressof rules. 11924 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11925 if (uOp->getOpcode() == UO_Deref) 11926 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11927 // (assuming the deref expression is valid). 11928 return uOp->getSubExpr()->getType(); 11929 } 11930 // Technically, there should be a check for array subscript 11931 // expressions here, but the result of one is always an lvalue anyway. 11932 } 11933 ValueDecl *dcl = getPrimaryDecl(op); 11934 11935 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11936 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11937 op->getBeginLoc())) 11938 return QualType(); 11939 11940 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11941 unsigned AddressOfError = AO_No_Error; 11942 11943 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11944 bool sfinae = (bool)isSFINAEContext(); 11945 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11946 : diag::ext_typecheck_addrof_temporary) 11947 << op->getType() << op->getSourceRange(); 11948 if (sfinae) 11949 return QualType(); 11950 // Materialize the temporary as an lvalue so that we can take its address. 11951 OrigOp = op = 11952 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11953 } else if (isa<ObjCSelectorExpr>(op)) { 11954 return Context.getPointerType(op->getType()); 11955 } else if (lval == Expr::LV_MemberFunction) { 11956 // If it's an instance method, make a member pointer. 11957 // The expression must have exactly the form &A::foo. 11958 11959 // If the underlying expression isn't a decl ref, give up. 11960 if (!isa<DeclRefExpr>(op)) { 11961 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11962 << OrigOp.get()->getSourceRange(); 11963 return QualType(); 11964 } 11965 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11966 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11967 11968 // The id-expression was parenthesized. 11969 if (OrigOp.get() != DRE) { 11970 Diag(OpLoc, diag::err_parens_pointer_member_function) 11971 << OrigOp.get()->getSourceRange(); 11972 11973 // The method was named without a qualifier. 11974 } else if (!DRE->getQualifier()) { 11975 if (MD->getParent()->getName().empty()) 11976 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11977 << op->getSourceRange(); 11978 else { 11979 SmallString<32> Str; 11980 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11981 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11982 << op->getSourceRange() 11983 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11984 } 11985 } 11986 11987 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11988 if (isa<CXXDestructorDecl>(MD)) 11989 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11990 11991 QualType MPTy = Context.getMemberPointerType( 11992 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11993 // Under the MS ABI, lock down the inheritance model now. 11994 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11995 (void)isCompleteType(OpLoc, MPTy); 11996 return MPTy; 11997 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11998 // C99 6.5.3.2p1 11999 // The operand must be either an l-value or a function designator 12000 if (!op->getType()->isFunctionType()) { 12001 // Use a special diagnostic for loads from property references. 12002 if (isa<PseudoObjectExpr>(op)) { 12003 AddressOfError = AO_Property_Expansion; 12004 } else { 12005 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12006 << op->getType() << op->getSourceRange(); 12007 return QualType(); 12008 } 12009 } 12010 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12011 // The operand cannot be a bit-field 12012 AddressOfError = AO_Bit_Field; 12013 } else if (op->getObjectKind() == OK_VectorComponent) { 12014 // The operand cannot be an element of a vector 12015 AddressOfError = AO_Vector_Element; 12016 } else if (dcl) { // C99 6.5.3.2p1 12017 // We have an lvalue with a decl. Make sure the decl is not declared 12018 // with the register storage-class specifier. 12019 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12020 // in C++ it is not error to take address of a register 12021 // variable (c++03 7.1.1P3) 12022 if (vd->getStorageClass() == SC_Register && 12023 !getLangOpts().CPlusPlus) { 12024 AddressOfError = AO_Register_Variable; 12025 } 12026 } else if (isa<MSPropertyDecl>(dcl)) { 12027 AddressOfError = AO_Property_Expansion; 12028 } else if (isa<FunctionTemplateDecl>(dcl)) { 12029 return Context.OverloadTy; 12030 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12031 // Okay: we can take the address of a field. 12032 // Could be a pointer to member, though, if there is an explicit 12033 // scope qualifier for the class. 12034 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12035 DeclContext *Ctx = dcl->getDeclContext(); 12036 if (Ctx && Ctx->isRecord()) { 12037 if (dcl->getType()->isReferenceType()) { 12038 Diag(OpLoc, 12039 diag::err_cannot_form_pointer_to_member_of_reference_type) 12040 << dcl->getDeclName() << dcl->getType(); 12041 return QualType(); 12042 } 12043 12044 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12045 Ctx = Ctx->getParent(); 12046 12047 QualType MPTy = Context.getMemberPointerType( 12048 op->getType(), 12049 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12050 // Under the MS ABI, lock down the inheritance model now. 12051 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12052 (void)isCompleteType(OpLoc, MPTy); 12053 return MPTy; 12054 } 12055 } 12056 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12057 !isa<BindingDecl>(dcl)) 12058 llvm_unreachable("Unknown/unexpected decl type"); 12059 } 12060 12061 if (AddressOfError != AO_No_Error) { 12062 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12063 return QualType(); 12064 } 12065 12066 if (lval == Expr::LV_IncompleteVoidType) { 12067 // Taking the address of a void variable is technically illegal, but we 12068 // allow it in cases which are otherwise valid. 12069 // Example: "extern void x; void* y = &x;". 12070 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12071 } 12072 12073 // If the operand has type "type", the result has type "pointer to type". 12074 if (op->getType()->isObjCObjectType()) 12075 return Context.getObjCObjectPointerType(op->getType()); 12076 12077 CheckAddressOfPackedMember(op); 12078 12079 return Context.getPointerType(op->getType()); 12080 } 12081 12082 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12083 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12084 if (!DRE) 12085 return; 12086 const Decl *D = DRE->getDecl(); 12087 if (!D) 12088 return; 12089 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12090 if (!Param) 12091 return; 12092 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12093 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12094 return; 12095 if (FunctionScopeInfo *FD = S.getCurFunction()) 12096 if (!FD->ModifiedNonNullParams.count(Param)) 12097 FD->ModifiedNonNullParams.insert(Param); 12098 } 12099 12100 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12101 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12102 SourceLocation OpLoc) { 12103 if (Op->isTypeDependent()) 12104 return S.Context.DependentTy; 12105 12106 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12107 if (ConvResult.isInvalid()) 12108 return QualType(); 12109 Op = ConvResult.get(); 12110 QualType OpTy = Op->getType(); 12111 QualType Result; 12112 12113 if (isa<CXXReinterpretCastExpr>(Op)) { 12114 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12115 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12116 Op->getSourceRange()); 12117 } 12118 12119 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12120 { 12121 Result = PT->getPointeeType(); 12122 } 12123 else if (const ObjCObjectPointerType *OPT = 12124 OpTy->getAs<ObjCObjectPointerType>()) 12125 Result = OPT->getPointeeType(); 12126 else { 12127 ExprResult PR = S.CheckPlaceholderExpr(Op); 12128 if (PR.isInvalid()) return QualType(); 12129 if (PR.get() != Op) 12130 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12131 } 12132 12133 if (Result.isNull()) { 12134 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12135 << OpTy << Op->getSourceRange(); 12136 return QualType(); 12137 } 12138 12139 // Note that per both C89 and C99, indirection is always legal, even if Result 12140 // is an incomplete type or void. It would be possible to warn about 12141 // dereferencing a void pointer, but it's completely well-defined, and such a 12142 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12143 // for pointers to 'void' but is fine for any other pointer type: 12144 // 12145 // C++ [expr.unary.op]p1: 12146 // [...] the expression to which [the unary * operator] is applied shall 12147 // be a pointer to an object type, or a pointer to a function type 12148 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12149 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12150 << OpTy << Op->getSourceRange(); 12151 12152 // Dereferences are usually l-values... 12153 VK = VK_LValue; 12154 12155 // ...except that certain expressions are never l-values in C. 12156 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12157 VK = VK_RValue; 12158 12159 return Result; 12160 } 12161 12162 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12163 BinaryOperatorKind Opc; 12164 switch (Kind) { 12165 default: llvm_unreachable("Unknown binop!"); 12166 case tok::periodstar: Opc = BO_PtrMemD; break; 12167 case tok::arrowstar: Opc = BO_PtrMemI; break; 12168 case tok::star: Opc = BO_Mul; break; 12169 case tok::slash: Opc = BO_Div; break; 12170 case tok::percent: Opc = BO_Rem; break; 12171 case tok::plus: Opc = BO_Add; break; 12172 case tok::minus: Opc = BO_Sub; break; 12173 case tok::lessless: Opc = BO_Shl; break; 12174 case tok::greatergreater: Opc = BO_Shr; break; 12175 case tok::lessequal: Opc = BO_LE; break; 12176 case tok::less: Opc = BO_LT; break; 12177 case tok::greaterequal: Opc = BO_GE; break; 12178 case tok::greater: Opc = BO_GT; break; 12179 case tok::exclaimequal: Opc = BO_NE; break; 12180 case tok::equalequal: Opc = BO_EQ; break; 12181 case tok::spaceship: Opc = BO_Cmp; break; 12182 case tok::amp: Opc = BO_And; break; 12183 case tok::caret: Opc = BO_Xor; break; 12184 case tok::pipe: Opc = BO_Or; break; 12185 case tok::ampamp: Opc = BO_LAnd; break; 12186 case tok::pipepipe: Opc = BO_LOr; break; 12187 case tok::equal: Opc = BO_Assign; break; 12188 case tok::starequal: Opc = BO_MulAssign; break; 12189 case tok::slashequal: Opc = BO_DivAssign; break; 12190 case tok::percentequal: Opc = BO_RemAssign; break; 12191 case tok::plusequal: Opc = BO_AddAssign; break; 12192 case tok::minusequal: Opc = BO_SubAssign; break; 12193 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12194 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12195 case tok::ampequal: Opc = BO_AndAssign; break; 12196 case tok::caretequal: Opc = BO_XorAssign; break; 12197 case tok::pipeequal: Opc = BO_OrAssign; break; 12198 case tok::comma: Opc = BO_Comma; break; 12199 } 12200 return Opc; 12201 } 12202 12203 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12204 tok::TokenKind Kind) { 12205 UnaryOperatorKind Opc; 12206 switch (Kind) { 12207 default: llvm_unreachable("Unknown unary op!"); 12208 case tok::plusplus: Opc = UO_PreInc; break; 12209 case tok::minusminus: Opc = UO_PreDec; break; 12210 case tok::amp: Opc = UO_AddrOf; break; 12211 case tok::star: Opc = UO_Deref; break; 12212 case tok::plus: Opc = UO_Plus; break; 12213 case tok::minus: Opc = UO_Minus; break; 12214 case tok::tilde: Opc = UO_Not; break; 12215 case tok::exclaim: Opc = UO_LNot; break; 12216 case tok::kw___real: Opc = UO_Real; break; 12217 case tok::kw___imag: Opc = UO_Imag; break; 12218 case tok::kw___extension__: Opc = UO_Extension; break; 12219 } 12220 return Opc; 12221 } 12222 12223 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12224 /// This warning suppressed in the event of macro expansions. 12225 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12226 SourceLocation OpLoc, bool IsBuiltin) { 12227 if (S.inTemplateInstantiation()) 12228 return; 12229 if (S.isUnevaluatedContext()) 12230 return; 12231 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12232 return; 12233 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12234 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12235 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12236 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12237 if (!LHSDeclRef || !RHSDeclRef || 12238 LHSDeclRef->getLocation().isMacroID() || 12239 RHSDeclRef->getLocation().isMacroID()) 12240 return; 12241 const ValueDecl *LHSDecl = 12242 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12243 const ValueDecl *RHSDecl = 12244 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12245 if (LHSDecl != RHSDecl) 12246 return; 12247 if (LHSDecl->getType().isVolatileQualified()) 12248 return; 12249 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12250 if (RefTy->getPointeeType().isVolatileQualified()) 12251 return; 12252 12253 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12254 : diag::warn_self_assignment_overloaded) 12255 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12256 << RHSExpr->getSourceRange(); 12257 } 12258 12259 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12260 /// is usually indicative of introspection within the Objective-C pointer. 12261 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12262 SourceLocation OpLoc) { 12263 if (!S.getLangOpts().ObjC) 12264 return; 12265 12266 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12267 const Expr *LHS = L.get(); 12268 const Expr *RHS = R.get(); 12269 12270 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12271 ObjCPointerExpr = LHS; 12272 OtherExpr = RHS; 12273 } 12274 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12275 ObjCPointerExpr = RHS; 12276 OtherExpr = LHS; 12277 } 12278 12279 // This warning is deliberately made very specific to reduce false 12280 // positives with logic that uses '&' for hashing. This logic mainly 12281 // looks for code trying to introspect into tagged pointers, which 12282 // code should generally never do. 12283 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12284 unsigned Diag = diag::warn_objc_pointer_masking; 12285 // Determine if we are introspecting the result of performSelectorXXX. 12286 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12287 // Special case messages to -performSelector and friends, which 12288 // can return non-pointer values boxed in a pointer value. 12289 // Some clients may wish to silence warnings in this subcase. 12290 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12291 Selector S = ME->getSelector(); 12292 StringRef SelArg0 = S.getNameForSlot(0); 12293 if (SelArg0.startswith("performSelector")) 12294 Diag = diag::warn_objc_pointer_masking_performSelector; 12295 } 12296 12297 S.Diag(OpLoc, Diag) 12298 << ObjCPointerExpr->getSourceRange(); 12299 } 12300 } 12301 12302 static NamedDecl *getDeclFromExpr(Expr *E) { 12303 if (!E) 12304 return nullptr; 12305 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12306 return DRE->getDecl(); 12307 if (auto *ME = dyn_cast<MemberExpr>(E)) 12308 return ME->getMemberDecl(); 12309 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12310 return IRE->getDecl(); 12311 return nullptr; 12312 } 12313 12314 // This helper function promotes a binary operator's operands (which are of a 12315 // half vector type) to a vector of floats and then truncates the result to 12316 // a vector of either half or short. 12317 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12318 BinaryOperatorKind Opc, QualType ResultTy, 12319 ExprValueKind VK, ExprObjectKind OK, 12320 bool IsCompAssign, SourceLocation OpLoc, 12321 FPOptions FPFeatures) { 12322 auto &Context = S.getASTContext(); 12323 assert((isVector(ResultTy, Context.HalfTy) || 12324 isVector(ResultTy, Context.ShortTy)) && 12325 "Result must be a vector of half or short"); 12326 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12327 isVector(RHS.get()->getType(), Context.HalfTy) && 12328 "both operands expected to be a half vector"); 12329 12330 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12331 QualType BinOpResTy = RHS.get()->getType(); 12332 12333 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12334 // change BinOpResTy to a vector of ints. 12335 if (isVector(ResultTy, Context.ShortTy)) 12336 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12337 12338 if (IsCompAssign) 12339 return new (Context) CompoundAssignOperator( 12340 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12341 OpLoc, FPFeatures); 12342 12343 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12344 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12345 VK, OK, OpLoc, FPFeatures); 12346 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12347 } 12348 12349 static std::pair<ExprResult, ExprResult> 12350 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12351 Expr *RHSExpr) { 12352 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12353 if (!S.getLangOpts().CPlusPlus) { 12354 // C cannot handle TypoExpr nodes on either side of a binop because it 12355 // doesn't handle dependent types properly, so make sure any TypoExprs have 12356 // been dealt with before checking the operands. 12357 LHS = S.CorrectDelayedTyposInExpr(LHS); 12358 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12359 if (Opc != BO_Assign) 12360 return ExprResult(E); 12361 // Avoid correcting the RHS to the same Expr as the LHS. 12362 Decl *D = getDeclFromExpr(E); 12363 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12364 }); 12365 } 12366 return std::make_pair(LHS, RHS); 12367 } 12368 12369 /// Returns true if conversion between vectors of halfs and vectors of floats 12370 /// is needed. 12371 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12372 QualType SrcType) { 12373 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12374 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12375 isVector(SrcType, Ctx.HalfTy); 12376 } 12377 12378 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12379 /// operator @p Opc at location @c TokLoc. This routine only supports 12380 /// built-in operations; ActOnBinOp handles overloaded operators. 12381 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12382 BinaryOperatorKind Opc, 12383 Expr *LHSExpr, Expr *RHSExpr) { 12384 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12385 // The syntax only allows initializer lists on the RHS of assignment, 12386 // so we don't need to worry about accepting invalid code for 12387 // non-assignment operators. 12388 // C++11 5.17p9: 12389 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12390 // of x = {} is x = T(). 12391 InitializationKind Kind = InitializationKind::CreateDirectList( 12392 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12393 InitializedEntity Entity = 12394 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12395 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12396 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12397 if (Init.isInvalid()) 12398 return Init; 12399 RHSExpr = Init.get(); 12400 } 12401 12402 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12403 QualType ResultTy; // Result type of the binary operator. 12404 // The following two variables are used for compound assignment operators 12405 QualType CompLHSTy; // Type of LHS after promotions for computation 12406 QualType CompResultTy; // Type of computation result 12407 ExprValueKind VK = VK_RValue; 12408 ExprObjectKind OK = OK_Ordinary; 12409 bool ConvertHalfVec = false; 12410 12411 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12412 if (!LHS.isUsable() || !RHS.isUsable()) 12413 return ExprError(); 12414 12415 if (getLangOpts().OpenCL) { 12416 QualType LHSTy = LHSExpr->getType(); 12417 QualType RHSTy = RHSExpr->getType(); 12418 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12419 // the ATOMIC_VAR_INIT macro. 12420 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12421 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12422 if (BO_Assign == Opc) 12423 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12424 else 12425 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12426 return ExprError(); 12427 } 12428 12429 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12430 // only with a builtin functions and therefore should be disallowed here. 12431 if (LHSTy->isImageType() || RHSTy->isImageType() || 12432 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12433 LHSTy->isPipeType() || RHSTy->isPipeType() || 12434 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12435 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12436 return ExprError(); 12437 } 12438 } 12439 12440 // Diagnose operations on the unsupported types for OpenMP device compilation. 12441 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12442 if (Opc != BO_Assign && Opc != BO_Comma) { 12443 checkOpenMPDeviceExpr(LHSExpr); 12444 checkOpenMPDeviceExpr(RHSExpr); 12445 } 12446 } 12447 12448 switch (Opc) { 12449 case BO_Assign: 12450 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12451 if (getLangOpts().CPlusPlus && 12452 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12453 VK = LHS.get()->getValueKind(); 12454 OK = LHS.get()->getObjectKind(); 12455 } 12456 if (!ResultTy.isNull()) { 12457 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12458 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12459 12460 // Avoid copying a block to the heap if the block is assigned to a local 12461 // auto variable that is declared in the same scope as the block. This 12462 // optimization is unsafe if the local variable is declared in an outer 12463 // scope. For example: 12464 // 12465 // BlockTy b; 12466 // { 12467 // b = ^{...}; 12468 // } 12469 // // It is unsafe to invoke the block here if it wasn't copied to the 12470 // // heap. 12471 // b(); 12472 12473 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12474 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12475 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12476 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12477 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12478 } 12479 RecordModifiableNonNullParam(*this, LHS.get()); 12480 break; 12481 case BO_PtrMemD: 12482 case BO_PtrMemI: 12483 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12484 Opc == BO_PtrMemI); 12485 break; 12486 case BO_Mul: 12487 case BO_Div: 12488 ConvertHalfVec = true; 12489 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12490 Opc == BO_Div); 12491 break; 12492 case BO_Rem: 12493 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12494 break; 12495 case BO_Add: 12496 ConvertHalfVec = true; 12497 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12498 break; 12499 case BO_Sub: 12500 ConvertHalfVec = true; 12501 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12502 break; 12503 case BO_Shl: 12504 case BO_Shr: 12505 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12506 break; 12507 case BO_LE: 12508 case BO_LT: 12509 case BO_GE: 12510 case BO_GT: 12511 ConvertHalfVec = true; 12512 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12513 break; 12514 case BO_EQ: 12515 case BO_NE: 12516 ConvertHalfVec = true; 12517 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12518 break; 12519 case BO_Cmp: 12520 ConvertHalfVec = true; 12521 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12522 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12523 break; 12524 case BO_And: 12525 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12526 LLVM_FALLTHROUGH; 12527 case BO_Xor: 12528 case BO_Or: 12529 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12530 break; 12531 case BO_LAnd: 12532 case BO_LOr: 12533 ConvertHalfVec = true; 12534 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12535 break; 12536 case BO_MulAssign: 12537 case BO_DivAssign: 12538 ConvertHalfVec = true; 12539 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12540 Opc == BO_DivAssign); 12541 CompLHSTy = CompResultTy; 12542 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12543 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12544 break; 12545 case BO_RemAssign: 12546 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12547 CompLHSTy = CompResultTy; 12548 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12549 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12550 break; 12551 case BO_AddAssign: 12552 ConvertHalfVec = true; 12553 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12554 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12555 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12556 break; 12557 case BO_SubAssign: 12558 ConvertHalfVec = true; 12559 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12560 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12561 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12562 break; 12563 case BO_ShlAssign: 12564 case BO_ShrAssign: 12565 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12566 CompLHSTy = CompResultTy; 12567 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12568 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12569 break; 12570 case BO_AndAssign: 12571 case BO_OrAssign: // fallthrough 12572 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12573 LLVM_FALLTHROUGH; 12574 case BO_XorAssign: 12575 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12576 CompLHSTy = CompResultTy; 12577 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12578 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12579 break; 12580 case BO_Comma: 12581 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12582 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12583 VK = RHS.get()->getValueKind(); 12584 OK = RHS.get()->getObjectKind(); 12585 } 12586 break; 12587 } 12588 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12589 return ExprError(); 12590 12591 // Some of the binary operations require promoting operands of half vector to 12592 // float vectors and truncating the result back to half vector. For now, we do 12593 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12594 // arm64). 12595 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12596 isVector(LHS.get()->getType(), Context.HalfTy) && 12597 "both sides are half vectors or neither sides are"); 12598 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12599 LHS.get()->getType()); 12600 12601 // Check for array bounds violations for both sides of the BinaryOperator 12602 CheckArrayAccess(LHS.get()); 12603 CheckArrayAccess(RHS.get()); 12604 12605 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12606 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12607 &Context.Idents.get("object_setClass"), 12608 SourceLocation(), LookupOrdinaryName); 12609 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12610 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12611 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12612 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12613 "object_setClass(") 12614 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12615 ",") 12616 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12617 } 12618 else 12619 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12620 } 12621 else if (const ObjCIvarRefExpr *OIRE = 12622 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12623 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12624 12625 // Opc is not a compound assignment if CompResultTy is null. 12626 if (CompResultTy.isNull()) { 12627 if (ConvertHalfVec) 12628 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12629 OpLoc, FPFeatures); 12630 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12631 OK, OpLoc, FPFeatures); 12632 } 12633 12634 // Handle compound assignments. 12635 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12636 OK_ObjCProperty) { 12637 VK = VK_LValue; 12638 OK = LHS.get()->getObjectKind(); 12639 } 12640 12641 if (ConvertHalfVec) 12642 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12643 OpLoc, FPFeatures); 12644 12645 return new (Context) CompoundAssignOperator( 12646 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12647 OpLoc, FPFeatures); 12648 } 12649 12650 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12651 /// operators are mixed in a way that suggests that the programmer forgot that 12652 /// comparison operators have higher precedence. The most typical example of 12653 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12654 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12655 SourceLocation OpLoc, Expr *LHSExpr, 12656 Expr *RHSExpr) { 12657 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12658 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12659 12660 // Check that one of the sides is a comparison operator and the other isn't. 12661 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12662 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12663 if (isLeftComp == isRightComp) 12664 return; 12665 12666 // Bitwise operations are sometimes used as eager logical ops. 12667 // Don't diagnose this. 12668 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12669 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12670 if (isLeftBitwise || isRightBitwise) 12671 return; 12672 12673 SourceRange DiagRange = isLeftComp 12674 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12675 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12676 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12677 SourceRange ParensRange = 12678 isLeftComp 12679 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12680 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12681 12682 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12683 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12684 SuggestParentheses(Self, OpLoc, 12685 Self.PDiag(diag::note_precedence_silence) << OpStr, 12686 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12687 SuggestParentheses(Self, OpLoc, 12688 Self.PDiag(diag::note_precedence_bitwise_first) 12689 << BinaryOperator::getOpcodeStr(Opc), 12690 ParensRange); 12691 } 12692 12693 /// It accepts a '&&' expr that is inside a '||' one. 12694 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12695 /// in parentheses. 12696 static void 12697 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12698 BinaryOperator *Bop) { 12699 assert(Bop->getOpcode() == BO_LAnd); 12700 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12701 << Bop->getSourceRange() << OpLoc; 12702 SuggestParentheses(Self, Bop->getOperatorLoc(), 12703 Self.PDiag(diag::note_precedence_silence) 12704 << Bop->getOpcodeStr(), 12705 Bop->getSourceRange()); 12706 } 12707 12708 /// Returns true if the given expression can be evaluated as a constant 12709 /// 'true'. 12710 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12711 bool Res; 12712 return !E->isValueDependent() && 12713 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12714 } 12715 12716 /// Returns true if the given expression can be evaluated as a constant 12717 /// 'false'. 12718 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12719 bool Res; 12720 return !E->isValueDependent() && 12721 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12722 } 12723 12724 /// Look for '&&' in the left hand of a '||' expr. 12725 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12726 Expr *LHSExpr, Expr *RHSExpr) { 12727 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12728 if (Bop->getOpcode() == BO_LAnd) { 12729 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12730 if (EvaluatesAsFalse(S, RHSExpr)) 12731 return; 12732 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12733 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12734 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12735 } else if (Bop->getOpcode() == BO_LOr) { 12736 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12737 // If it's "a || b && 1 || c" we didn't warn earlier for 12738 // "a || b && 1", but warn now. 12739 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12740 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12741 } 12742 } 12743 } 12744 } 12745 12746 /// Look for '&&' in the right hand of a '||' expr. 12747 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12748 Expr *LHSExpr, Expr *RHSExpr) { 12749 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12750 if (Bop->getOpcode() == BO_LAnd) { 12751 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12752 if (EvaluatesAsFalse(S, LHSExpr)) 12753 return; 12754 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12755 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12756 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12757 } 12758 } 12759 } 12760 12761 /// Look for bitwise op in the left or right hand of a bitwise op with 12762 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12763 /// the '&' expression in parentheses. 12764 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12765 SourceLocation OpLoc, Expr *SubExpr) { 12766 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12767 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12768 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12769 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12770 << Bop->getSourceRange() << OpLoc; 12771 SuggestParentheses(S, Bop->getOperatorLoc(), 12772 S.PDiag(diag::note_precedence_silence) 12773 << Bop->getOpcodeStr(), 12774 Bop->getSourceRange()); 12775 } 12776 } 12777 } 12778 12779 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12780 Expr *SubExpr, StringRef Shift) { 12781 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12782 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12783 StringRef Op = Bop->getOpcodeStr(); 12784 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12785 << Bop->getSourceRange() << OpLoc << Shift << Op; 12786 SuggestParentheses(S, Bop->getOperatorLoc(), 12787 S.PDiag(diag::note_precedence_silence) << Op, 12788 Bop->getSourceRange()); 12789 } 12790 } 12791 } 12792 12793 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12794 Expr *LHSExpr, Expr *RHSExpr) { 12795 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12796 if (!OCE) 12797 return; 12798 12799 FunctionDecl *FD = OCE->getDirectCallee(); 12800 if (!FD || !FD->isOverloadedOperator()) 12801 return; 12802 12803 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12804 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12805 return; 12806 12807 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12808 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12809 << (Kind == OO_LessLess); 12810 SuggestParentheses(S, OCE->getOperatorLoc(), 12811 S.PDiag(diag::note_precedence_silence) 12812 << (Kind == OO_LessLess ? "<<" : ">>"), 12813 OCE->getSourceRange()); 12814 SuggestParentheses( 12815 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12816 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12817 } 12818 12819 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12820 /// precedence. 12821 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12822 SourceLocation OpLoc, Expr *LHSExpr, 12823 Expr *RHSExpr){ 12824 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12825 if (BinaryOperator::isBitwiseOp(Opc)) 12826 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12827 12828 // Diagnose "arg1 & arg2 | arg3" 12829 if ((Opc == BO_Or || Opc == BO_Xor) && 12830 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12831 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12832 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12833 } 12834 12835 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12836 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12837 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12838 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12839 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12840 } 12841 12842 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12843 || Opc == BO_Shr) { 12844 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12845 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12846 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12847 } 12848 12849 // Warn on overloaded shift operators and comparisons, such as: 12850 // cout << 5 == 4; 12851 if (BinaryOperator::isComparisonOp(Opc)) 12852 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12853 } 12854 12855 // Binary Operators. 'Tok' is the token for the operator. 12856 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12857 tok::TokenKind Kind, 12858 Expr *LHSExpr, Expr *RHSExpr) { 12859 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12860 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12861 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12862 12863 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12864 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12865 12866 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12867 } 12868 12869 /// Build an overloaded binary operator expression in the given scope. 12870 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12871 BinaryOperatorKind Opc, 12872 Expr *LHS, Expr *RHS) { 12873 switch (Opc) { 12874 case BO_Assign: 12875 case BO_DivAssign: 12876 case BO_RemAssign: 12877 case BO_SubAssign: 12878 case BO_AndAssign: 12879 case BO_OrAssign: 12880 case BO_XorAssign: 12881 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12882 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12883 break; 12884 default: 12885 break; 12886 } 12887 12888 // Find all of the overloaded operators visible from this 12889 // point. We perform both an operator-name lookup from the local 12890 // scope and an argument-dependent lookup based on the types of 12891 // the arguments. 12892 UnresolvedSet<16> Functions; 12893 OverloadedOperatorKind OverOp 12894 = BinaryOperator::getOverloadedOperator(Opc); 12895 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12896 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12897 RHS->getType(), Functions); 12898 12899 // Build the (potentially-overloaded, potentially-dependent) 12900 // binary operation. 12901 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12902 } 12903 12904 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12905 BinaryOperatorKind Opc, 12906 Expr *LHSExpr, Expr *RHSExpr) { 12907 ExprResult LHS, RHS; 12908 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12909 if (!LHS.isUsable() || !RHS.isUsable()) 12910 return ExprError(); 12911 LHSExpr = LHS.get(); 12912 RHSExpr = RHS.get(); 12913 12914 // We want to end up calling one of checkPseudoObjectAssignment 12915 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12916 // both expressions are overloadable or either is type-dependent), 12917 // or CreateBuiltinBinOp (in any other case). We also want to get 12918 // any placeholder types out of the way. 12919 12920 // Handle pseudo-objects in the LHS. 12921 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12922 // Assignments with a pseudo-object l-value need special analysis. 12923 if (pty->getKind() == BuiltinType::PseudoObject && 12924 BinaryOperator::isAssignmentOp(Opc)) 12925 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12926 12927 // Don't resolve overloads if the other type is overloadable. 12928 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12929 // We can't actually test that if we still have a placeholder, 12930 // though. Fortunately, none of the exceptions we see in that 12931 // code below are valid when the LHS is an overload set. Note 12932 // that an overload set can be dependently-typed, but it never 12933 // instantiates to having an overloadable type. 12934 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12935 if (resolvedRHS.isInvalid()) return ExprError(); 12936 RHSExpr = resolvedRHS.get(); 12937 12938 if (RHSExpr->isTypeDependent() || 12939 RHSExpr->getType()->isOverloadableType()) 12940 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12941 } 12942 12943 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12944 // template, diagnose the missing 'template' keyword instead of diagnosing 12945 // an invalid use of a bound member function. 12946 // 12947 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12948 // to C++1z [over.over]/1.4, but we already checked for that case above. 12949 if (Opc == BO_LT && inTemplateInstantiation() && 12950 (pty->getKind() == BuiltinType::BoundMember || 12951 pty->getKind() == BuiltinType::Overload)) { 12952 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12953 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12954 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12955 return isa<FunctionTemplateDecl>(ND); 12956 })) { 12957 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12958 : OE->getNameLoc(), 12959 diag::err_template_kw_missing) 12960 << OE->getName().getAsString() << ""; 12961 return ExprError(); 12962 } 12963 } 12964 12965 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12966 if (LHS.isInvalid()) return ExprError(); 12967 LHSExpr = LHS.get(); 12968 } 12969 12970 // Handle pseudo-objects in the RHS. 12971 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12972 // An overload in the RHS can potentially be resolved by the type 12973 // being assigned to. 12974 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12975 if (getLangOpts().CPlusPlus && 12976 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12977 LHSExpr->getType()->isOverloadableType())) 12978 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12979 12980 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12981 } 12982 12983 // Don't resolve overloads if the other type is overloadable. 12984 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12985 LHSExpr->getType()->isOverloadableType()) 12986 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12987 12988 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12989 if (!resolvedRHS.isUsable()) return ExprError(); 12990 RHSExpr = resolvedRHS.get(); 12991 } 12992 12993 if (getLangOpts().CPlusPlus) { 12994 // If either expression is type-dependent, always build an 12995 // overloaded op. 12996 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12997 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12998 12999 // Otherwise, build an overloaded op if either expression has an 13000 // overloadable type. 13001 if (LHSExpr->getType()->isOverloadableType() || 13002 RHSExpr->getType()->isOverloadableType()) 13003 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13004 } 13005 13006 // Build a built-in binary operation. 13007 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13008 } 13009 13010 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13011 if (T.isNull() || T->isDependentType()) 13012 return false; 13013 13014 if (!T->isPromotableIntegerType()) 13015 return true; 13016 13017 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13018 } 13019 13020 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13021 UnaryOperatorKind Opc, 13022 Expr *InputExpr) { 13023 ExprResult Input = InputExpr; 13024 ExprValueKind VK = VK_RValue; 13025 ExprObjectKind OK = OK_Ordinary; 13026 QualType resultType; 13027 bool CanOverflow = false; 13028 13029 bool ConvertHalfVec = false; 13030 if (getLangOpts().OpenCL) { 13031 QualType Ty = InputExpr->getType(); 13032 // The only legal unary operation for atomics is '&'. 13033 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13034 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13035 // only with a builtin functions and therefore should be disallowed here. 13036 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13037 || Ty->isBlockPointerType())) { 13038 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13039 << InputExpr->getType() 13040 << Input.get()->getSourceRange()); 13041 } 13042 } 13043 // Diagnose operations on the unsupported types for OpenMP device compilation. 13044 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13045 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13046 UnaryOperator::isArithmeticOp(Opc)) 13047 checkOpenMPDeviceExpr(InputExpr); 13048 } 13049 13050 switch (Opc) { 13051 case UO_PreInc: 13052 case UO_PreDec: 13053 case UO_PostInc: 13054 case UO_PostDec: 13055 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13056 OpLoc, 13057 Opc == UO_PreInc || 13058 Opc == UO_PostInc, 13059 Opc == UO_PreInc || 13060 Opc == UO_PreDec); 13061 CanOverflow = isOverflowingIntegerType(Context, resultType); 13062 break; 13063 case UO_AddrOf: 13064 resultType = CheckAddressOfOperand(Input, OpLoc); 13065 CheckAddressOfNoDeref(InputExpr); 13066 RecordModifiableNonNullParam(*this, InputExpr); 13067 break; 13068 case UO_Deref: { 13069 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13070 if (Input.isInvalid()) return ExprError(); 13071 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13072 break; 13073 } 13074 case UO_Plus: 13075 case UO_Minus: 13076 CanOverflow = Opc == UO_Minus && 13077 isOverflowingIntegerType(Context, Input.get()->getType()); 13078 Input = UsualUnaryConversions(Input.get()); 13079 if (Input.isInvalid()) return ExprError(); 13080 // Unary plus and minus require promoting an operand of half vector to a 13081 // float vector and truncating the result back to a half vector. For now, we 13082 // do this only when HalfArgsAndReturns is set (that is, when the target is 13083 // arm or arm64). 13084 ConvertHalfVec = 13085 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13086 13087 // If the operand is a half vector, promote it to a float vector. 13088 if (ConvertHalfVec) 13089 Input = convertVector(Input.get(), Context.FloatTy, *this); 13090 resultType = Input.get()->getType(); 13091 if (resultType->isDependentType()) 13092 break; 13093 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13094 break; 13095 else if (resultType->isVectorType() && 13096 // The z vector extensions don't allow + or - with bool vectors. 13097 (!Context.getLangOpts().ZVector || 13098 resultType->getAs<VectorType>()->getVectorKind() != 13099 VectorType::AltiVecBool)) 13100 break; 13101 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13102 Opc == UO_Plus && 13103 resultType->isPointerType()) 13104 break; 13105 13106 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13107 << resultType << Input.get()->getSourceRange()); 13108 13109 case UO_Not: // bitwise complement 13110 Input = UsualUnaryConversions(Input.get()); 13111 if (Input.isInvalid()) 13112 return ExprError(); 13113 resultType = Input.get()->getType(); 13114 13115 if (resultType->isDependentType()) 13116 break; 13117 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13118 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13119 // C99 does not support '~' for complex conjugation. 13120 Diag(OpLoc, diag::ext_integer_complement_complex) 13121 << resultType << Input.get()->getSourceRange(); 13122 else if (resultType->hasIntegerRepresentation()) 13123 break; 13124 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13125 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13126 // on vector float types. 13127 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13128 if (!T->isIntegerType()) 13129 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13130 << resultType << Input.get()->getSourceRange()); 13131 } else { 13132 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13133 << resultType << Input.get()->getSourceRange()); 13134 } 13135 break; 13136 13137 case UO_LNot: // logical negation 13138 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13139 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13140 if (Input.isInvalid()) return ExprError(); 13141 resultType = Input.get()->getType(); 13142 13143 // Though we still have to promote half FP to float... 13144 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13145 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13146 resultType = Context.FloatTy; 13147 } 13148 13149 if (resultType->isDependentType()) 13150 break; 13151 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13152 // C99 6.5.3.3p1: ok, fallthrough; 13153 if (Context.getLangOpts().CPlusPlus) { 13154 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13155 // operand contextually converted to bool. 13156 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13157 ScalarTypeToBooleanCastKind(resultType)); 13158 } else if (Context.getLangOpts().OpenCL && 13159 Context.getLangOpts().OpenCLVersion < 120) { 13160 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13161 // operate on scalar float types. 13162 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13163 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13164 << resultType << Input.get()->getSourceRange()); 13165 } 13166 } else if (resultType->isExtVectorType()) { 13167 if (Context.getLangOpts().OpenCL && 13168 Context.getLangOpts().OpenCLVersion < 120) { 13169 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13170 // operate on vector float types. 13171 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13172 if (!T->isIntegerType()) 13173 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13174 << resultType << Input.get()->getSourceRange()); 13175 } 13176 // Vector logical not returns the signed variant of the operand type. 13177 resultType = GetSignedVectorType(resultType); 13178 break; 13179 } else { 13180 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13181 // type in C++. We should allow that here too. 13182 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13183 << resultType << Input.get()->getSourceRange()); 13184 } 13185 13186 // LNot always has type int. C99 6.5.3.3p5. 13187 // In C++, it's bool. C++ 5.3.1p8 13188 resultType = Context.getLogicalOperationType(); 13189 break; 13190 case UO_Real: 13191 case UO_Imag: 13192 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13193 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13194 // complex l-values to ordinary l-values and all other values to r-values. 13195 if (Input.isInvalid()) return ExprError(); 13196 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13197 if (Input.get()->getValueKind() != VK_RValue && 13198 Input.get()->getObjectKind() == OK_Ordinary) 13199 VK = Input.get()->getValueKind(); 13200 } else if (!getLangOpts().CPlusPlus) { 13201 // In C, a volatile scalar is read by __imag. In C++, it is not. 13202 Input = DefaultLvalueConversion(Input.get()); 13203 } 13204 break; 13205 case UO_Extension: 13206 resultType = Input.get()->getType(); 13207 VK = Input.get()->getValueKind(); 13208 OK = Input.get()->getObjectKind(); 13209 break; 13210 case UO_Coawait: 13211 // It's unnecessary to represent the pass-through operator co_await in the 13212 // AST; just return the input expression instead. 13213 assert(!Input.get()->getType()->isDependentType() && 13214 "the co_await expression must be non-dependant before " 13215 "building operator co_await"); 13216 return Input; 13217 } 13218 if (resultType.isNull() || Input.isInvalid()) 13219 return ExprError(); 13220 13221 // Check for array bounds violations in the operand of the UnaryOperator, 13222 // except for the '*' and '&' operators that have to be handled specially 13223 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13224 // that are explicitly defined as valid by the standard). 13225 if (Opc != UO_AddrOf && Opc != UO_Deref) 13226 CheckArrayAccess(Input.get()); 13227 13228 auto *UO = new (Context) 13229 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13230 13231 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13232 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13233 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13234 13235 // Convert the result back to a half vector. 13236 if (ConvertHalfVec) 13237 return convertVector(UO, Context.HalfTy, *this); 13238 return UO; 13239 } 13240 13241 /// Determine whether the given expression is a qualified member 13242 /// access expression, of a form that could be turned into a pointer to member 13243 /// with the address-of operator. 13244 bool Sema::isQualifiedMemberAccess(Expr *E) { 13245 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13246 if (!DRE->getQualifier()) 13247 return false; 13248 13249 ValueDecl *VD = DRE->getDecl(); 13250 if (!VD->isCXXClassMember()) 13251 return false; 13252 13253 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13254 return true; 13255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13256 return Method->isInstance(); 13257 13258 return false; 13259 } 13260 13261 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13262 if (!ULE->getQualifier()) 13263 return false; 13264 13265 for (NamedDecl *D : ULE->decls()) { 13266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13267 if (Method->isInstance()) 13268 return true; 13269 } else { 13270 // Overload set does not contain methods. 13271 break; 13272 } 13273 } 13274 13275 return false; 13276 } 13277 13278 return false; 13279 } 13280 13281 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13282 UnaryOperatorKind Opc, Expr *Input) { 13283 // First things first: handle placeholders so that the 13284 // overloaded-operator check considers the right type. 13285 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13286 // Increment and decrement of pseudo-object references. 13287 if (pty->getKind() == BuiltinType::PseudoObject && 13288 UnaryOperator::isIncrementDecrementOp(Opc)) 13289 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13290 13291 // extension is always a builtin operator. 13292 if (Opc == UO_Extension) 13293 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13294 13295 // & gets special logic for several kinds of placeholder. 13296 // The builtin code knows what to do. 13297 if (Opc == UO_AddrOf && 13298 (pty->getKind() == BuiltinType::Overload || 13299 pty->getKind() == BuiltinType::UnknownAny || 13300 pty->getKind() == BuiltinType::BoundMember)) 13301 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13302 13303 // Anything else needs to be handled now. 13304 ExprResult Result = CheckPlaceholderExpr(Input); 13305 if (Result.isInvalid()) return ExprError(); 13306 Input = Result.get(); 13307 } 13308 13309 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13310 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13311 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13312 // Find all of the overloaded operators visible from this 13313 // point. We perform both an operator-name lookup from the local 13314 // scope and an argument-dependent lookup based on the types of 13315 // the arguments. 13316 UnresolvedSet<16> Functions; 13317 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13318 if (S && OverOp != OO_None) 13319 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13320 Functions); 13321 13322 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13323 } 13324 13325 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13326 } 13327 13328 // Unary Operators. 'Tok' is the token for the operator. 13329 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13330 tok::TokenKind Op, Expr *Input) { 13331 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13332 } 13333 13334 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13335 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13336 LabelDecl *TheDecl) { 13337 TheDecl->markUsed(Context); 13338 // Create the AST node. The address of a label always has type 'void*'. 13339 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13340 Context.getPointerType(Context.VoidTy)); 13341 } 13342 13343 void Sema::ActOnStartStmtExpr() { 13344 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13345 } 13346 13347 void Sema::ActOnStmtExprError() { 13348 // Note that function is also called by TreeTransform when leaving a 13349 // StmtExpr scope without rebuilding anything. 13350 13351 DiscardCleanupsInEvaluationContext(); 13352 PopExpressionEvaluationContext(); 13353 } 13354 13355 ExprResult 13356 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13357 SourceLocation RPLoc) { // "({..})" 13358 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13359 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13360 13361 if (hasAnyUnrecoverableErrorsInThisFunction()) 13362 DiscardCleanupsInEvaluationContext(); 13363 assert(!Cleanup.exprNeedsCleanups() && 13364 "cleanups within StmtExpr not correctly bound!"); 13365 PopExpressionEvaluationContext(); 13366 13367 // FIXME: there are a variety of strange constraints to enforce here, for 13368 // example, it is not possible to goto into a stmt expression apparently. 13369 // More semantic analysis is needed. 13370 13371 // If there are sub-stmts in the compound stmt, take the type of the last one 13372 // as the type of the stmtexpr. 13373 QualType Ty = Context.VoidTy; 13374 bool StmtExprMayBindToTemp = false; 13375 if (!Compound->body_empty()) { 13376 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) { 13377 if (const Expr *Value = LastStmt->getExprStmt()) { 13378 StmtExprMayBindToTemp = true; 13379 Ty = Value->getType(); 13380 } 13381 } 13382 } 13383 13384 // FIXME: Check that expression type is complete/non-abstract; statement 13385 // expressions are not lvalues. 13386 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13387 if (StmtExprMayBindToTemp) 13388 return MaybeBindToTemporary(ResStmtExpr); 13389 return ResStmtExpr; 13390 } 13391 13392 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13393 if (ER.isInvalid()) 13394 return ExprError(); 13395 13396 // Do function/array conversion on the last expression, but not 13397 // lvalue-to-rvalue. However, initialize an unqualified type. 13398 ER = DefaultFunctionArrayConversion(ER.get()); 13399 if (ER.isInvalid()) 13400 return ExprError(); 13401 Expr *E = ER.get(); 13402 13403 if (E->isTypeDependent()) 13404 return E; 13405 13406 // In ARC, if the final expression ends in a consume, splice 13407 // the consume out and bind it later. In the alternate case 13408 // (when dealing with a retainable type), the result 13409 // initialization will create a produce. In both cases the 13410 // result will be +1, and we'll need to balance that out with 13411 // a bind. 13412 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13413 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13414 return Cast->getSubExpr(); 13415 13416 // FIXME: Provide a better location for the initialization. 13417 return PerformCopyInitialization( 13418 InitializedEntity::InitializeStmtExprResult( 13419 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13420 SourceLocation(), E); 13421 } 13422 13423 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13424 TypeSourceInfo *TInfo, 13425 ArrayRef<OffsetOfComponent> Components, 13426 SourceLocation RParenLoc) { 13427 QualType ArgTy = TInfo->getType(); 13428 bool Dependent = ArgTy->isDependentType(); 13429 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13430 13431 // We must have at least one component that refers to the type, and the first 13432 // one is known to be a field designator. Verify that the ArgTy represents 13433 // a struct/union/class. 13434 if (!Dependent && !ArgTy->isRecordType()) 13435 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13436 << ArgTy << TypeRange); 13437 13438 // Type must be complete per C99 7.17p3 because a declaring a variable 13439 // with an incomplete type would be ill-formed. 13440 if (!Dependent 13441 && RequireCompleteType(BuiltinLoc, ArgTy, 13442 diag::err_offsetof_incomplete_type, TypeRange)) 13443 return ExprError(); 13444 13445 bool DidWarnAboutNonPOD = false; 13446 QualType CurrentType = ArgTy; 13447 SmallVector<OffsetOfNode, 4> Comps; 13448 SmallVector<Expr*, 4> Exprs; 13449 for (const OffsetOfComponent &OC : Components) { 13450 if (OC.isBrackets) { 13451 // Offset of an array sub-field. TODO: Should we allow vector elements? 13452 if (!CurrentType->isDependentType()) { 13453 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13454 if(!AT) 13455 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13456 << CurrentType); 13457 CurrentType = AT->getElementType(); 13458 } else 13459 CurrentType = Context.DependentTy; 13460 13461 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13462 if (IdxRval.isInvalid()) 13463 return ExprError(); 13464 Expr *Idx = IdxRval.get(); 13465 13466 // The expression must be an integral expression. 13467 // FIXME: An integral constant expression? 13468 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13469 !Idx->getType()->isIntegerType()) 13470 return ExprError( 13471 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13472 << Idx->getSourceRange()); 13473 13474 // Record this array index. 13475 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13476 Exprs.push_back(Idx); 13477 continue; 13478 } 13479 13480 // Offset of a field. 13481 if (CurrentType->isDependentType()) { 13482 // We have the offset of a field, but we can't look into the dependent 13483 // type. Just record the identifier of the field. 13484 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13485 CurrentType = Context.DependentTy; 13486 continue; 13487 } 13488 13489 // We need to have a complete type to look into. 13490 if (RequireCompleteType(OC.LocStart, CurrentType, 13491 diag::err_offsetof_incomplete_type)) 13492 return ExprError(); 13493 13494 // Look for the designated field. 13495 const RecordType *RC = CurrentType->getAs<RecordType>(); 13496 if (!RC) 13497 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13498 << CurrentType); 13499 RecordDecl *RD = RC->getDecl(); 13500 13501 // C++ [lib.support.types]p5: 13502 // The macro offsetof accepts a restricted set of type arguments in this 13503 // International Standard. type shall be a POD structure or a POD union 13504 // (clause 9). 13505 // C++11 [support.types]p4: 13506 // If type is not a standard-layout class (Clause 9), the results are 13507 // undefined. 13508 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13509 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13510 unsigned DiagID = 13511 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13512 : diag::ext_offsetof_non_pod_type; 13513 13514 if (!IsSafe && !DidWarnAboutNonPOD && 13515 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13516 PDiag(DiagID) 13517 << SourceRange(Components[0].LocStart, OC.LocEnd) 13518 << CurrentType)) 13519 DidWarnAboutNonPOD = true; 13520 } 13521 13522 // Look for the field. 13523 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13524 LookupQualifiedName(R, RD); 13525 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13526 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13527 if (!MemberDecl) { 13528 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13529 MemberDecl = IndirectMemberDecl->getAnonField(); 13530 } 13531 13532 if (!MemberDecl) 13533 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13534 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13535 OC.LocEnd)); 13536 13537 // C99 7.17p3: 13538 // (If the specified member is a bit-field, the behavior is undefined.) 13539 // 13540 // We diagnose this as an error. 13541 if (MemberDecl->isBitField()) { 13542 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13543 << MemberDecl->getDeclName() 13544 << SourceRange(BuiltinLoc, RParenLoc); 13545 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13546 return ExprError(); 13547 } 13548 13549 RecordDecl *Parent = MemberDecl->getParent(); 13550 if (IndirectMemberDecl) 13551 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13552 13553 // If the member was found in a base class, introduce OffsetOfNodes for 13554 // the base class indirections. 13555 CXXBasePaths Paths; 13556 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13557 Paths)) { 13558 if (Paths.getDetectedVirtual()) { 13559 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13560 << MemberDecl->getDeclName() 13561 << SourceRange(BuiltinLoc, RParenLoc); 13562 return ExprError(); 13563 } 13564 13565 CXXBasePath &Path = Paths.front(); 13566 for (const CXXBasePathElement &B : Path) 13567 Comps.push_back(OffsetOfNode(B.Base)); 13568 } 13569 13570 if (IndirectMemberDecl) { 13571 for (auto *FI : IndirectMemberDecl->chain()) { 13572 assert(isa<FieldDecl>(FI)); 13573 Comps.push_back(OffsetOfNode(OC.LocStart, 13574 cast<FieldDecl>(FI), OC.LocEnd)); 13575 } 13576 } else 13577 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13578 13579 CurrentType = MemberDecl->getType().getNonReferenceType(); 13580 } 13581 13582 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13583 Comps, Exprs, RParenLoc); 13584 } 13585 13586 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13587 SourceLocation BuiltinLoc, 13588 SourceLocation TypeLoc, 13589 ParsedType ParsedArgTy, 13590 ArrayRef<OffsetOfComponent> Components, 13591 SourceLocation RParenLoc) { 13592 13593 TypeSourceInfo *ArgTInfo; 13594 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13595 if (ArgTy.isNull()) 13596 return ExprError(); 13597 13598 if (!ArgTInfo) 13599 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13600 13601 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13602 } 13603 13604 13605 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13606 Expr *CondExpr, 13607 Expr *LHSExpr, Expr *RHSExpr, 13608 SourceLocation RPLoc) { 13609 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13610 13611 ExprValueKind VK = VK_RValue; 13612 ExprObjectKind OK = OK_Ordinary; 13613 QualType resType; 13614 bool ValueDependent = false; 13615 bool CondIsTrue = false; 13616 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13617 resType = Context.DependentTy; 13618 ValueDependent = true; 13619 } else { 13620 // The conditional expression is required to be a constant expression. 13621 llvm::APSInt condEval(32); 13622 ExprResult CondICE 13623 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13624 diag::err_typecheck_choose_expr_requires_constant, false); 13625 if (CondICE.isInvalid()) 13626 return ExprError(); 13627 CondExpr = CondICE.get(); 13628 CondIsTrue = condEval.getZExtValue(); 13629 13630 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13631 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13632 13633 resType = ActiveExpr->getType(); 13634 ValueDependent = ActiveExpr->isValueDependent(); 13635 VK = ActiveExpr->getValueKind(); 13636 OK = ActiveExpr->getObjectKind(); 13637 } 13638 13639 return new (Context) 13640 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13641 CondIsTrue, resType->isDependentType(), ValueDependent); 13642 } 13643 13644 //===----------------------------------------------------------------------===// 13645 // Clang Extensions. 13646 //===----------------------------------------------------------------------===// 13647 13648 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13649 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13650 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13651 13652 if (LangOpts.CPlusPlus) { 13653 Decl *ManglingContextDecl; 13654 if (MangleNumberingContext *MCtx = 13655 getCurrentMangleNumberContext(Block->getDeclContext(), 13656 ManglingContextDecl)) { 13657 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13658 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13659 } 13660 } 13661 13662 PushBlockScope(CurScope, Block); 13663 CurContext->addDecl(Block); 13664 if (CurScope) 13665 PushDeclContext(CurScope, Block); 13666 else 13667 CurContext = Block; 13668 13669 getCurBlock()->HasImplicitReturnType = true; 13670 13671 // Enter a new evaluation context to insulate the block from any 13672 // cleanups from the enclosing full-expression. 13673 PushExpressionEvaluationContext( 13674 ExpressionEvaluationContext::PotentiallyEvaluated); 13675 } 13676 13677 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13678 Scope *CurScope) { 13679 assert(ParamInfo.getIdentifier() == nullptr && 13680 "block-id should have no identifier!"); 13681 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13682 BlockScopeInfo *CurBlock = getCurBlock(); 13683 13684 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13685 QualType T = Sig->getType(); 13686 13687 // FIXME: We should allow unexpanded parameter packs here, but that would, 13688 // in turn, make the block expression contain unexpanded parameter packs. 13689 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13690 // Drop the parameters. 13691 FunctionProtoType::ExtProtoInfo EPI; 13692 EPI.HasTrailingReturn = false; 13693 EPI.TypeQuals.addConst(); 13694 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13695 Sig = Context.getTrivialTypeSourceInfo(T); 13696 } 13697 13698 // GetTypeForDeclarator always produces a function type for a block 13699 // literal signature. Furthermore, it is always a FunctionProtoType 13700 // unless the function was written with a typedef. 13701 assert(T->isFunctionType() && 13702 "GetTypeForDeclarator made a non-function block signature"); 13703 13704 // Look for an explicit signature in that function type. 13705 FunctionProtoTypeLoc ExplicitSignature; 13706 13707 if ((ExplicitSignature = 13708 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13709 13710 // Check whether that explicit signature was synthesized by 13711 // GetTypeForDeclarator. If so, don't save that as part of the 13712 // written signature. 13713 if (ExplicitSignature.getLocalRangeBegin() == 13714 ExplicitSignature.getLocalRangeEnd()) { 13715 // This would be much cheaper if we stored TypeLocs instead of 13716 // TypeSourceInfos. 13717 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13718 unsigned Size = Result.getFullDataSize(); 13719 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13720 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13721 13722 ExplicitSignature = FunctionProtoTypeLoc(); 13723 } 13724 } 13725 13726 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13727 CurBlock->FunctionType = T; 13728 13729 const FunctionType *Fn = T->getAs<FunctionType>(); 13730 QualType RetTy = Fn->getReturnType(); 13731 bool isVariadic = 13732 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13733 13734 CurBlock->TheDecl->setIsVariadic(isVariadic); 13735 13736 // Context.DependentTy is used as a placeholder for a missing block 13737 // return type. TODO: what should we do with declarators like: 13738 // ^ * { ... } 13739 // If the answer is "apply template argument deduction".... 13740 if (RetTy != Context.DependentTy) { 13741 CurBlock->ReturnType = RetTy; 13742 CurBlock->TheDecl->setBlockMissingReturnType(false); 13743 CurBlock->HasImplicitReturnType = false; 13744 } 13745 13746 // Push block parameters from the declarator if we had them. 13747 SmallVector<ParmVarDecl*, 8> Params; 13748 if (ExplicitSignature) { 13749 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13750 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13751 if (Param->getIdentifier() == nullptr && 13752 !Param->isImplicit() && 13753 !Param->isInvalidDecl() && 13754 !getLangOpts().CPlusPlus) 13755 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13756 Params.push_back(Param); 13757 } 13758 13759 // Fake up parameter variables if we have a typedef, like 13760 // ^ fntype { ... } 13761 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13762 for (const auto &I : Fn->param_types()) { 13763 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13764 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13765 Params.push_back(Param); 13766 } 13767 } 13768 13769 // Set the parameters on the block decl. 13770 if (!Params.empty()) { 13771 CurBlock->TheDecl->setParams(Params); 13772 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13773 /*CheckParameterNames=*/false); 13774 } 13775 13776 // Finally we can process decl attributes. 13777 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13778 13779 // Put the parameter variables in scope. 13780 for (auto AI : CurBlock->TheDecl->parameters()) { 13781 AI->setOwningFunction(CurBlock->TheDecl); 13782 13783 // If this has an identifier, add it to the scope stack. 13784 if (AI->getIdentifier()) { 13785 CheckShadow(CurBlock->TheScope, AI); 13786 13787 PushOnScopeChains(AI, CurBlock->TheScope); 13788 } 13789 } 13790 } 13791 13792 /// ActOnBlockError - If there is an error parsing a block, this callback 13793 /// is invoked to pop the information about the block from the action impl. 13794 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13795 // Leave the expression-evaluation context. 13796 DiscardCleanupsInEvaluationContext(); 13797 PopExpressionEvaluationContext(); 13798 13799 // Pop off CurBlock, handle nested blocks. 13800 PopDeclContext(); 13801 PopFunctionScopeInfo(); 13802 } 13803 13804 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13805 /// literal was successfully completed. ^(int x){...} 13806 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13807 Stmt *Body, Scope *CurScope) { 13808 // If blocks are disabled, emit an error. 13809 if (!LangOpts.Blocks) 13810 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13811 13812 // Leave the expression-evaluation context. 13813 if (hasAnyUnrecoverableErrorsInThisFunction()) 13814 DiscardCleanupsInEvaluationContext(); 13815 assert(!Cleanup.exprNeedsCleanups() && 13816 "cleanups within block not correctly bound!"); 13817 PopExpressionEvaluationContext(); 13818 13819 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13820 BlockDecl *BD = BSI->TheDecl; 13821 13822 if (BSI->HasImplicitReturnType) 13823 deduceClosureReturnType(*BSI); 13824 13825 PopDeclContext(); 13826 13827 QualType RetTy = Context.VoidTy; 13828 if (!BSI->ReturnType.isNull()) 13829 RetTy = BSI->ReturnType; 13830 13831 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13832 QualType BlockTy; 13833 13834 // Set the captured variables on the block. 13835 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13836 SmallVector<BlockDecl::Capture, 4> Captures; 13837 for (Capture &Cap : BSI->Captures) { 13838 if (Cap.isThisCapture()) 13839 continue; 13840 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13841 Cap.isNested(), Cap.getInitExpr()); 13842 Captures.push_back(NewCap); 13843 } 13844 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13845 13846 // If the user wrote a function type in some form, try to use that. 13847 if (!BSI->FunctionType.isNull()) { 13848 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13849 13850 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13851 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13852 13853 // Turn protoless block types into nullary block types. 13854 if (isa<FunctionNoProtoType>(FTy)) { 13855 FunctionProtoType::ExtProtoInfo EPI; 13856 EPI.ExtInfo = Ext; 13857 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13858 13859 // Otherwise, if we don't need to change anything about the function type, 13860 // preserve its sugar structure. 13861 } else if (FTy->getReturnType() == RetTy && 13862 (!NoReturn || FTy->getNoReturnAttr())) { 13863 BlockTy = BSI->FunctionType; 13864 13865 // Otherwise, make the minimal modifications to the function type. 13866 } else { 13867 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13868 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13869 EPI.TypeQuals = Qualifiers(); 13870 EPI.ExtInfo = Ext; 13871 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13872 } 13873 13874 // If we don't have a function type, just build one from nothing. 13875 } else { 13876 FunctionProtoType::ExtProtoInfo EPI; 13877 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13878 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13879 } 13880 13881 DiagnoseUnusedParameters(BD->parameters()); 13882 BlockTy = Context.getBlockPointerType(BlockTy); 13883 13884 // If needed, diagnose invalid gotos and switches in the block. 13885 if (getCurFunction()->NeedsScopeChecking() && 13886 !PP.isCodeCompletionEnabled()) 13887 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13888 13889 BD->setBody(cast<CompoundStmt>(Body)); 13890 13891 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13892 DiagnoseUnguardedAvailabilityViolations(BD); 13893 13894 // Try to apply the named return value optimization. We have to check again 13895 // if we can do this, though, because blocks keep return statements around 13896 // to deduce an implicit return type. 13897 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13898 !BD->isDependentContext()) 13899 computeNRVO(Body, BSI); 13900 13901 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13902 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13903 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13904 13905 // If the block isn't obviously global, i.e. it captures anything at 13906 // all, then we need to do a few things in the surrounding context: 13907 if (Result->getBlockDecl()->hasCaptures()) { 13908 // First, this expression has a new cleanup object. 13909 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13910 Cleanup.setExprNeedsCleanups(true); 13911 13912 // It also gets a branch-protected scope if any of the captured 13913 // variables needs destruction. 13914 for (const auto &CI : Result->getBlockDecl()->captures()) { 13915 const VarDecl *var = CI.getVariable(); 13916 if (var->getType().isDestructedType() != QualType::DK_none) { 13917 setFunctionHasBranchProtectedScope(); 13918 break; 13919 } 13920 } 13921 } 13922 13923 if (getCurFunction()) 13924 getCurFunction()->addBlock(BD); 13925 13926 return Result; 13927 } 13928 13929 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13930 SourceLocation RPLoc) { 13931 TypeSourceInfo *TInfo; 13932 GetTypeFromParser(Ty, &TInfo); 13933 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13934 } 13935 13936 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13937 Expr *E, TypeSourceInfo *TInfo, 13938 SourceLocation RPLoc) { 13939 Expr *OrigExpr = E; 13940 bool IsMS = false; 13941 13942 // CUDA device code does not support varargs. 13943 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13944 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13945 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13946 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13947 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13948 } 13949 } 13950 13951 // NVPTX does not support va_arg expression. 13952 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 13953 Context.getTargetInfo().getTriple().isNVPTX()) 13954 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 13955 13956 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13957 // as Microsoft ABI on an actual Microsoft platform, where 13958 // __builtin_ms_va_list and __builtin_va_list are the same.) 13959 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13960 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13961 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13962 if (Context.hasSameType(MSVaListType, E->getType())) { 13963 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13964 return ExprError(); 13965 IsMS = true; 13966 } 13967 } 13968 13969 // Get the va_list type 13970 QualType VaListType = Context.getBuiltinVaListType(); 13971 if (!IsMS) { 13972 if (VaListType->isArrayType()) { 13973 // Deal with implicit array decay; for example, on x86-64, 13974 // va_list is an array, but it's supposed to decay to 13975 // a pointer for va_arg. 13976 VaListType = Context.getArrayDecayedType(VaListType); 13977 // Make sure the input expression also decays appropriately. 13978 ExprResult Result = UsualUnaryConversions(E); 13979 if (Result.isInvalid()) 13980 return ExprError(); 13981 E = Result.get(); 13982 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13983 // If va_list is a record type and we are compiling in C++ mode, 13984 // check the argument using reference binding. 13985 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13986 Context, Context.getLValueReferenceType(VaListType), false); 13987 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13988 if (Init.isInvalid()) 13989 return ExprError(); 13990 E = Init.getAs<Expr>(); 13991 } else { 13992 // Otherwise, the va_list argument must be an l-value because 13993 // it is modified by va_arg. 13994 if (!E->isTypeDependent() && 13995 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13996 return ExprError(); 13997 } 13998 } 13999 14000 if (!IsMS && !E->isTypeDependent() && 14001 !Context.hasSameType(VaListType, E->getType())) 14002 return ExprError( 14003 Diag(E->getBeginLoc(), 14004 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14005 << OrigExpr->getType() << E->getSourceRange()); 14006 14007 if (!TInfo->getType()->isDependentType()) { 14008 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14009 diag::err_second_parameter_to_va_arg_incomplete, 14010 TInfo->getTypeLoc())) 14011 return ExprError(); 14012 14013 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14014 TInfo->getType(), 14015 diag::err_second_parameter_to_va_arg_abstract, 14016 TInfo->getTypeLoc())) 14017 return ExprError(); 14018 14019 if (!TInfo->getType().isPODType(Context)) { 14020 Diag(TInfo->getTypeLoc().getBeginLoc(), 14021 TInfo->getType()->isObjCLifetimeType() 14022 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14023 : diag::warn_second_parameter_to_va_arg_not_pod) 14024 << TInfo->getType() 14025 << TInfo->getTypeLoc().getSourceRange(); 14026 } 14027 14028 // Check for va_arg where arguments of the given type will be promoted 14029 // (i.e. this va_arg is guaranteed to have undefined behavior). 14030 QualType PromoteType; 14031 if (TInfo->getType()->isPromotableIntegerType()) { 14032 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14033 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14034 PromoteType = QualType(); 14035 } 14036 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14037 PromoteType = Context.DoubleTy; 14038 if (!PromoteType.isNull()) 14039 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14040 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14041 << TInfo->getType() 14042 << PromoteType 14043 << TInfo->getTypeLoc().getSourceRange()); 14044 } 14045 14046 QualType T = TInfo->getType().getNonLValueExprType(Context); 14047 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14048 } 14049 14050 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14051 // The type of __null will be int or long, depending on the size of 14052 // pointers on the target. 14053 QualType Ty; 14054 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14055 if (pw == Context.getTargetInfo().getIntWidth()) 14056 Ty = Context.IntTy; 14057 else if (pw == Context.getTargetInfo().getLongWidth()) 14058 Ty = Context.LongTy; 14059 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14060 Ty = Context.LongLongTy; 14061 else { 14062 llvm_unreachable("I don't know size of pointer!"); 14063 } 14064 14065 return new (Context) GNUNullExpr(Ty, TokenLoc); 14066 } 14067 14068 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14069 bool Diagnose) { 14070 if (!getLangOpts().ObjC) 14071 return false; 14072 14073 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14074 if (!PT) 14075 return false; 14076 14077 if (!PT->isObjCIdType()) { 14078 // Check if the destination is the 'NSString' interface. 14079 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14080 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14081 return false; 14082 } 14083 14084 // Ignore any parens, implicit casts (should only be 14085 // array-to-pointer decays), and not-so-opaque values. The last is 14086 // important for making this trigger for property assignments. 14087 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14088 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14089 if (OV->getSourceExpr()) 14090 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14091 14092 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14093 if (!SL || !SL->isAscii()) 14094 return false; 14095 if (Diagnose) { 14096 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14097 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14098 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14099 } 14100 return true; 14101 } 14102 14103 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14104 const Expr *SrcExpr) { 14105 if (!DstType->isFunctionPointerType() || 14106 !SrcExpr->getType()->isFunctionType()) 14107 return false; 14108 14109 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14110 if (!DRE) 14111 return false; 14112 14113 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14114 if (!FD) 14115 return false; 14116 14117 return !S.checkAddressOfFunctionIsAvailable(FD, 14118 /*Complain=*/true, 14119 SrcExpr->getBeginLoc()); 14120 } 14121 14122 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14123 SourceLocation Loc, 14124 QualType DstType, QualType SrcType, 14125 Expr *SrcExpr, AssignmentAction Action, 14126 bool *Complained) { 14127 if (Complained) 14128 *Complained = false; 14129 14130 // Decode the result (notice that AST's are still created for extensions). 14131 bool CheckInferredResultType = false; 14132 bool isInvalid = false; 14133 unsigned DiagKind = 0; 14134 FixItHint Hint; 14135 ConversionFixItGenerator ConvHints; 14136 bool MayHaveConvFixit = false; 14137 bool MayHaveFunctionDiff = false; 14138 const ObjCInterfaceDecl *IFace = nullptr; 14139 const ObjCProtocolDecl *PDecl = nullptr; 14140 14141 switch (ConvTy) { 14142 case Compatible: 14143 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14144 return false; 14145 14146 case PointerToInt: 14147 DiagKind = diag::ext_typecheck_convert_pointer_int; 14148 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14149 MayHaveConvFixit = true; 14150 break; 14151 case IntToPointer: 14152 DiagKind = diag::ext_typecheck_convert_int_pointer; 14153 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14154 MayHaveConvFixit = true; 14155 break; 14156 case IncompatiblePointer: 14157 if (Action == AA_Passing_CFAudited) 14158 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14159 else if (SrcType->isFunctionPointerType() && 14160 DstType->isFunctionPointerType()) 14161 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14162 else 14163 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14164 14165 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14166 SrcType->isObjCObjectPointerType(); 14167 if (Hint.isNull() && !CheckInferredResultType) { 14168 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14169 } 14170 else if (CheckInferredResultType) { 14171 SrcType = SrcType.getUnqualifiedType(); 14172 DstType = DstType.getUnqualifiedType(); 14173 } 14174 MayHaveConvFixit = true; 14175 break; 14176 case IncompatiblePointerSign: 14177 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14178 break; 14179 case FunctionVoidPointer: 14180 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14181 break; 14182 case IncompatiblePointerDiscardsQualifiers: { 14183 // Perform array-to-pointer decay if necessary. 14184 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14185 14186 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14187 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14188 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14189 DiagKind = diag::err_typecheck_incompatible_address_space; 14190 break; 14191 14192 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14193 DiagKind = diag::err_typecheck_incompatible_ownership; 14194 break; 14195 } 14196 14197 llvm_unreachable("unknown error case for discarding qualifiers!"); 14198 // fallthrough 14199 } 14200 case CompatiblePointerDiscardsQualifiers: 14201 // If the qualifiers lost were because we were applying the 14202 // (deprecated) C++ conversion from a string literal to a char* 14203 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14204 // Ideally, this check would be performed in 14205 // checkPointerTypesForAssignment. However, that would require a 14206 // bit of refactoring (so that the second argument is an 14207 // expression, rather than a type), which should be done as part 14208 // of a larger effort to fix checkPointerTypesForAssignment for 14209 // C++ semantics. 14210 if (getLangOpts().CPlusPlus && 14211 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14212 return false; 14213 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14214 break; 14215 case IncompatibleNestedPointerQualifiers: 14216 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14217 break; 14218 case IntToBlockPointer: 14219 DiagKind = diag::err_int_to_block_pointer; 14220 break; 14221 case IncompatibleBlockPointer: 14222 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14223 break; 14224 case IncompatibleObjCQualifiedId: { 14225 if (SrcType->isObjCQualifiedIdType()) { 14226 const ObjCObjectPointerType *srcOPT = 14227 SrcType->getAs<ObjCObjectPointerType>(); 14228 for (auto *srcProto : srcOPT->quals()) { 14229 PDecl = srcProto; 14230 break; 14231 } 14232 if (const ObjCInterfaceType *IFaceT = 14233 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14234 IFace = IFaceT->getDecl(); 14235 } 14236 else if (DstType->isObjCQualifiedIdType()) { 14237 const ObjCObjectPointerType *dstOPT = 14238 DstType->getAs<ObjCObjectPointerType>(); 14239 for (auto *dstProto : dstOPT->quals()) { 14240 PDecl = dstProto; 14241 break; 14242 } 14243 if (const ObjCInterfaceType *IFaceT = 14244 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14245 IFace = IFaceT->getDecl(); 14246 } 14247 DiagKind = diag::warn_incompatible_qualified_id; 14248 break; 14249 } 14250 case IncompatibleVectors: 14251 DiagKind = diag::warn_incompatible_vectors; 14252 break; 14253 case IncompatibleObjCWeakRef: 14254 DiagKind = diag::err_arc_weak_unavailable_assign; 14255 break; 14256 case Incompatible: 14257 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14258 if (Complained) 14259 *Complained = true; 14260 return true; 14261 } 14262 14263 DiagKind = diag::err_typecheck_convert_incompatible; 14264 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14265 MayHaveConvFixit = true; 14266 isInvalid = true; 14267 MayHaveFunctionDiff = true; 14268 break; 14269 } 14270 14271 QualType FirstType, SecondType; 14272 switch (Action) { 14273 case AA_Assigning: 14274 case AA_Initializing: 14275 // The destination type comes first. 14276 FirstType = DstType; 14277 SecondType = SrcType; 14278 break; 14279 14280 case AA_Returning: 14281 case AA_Passing: 14282 case AA_Passing_CFAudited: 14283 case AA_Converting: 14284 case AA_Sending: 14285 case AA_Casting: 14286 // The source type comes first. 14287 FirstType = SrcType; 14288 SecondType = DstType; 14289 break; 14290 } 14291 14292 PartialDiagnostic FDiag = PDiag(DiagKind); 14293 if (Action == AA_Passing_CFAudited) 14294 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14295 else 14296 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14297 14298 // If we can fix the conversion, suggest the FixIts. 14299 assert(ConvHints.isNull() || Hint.isNull()); 14300 if (!ConvHints.isNull()) { 14301 for (FixItHint &H : ConvHints.Hints) 14302 FDiag << H; 14303 } else { 14304 FDiag << Hint; 14305 } 14306 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14307 14308 if (MayHaveFunctionDiff) 14309 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14310 14311 Diag(Loc, FDiag); 14312 if (DiagKind == diag::warn_incompatible_qualified_id && 14313 PDecl && IFace && !IFace->hasDefinition()) 14314 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14315 << IFace << PDecl; 14316 14317 if (SecondType == Context.OverloadTy) 14318 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14319 FirstType, /*TakingAddress=*/true); 14320 14321 if (CheckInferredResultType) 14322 EmitRelatedResultTypeNote(SrcExpr); 14323 14324 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14325 EmitRelatedResultTypeNoteForReturn(DstType); 14326 14327 if (Complained) 14328 *Complained = true; 14329 return isInvalid; 14330 } 14331 14332 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14333 llvm::APSInt *Result) { 14334 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14335 public: 14336 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14337 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14338 } 14339 } Diagnoser; 14340 14341 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14342 } 14343 14344 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14345 llvm::APSInt *Result, 14346 unsigned DiagID, 14347 bool AllowFold) { 14348 class IDDiagnoser : public VerifyICEDiagnoser { 14349 unsigned DiagID; 14350 14351 public: 14352 IDDiagnoser(unsigned DiagID) 14353 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14354 14355 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14356 S.Diag(Loc, DiagID) << SR; 14357 } 14358 } Diagnoser(DiagID); 14359 14360 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14361 } 14362 14363 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14364 SourceRange SR) { 14365 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14366 } 14367 14368 ExprResult 14369 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14370 VerifyICEDiagnoser &Diagnoser, 14371 bool AllowFold) { 14372 SourceLocation DiagLoc = E->getBeginLoc(); 14373 14374 if (getLangOpts().CPlusPlus11) { 14375 // C++11 [expr.const]p5: 14376 // If an expression of literal class type is used in a context where an 14377 // integral constant expression is required, then that class type shall 14378 // have a single non-explicit conversion function to an integral or 14379 // unscoped enumeration type 14380 ExprResult Converted; 14381 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14382 public: 14383 CXX11ConvertDiagnoser(bool Silent) 14384 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14385 Silent, true) {} 14386 14387 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14388 QualType T) override { 14389 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14390 } 14391 14392 SemaDiagnosticBuilder diagnoseIncomplete( 14393 Sema &S, SourceLocation Loc, QualType T) override { 14394 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14395 } 14396 14397 SemaDiagnosticBuilder diagnoseExplicitConv( 14398 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14399 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14400 } 14401 14402 SemaDiagnosticBuilder noteExplicitConv( 14403 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14404 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14405 << ConvTy->isEnumeralType() << ConvTy; 14406 } 14407 14408 SemaDiagnosticBuilder diagnoseAmbiguous( 14409 Sema &S, SourceLocation Loc, QualType T) override { 14410 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14411 } 14412 14413 SemaDiagnosticBuilder noteAmbiguous( 14414 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14415 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14416 << ConvTy->isEnumeralType() << ConvTy; 14417 } 14418 14419 SemaDiagnosticBuilder diagnoseConversion( 14420 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14421 llvm_unreachable("conversion functions are permitted"); 14422 } 14423 } ConvertDiagnoser(Diagnoser.Suppress); 14424 14425 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14426 ConvertDiagnoser); 14427 if (Converted.isInvalid()) 14428 return Converted; 14429 E = Converted.get(); 14430 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14431 return ExprError(); 14432 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14433 // An ICE must be of integral or unscoped enumeration type. 14434 if (!Diagnoser.Suppress) 14435 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14436 return ExprError(); 14437 } 14438 14439 if (!isa<ConstantExpr>(E)) 14440 E = ConstantExpr::Create(Context, E); 14441 14442 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14443 // in the non-ICE case. 14444 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14445 if (Result) 14446 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14447 return E; 14448 } 14449 14450 Expr::EvalResult EvalResult; 14451 SmallVector<PartialDiagnosticAt, 8> Notes; 14452 EvalResult.Diag = &Notes; 14453 14454 // Try to evaluate the expression, and produce diagnostics explaining why it's 14455 // not a constant expression as a side-effect. 14456 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14457 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14458 14459 // In C++11, we can rely on diagnostics being produced for any expression 14460 // which is not a constant expression. If no diagnostics were produced, then 14461 // this is a constant expression. 14462 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14463 if (Result) 14464 *Result = EvalResult.Val.getInt(); 14465 return E; 14466 } 14467 14468 // If our only note is the usual "invalid subexpression" note, just point 14469 // the caret at its location rather than producing an essentially 14470 // redundant note. 14471 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14472 diag::note_invalid_subexpr_in_const_expr) { 14473 DiagLoc = Notes[0].first; 14474 Notes.clear(); 14475 } 14476 14477 if (!Folded || !AllowFold) { 14478 if (!Diagnoser.Suppress) { 14479 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14480 for (const PartialDiagnosticAt &Note : Notes) 14481 Diag(Note.first, Note.second); 14482 } 14483 14484 return ExprError(); 14485 } 14486 14487 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14488 for (const PartialDiagnosticAt &Note : Notes) 14489 Diag(Note.first, Note.second); 14490 14491 if (Result) 14492 *Result = EvalResult.Val.getInt(); 14493 return E; 14494 } 14495 14496 namespace { 14497 // Handle the case where we conclude a expression which we speculatively 14498 // considered to be unevaluated is actually evaluated. 14499 class TransformToPE : public TreeTransform<TransformToPE> { 14500 typedef TreeTransform<TransformToPE> BaseTransform; 14501 14502 public: 14503 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14504 14505 // Make sure we redo semantic analysis 14506 bool AlwaysRebuild() { return true; } 14507 14508 // We need to special-case DeclRefExprs referring to FieldDecls which 14509 // are not part of a member pointer formation; normal TreeTransforming 14510 // doesn't catch this case because of the way we represent them in the AST. 14511 // FIXME: This is a bit ugly; is it really the best way to handle this 14512 // case? 14513 // 14514 // Error on DeclRefExprs referring to FieldDecls. 14515 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14516 if (isa<FieldDecl>(E->getDecl()) && 14517 !SemaRef.isUnevaluatedContext()) 14518 return SemaRef.Diag(E->getLocation(), 14519 diag::err_invalid_non_static_member_use) 14520 << E->getDecl() << E->getSourceRange(); 14521 14522 return BaseTransform::TransformDeclRefExpr(E); 14523 } 14524 14525 // Exception: filter out member pointer formation 14526 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14527 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14528 return E; 14529 14530 return BaseTransform::TransformUnaryOperator(E); 14531 } 14532 14533 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14534 // Lambdas never need to be transformed. 14535 return E; 14536 } 14537 }; 14538 } 14539 14540 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14541 assert(isUnevaluatedContext() && 14542 "Should only transform unevaluated expressions"); 14543 ExprEvalContexts.back().Context = 14544 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14545 if (isUnevaluatedContext()) 14546 return E; 14547 return TransformToPE(*this).TransformExpr(E); 14548 } 14549 14550 void 14551 Sema::PushExpressionEvaluationContext( 14552 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14553 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14554 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14555 LambdaContextDecl, ExprContext); 14556 Cleanup.reset(); 14557 if (!MaybeODRUseExprs.empty()) 14558 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14559 } 14560 14561 void 14562 Sema::PushExpressionEvaluationContext( 14563 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14564 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14565 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14566 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14567 } 14568 14569 namespace { 14570 14571 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 14572 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 14573 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 14574 if (E->getOpcode() == UO_Deref) 14575 return CheckPossibleDeref(S, E->getSubExpr()); 14576 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 14577 return CheckPossibleDeref(S, E->getBase()); 14578 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 14579 return CheckPossibleDeref(S, E->getBase()); 14580 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 14581 QualType Inner; 14582 QualType Ty = E->getType(); 14583 if (const auto *Ptr = Ty->getAs<PointerType>()) 14584 Inner = Ptr->getPointeeType(); 14585 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 14586 Inner = Arr->getElementType(); 14587 else 14588 return nullptr; 14589 14590 if (Inner->hasAttr(attr::NoDeref)) 14591 return E; 14592 } 14593 return nullptr; 14594 } 14595 14596 } // namespace 14597 14598 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 14599 for (const Expr *E : Rec.PossibleDerefs) { 14600 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 14601 if (DeclRef) { 14602 const ValueDecl *Decl = DeclRef->getDecl(); 14603 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 14604 << Decl->getName() << E->getSourceRange(); 14605 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 14606 } else { 14607 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 14608 << E->getSourceRange(); 14609 } 14610 } 14611 Rec.PossibleDerefs.clear(); 14612 } 14613 14614 void Sema::PopExpressionEvaluationContext() { 14615 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14616 unsigned NumTypos = Rec.NumTypos; 14617 14618 if (!Rec.Lambdas.empty()) { 14619 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14620 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14621 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14622 unsigned D; 14623 if (Rec.isUnevaluated()) { 14624 // C++11 [expr.prim.lambda]p2: 14625 // A lambda-expression shall not appear in an unevaluated operand 14626 // (Clause 5). 14627 D = diag::err_lambda_unevaluated_operand; 14628 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14629 // C++1y [expr.const]p2: 14630 // A conditional-expression e is a core constant expression unless the 14631 // evaluation of e, following the rules of the abstract machine, would 14632 // evaluate [...] a lambda-expression. 14633 D = diag::err_lambda_in_constant_expression; 14634 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14635 // C++17 [expr.prim.lamda]p2: 14636 // A lambda-expression shall not appear [...] in a template-argument. 14637 D = diag::err_lambda_in_invalid_context; 14638 } else 14639 llvm_unreachable("Couldn't infer lambda error message."); 14640 14641 for (const auto *L : Rec.Lambdas) 14642 Diag(L->getBeginLoc(), D); 14643 } else { 14644 // Mark the capture expressions odr-used. This was deferred 14645 // during lambda expression creation. 14646 for (auto *Lambda : Rec.Lambdas) { 14647 for (auto *C : Lambda->capture_inits()) 14648 MarkDeclarationsReferencedInExpr(C); 14649 } 14650 } 14651 } 14652 14653 WarnOnPendingNoDerefs(Rec); 14654 14655 // When are coming out of an unevaluated context, clear out any 14656 // temporaries that we may have created as part of the evaluation of 14657 // the expression in that context: they aren't relevant because they 14658 // will never be constructed. 14659 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14660 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14661 ExprCleanupObjects.end()); 14662 Cleanup = Rec.ParentCleanup; 14663 CleanupVarDeclMarking(); 14664 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14665 // Otherwise, merge the contexts together. 14666 } else { 14667 Cleanup.mergeFrom(Rec.ParentCleanup); 14668 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14669 Rec.SavedMaybeODRUseExprs.end()); 14670 } 14671 14672 // Pop the current expression evaluation context off the stack. 14673 ExprEvalContexts.pop_back(); 14674 14675 // The global expression evaluation context record is never popped. 14676 ExprEvalContexts.back().NumTypos += NumTypos; 14677 } 14678 14679 void Sema::DiscardCleanupsInEvaluationContext() { 14680 ExprCleanupObjects.erase( 14681 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14682 ExprCleanupObjects.end()); 14683 Cleanup.reset(); 14684 MaybeODRUseExprs.clear(); 14685 } 14686 14687 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14688 ExprResult Result = CheckPlaceholderExpr(E); 14689 if (Result.isInvalid()) 14690 return ExprError(); 14691 E = Result.get(); 14692 if (!E->getType()->isVariablyModifiedType()) 14693 return E; 14694 return TransformToPotentiallyEvaluated(E); 14695 } 14696 14697 /// Are we within a context in which some evaluation could be performed (be it 14698 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14699 /// captured by C++'s idea of an "unevaluated context". 14700 static bool isEvaluatableContext(Sema &SemaRef) { 14701 switch (SemaRef.ExprEvalContexts.back().Context) { 14702 case Sema::ExpressionEvaluationContext::Unevaluated: 14703 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14704 // Expressions in this context are never evaluated. 14705 return false; 14706 14707 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14708 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14709 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14710 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14711 // Expressions in this context could be evaluated. 14712 return true; 14713 14714 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14715 // Referenced declarations will only be used if the construct in the 14716 // containing expression is used, at which point we'll be given another 14717 // turn to mark them. 14718 return false; 14719 } 14720 llvm_unreachable("Invalid context"); 14721 } 14722 14723 /// Are we within a context in which references to resolved functions or to 14724 /// variables result in odr-use? 14725 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14726 // An expression in a template is not really an expression until it's been 14727 // instantiated, so it doesn't trigger odr-use. 14728 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14729 return false; 14730 14731 switch (SemaRef.ExprEvalContexts.back().Context) { 14732 case Sema::ExpressionEvaluationContext::Unevaluated: 14733 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14734 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14735 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14736 return false; 14737 14738 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14739 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14740 return true; 14741 14742 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14743 return false; 14744 } 14745 llvm_unreachable("Invalid context"); 14746 } 14747 14748 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14749 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14750 return Func->isConstexpr() && 14751 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14752 } 14753 14754 /// Mark a function referenced, and check whether it is odr-used 14755 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14756 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14757 bool MightBeOdrUse) { 14758 assert(Func && "No function?"); 14759 14760 Func->setReferenced(); 14761 14762 // C++11 [basic.def.odr]p3: 14763 // A function whose name appears as a potentially-evaluated expression is 14764 // odr-used if it is the unique lookup result or the selected member of a 14765 // set of overloaded functions [...]. 14766 // 14767 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14768 // can just check that here. 14769 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14770 14771 // Determine whether we require a function definition to exist, per 14772 // C++11 [temp.inst]p3: 14773 // Unless a function template specialization has been explicitly 14774 // instantiated or explicitly specialized, the function template 14775 // specialization is implicitly instantiated when the specialization is 14776 // referenced in a context that requires a function definition to exist. 14777 // 14778 // That is either when this is an odr-use, or when a usage of a constexpr 14779 // function occurs within an evaluatable context. 14780 bool NeedDefinition = 14781 OdrUse || (isEvaluatableContext(*this) && 14782 isImplicitlyDefinableConstexprFunction(Func)); 14783 14784 // C++14 [temp.expl.spec]p6: 14785 // If a template [...] is explicitly specialized then that specialization 14786 // shall be declared before the first use of that specialization that would 14787 // cause an implicit instantiation to take place, in every translation unit 14788 // in which such a use occurs 14789 if (NeedDefinition && 14790 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14791 Func->getMemberSpecializationInfo())) 14792 checkSpecializationVisibility(Loc, Func); 14793 14794 // C++14 [except.spec]p17: 14795 // An exception-specification is considered to be needed when: 14796 // - the function is odr-used or, if it appears in an unevaluated operand, 14797 // would be odr-used if the expression were potentially-evaluated; 14798 // 14799 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14800 // function is a pure virtual function we're calling, and in that case the 14801 // function was selected by overload resolution and we need to resolve its 14802 // exception specification for a different reason. 14803 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14804 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14805 ResolveExceptionSpec(Loc, FPT); 14806 14807 if (getLangOpts().CUDA) 14808 CheckCUDACall(Loc, Func); 14809 14810 // If we don't need to mark the function as used, and we don't need to 14811 // try to provide a definition, there's nothing more to do. 14812 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14813 (!NeedDefinition || Func->getBody())) 14814 return; 14815 14816 // Note that this declaration has been used. 14817 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14818 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14819 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14820 if (Constructor->isDefaultConstructor()) { 14821 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14822 return; 14823 DefineImplicitDefaultConstructor(Loc, Constructor); 14824 } else if (Constructor->isCopyConstructor()) { 14825 DefineImplicitCopyConstructor(Loc, Constructor); 14826 } else if (Constructor->isMoveConstructor()) { 14827 DefineImplicitMoveConstructor(Loc, Constructor); 14828 } 14829 } else if (Constructor->getInheritedConstructor()) { 14830 DefineInheritingConstructor(Loc, Constructor); 14831 } 14832 } else if (CXXDestructorDecl *Destructor = 14833 dyn_cast<CXXDestructorDecl>(Func)) { 14834 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14835 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14836 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14837 return; 14838 DefineImplicitDestructor(Loc, Destructor); 14839 } 14840 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14841 MarkVTableUsed(Loc, Destructor->getParent()); 14842 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14843 if (MethodDecl->isOverloadedOperator() && 14844 MethodDecl->getOverloadedOperator() == OO_Equal) { 14845 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14846 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14847 if (MethodDecl->isCopyAssignmentOperator()) 14848 DefineImplicitCopyAssignment(Loc, MethodDecl); 14849 else if (MethodDecl->isMoveAssignmentOperator()) 14850 DefineImplicitMoveAssignment(Loc, MethodDecl); 14851 } 14852 } else if (isa<CXXConversionDecl>(MethodDecl) && 14853 MethodDecl->getParent()->isLambda()) { 14854 CXXConversionDecl *Conversion = 14855 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14856 if (Conversion->isLambdaToBlockPointerConversion()) 14857 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14858 else 14859 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14860 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14861 MarkVTableUsed(Loc, MethodDecl->getParent()); 14862 } 14863 14864 // Recursive functions should be marked when used from another function. 14865 // FIXME: Is this really right? 14866 if (CurContext == Func) return; 14867 14868 // Implicit instantiation of function templates and member functions of 14869 // class templates. 14870 if (Func->isImplicitlyInstantiable()) { 14871 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14872 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14873 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14874 if (FirstInstantiation) { 14875 PointOfInstantiation = Loc; 14876 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14877 } else if (TSK != TSK_ImplicitInstantiation) { 14878 // Use the point of use as the point of instantiation, instead of the 14879 // point of explicit instantiation (which we track as the actual point of 14880 // instantiation). This gives better backtraces in diagnostics. 14881 PointOfInstantiation = Loc; 14882 } 14883 14884 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14885 Func->isConstexpr()) { 14886 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14887 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14888 CodeSynthesisContexts.size()) 14889 PendingLocalImplicitInstantiations.push_back( 14890 std::make_pair(Func, PointOfInstantiation)); 14891 else if (Func->isConstexpr()) 14892 // Do not defer instantiations of constexpr functions, to avoid the 14893 // expression evaluator needing to call back into Sema if it sees a 14894 // call to such a function. 14895 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14896 else { 14897 Func->setInstantiationIsPending(true); 14898 PendingInstantiations.push_back(std::make_pair(Func, 14899 PointOfInstantiation)); 14900 // Notify the consumer that a function was implicitly instantiated. 14901 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14902 } 14903 } 14904 } else { 14905 // Walk redefinitions, as some of them may be instantiable. 14906 for (auto i : Func->redecls()) { 14907 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14908 MarkFunctionReferenced(Loc, i, OdrUse); 14909 } 14910 } 14911 14912 if (!OdrUse) return; 14913 14914 // Keep track of used but undefined functions. 14915 if (!Func->isDefined()) { 14916 if (mightHaveNonExternalLinkage(Func)) 14917 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14918 else if (Func->getMostRecentDecl()->isInlined() && 14919 !LangOpts.GNUInline && 14920 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14921 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14922 else if (isExternalWithNoLinkageType(Func)) 14923 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14924 } 14925 14926 Func->markUsed(Context); 14927 14928 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice) 14929 checkOpenMPDeviceFunction(Loc, Func); 14930 } 14931 14932 static void 14933 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14934 ValueDecl *var, DeclContext *DC) { 14935 DeclContext *VarDC = var->getDeclContext(); 14936 14937 // If the parameter still belongs to the translation unit, then 14938 // we're actually just using one parameter in the declaration of 14939 // the next. 14940 if (isa<ParmVarDecl>(var) && 14941 isa<TranslationUnitDecl>(VarDC)) 14942 return; 14943 14944 // For C code, don't diagnose about capture if we're not actually in code 14945 // right now; it's impossible to write a non-constant expression outside of 14946 // function context, so we'll get other (more useful) diagnostics later. 14947 // 14948 // For C++, things get a bit more nasty... it would be nice to suppress this 14949 // diagnostic for certain cases like using a local variable in an array bound 14950 // for a member of a local class, but the correct predicate is not obvious. 14951 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14952 return; 14953 14954 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14955 unsigned ContextKind = 3; // unknown 14956 if (isa<CXXMethodDecl>(VarDC) && 14957 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14958 ContextKind = 2; 14959 } else if (isa<FunctionDecl>(VarDC)) { 14960 ContextKind = 0; 14961 } else if (isa<BlockDecl>(VarDC)) { 14962 ContextKind = 1; 14963 } 14964 14965 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14966 << var << ValueKind << ContextKind << VarDC; 14967 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14968 << var; 14969 14970 // FIXME: Add additional diagnostic info about class etc. which prevents 14971 // capture. 14972 } 14973 14974 14975 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14976 bool &SubCapturesAreNested, 14977 QualType &CaptureType, 14978 QualType &DeclRefType) { 14979 // Check whether we've already captured it. 14980 if (CSI->CaptureMap.count(Var)) { 14981 // If we found a capture, any subcaptures are nested. 14982 SubCapturesAreNested = true; 14983 14984 // Retrieve the capture type for this variable. 14985 CaptureType = CSI->getCapture(Var).getCaptureType(); 14986 14987 // Compute the type of an expression that refers to this variable. 14988 DeclRefType = CaptureType.getNonReferenceType(); 14989 14990 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14991 // are mutable in the sense that user can change their value - they are 14992 // private instances of the captured declarations. 14993 const Capture &Cap = CSI->getCapture(Var); 14994 if (Cap.isCopyCapture() && 14995 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14996 !(isa<CapturedRegionScopeInfo>(CSI) && 14997 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14998 DeclRefType.addConst(); 14999 return true; 15000 } 15001 return false; 15002 } 15003 15004 // Only block literals, captured statements, and lambda expressions can 15005 // capture; other scopes don't work. 15006 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15007 SourceLocation Loc, 15008 const bool Diagnose, Sema &S) { 15009 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15010 return getLambdaAwareParentOfDeclContext(DC); 15011 else if (Var->hasLocalStorage()) { 15012 if (Diagnose) 15013 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15014 } 15015 return nullptr; 15016 } 15017 15018 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15019 // certain types of variables (unnamed, variably modified types etc.) 15020 // so check for eligibility. 15021 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15022 SourceLocation Loc, 15023 const bool Diagnose, Sema &S) { 15024 15025 bool IsBlock = isa<BlockScopeInfo>(CSI); 15026 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15027 15028 // Lambdas are not allowed to capture unnamed variables 15029 // (e.g. anonymous unions). 15030 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15031 // assuming that's the intent. 15032 if (IsLambda && !Var->getDeclName()) { 15033 if (Diagnose) { 15034 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15035 S.Diag(Var->getLocation(), diag::note_declared_at); 15036 } 15037 return false; 15038 } 15039 15040 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15041 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15042 if (Diagnose) { 15043 S.Diag(Loc, diag::err_ref_vm_type); 15044 S.Diag(Var->getLocation(), diag::note_previous_decl) 15045 << Var->getDeclName(); 15046 } 15047 return false; 15048 } 15049 // Prohibit structs with flexible array members too. 15050 // We cannot capture what is in the tail end of the struct. 15051 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15052 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15053 if (Diagnose) { 15054 if (IsBlock) 15055 S.Diag(Loc, diag::err_ref_flexarray_type); 15056 else 15057 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15058 << Var->getDeclName(); 15059 S.Diag(Var->getLocation(), diag::note_previous_decl) 15060 << Var->getDeclName(); 15061 } 15062 return false; 15063 } 15064 } 15065 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15066 // Lambdas and captured statements are not allowed to capture __block 15067 // variables; they don't support the expected semantics. 15068 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15069 if (Diagnose) { 15070 S.Diag(Loc, diag::err_capture_block_variable) 15071 << Var->getDeclName() << !IsLambda; 15072 S.Diag(Var->getLocation(), diag::note_previous_decl) 15073 << Var->getDeclName(); 15074 } 15075 return false; 15076 } 15077 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15078 if (S.getLangOpts().OpenCL && IsBlock && 15079 Var->getType()->isBlockPointerType()) { 15080 if (Diagnose) 15081 S.Diag(Loc, diag::err_opencl_block_ref_block); 15082 return false; 15083 } 15084 15085 return true; 15086 } 15087 15088 // Returns true if the capture by block was successful. 15089 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15090 SourceLocation Loc, 15091 const bool BuildAndDiagnose, 15092 QualType &CaptureType, 15093 QualType &DeclRefType, 15094 const bool Nested, 15095 Sema &S) { 15096 Expr *CopyExpr = nullptr; 15097 bool ByRef = false; 15098 15099 // Blocks are not allowed to capture arrays, excepting OpenCL. 15100 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15101 // (decayed to pointers). 15102 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15103 if (BuildAndDiagnose) { 15104 S.Diag(Loc, diag::err_ref_array_type); 15105 S.Diag(Var->getLocation(), diag::note_previous_decl) 15106 << Var->getDeclName(); 15107 } 15108 return false; 15109 } 15110 15111 // Forbid the block-capture of autoreleasing variables. 15112 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15113 if (BuildAndDiagnose) { 15114 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15115 << /*block*/ 0; 15116 S.Diag(Var->getLocation(), diag::note_previous_decl) 15117 << Var->getDeclName(); 15118 } 15119 return false; 15120 } 15121 15122 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15123 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15124 // This function finds out whether there is an AttributedType of kind 15125 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 15126 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 15127 // rather than being added implicitly by the compiler. 15128 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 15129 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 15130 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 15131 return true; 15132 15133 // Peel off AttributedTypes that are not of kind ObjCOwnership. 15134 Ty = AttrTy->getModifiedType(); 15135 } 15136 15137 return false; 15138 }; 15139 15140 QualType PointeeTy = PT->getPointeeType(); 15141 15142 if (PointeeTy->getAs<ObjCObjectPointerType>() && 15143 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15144 !IsObjCOwnershipAttributedType(PointeeTy)) { 15145 if (BuildAndDiagnose) { 15146 SourceLocation VarLoc = Var->getLocation(); 15147 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15148 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15149 } 15150 } 15151 } 15152 15153 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15154 if (HasBlocksAttr || CaptureType->isReferenceType() || 15155 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15156 // Block capture by reference does not change the capture or 15157 // declaration reference types. 15158 ByRef = true; 15159 } else { 15160 // Block capture by copy introduces 'const'. 15161 CaptureType = CaptureType.getNonReferenceType().withConst(); 15162 DeclRefType = CaptureType; 15163 15164 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 15165 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 15166 // The capture logic needs the destructor, so make sure we mark it. 15167 // Usually this is unnecessary because most local variables have 15168 // their destructors marked at declaration time, but parameters are 15169 // an exception because it's technically only the call site that 15170 // actually requires the destructor. 15171 if (isa<ParmVarDecl>(Var)) 15172 S.FinalizeVarWithDestructor(Var, Record); 15173 15174 // Enter a new evaluation context to insulate the copy 15175 // full-expression. 15176 EnterExpressionEvaluationContext scope( 15177 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 15178 15179 // According to the blocks spec, the capture of a variable from 15180 // the stack requires a const copy constructor. This is not true 15181 // of the copy/move done to move a __block variable to the heap. 15182 Expr *DeclRef = new (S.Context) DeclRefExpr( 15183 S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc); 15184 15185 ExprResult Result 15186 = S.PerformCopyInitialization( 15187 InitializedEntity::InitializeBlock(Var->getLocation(), 15188 CaptureType, false), 15189 Loc, DeclRef); 15190 15191 // Build a full-expression copy expression if initialization 15192 // succeeded and used a non-trivial constructor. Recover from 15193 // errors by pretending that the copy isn't necessary. 15194 if (!Result.isInvalid() && 15195 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15196 ->isTrivial()) { 15197 Result = S.MaybeCreateExprWithCleanups(Result); 15198 CopyExpr = Result.get(); 15199 } 15200 } 15201 } 15202 } 15203 15204 // Actually capture the variable. 15205 if (BuildAndDiagnose) 15206 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 15207 SourceLocation(), CaptureType, CopyExpr); 15208 15209 return true; 15210 15211 } 15212 15213 15214 /// Capture the given variable in the captured region. 15215 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15216 VarDecl *Var, 15217 SourceLocation Loc, 15218 const bool BuildAndDiagnose, 15219 QualType &CaptureType, 15220 QualType &DeclRefType, 15221 const bool RefersToCapturedVariable, 15222 Sema &S) { 15223 // By default, capture variables by reference. 15224 bool ByRef = true; 15225 // Using an LValue reference type is consistent with Lambdas (see below). 15226 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15227 if (S.isOpenMPCapturedDecl(Var)) { 15228 bool HasConst = DeclRefType.isConstQualified(); 15229 DeclRefType = DeclRefType.getUnqualifiedType(); 15230 // Don't lose diagnostics about assignments to const. 15231 if (HasConst) 15232 DeclRefType.addConst(); 15233 } 15234 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 15235 } 15236 15237 if (ByRef) 15238 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15239 else 15240 CaptureType = DeclRefType; 15241 15242 Expr *CopyExpr = nullptr; 15243 if (BuildAndDiagnose) { 15244 // The current implementation assumes that all variables are captured 15245 // by references. Since there is no capture by copy, no expression 15246 // evaluation will be needed. 15247 RecordDecl *RD = RSI->TheRecordDecl; 15248 15249 FieldDecl *Field 15250 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 15251 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 15252 nullptr, false, ICIS_NoInit); 15253 Field->setImplicit(true); 15254 Field->setAccess(AS_private); 15255 RD->addDecl(Field); 15256 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 15257 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 15258 15259 CopyExpr = new (S.Context) DeclRefExpr( 15260 S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc); 15261 Var->setReferenced(true); 15262 Var->markUsed(S.Context); 15263 } 15264 15265 // Actually capture the variable. 15266 if (BuildAndDiagnose) 15267 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 15268 SourceLocation(), CaptureType, CopyExpr); 15269 15270 15271 return true; 15272 } 15273 15274 /// Create a field within the lambda class for the variable 15275 /// being captured. 15276 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 15277 QualType FieldType, QualType DeclRefType, 15278 SourceLocation Loc, 15279 bool RefersToCapturedVariable) { 15280 CXXRecordDecl *Lambda = LSI->Lambda; 15281 15282 // Build the non-static data member. 15283 FieldDecl *Field 15284 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 15285 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 15286 nullptr, false, ICIS_NoInit); 15287 // If the variable being captured has an invalid type, mark the lambda class 15288 // as invalid as well. 15289 if (!FieldType->isDependentType()) { 15290 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 15291 Lambda->setInvalidDecl(); 15292 Field->setInvalidDecl(); 15293 } else { 15294 NamedDecl *Def; 15295 FieldType->isIncompleteType(&Def); 15296 if (Def && Def->isInvalidDecl()) { 15297 Lambda->setInvalidDecl(); 15298 Field->setInvalidDecl(); 15299 } 15300 } 15301 } 15302 Field->setImplicit(true); 15303 Field->setAccess(AS_private); 15304 Lambda->addDecl(Field); 15305 } 15306 15307 /// Capture the given variable in the lambda. 15308 static bool captureInLambda(LambdaScopeInfo *LSI, 15309 VarDecl *Var, 15310 SourceLocation Loc, 15311 const bool BuildAndDiagnose, 15312 QualType &CaptureType, 15313 QualType &DeclRefType, 15314 const bool RefersToCapturedVariable, 15315 const Sema::TryCaptureKind Kind, 15316 SourceLocation EllipsisLoc, 15317 const bool IsTopScope, 15318 Sema &S) { 15319 15320 // Determine whether we are capturing by reference or by value. 15321 bool ByRef = false; 15322 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15323 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15324 } else { 15325 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15326 } 15327 15328 // Compute the type of the field that will capture this variable. 15329 if (ByRef) { 15330 // C++11 [expr.prim.lambda]p15: 15331 // An entity is captured by reference if it is implicitly or 15332 // explicitly captured but not captured by copy. It is 15333 // unspecified whether additional unnamed non-static data 15334 // members are declared in the closure type for entities 15335 // captured by reference. 15336 // 15337 // FIXME: It is not clear whether we want to build an lvalue reference 15338 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15339 // to do the former, while EDG does the latter. Core issue 1249 will 15340 // clarify, but for now we follow GCC because it's a more permissive and 15341 // easily defensible position. 15342 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15343 } else { 15344 // C++11 [expr.prim.lambda]p14: 15345 // For each entity captured by copy, an unnamed non-static 15346 // data member is declared in the closure type. The 15347 // declaration order of these members is unspecified. The type 15348 // of such a data member is the type of the corresponding 15349 // captured entity if the entity is not a reference to an 15350 // object, or the referenced type otherwise. [Note: If the 15351 // captured entity is a reference to a function, the 15352 // corresponding data member is also a reference to a 15353 // function. - end note ] 15354 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15355 if (!RefType->getPointeeType()->isFunctionType()) 15356 CaptureType = RefType->getPointeeType(); 15357 } 15358 15359 // Forbid the lambda copy-capture of autoreleasing variables. 15360 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15361 if (BuildAndDiagnose) { 15362 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15363 S.Diag(Var->getLocation(), diag::note_previous_decl) 15364 << Var->getDeclName(); 15365 } 15366 return false; 15367 } 15368 15369 // Make sure that by-copy captures are of a complete and non-abstract type. 15370 if (BuildAndDiagnose) { 15371 if (!CaptureType->isDependentType() && 15372 S.RequireCompleteType(Loc, CaptureType, 15373 diag::err_capture_of_incomplete_type, 15374 Var->getDeclName())) 15375 return false; 15376 15377 if (S.RequireNonAbstractType(Loc, CaptureType, 15378 diag::err_capture_of_abstract_type)) 15379 return false; 15380 } 15381 } 15382 15383 // Capture this variable in the lambda. 15384 if (BuildAndDiagnose) 15385 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15386 RefersToCapturedVariable); 15387 15388 // Compute the type of a reference to this captured variable. 15389 if (ByRef) 15390 DeclRefType = CaptureType.getNonReferenceType(); 15391 else { 15392 // C++ [expr.prim.lambda]p5: 15393 // The closure type for a lambda-expression has a public inline 15394 // function call operator [...]. This function call operator is 15395 // declared const (9.3.1) if and only if the lambda-expression's 15396 // parameter-declaration-clause is not followed by mutable. 15397 DeclRefType = CaptureType.getNonReferenceType(); 15398 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15399 DeclRefType.addConst(); 15400 } 15401 15402 // Add the capture. 15403 if (BuildAndDiagnose) 15404 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15405 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15406 15407 return true; 15408 } 15409 15410 bool Sema::tryCaptureVariable( 15411 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15412 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15413 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15414 // An init-capture is notionally from the context surrounding its 15415 // declaration, but its parent DC is the lambda class. 15416 DeclContext *VarDC = Var->getDeclContext(); 15417 if (Var->isInitCapture()) 15418 VarDC = VarDC->getParent(); 15419 15420 DeclContext *DC = CurContext; 15421 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15422 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15423 // We need to sync up the Declaration Context with the 15424 // FunctionScopeIndexToStopAt 15425 if (FunctionScopeIndexToStopAt) { 15426 unsigned FSIndex = FunctionScopes.size() - 1; 15427 while (FSIndex != MaxFunctionScopesIndex) { 15428 DC = getLambdaAwareParentOfDeclContext(DC); 15429 --FSIndex; 15430 } 15431 } 15432 15433 15434 // If the variable is declared in the current context, there is no need to 15435 // capture it. 15436 if (VarDC == DC) return true; 15437 15438 // Capture global variables if it is required to use private copy of this 15439 // variable. 15440 bool IsGlobal = !Var->hasLocalStorage(); 15441 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15442 return true; 15443 Var = Var->getCanonicalDecl(); 15444 15445 // Walk up the stack to determine whether we can capture the variable, 15446 // performing the "simple" checks that don't depend on type. We stop when 15447 // we've either hit the declared scope of the variable or find an existing 15448 // capture of that variable. We start from the innermost capturing-entity 15449 // (the DC) and ensure that all intervening capturing-entities 15450 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15451 // declcontext can either capture the variable or have already captured 15452 // the variable. 15453 CaptureType = Var->getType(); 15454 DeclRefType = CaptureType.getNonReferenceType(); 15455 bool Nested = false; 15456 bool Explicit = (Kind != TryCapture_Implicit); 15457 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15458 do { 15459 // Only block literals, captured statements, and lambda expressions can 15460 // capture; other scopes don't work. 15461 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15462 ExprLoc, 15463 BuildAndDiagnose, 15464 *this); 15465 // We need to check for the parent *first* because, if we *have* 15466 // private-captured a global variable, we need to recursively capture it in 15467 // intermediate blocks, lambdas, etc. 15468 if (!ParentDC) { 15469 if (IsGlobal) { 15470 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15471 break; 15472 } 15473 return true; 15474 } 15475 15476 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15477 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15478 15479 15480 // Check whether we've already captured it. 15481 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15482 DeclRefType)) { 15483 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15484 break; 15485 } 15486 // If we are instantiating a generic lambda call operator body, 15487 // we do not want to capture new variables. What was captured 15488 // during either a lambdas transformation or initial parsing 15489 // should be used. 15490 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15491 if (BuildAndDiagnose) { 15492 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15493 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15494 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15495 Diag(Var->getLocation(), diag::note_previous_decl) 15496 << Var->getDeclName(); 15497 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15498 } else 15499 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15500 } 15501 return true; 15502 } 15503 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15504 // certain types of variables (unnamed, variably modified types etc.) 15505 // so check for eligibility. 15506 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15507 return true; 15508 15509 // Try to capture variable-length arrays types. 15510 if (Var->getType()->isVariablyModifiedType()) { 15511 // We're going to walk down into the type and look for VLA 15512 // expressions. 15513 QualType QTy = Var->getType(); 15514 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15515 QTy = PVD->getOriginalType(); 15516 captureVariablyModifiedType(Context, QTy, CSI); 15517 } 15518 15519 if (getLangOpts().OpenMP) { 15520 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15521 // OpenMP private variables should not be captured in outer scope, so 15522 // just break here. Similarly, global variables that are captured in a 15523 // target region should not be captured outside the scope of the region. 15524 if (RSI->CapRegionKind == CR_OpenMP) { 15525 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15526 auto IsTargetCap = !IsOpenMPPrivateDecl && 15527 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15528 // When we detect target captures we are looking from inside the 15529 // target region, therefore we need to propagate the capture from the 15530 // enclosing region. Therefore, the capture is not initially nested. 15531 if (IsTargetCap) 15532 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15533 15534 if (IsTargetCap || IsOpenMPPrivateDecl) { 15535 Nested = !IsTargetCap; 15536 DeclRefType = DeclRefType.getUnqualifiedType(); 15537 CaptureType = Context.getLValueReferenceType(DeclRefType); 15538 break; 15539 } 15540 } 15541 } 15542 } 15543 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15544 // No capture-default, and this is not an explicit capture 15545 // so cannot capture this variable. 15546 if (BuildAndDiagnose) { 15547 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15548 Diag(Var->getLocation(), diag::note_previous_decl) 15549 << Var->getDeclName(); 15550 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15551 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15552 diag::note_lambda_decl); 15553 // FIXME: If we error out because an outer lambda can not implicitly 15554 // capture a variable that an inner lambda explicitly captures, we 15555 // should have the inner lambda do the explicit capture - because 15556 // it makes for cleaner diagnostics later. This would purely be done 15557 // so that the diagnostic does not misleadingly claim that a variable 15558 // can not be captured by a lambda implicitly even though it is captured 15559 // explicitly. Suggestion: 15560 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15561 // at the function head 15562 // - cache the StartingDeclContext - this must be a lambda 15563 // - captureInLambda in the innermost lambda the variable. 15564 } 15565 return true; 15566 } 15567 15568 FunctionScopesIndex--; 15569 DC = ParentDC; 15570 Explicit = false; 15571 } while (!VarDC->Equals(DC)); 15572 15573 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15574 // computing the type of the capture at each step, checking type-specific 15575 // requirements, and adding captures if requested. 15576 // If the variable had already been captured previously, we start capturing 15577 // at the lambda nested within that one. 15578 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15579 ++I) { 15580 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15581 15582 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15583 if (!captureInBlock(BSI, Var, ExprLoc, 15584 BuildAndDiagnose, CaptureType, 15585 DeclRefType, Nested, *this)) 15586 return true; 15587 Nested = true; 15588 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15589 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15590 BuildAndDiagnose, CaptureType, 15591 DeclRefType, Nested, *this)) 15592 return true; 15593 Nested = true; 15594 } else { 15595 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15596 if (!captureInLambda(LSI, Var, ExprLoc, 15597 BuildAndDiagnose, CaptureType, 15598 DeclRefType, Nested, Kind, EllipsisLoc, 15599 /*IsTopScope*/I == N - 1, *this)) 15600 return true; 15601 Nested = true; 15602 } 15603 } 15604 return false; 15605 } 15606 15607 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15608 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15609 QualType CaptureType; 15610 QualType DeclRefType; 15611 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15612 /*BuildAndDiagnose=*/true, CaptureType, 15613 DeclRefType, nullptr); 15614 } 15615 15616 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15617 QualType CaptureType; 15618 QualType DeclRefType; 15619 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15620 /*BuildAndDiagnose=*/false, CaptureType, 15621 DeclRefType, nullptr); 15622 } 15623 15624 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15625 QualType CaptureType; 15626 QualType DeclRefType; 15627 15628 // Determine whether we can capture this variable. 15629 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15630 /*BuildAndDiagnose=*/false, CaptureType, 15631 DeclRefType, nullptr)) 15632 return QualType(); 15633 15634 return DeclRefType; 15635 } 15636 15637 15638 15639 // If either the type of the variable or the initializer is dependent, 15640 // return false. Otherwise, determine whether the variable is a constant 15641 // expression. Use this if you need to know if a variable that might or 15642 // might not be dependent is truly a constant expression. 15643 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15644 ASTContext &Context) { 15645 15646 if (Var->getType()->isDependentType()) 15647 return false; 15648 const VarDecl *DefVD = nullptr; 15649 Var->getAnyInitializer(DefVD); 15650 if (!DefVD) 15651 return false; 15652 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15653 Expr *Init = cast<Expr>(Eval->Value); 15654 if (Init->isValueDependent()) 15655 return false; 15656 return IsVariableAConstantExpression(Var, Context); 15657 } 15658 15659 15660 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15661 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15662 // an object that satisfies the requirements for appearing in a 15663 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15664 // is immediately applied." This function handles the lvalue-to-rvalue 15665 // conversion part. 15666 MaybeODRUseExprs.erase(E->IgnoreParens()); 15667 15668 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15669 // to a variable that is a constant expression, and if so, identify it as 15670 // a reference to a variable that does not involve an odr-use of that 15671 // variable. 15672 if (LambdaScopeInfo *LSI = getCurLambda()) { 15673 Expr *SansParensExpr = E->IgnoreParens(); 15674 VarDecl *Var = nullptr; 15675 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15676 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15677 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15678 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15679 15680 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15681 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15682 } 15683 } 15684 15685 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15686 Res = CorrectDelayedTyposInExpr(Res); 15687 15688 if (!Res.isUsable()) 15689 return Res; 15690 15691 // If a constant-expression is a reference to a variable where we delay 15692 // deciding whether it is an odr-use, just assume we will apply the 15693 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15694 // (a non-type template argument), we have special handling anyway. 15695 UpdateMarkingForLValueToRValue(Res.get()); 15696 return Res; 15697 } 15698 15699 void Sema::CleanupVarDeclMarking() { 15700 for (Expr *E : MaybeODRUseExprs) { 15701 VarDecl *Var; 15702 SourceLocation Loc; 15703 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15704 Var = cast<VarDecl>(DRE->getDecl()); 15705 Loc = DRE->getLocation(); 15706 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15707 Var = cast<VarDecl>(ME->getMemberDecl()); 15708 Loc = ME->getMemberLoc(); 15709 } else { 15710 llvm_unreachable("Unexpected expression"); 15711 } 15712 15713 MarkVarDeclODRUsed(Var, Loc, *this, 15714 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15715 } 15716 15717 MaybeODRUseExprs.clear(); 15718 } 15719 15720 15721 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15722 VarDecl *Var, Expr *E) { 15723 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15724 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15725 Var->setReferenced(); 15726 15727 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15728 15729 bool OdrUseContext = isOdrUseContext(SemaRef); 15730 bool UsableInConstantExpr = 15731 Var->isUsableInConstantExpressions(SemaRef.Context); 15732 bool NeedDefinition = 15733 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15734 15735 VarTemplateSpecializationDecl *VarSpec = 15736 dyn_cast<VarTemplateSpecializationDecl>(Var); 15737 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15738 "Can't instantiate a partial template specialization."); 15739 15740 // If this might be a member specialization of a static data member, check 15741 // the specialization is visible. We already did the checks for variable 15742 // template specializations when we created them. 15743 if (NeedDefinition && TSK != TSK_Undeclared && 15744 !isa<VarTemplateSpecializationDecl>(Var)) 15745 SemaRef.checkSpecializationVisibility(Loc, Var); 15746 15747 // Perform implicit instantiation of static data members, static data member 15748 // templates of class templates, and variable template specializations. Delay 15749 // instantiations of variable templates, except for those that could be used 15750 // in a constant expression. 15751 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15752 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15753 // instantiation declaration if a variable is usable in a constant 15754 // expression (among other cases). 15755 bool TryInstantiating = 15756 TSK == TSK_ImplicitInstantiation || 15757 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15758 15759 if (TryInstantiating) { 15760 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15761 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15762 if (FirstInstantiation) { 15763 PointOfInstantiation = Loc; 15764 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15765 } 15766 15767 bool InstantiationDependent = false; 15768 bool IsNonDependent = 15769 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15770 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15771 : true; 15772 15773 // Do not instantiate specializations that are still type-dependent. 15774 if (IsNonDependent) { 15775 if (UsableInConstantExpr) { 15776 // Do not defer instantiations of variables that could be used in a 15777 // constant expression. 15778 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15779 } else if (FirstInstantiation || 15780 isa<VarTemplateSpecializationDecl>(Var)) { 15781 // FIXME: For a specialization of a variable template, we don't 15782 // distinguish between "declaration and type implicitly instantiated" 15783 // and "implicit instantiation of definition requested", so we have 15784 // no direct way to avoid enqueueing the pending instantiation 15785 // multiple times. 15786 SemaRef.PendingInstantiations 15787 .push_back(std::make_pair(Var, PointOfInstantiation)); 15788 } 15789 } 15790 } 15791 } 15792 15793 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15794 // the requirements for appearing in a constant expression (5.19) and, if 15795 // it is an object, the lvalue-to-rvalue conversion (4.1) 15796 // is immediately applied." We check the first part here, and 15797 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15798 // Note that we use the C++11 definition everywhere because nothing in 15799 // C++03 depends on whether we get the C++03 version correct. The second 15800 // part does not apply to references, since they are not objects. 15801 if (OdrUseContext && E && 15802 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15803 // A reference initialized by a constant expression can never be 15804 // odr-used, so simply ignore it. 15805 if (!Var->getType()->isReferenceType() || 15806 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15807 SemaRef.MaybeODRUseExprs.insert(E); 15808 } else if (OdrUseContext) { 15809 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15810 /*MaxFunctionScopeIndex ptr*/ nullptr); 15811 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15812 // If this is a dependent context, we don't need to mark variables as 15813 // odr-used, but we may still need to track them for lambda capture. 15814 // FIXME: Do we also need to do this inside dependent typeid expressions 15815 // (which are modeled as unevaluated at this point)? 15816 const bool RefersToEnclosingScope = 15817 (SemaRef.CurContext != Var->getDeclContext() && 15818 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15819 if (RefersToEnclosingScope) { 15820 LambdaScopeInfo *const LSI = 15821 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15822 if (LSI && (!LSI->CallOperator || 15823 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15824 // If a variable could potentially be odr-used, defer marking it so 15825 // until we finish analyzing the full expression for any 15826 // lvalue-to-rvalue 15827 // or discarded value conversions that would obviate odr-use. 15828 // Add it to the list of potential captures that will be analyzed 15829 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15830 // unless the variable is a reference that was initialized by a constant 15831 // expression (this will never need to be captured or odr-used). 15832 assert(E && "Capture variable should be used in an expression."); 15833 if (!Var->getType()->isReferenceType() || 15834 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15835 LSI->addPotentialCapture(E->IgnoreParens()); 15836 } 15837 } 15838 } 15839 } 15840 15841 /// Mark a variable referenced, and check whether it is odr-used 15842 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15843 /// used directly for normal expressions referring to VarDecl. 15844 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15845 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15846 } 15847 15848 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15849 Decl *D, Expr *E, bool MightBeOdrUse) { 15850 if (SemaRef.isInOpenMPDeclareTargetContext()) 15851 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15852 15853 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15854 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15855 return; 15856 } 15857 15858 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15859 15860 // If this is a call to a method via a cast, also mark the method in the 15861 // derived class used in case codegen can devirtualize the call. 15862 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15863 if (!ME) 15864 return; 15865 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15866 if (!MD) 15867 return; 15868 // Only attempt to devirtualize if this is truly a virtual call. 15869 bool IsVirtualCall = MD->isVirtual() && 15870 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15871 if (!IsVirtualCall) 15872 return; 15873 15874 // If it's possible to devirtualize the call, mark the called function 15875 // referenced. 15876 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15877 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15878 if (DM) 15879 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15880 } 15881 15882 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15883 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15884 // TODO: update this with DR# once a defect report is filed. 15885 // C++11 defect. The address of a pure member should not be an ODR use, even 15886 // if it's a qualified reference. 15887 bool OdrUse = true; 15888 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15889 if (Method->isVirtual() && 15890 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15891 OdrUse = false; 15892 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15893 } 15894 15895 /// Perform reference-marking and odr-use handling for a MemberExpr. 15896 void Sema::MarkMemberReferenced(MemberExpr *E) { 15897 // C++11 [basic.def.odr]p2: 15898 // A non-overloaded function whose name appears as a potentially-evaluated 15899 // expression or a member of a set of candidate functions, if selected by 15900 // overload resolution when referred to from a potentially-evaluated 15901 // expression, is odr-used, unless it is a pure virtual function and its 15902 // name is not explicitly qualified. 15903 bool MightBeOdrUse = true; 15904 if (E->performsVirtualDispatch(getLangOpts())) { 15905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15906 if (Method->isPure()) 15907 MightBeOdrUse = false; 15908 } 15909 SourceLocation Loc = 15910 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15911 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15912 } 15913 15914 /// Perform marking for a reference to an arbitrary declaration. It 15915 /// marks the declaration referenced, and performs odr-use checking for 15916 /// functions and variables. This method should not be used when building a 15917 /// normal expression which refers to a variable. 15918 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15919 bool MightBeOdrUse) { 15920 if (MightBeOdrUse) { 15921 if (auto *VD = dyn_cast<VarDecl>(D)) { 15922 MarkVariableReferenced(Loc, VD); 15923 return; 15924 } 15925 } 15926 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15927 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15928 return; 15929 } 15930 D->setReferenced(); 15931 } 15932 15933 namespace { 15934 // Mark all of the declarations used by a type as referenced. 15935 // FIXME: Not fully implemented yet! We need to have a better understanding 15936 // of when we're entering a context we should not recurse into. 15937 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15938 // TreeTransforms rebuilding the type in a new context. Rather than 15939 // duplicating the TreeTransform logic, we should consider reusing it here. 15940 // Currently that causes problems when rebuilding LambdaExprs. 15941 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15942 Sema &S; 15943 SourceLocation Loc; 15944 15945 public: 15946 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15947 15948 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15949 15950 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15951 }; 15952 } 15953 15954 bool MarkReferencedDecls::TraverseTemplateArgument( 15955 const TemplateArgument &Arg) { 15956 { 15957 // A non-type template argument is a constant-evaluated context. 15958 EnterExpressionEvaluationContext Evaluated( 15959 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15960 if (Arg.getKind() == TemplateArgument::Declaration) { 15961 if (Decl *D = Arg.getAsDecl()) 15962 S.MarkAnyDeclReferenced(Loc, D, true); 15963 } else if (Arg.getKind() == TemplateArgument::Expression) { 15964 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15965 } 15966 } 15967 15968 return Inherited::TraverseTemplateArgument(Arg); 15969 } 15970 15971 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15972 MarkReferencedDecls Marker(*this, Loc); 15973 Marker.TraverseType(T); 15974 } 15975 15976 namespace { 15977 /// Helper class that marks all of the declarations referenced by 15978 /// potentially-evaluated subexpressions as "referenced". 15979 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15980 Sema &S; 15981 bool SkipLocalVariables; 15982 15983 public: 15984 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15985 15986 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15987 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15988 15989 void VisitDeclRefExpr(DeclRefExpr *E) { 15990 // If we were asked not to visit local variables, don't. 15991 if (SkipLocalVariables) { 15992 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15993 if (VD->hasLocalStorage()) 15994 return; 15995 } 15996 15997 S.MarkDeclRefReferenced(E); 15998 } 15999 16000 void VisitMemberExpr(MemberExpr *E) { 16001 S.MarkMemberReferenced(E); 16002 Inherited::VisitMemberExpr(E); 16003 } 16004 16005 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 16006 S.MarkFunctionReferenced( 16007 E->getBeginLoc(), 16008 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 16009 Visit(E->getSubExpr()); 16010 } 16011 16012 void VisitCXXNewExpr(CXXNewExpr *E) { 16013 if (E->getOperatorNew()) 16014 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 16015 if (E->getOperatorDelete()) 16016 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16017 Inherited::VisitCXXNewExpr(E); 16018 } 16019 16020 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16021 if (E->getOperatorDelete()) 16022 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 16023 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 16024 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 16025 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 16026 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 16027 } 16028 16029 Inherited::VisitCXXDeleteExpr(E); 16030 } 16031 16032 void VisitCXXConstructExpr(CXXConstructExpr *E) { 16033 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 16034 Inherited::VisitCXXConstructExpr(E); 16035 } 16036 16037 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 16038 Visit(E->getExpr()); 16039 } 16040 16041 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 16042 Inherited::VisitImplicitCastExpr(E); 16043 16044 if (E->getCastKind() == CK_LValueToRValue) 16045 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 16046 } 16047 }; 16048 } 16049 16050 /// Mark any declarations that appear within this expression or any 16051 /// potentially-evaluated subexpressions as "referenced". 16052 /// 16053 /// \param SkipLocalVariables If true, don't mark local variables as 16054 /// 'referenced'. 16055 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 16056 bool SkipLocalVariables) { 16057 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 16058 } 16059 16060 /// Emit a diagnostic that describes an effect on the run-time behavior 16061 /// of the program being compiled. 16062 /// 16063 /// This routine emits the given diagnostic when the code currently being 16064 /// type-checked is "potentially evaluated", meaning that there is a 16065 /// possibility that the code will actually be executable. Code in sizeof() 16066 /// expressions, code used only during overload resolution, etc., are not 16067 /// potentially evaluated. This routine will suppress such diagnostics or, 16068 /// in the absolutely nutty case of potentially potentially evaluated 16069 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 16070 /// later. 16071 /// 16072 /// This routine should be used for all diagnostics that describe the run-time 16073 /// behavior of a program, such as passing a non-POD value through an ellipsis. 16074 /// Failure to do so will likely result in spurious diagnostics or failures 16075 /// during overload resolution or within sizeof/alignof/typeof/typeid. 16076 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 16077 const PartialDiagnostic &PD) { 16078 switch (ExprEvalContexts.back().Context) { 16079 case ExpressionEvaluationContext::Unevaluated: 16080 case ExpressionEvaluationContext::UnevaluatedList: 16081 case ExpressionEvaluationContext::UnevaluatedAbstract: 16082 case ExpressionEvaluationContext::DiscardedStatement: 16083 // The argument will never be evaluated, so don't complain. 16084 break; 16085 16086 case ExpressionEvaluationContext::ConstantEvaluated: 16087 // Relevant diagnostics should be produced by constant evaluation. 16088 break; 16089 16090 case ExpressionEvaluationContext::PotentiallyEvaluated: 16091 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16092 if (Statement && getCurFunctionOrMethodDecl()) { 16093 FunctionScopes.back()->PossiblyUnreachableDiags. 16094 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 16095 return true; 16096 } 16097 16098 // The initializer of a constexpr variable or of the first declaration of a 16099 // static data member is not syntactically a constant evaluated constant, 16100 // but nonetheless is always required to be a constant expression, so we 16101 // can skip diagnosing. 16102 // FIXME: Using the mangling context here is a hack. 16103 if (auto *VD = dyn_cast_or_null<VarDecl>( 16104 ExprEvalContexts.back().ManglingContextDecl)) { 16105 if (VD->isConstexpr() || 16106 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 16107 break; 16108 // FIXME: For any other kind of variable, we should build a CFG for its 16109 // initializer and check whether the context in question is reachable. 16110 } 16111 16112 Diag(Loc, PD); 16113 return true; 16114 } 16115 16116 return false; 16117 } 16118 16119 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 16120 CallExpr *CE, FunctionDecl *FD) { 16121 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 16122 return false; 16123 16124 // If we're inside a decltype's expression, don't check for a valid return 16125 // type or construct temporaries until we know whether this is the last call. 16126 if (ExprEvalContexts.back().ExprContext == 16127 ExpressionEvaluationContextRecord::EK_Decltype) { 16128 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 16129 return false; 16130 } 16131 16132 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 16133 FunctionDecl *FD; 16134 CallExpr *CE; 16135 16136 public: 16137 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 16138 : FD(FD), CE(CE) { } 16139 16140 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16141 if (!FD) { 16142 S.Diag(Loc, diag::err_call_incomplete_return) 16143 << T << CE->getSourceRange(); 16144 return; 16145 } 16146 16147 S.Diag(Loc, diag::err_call_function_incomplete_return) 16148 << CE->getSourceRange() << FD->getDeclName() << T; 16149 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 16150 << FD->getDeclName(); 16151 } 16152 } Diagnoser(FD, CE); 16153 16154 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 16155 return true; 16156 16157 return false; 16158 } 16159 16160 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 16161 // will prevent this condition from triggering, which is what we want. 16162 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 16163 SourceLocation Loc; 16164 16165 unsigned diagnostic = diag::warn_condition_is_assignment; 16166 bool IsOrAssign = false; 16167 16168 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 16169 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 16170 return; 16171 16172 IsOrAssign = Op->getOpcode() == BO_OrAssign; 16173 16174 // Greylist some idioms by putting them into a warning subcategory. 16175 if (ObjCMessageExpr *ME 16176 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 16177 Selector Sel = ME->getSelector(); 16178 16179 // self = [<foo> init...] 16180 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 16181 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16182 16183 // <foo> = [<bar> nextObject] 16184 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 16185 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16186 } 16187 16188 Loc = Op->getOperatorLoc(); 16189 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 16190 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 16191 return; 16192 16193 IsOrAssign = Op->getOperator() == OO_PipeEqual; 16194 Loc = Op->getOperatorLoc(); 16195 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 16196 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 16197 else { 16198 // Not an assignment. 16199 return; 16200 } 16201 16202 Diag(Loc, diagnostic) << E->getSourceRange(); 16203 16204 SourceLocation Open = E->getBeginLoc(); 16205 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 16206 Diag(Loc, diag::note_condition_assign_silence) 16207 << FixItHint::CreateInsertion(Open, "(") 16208 << FixItHint::CreateInsertion(Close, ")"); 16209 16210 if (IsOrAssign) 16211 Diag(Loc, diag::note_condition_or_assign_to_comparison) 16212 << FixItHint::CreateReplacement(Loc, "!="); 16213 else 16214 Diag(Loc, diag::note_condition_assign_to_comparison) 16215 << FixItHint::CreateReplacement(Loc, "=="); 16216 } 16217 16218 /// Redundant parentheses over an equality comparison can indicate 16219 /// that the user intended an assignment used as condition. 16220 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 16221 // Don't warn if the parens came from a macro. 16222 SourceLocation parenLoc = ParenE->getBeginLoc(); 16223 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 16224 return; 16225 // Don't warn for dependent expressions. 16226 if (ParenE->isTypeDependent()) 16227 return; 16228 16229 Expr *E = ParenE->IgnoreParens(); 16230 16231 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 16232 if (opE->getOpcode() == BO_EQ && 16233 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 16234 == Expr::MLV_Valid) { 16235 SourceLocation Loc = opE->getOperatorLoc(); 16236 16237 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 16238 SourceRange ParenERange = ParenE->getSourceRange(); 16239 Diag(Loc, diag::note_equality_comparison_silence) 16240 << FixItHint::CreateRemoval(ParenERange.getBegin()) 16241 << FixItHint::CreateRemoval(ParenERange.getEnd()); 16242 Diag(Loc, diag::note_equality_comparison_to_assign) 16243 << FixItHint::CreateReplacement(Loc, "="); 16244 } 16245 } 16246 16247 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 16248 bool IsConstexpr) { 16249 DiagnoseAssignmentAsCondition(E); 16250 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 16251 DiagnoseEqualityWithExtraParens(parenE); 16252 16253 ExprResult result = CheckPlaceholderExpr(E); 16254 if (result.isInvalid()) return ExprError(); 16255 E = result.get(); 16256 16257 if (!E->isTypeDependent()) { 16258 if (getLangOpts().CPlusPlus) 16259 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 16260 16261 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 16262 if (ERes.isInvalid()) 16263 return ExprError(); 16264 E = ERes.get(); 16265 16266 QualType T = E->getType(); 16267 if (!T->isScalarType()) { // C99 6.8.4.1p1 16268 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 16269 << T << E->getSourceRange(); 16270 return ExprError(); 16271 } 16272 CheckBoolLikeConversion(E, Loc); 16273 } 16274 16275 return E; 16276 } 16277 16278 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 16279 Expr *SubExpr, ConditionKind CK) { 16280 // Empty conditions are valid in for-statements. 16281 if (!SubExpr) 16282 return ConditionResult(); 16283 16284 ExprResult Cond; 16285 switch (CK) { 16286 case ConditionKind::Boolean: 16287 Cond = CheckBooleanCondition(Loc, SubExpr); 16288 break; 16289 16290 case ConditionKind::ConstexprIf: 16291 Cond = CheckBooleanCondition(Loc, SubExpr, true); 16292 break; 16293 16294 case ConditionKind::Switch: 16295 Cond = CheckSwitchCondition(Loc, SubExpr); 16296 break; 16297 } 16298 if (Cond.isInvalid()) 16299 return ConditionError(); 16300 16301 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 16302 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 16303 if (!FullExpr.get()) 16304 return ConditionError(); 16305 16306 return ConditionResult(*this, nullptr, FullExpr, 16307 CK == ConditionKind::ConstexprIf); 16308 } 16309 16310 namespace { 16311 /// A visitor for rebuilding a call to an __unknown_any expression 16312 /// to have an appropriate type. 16313 struct RebuildUnknownAnyFunction 16314 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 16315 16316 Sema &S; 16317 16318 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 16319 16320 ExprResult VisitStmt(Stmt *S) { 16321 llvm_unreachable("unexpected statement!"); 16322 } 16323 16324 ExprResult VisitExpr(Expr *E) { 16325 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 16326 << E->getSourceRange(); 16327 return ExprError(); 16328 } 16329 16330 /// Rebuild an expression which simply semantically wraps another 16331 /// expression which it shares the type and value kind of. 16332 template <class T> ExprResult rebuildSugarExpr(T *E) { 16333 ExprResult SubResult = Visit(E->getSubExpr()); 16334 if (SubResult.isInvalid()) return ExprError(); 16335 16336 Expr *SubExpr = SubResult.get(); 16337 E->setSubExpr(SubExpr); 16338 E->setType(SubExpr->getType()); 16339 E->setValueKind(SubExpr->getValueKind()); 16340 assert(E->getObjectKind() == OK_Ordinary); 16341 return E; 16342 } 16343 16344 ExprResult VisitParenExpr(ParenExpr *E) { 16345 return rebuildSugarExpr(E); 16346 } 16347 16348 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16349 return rebuildSugarExpr(E); 16350 } 16351 16352 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16353 ExprResult SubResult = Visit(E->getSubExpr()); 16354 if (SubResult.isInvalid()) return ExprError(); 16355 16356 Expr *SubExpr = SubResult.get(); 16357 E->setSubExpr(SubExpr); 16358 E->setType(S.Context.getPointerType(SubExpr->getType())); 16359 assert(E->getValueKind() == VK_RValue); 16360 assert(E->getObjectKind() == OK_Ordinary); 16361 return E; 16362 } 16363 16364 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16365 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16366 16367 E->setType(VD->getType()); 16368 16369 assert(E->getValueKind() == VK_RValue); 16370 if (S.getLangOpts().CPlusPlus && 16371 !(isa<CXXMethodDecl>(VD) && 16372 cast<CXXMethodDecl>(VD)->isInstance())) 16373 E->setValueKind(VK_LValue); 16374 16375 return E; 16376 } 16377 16378 ExprResult VisitMemberExpr(MemberExpr *E) { 16379 return resolveDecl(E, E->getMemberDecl()); 16380 } 16381 16382 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16383 return resolveDecl(E, E->getDecl()); 16384 } 16385 }; 16386 } 16387 16388 /// Given a function expression of unknown-any type, try to rebuild it 16389 /// to have a function type. 16390 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16391 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16392 if (Result.isInvalid()) return ExprError(); 16393 return S.DefaultFunctionArrayConversion(Result.get()); 16394 } 16395 16396 namespace { 16397 /// A visitor for rebuilding an expression of type __unknown_anytype 16398 /// into one which resolves the type directly on the referring 16399 /// expression. Strict preservation of the original source 16400 /// structure is not a goal. 16401 struct RebuildUnknownAnyExpr 16402 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16403 16404 Sema &S; 16405 16406 /// The current destination type. 16407 QualType DestType; 16408 16409 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16410 : S(S), DestType(CastType) {} 16411 16412 ExprResult VisitStmt(Stmt *S) { 16413 llvm_unreachable("unexpected statement!"); 16414 } 16415 16416 ExprResult VisitExpr(Expr *E) { 16417 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16418 << E->getSourceRange(); 16419 return ExprError(); 16420 } 16421 16422 ExprResult VisitCallExpr(CallExpr *E); 16423 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16424 16425 /// Rebuild an expression which simply semantically wraps another 16426 /// expression which it shares the type and value kind of. 16427 template <class T> ExprResult rebuildSugarExpr(T *E) { 16428 ExprResult SubResult = Visit(E->getSubExpr()); 16429 if (SubResult.isInvalid()) return ExprError(); 16430 Expr *SubExpr = SubResult.get(); 16431 E->setSubExpr(SubExpr); 16432 E->setType(SubExpr->getType()); 16433 E->setValueKind(SubExpr->getValueKind()); 16434 assert(E->getObjectKind() == OK_Ordinary); 16435 return E; 16436 } 16437 16438 ExprResult VisitParenExpr(ParenExpr *E) { 16439 return rebuildSugarExpr(E); 16440 } 16441 16442 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16443 return rebuildSugarExpr(E); 16444 } 16445 16446 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16447 const PointerType *Ptr = DestType->getAs<PointerType>(); 16448 if (!Ptr) { 16449 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16450 << E->getSourceRange(); 16451 return ExprError(); 16452 } 16453 16454 if (isa<CallExpr>(E->getSubExpr())) { 16455 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16456 << E->getSourceRange(); 16457 return ExprError(); 16458 } 16459 16460 assert(E->getValueKind() == VK_RValue); 16461 assert(E->getObjectKind() == OK_Ordinary); 16462 E->setType(DestType); 16463 16464 // Build the sub-expression as if it were an object of the pointee type. 16465 DestType = Ptr->getPointeeType(); 16466 ExprResult SubResult = Visit(E->getSubExpr()); 16467 if (SubResult.isInvalid()) return ExprError(); 16468 E->setSubExpr(SubResult.get()); 16469 return E; 16470 } 16471 16472 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16473 16474 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16475 16476 ExprResult VisitMemberExpr(MemberExpr *E) { 16477 return resolveDecl(E, E->getMemberDecl()); 16478 } 16479 16480 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16481 return resolveDecl(E, E->getDecl()); 16482 } 16483 }; 16484 } 16485 16486 /// Rebuilds a call expression which yielded __unknown_anytype. 16487 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16488 Expr *CalleeExpr = E->getCallee(); 16489 16490 enum FnKind { 16491 FK_MemberFunction, 16492 FK_FunctionPointer, 16493 FK_BlockPointer 16494 }; 16495 16496 FnKind Kind; 16497 QualType CalleeType = CalleeExpr->getType(); 16498 if (CalleeType == S.Context.BoundMemberTy) { 16499 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16500 Kind = FK_MemberFunction; 16501 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16502 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16503 CalleeType = Ptr->getPointeeType(); 16504 Kind = FK_FunctionPointer; 16505 } else { 16506 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16507 Kind = FK_BlockPointer; 16508 } 16509 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16510 16511 // Verify that this is a legal result type of a function. 16512 if (DestType->isArrayType() || DestType->isFunctionType()) { 16513 unsigned diagID = diag::err_func_returning_array_function; 16514 if (Kind == FK_BlockPointer) 16515 diagID = diag::err_block_returning_array_function; 16516 16517 S.Diag(E->getExprLoc(), diagID) 16518 << DestType->isFunctionType() << DestType; 16519 return ExprError(); 16520 } 16521 16522 // Otherwise, go ahead and set DestType as the call's result. 16523 E->setType(DestType.getNonLValueExprType(S.Context)); 16524 E->setValueKind(Expr::getValueKindForType(DestType)); 16525 assert(E->getObjectKind() == OK_Ordinary); 16526 16527 // Rebuild the function type, replacing the result type with DestType. 16528 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16529 if (Proto) { 16530 // __unknown_anytype(...) is a special case used by the debugger when 16531 // it has no idea what a function's signature is. 16532 // 16533 // We want to build this call essentially under the K&R 16534 // unprototyped rules, but making a FunctionNoProtoType in C++ 16535 // would foul up all sorts of assumptions. However, we cannot 16536 // simply pass all arguments as variadic arguments, nor can we 16537 // portably just call the function under a non-variadic type; see 16538 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16539 // However, it turns out that in practice it is generally safe to 16540 // call a function declared as "A foo(B,C,D);" under the prototype 16541 // "A foo(B,C,D,...);". The only known exception is with the 16542 // Windows ABI, where any variadic function is implicitly cdecl 16543 // regardless of its normal CC. Therefore we change the parameter 16544 // types to match the types of the arguments. 16545 // 16546 // This is a hack, but it is far superior to moving the 16547 // corresponding target-specific code from IR-gen to Sema/AST. 16548 16549 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16550 SmallVector<QualType, 8> ArgTypes; 16551 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16552 ArgTypes.reserve(E->getNumArgs()); 16553 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16554 Expr *Arg = E->getArg(i); 16555 QualType ArgType = Arg->getType(); 16556 if (E->isLValue()) { 16557 ArgType = S.Context.getLValueReferenceType(ArgType); 16558 } else if (E->isXValue()) { 16559 ArgType = S.Context.getRValueReferenceType(ArgType); 16560 } 16561 ArgTypes.push_back(ArgType); 16562 } 16563 ParamTypes = ArgTypes; 16564 } 16565 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16566 Proto->getExtProtoInfo()); 16567 } else { 16568 DestType = S.Context.getFunctionNoProtoType(DestType, 16569 FnType->getExtInfo()); 16570 } 16571 16572 // Rebuild the appropriate pointer-to-function type. 16573 switch (Kind) { 16574 case FK_MemberFunction: 16575 // Nothing to do. 16576 break; 16577 16578 case FK_FunctionPointer: 16579 DestType = S.Context.getPointerType(DestType); 16580 break; 16581 16582 case FK_BlockPointer: 16583 DestType = S.Context.getBlockPointerType(DestType); 16584 break; 16585 } 16586 16587 // Finally, we can recurse. 16588 ExprResult CalleeResult = Visit(CalleeExpr); 16589 if (!CalleeResult.isUsable()) return ExprError(); 16590 E->setCallee(CalleeResult.get()); 16591 16592 // Bind a temporary if necessary. 16593 return S.MaybeBindToTemporary(E); 16594 } 16595 16596 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16597 // Verify that this is a legal result type of a call. 16598 if (DestType->isArrayType() || DestType->isFunctionType()) { 16599 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16600 << DestType->isFunctionType() << DestType; 16601 return ExprError(); 16602 } 16603 16604 // Rewrite the method result type if available. 16605 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16606 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16607 Method->setReturnType(DestType); 16608 } 16609 16610 // Change the type of the message. 16611 E->setType(DestType.getNonReferenceType()); 16612 E->setValueKind(Expr::getValueKindForType(DestType)); 16613 16614 return S.MaybeBindToTemporary(E); 16615 } 16616 16617 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16618 // The only case we should ever see here is a function-to-pointer decay. 16619 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16620 assert(E->getValueKind() == VK_RValue); 16621 assert(E->getObjectKind() == OK_Ordinary); 16622 16623 E->setType(DestType); 16624 16625 // Rebuild the sub-expression as the pointee (function) type. 16626 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16627 16628 ExprResult Result = Visit(E->getSubExpr()); 16629 if (!Result.isUsable()) return ExprError(); 16630 16631 E->setSubExpr(Result.get()); 16632 return E; 16633 } else if (E->getCastKind() == CK_LValueToRValue) { 16634 assert(E->getValueKind() == VK_RValue); 16635 assert(E->getObjectKind() == OK_Ordinary); 16636 16637 assert(isa<BlockPointerType>(E->getType())); 16638 16639 E->setType(DestType); 16640 16641 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16642 DestType = S.Context.getLValueReferenceType(DestType); 16643 16644 ExprResult Result = Visit(E->getSubExpr()); 16645 if (!Result.isUsable()) return ExprError(); 16646 16647 E->setSubExpr(Result.get()); 16648 return E; 16649 } else { 16650 llvm_unreachable("Unhandled cast type!"); 16651 } 16652 } 16653 16654 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16655 ExprValueKind ValueKind = VK_LValue; 16656 QualType Type = DestType; 16657 16658 // We know how to make this work for certain kinds of decls: 16659 16660 // - functions 16661 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16662 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16663 DestType = Ptr->getPointeeType(); 16664 ExprResult Result = resolveDecl(E, VD); 16665 if (Result.isInvalid()) return ExprError(); 16666 return S.ImpCastExprToType(Result.get(), Type, 16667 CK_FunctionToPointerDecay, VK_RValue); 16668 } 16669 16670 if (!Type->isFunctionType()) { 16671 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16672 << VD << E->getSourceRange(); 16673 return ExprError(); 16674 } 16675 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16676 // We must match the FunctionDecl's type to the hack introduced in 16677 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16678 // type. See the lengthy commentary in that routine. 16679 QualType FDT = FD->getType(); 16680 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16681 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16682 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16683 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16684 SourceLocation Loc = FD->getLocation(); 16685 FunctionDecl *NewFD = FunctionDecl::Create(S.Context, 16686 FD->getDeclContext(), 16687 Loc, Loc, FD->getNameInfo().getName(), 16688 DestType, FD->getTypeSourceInfo(), 16689 SC_None, false/*isInlineSpecified*/, 16690 FD->hasPrototype(), 16691 false/*isConstexprSpecified*/); 16692 16693 if (FD->getQualifier()) 16694 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16695 16696 SmallVector<ParmVarDecl*, 16> Params; 16697 for (const auto &AI : FT->param_types()) { 16698 ParmVarDecl *Param = 16699 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16700 Param->setScopeInfo(0, Params.size()); 16701 Params.push_back(Param); 16702 } 16703 NewFD->setParams(Params); 16704 DRE->setDecl(NewFD); 16705 VD = DRE->getDecl(); 16706 } 16707 } 16708 16709 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16710 if (MD->isInstance()) { 16711 ValueKind = VK_RValue; 16712 Type = S.Context.BoundMemberTy; 16713 } 16714 16715 // Function references aren't l-values in C. 16716 if (!S.getLangOpts().CPlusPlus) 16717 ValueKind = VK_RValue; 16718 16719 // - variables 16720 } else if (isa<VarDecl>(VD)) { 16721 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16722 Type = RefTy->getPointeeType(); 16723 } else if (Type->isFunctionType()) { 16724 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16725 << VD << E->getSourceRange(); 16726 return ExprError(); 16727 } 16728 16729 // - nothing else 16730 } else { 16731 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16732 << VD << E->getSourceRange(); 16733 return ExprError(); 16734 } 16735 16736 // Modifying the declaration like this is friendly to IR-gen but 16737 // also really dangerous. 16738 VD->setType(DestType); 16739 E->setType(Type); 16740 E->setValueKind(ValueKind); 16741 return E; 16742 } 16743 16744 /// Check a cast of an unknown-any type. We intentionally only 16745 /// trigger this for C-style casts. 16746 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16747 Expr *CastExpr, CastKind &CastKind, 16748 ExprValueKind &VK, CXXCastPath &Path) { 16749 // The type we're casting to must be either void or complete. 16750 if (!CastType->isVoidType() && 16751 RequireCompleteType(TypeRange.getBegin(), CastType, 16752 diag::err_typecheck_cast_to_incomplete)) 16753 return ExprError(); 16754 16755 // Rewrite the casted expression from scratch. 16756 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16757 if (!result.isUsable()) return ExprError(); 16758 16759 CastExpr = result.get(); 16760 VK = CastExpr->getValueKind(); 16761 CastKind = CK_NoOp; 16762 16763 return CastExpr; 16764 } 16765 16766 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16767 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16768 } 16769 16770 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16771 Expr *arg, QualType ¶mType) { 16772 // If the syntactic form of the argument is not an explicit cast of 16773 // any sort, just do default argument promotion. 16774 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16775 if (!castArg) { 16776 ExprResult result = DefaultArgumentPromotion(arg); 16777 if (result.isInvalid()) return ExprError(); 16778 paramType = result.get()->getType(); 16779 return result; 16780 } 16781 16782 // Otherwise, use the type that was written in the explicit cast. 16783 assert(!arg->hasPlaceholderType()); 16784 paramType = castArg->getTypeAsWritten(); 16785 16786 // Copy-initialize a parameter of that type. 16787 InitializedEntity entity = 16788 InitializedEntity::InitializeParameter(Context, paramType, 16789 /*consumed*/ false); 16790 return PerformCopyInitialization(entity, callLoc, arg); 16791 } 16792 16793 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16794 Expr *orig = E; 16795 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16796 while (true) { 16797 E = E->IgnoreParenImpCasts(); 16798 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16799 E = call->getCallee(); 16800 diagID = diag::err_uncasted_call_of_unknown_any; 16801 } else { 16802 break; 16803 } 16804 } 16805 16806 SourceLocation loc; 16807 NamedDecl *d; 16808 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16809 loc = ref->getLocation(); 16810 d = ref->getDecl(); 16811 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16812 loc = mem->getMemberLoc(); 16813 d = mem->getMemberDecl(); 16814 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16815 diagID = diag::err_uncasted_call_of_unknown_any; 16816 loc = msg->getSelectorStartLoc(); 16817 d = msg->getMethodDecl(); 16818 if (!d) { 16819 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16820 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16821 << orig->getSourceRange(); 16822 return ExprError(); 16823 } 16824 } else { 16825 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16826 << E->getSourceRange(); 16827 return ExprError(); 16828 } 16829 16830 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16831 16832 // Never recoverable. 16833 return ExprError(); 16834 } 16835 16836 /// Check for operands with placeholder types and complain if found. 16837 /// Returns ExprError() if there was an error and no recovery was possible. 16838 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16839 if (!getLangOpts().CPlusPlus) { 16840 // C cannot handle TypoExpr nodes on either side of a binop because it 16841 // doesn't handle dependent types properly, so make sure any TypoExprs have 16842 // been dealt with before checking the operands. 16843 ExprResult Result = CorrectDelayedTyposInExpr(E); 16844 if (!Result.isUsable()) return ExprError(); 16845 E = Result.get(); 16846 } 16847 16848 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16849 if (!placeholderType) return E; 16850 16851 switch (placeholderType->getKind()) { 16852 16853 // Overloaded expressions. 16854 case BuiltinType::Overload: { 16855 // Try to resolve a single function template specialization. 16856 // This is obligatory. 16857 ExprResult Result = E; 16858 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16859 return Result; 16860 16861 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16862 // leaves Result unchanged on failure. 16863 Result = E; 16864 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16865 return Result; 16866 16867 // If that failed, try to recover with a call. 16868 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16869 /*complain*/ true); 16870 return Result; 16871 } 16872 16873 // Bound member functions. 16874 case BuiltinType::BoundMember: { 16875 ExprResult result = E; 16876 const Expr *BME = E->IgnoreParens(); 16877 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16878 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16879 if (isa<CXXPseudoDestructorExpr>(BME)) { 16880 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16881 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16882 if (ME->getMemberNameInfo().getName().getNameKind() == 16883 DeclarationName::CXXDestructorName) 16884 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16885 } 16886 tryToRecoverWithCall(result, PD, 16887 /*complain*/ true); 16888 return result; 16889 } 16890 16891 // ARC unbridged casts. 16892 case BuiltinType::ARCUnbridgedCast: { 16893 Expr *realCast = stripARCUnbridgedCast(E); 16894 diagnoseARCUnbridgedCast(realCast); 16895 return realCast; 16896 } 16897 16898 // Expressions of unknown type. 16899 case BuiltinType::UnknownAny: 16900 return diagnoseUnknownAnyExpr(*this, E); 16901 16902 // Pseudo-objects. 16903 case BuiltinType::PseudoObject: 16904 return checkPseudoObjectRValue(E); 16905 16906 case BuiltinType::BuiltinFn: { 16907 // Accept __noop without parens by implicitly converting it to a call expr. 16908 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16909 if (DRE) { 16910 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16911 if (FD->getBuiltinID() == Builtin::BI__noop) { 16912 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16913 CK_BuiltinFnToFnPtr) 16914 .get(); 16915 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 16916 VK_RValue, SourceLocation()); 16917 } 16918 } 16919 16920 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16921 return ExprError(); 16922 } 16923 16924 // Expressions of unknown type. 16925 case BuiltinType::OMPArraySection: 16926 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16927 return ExprError(); 16928 16929 // Everything else should be impossible. 16930 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16931 case BuiltinType::Id: 16932 #include "clang/Basic/OpenCLImageTypes.def" 16933 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16934 case BuiltinType::Id: 16935 #include "clang/Basic/OpenCLExtensionTypes.def" 16936 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16937 #define PLACEHOLDER_TYPE(Id, SingletonId) 16938 #include "clang/AST/BuiltinTypes.def" 16939 break; 16940 } 16941 16942 llvm_unreachable("invalid placeholder type!"); 16943 } 16944 16945 bool Sema::CheckCaseExpression(Expr *E) { 16946 if (E->isTypeDependent()) 16947 return true; 16948 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16949 return E->getType()->isIntegralOrEnumerationType(); 16950 return false; 16951 } 16952 16953 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16954 ExprResult 16955 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16956 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16957 "Unknown Objective-C Boolean value!"); 16958 QualType BoolT = Context.ObjCBuiltinBoolTy; 16959 if (!Context.getBOOLDecl()) { 16960 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16961 Sema::LookupOrdinaryName); 16962 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16963 NamedDecl *ND = Result.getFoundDecl(); 16964 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16965 Context.setBOOLDecl(TD); 16966 } 16967 } 16968 if (Context.getBOOLDecl()) 16969 BoolT = Context.getBOOLType(); 16970 return new (Context) 16971 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16972 } 16973 16974 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16975 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16976 SourceLocation RParen) { 16977 16978 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16979 16980 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16981 [&](const AvailabilitySpec &Spec) { 16982 return Spec.getPlatform() == Platform; 16983 }); 16984 16985 VersionTuple Version; 16986 if (Spec != AvailSpecs.end()) 16987 Version = Spec->getVersion(); 16988 16989 // The use of `@available` in the enclosing function should be analyzed to 16990 // warn when it's used inappropriately (i.e. not if(@available)). 16991 if (getCurFunctionOrMethodDecl()) 16992 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16993 else if (getCurBlock() || getCurLambda()) 16994 getCurFunction()->HasPotentialAvailabilityViolations = true; 16995 16996 return new (Context) 16997 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16998 } 16999