1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks, 210 ObjCInterfaceDecl *ClassReceiver) { 211 SourceLocation Loc = Locs.front(); 212 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 213 // If there were any diagnostics suppressed by template argument deduction, 214 // emit them now. 215 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 216 if (Pos != SuppressedDiagnostics.end()) { 217 for (const PartialDiagnosticAt &Suppressed : Pos->second) 218 Diag(Suppressed.first, Suppressed.second); 219 220 // Clear out the list of suppressed diagnostics, so that we don't emit 221 // them again for this specialization. However, we don't obsolete this 222 // entry from the table, because we want to avoid ever emitting these 223 // diagnostics again. 224 Pos->second.clear(); 225 } 226 227 // C++ [basic.start.main]p3: 228 // The function 'main' shall not be used within a program. 229 if (cast<FunctionDecl>(D)->isMain()) 230 Diag(Loc, diag::ext_main_used); 231 } 232 233 // See if this is an auto-typed variable whose initializer we are parsing. 234 if (ParsingInitForAutoVars.count(D)) { 235 if (isa<BindingDecl>(D)) { 236 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 237 << D->getDeclName(); 238 } else { 239 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 240 << D->getDeclName() << cast<VarDecl>(D)->getType(); 241 } 242 return true; 243 } 244 245 // See if this is a deleted function. 246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 247 if (FD->isDeleted()) { 248 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 249 if (Ctor && Ctor->isInheritingConstructor()) 250 Diag(Loc, diag::err_deleted_inherited_ctor_use) 251 << Ctor->getParent() 252 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 253 else 254 Diag(Loc, diag::err_deleted_function_use); 255 NoteDeletedFunction(FD); 256 return true; 257 } 258 259 // If the function has a deduced return type, and we can't deduce it, 260 // then we can't use it either. 261 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 262 DeduceReturnType(FD, Loc)) 263 return true; 264 265 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 266 return true; 267 } 268 269 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 270 // Lambdas are only default-constructible or assignable in C++2a onwards. 271 if (MD->getParent()->isLambda() && 272 ((isa<CXXConstructorDecl>(MD) && 273 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 274 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 275 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 276 << !isa<CXXConstructorDecl>(MD); 277 } 278 } 279 280 auto getReferencedObjCProp = [](const NamedDecl *D) -> 281 const ObjCPropertyDecl * { 282 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 283 return MD->findPropertyDecl(); 284 return nullptr; 285 }; 286 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 287 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 288 return true; 289 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 290 return true; 291 } 292 293 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 294 // Only the variables omp_in and omp_out are allowed in the combiner. 295 // Only the variables omp_priv and omp_orig are allowed in the 296 // initializer-clause. 297 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 298 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 299 isa<VarDecl>(D)) { 300 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 301 << getCurFunction()->HasOMPDeclareReductionCombiner; 302 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 303 return true; 304 } 305 306 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 307 AvoidPartialAvailabilityChecks, ClassReceiver); 308 309 DiagnoseUnusedOfDecl(*this, D, Loc); 310 311 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 312 313 return false; 314 } 315 316 /// Retrieve the message suffix that should be added to a 317 /// diagnostic complaining about the given function being deleted or 318 /// unavailable. 319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 320 std::string Message; 321 if (FD->getAvailability(&Message)) 322 return ": " + Message; 323 324 return std::string(); 325 } 326 327 /// DiagnoseSentinelCalls - This routine checks whether a call or 328 /// message-send is to a declaration with the sentinel attribute, and 329 /// if so, it checks that the requirements of the sentinel are 330 /// satisfied. 331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 332 ArrayRef<Expr *> Args) { 333 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 334 if (!attr) 335 return; 336 337 // The number of formal parameters of the declaration. 338 unsigned numFormalParams; 339 340 // The kind of declaration. This is also an index into a %select in 341 // the diagnostic. 342 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 343 344 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 345 numFormalParams = MD->param_size(); 346 calleeType = CT_Method; 347 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 348 numFormalParams = FD->param_size(); 349 calleeType = CT_Function; 350 } else if (isa<VarDecl>(D)) { 351 QualType type = cast<ValueDecl>(D)->getType(); 352 const FunctionType *fn = nullptr; 353 if (const PointerType *ptr = type->getAs<PointerType>()) { 354 fn = ptr->getPointeeType()->getAs<FunctionType>(); 355 if (!fn) return; 356 calleeType = CT_Function; 357 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 358 fn = ptr->getPointeeType()->castAs<FunctionType>(); 359 calleeType = CT_Block; 360 } else { 361 return; 362 } 363 364 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 365 numFormalParams = proto->getNumParams(); 366 } else { 367 numFormalParams = 0; 368 } 369 } else { 370 return; 371 } 372 373 // "nullPos" is the number of formal parameters at the end which 374 // effectively count as part of the variadic arguments. This is 375 // useful if you would prefer to not have *any* formal parameters, 376 // but the language forces you to have at least one. 377 unsigned nullPos = attr->getNullPos(); 378 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 379 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 380 381 // The number of arguments which should follow the sentinel. 382 unsigned numArgsAfterSentinel = attr->getSentinel(); 383 384 // If there aren't enough arguments for all the formal parameters, 385 // the sentinel, and the args after the sentinel, complain. 386 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 387 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 388 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 389 return; 390 } 391 392 // Otherwise, find the sentinel expression. 393 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 394 if (!sentinelExpr) return; 395 if (sentinelExpr->isValueDependent()) return; 396 if (Context.isSentinelNullExpr(sentinelExpr)) return; 397 398 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 399 // or 'NULL' if those are actually defined in the context. Only use 400 // 'nil' for ObjC methods, where it's much more likely that the 401 // variadic arguments form a list of object pointers. 402 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 403 std::string NullValue; 404 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 405 NullValue = "nil"; 406 else if (getLangOpts().CPlusPlus11) 407 NullValue = "nullptr"; 408 else if (PP.isMacroDefined("NULL")) 409 NullValue = "NULL"; 410 else 411 NullValue = "(void*) 0"; 412 413 if (MissingNilLoc.isInvalid()) 414 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 415 else 416 Diag(MissingNilLoc, diag::warn_missing_sentinel) 417 << int(calleeType) 418 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 419 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 420 } 421 422 SourceRange Sema::getExprRange(Expr *E) const { 423 return E ? E->getSourceRange() : SourceRange(); 424 } 425 426 //===----------------------------------------------------------------------===// 427 // Standard Promotions and Conversions 428 //===----------------------------------------------------------------------===// 429 430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 432 // Handle any placeholder expressions which made it here. 433 if (E->getType()->isPlaceholderType()) { 434 ExprResult result = CheckPlaceholderExpr(E); 435 if (result.isInvalid()) return ExprError(); 436 E = result.get(); 437 } 438 439 QualType Ty = E->getType(); 440 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 441 442 if (Ty->isFunctionType()) { 443 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 444 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 445 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 446 return ExprError(); 447 448 E = ImpCastExprToType(E, Context.getPointerType(Ty), 449 CK_FunctionToPointerDecay).get(); 450 } else if (Ty->isArrayType()) { 451 // In C90 mode, arrays only promote to pointers if the array expression is 452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 453 // type 'array of type' is converted to an expression that has type 'pointer 454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 455 // that has type 'array of type' ...". The relevant change is "an lvalue" 456 // (C90) to "an expression" (C99). 457 // 458 // C++ 4.2p1: 459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 460 // T" can be converted to an rvalue of type "pointer to T". 461 // 462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 464 CK_ArrayToPointerDecay).get(); 465 } 466 return E; 467 } 468 469 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 470 // Check to see if we are dereferencing a null pointer. If so, 471 // and if not volatile-qualified, this is undefined behavior that the 472 // optimizer will delete, so warn about it. People sometimes try to use this 473 // to get a deterministic trap and are surprised by clang's behavior. This 474 // only handles the pattern "*null", which is a very syntactic check. 475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 476 if (UO->getOpcode() == UO_Deref && 477 UO->getSubExpr()->IgnoreParenCasts()-> 478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 479 !UO->getType().isVolatileQualified()) { 480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 481 S.PDiag(diag::warn_indirection_through_null) 482 << UO->getSubExpr()->getSourceRange()); 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::note_indirection_through_null)); 485 } 486 } 487 488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 489 SourceLocation AssignLoc, 490 const Expr* RHS) { 491 const ObjCIvarDecl *IV = OIRE->getDecl(); 492 if (!IV) 493 return; 494 495 DeclarationName MemberName = IV->getDeclName(); 496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 497 if (!Member || !Member->isStr("isa")) 498 return; 499 500 const Expr *Base = OIRE->getBase(); 501 QualType BaseType = Base->getType(); 502 if (OIRE->isArrow()) 503 BaseType = BaseType->getPointeeType(); 504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 506 ObjCInterfaceDecl *ClassDeclared = nullptr; 507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 508 if (!ClassDeclared->getSuperClass() 509 && (*ClassDeclared->ivar_begin()) == IV) { 510 if (RHS) { 511 NamedDecl *ObjectSetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_setClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectSetClass) { 516 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 518 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 519 "object_setClass(") 520 << FixItHint::CreateReplacement( 521 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 522 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 523 } 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 526 } else { 527 NamedDecl *ObjectGetClass = 528 S.LookupSingleName(S.TUScope, 529 &S.Context.Idents.get("object_getClass"), 530 SourceLocation(), S.LookupOrdinaryName); 531 if (ObjectGetClass) 532 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 533 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 534 "object_getClass(") 535 << FixItHint::CreateReplacement( 536 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 537 else 538 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 539 } 540 S.Diag(IV->getLocation(), diag::note_ivar_decl); 541 } 542 } 543 } 544 545 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 546 // Handle any placeholder expressions which made it here. 547 if (E->getType()->isPlaceholderType()) { 548 ExprResult result = CheckPlaceholderExpr(E); 549 if (result.isInvalid()) return ExprError(); 550 E = result.get(); 551 } 552 553 // C++ [conv.lval]p1: 554 // A glvalue of a non-function, non-array type T can be 555 // converted to a prvalue. 556 if (!E->isGLValue()) return E; 557 558 QualType T = E->getType(); 559 assert(!T.isNull() && "r-value conversion on typeless expression?"); 560 561 // We don't want to throw lvalue-to-rvalue casts on top of 562 // expressions of certain types in C++. 563 if (getLangOpts().CPlusPlus && 564 (E->getType() == Context.OverloadTy || 565 T->isDependentType() || 566 T->isRecordType())) 567 return E; 568 569 // The C standard is actually really unclear on this point, and 570 // DR106 tells us what the result should be but not why. It's 571 // generally best to say that void types just doesn't undergo 572 // lvalue-to-rvalue at all. Note that expressions of unqualified 573 // 'void' type are never l-values, but qualified void can be. 574 if (T->isVoidType()) 575 return E; 576 577 // OpenCL usually rejects direct accesses to values of 'half' type. 578 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 579 T->isHalfType()) { 580 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 581 << 0 << T; 582 return ExprError(); 583 } 584 585 CheckForNullPointerDereference(*this, E); 586 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 587 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 588 &Context.Idents.get("object_getClass"), 589 SourceLocation(), LookupOrdinaryName); 590 if (ObjectGetClass) 591 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 592 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 593 << FixItHint::CreateReplacement( 594 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 595 else 596 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 597 } 598 else if (const ObjCIvarRefExpr *OIRE = 599 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 600 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 601 602 // C++ [conv.lval]p1: 603 // [...] If T is a non-class type, the type of the prvalue is the 604 // cv-unqualified version of T. Otherwise, the type of the 605 // rvalue is T. 606 // 607 // C99 6.3.2.1p2: 608 // If the lvalue has qualified type, the value has the unqualified 609 // version of the type of the lvalue; otherwise, the value has the 610 // type of the lvalue. 611 if (T.hasQualifiers()) 612 T = T.getUnqualifiedType(); 613 614 // Under the MS ABI, lock down the inheritance model now. 615 if (T->isMemberPointerType() && 616 Context.getTargetInfo().getCXXABI().isMicrosoft()) 617 (void)isCompleteType(E->getExprLoc(), T); 618 619 UpdateMarkingForLValueToRValue(E); 620 621 // Loading a __weak object implicitly retains the value, so we need a cleanup to 622 // balance that. 623 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 624 Cleanup.setExprNeedsCleanups(true); 625 626 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 627 nullptr, VK_RValue); 628 629 // C11 6.3.2.1p2: 630 // ... if the lvalue has atomic type, the value has the non-atomic version 631 // of the type of the lvalue ... 632 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 633 T = Atomic->getValueType().getUnqualifiedType(); 634 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 635 nullptr, VK_RValue); 636 } 637 638 return Res; 639 } 640 641 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 642 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 643 if (Res.isInvalid()) 644 return ExprError(); 645 Res = DefaultLvalueConversion(Res.get()); 646 if (Res.isInvalid()) 647 return ExprError(); 648 return Res; 649 } 650 651 /// CallExprUnaryConversions - a special case of an unary conversion 652 /// performed on a function designator of a call expression. 653 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 654 QualType Ty = E->getType(); 655 ExprResult Res = E; 656 // Only do implicit cast for a function type, but not for a pointer 657 // to function type. 658 if (Ty->isFunctionType()) { 659 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 660 CK_FunctionToPointerDecay).get(); 661 if (Res.isInvalid()) 662 return ExprError(); 663 } 664 Res = DefaultLvalueConversion(Res.get()); 665 if (Res.isInvalid()) 666 return ExprError(); 667 return Res.get(); 668 } 669 670 /// UsualUnaryConversions - Performs various conversions that are common to most 671 /// operators (C99 6.3). The conversions of array and function types are 672 /// sometimes suppressed. For example, the array->pointer conversion doesn't 673 /// apply if the array is an argument to the sizeof or address (&) operators. 674 /// In these instances, this routine should *not* be called. 675 ExprResult Sema::UsualUnaryConversions(Expr *E) { 676 // First, convert to an r-value. 677 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 678 if (Res.isInvalid()) 679 return ExprError(); 680 E = Res.get(); 681 682 QualType Ty = E->getType(); 683 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 684 685 // Half FP have to be promoted to float unless it is natively supported 686 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 687 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 688 689 // Try to perform integral promotions if the object has a theoretically 690 // promotable type. 691 if (Ty->isIntegralOrUnscopedEnumerationType()) { 692 // C99 6.3.1.1p2: 693 // 694 // The following may be used in an expression wherever an int or 695 // unsigned int may be used: 696 // - an object or expression with an integer type whose integer 697 // conversion rank is less than or equal to the rank of int 698 // and unsigned int. 699 // - A bit-field of type _Bool, int, signed int, or unsigned int. 700 // 701 // If an int can represent all values of the original type, the 702 // value is converted to an int; otherwise, it is converted to an 703 // unsigned int. These are called the integer promotions. All 704 // other types are unchanged by the integer promotions. 705 706 QualType PTy = Context.isPromotableBitField(E); 707 if (!PTy.isNull()) { 708 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 709 return E; 710 } 711 if (Ty->isPromotableIntegerType()) { 712 QualType PT = Context.getPromotedIntegerType(Ty); 713 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 714 return E; 715 } 716 } 717 return E; 718 } 719 720 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 721 /// do not have a prototype. Arguments that have type float or __fp16 722 /// are promoted to double. All other argument types are converted by 723 /// UsualUnaryConversions(). 724 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 725 QualType Ty = E->getType(); 726 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 727 728 ExprResult Res = UsualUnaryConversions(E); 729 if (Res.isInvalid()) 730 return ExprError(); 731 E = Res.get(); 732 733 QualType ScalarTy = Ty; 734 unsigned NumElts = 0; 735 if (const ExtVectorType *VecTy = Ty->getAs<ExtVectorType>()) { 736 NumElts = VecTy->getNumElements(); 737 ScalarTy = VecTy->getElementType(); 738 } 739 740 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 741 // promote to double. 742 // Note that default argument promotion applies only to float (and 743 // half/fp16); it does not apply to _Float16. 744 const BuiltinType *BTy = ScalarTy->getAs<BuiltinType>(); 745 if (BTy && (BTy->getKind() == BuiltinType::Half || 746 BTy->getKind() == BuiltinType::Float)) { 747 if (getLangOpts().OpenCL && 748 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 749 if (BTy->getKind() == BuiltinType::Half) { 750 QualType Ty = Context.FloatTy; 751 if (NumElts != 0) 752 Ty = Context.getExtVectorType(Ty, NumElts); 753 E = ImpCastExprToType(E, Ty, CK_FloatingCast).get(); 754 } 755 } else { 756 QualType Ty = Context.DoubleTy; 757 if (NumElts != 0) 758 Ty = Context.getExtVectorType(Ty, NumElts); 759 E = ImpCastExprToType(E, Ty, CK_FloatingCast).get(); 760 } 761 } 762 763 // C++ performs lvalue-to-rvalue conversion as a default argument 764 // promotion, even on class types, but note: 765 // C++11 [conv.lval]p2: 766 // When an lvalue-to-rvalue conversion occurs in an unevaluated 767 // operand or a subexpression thereof the value contained in the 768 // referenced object is not accessed. Otherwise, if the glvalue 769 // has a class type, the conversion copy-initializes a temporary 770 // of type T from the glvalue and the result of the conversion 771 // is a prvalue for the temporary. 772 // FIXME: add some way to gate this entire thing for correctness in 773 // potentially potentially evaluated contexts. 774 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 775 ExprResult Temp = PerformCopyInitialization( 776 InitializedEntity::InitializeTemporary(E->getType()), 777 E->getExprLoc(), E); 778 if (Temp.isInvalid()) 779 return ExprError(); 780 E = Temp.get(); 781 } 782 783 return E; 784 } 785 786 /// Determine the degree of POD-ness for an expression. 787 /// Incomplete types are considered POD, since this check can be performed 788 /// when we're in an unevaluated context. 789 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 790 if (Ty->isIncompleteType()) { 791 // C++11 [expr.call]p7: 792 // After these conversions, if the argument does not have arithmetic, 793 // enumeration, pointer, pointer to member, or class type, the program 794 // is ill-formed. 795 // 796 // Since we've already performed array-to-pointer and function-to-pointer 797 // decay, the only such type in C++ is cv void. This also handles 798 // initializer lists as variadic arguments. 799 if (Ty->isVoidType()) 800 return VAK_Invalid; 801 802 if (Ty->isObjCObjectType()) 803 return VAK_Invalid; 804 return VAK_Valid; 805 } 806 807 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 808 return VAK_Invalid; 809 810 if (Ty.isCXX98PODType(Context)) 811 return VAK_Valid; 812 813 // C++11 [expr.call]p7: 814 // Passing a potentially-evaluated argument of class type (Clause 9) 815 // having a non-trivial copy constructor, a non-trivial move constructor, 816 // or a non-trivial destructor, with no corresponding parameter, 817 // is conditionally-supported with implementation-defined semantics. 818 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 819 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 820 if (!Record->hasNonTrivialCopyConstructor() && 821 !Record->hasNonTrivialMoveConstructor() && 822 !Record->hasNonTrivialDestructor()) 823 return VAK_ValidInCXX11; 824 825 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 826 return VAK_Valid; 827 828 if (Ty->isObjCObjectType()) 829 return VAK_Invalid; 830 831 if (getLangOpts().MSVCCompat) 832 return VAK_MSVCUndefined; 833 834 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 835 // permitted to reject them. We should consider doing so. 836 return VAK_Undefined; 837 } 838 839 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 840 // Don't allow one to pass an Objective-C interface to a vararg. 841 const QualType &Ty = E->getType(); 842 VarArgKind VAK = isValidVarArgType(Ty); 843 844 // Complain about passing non-POD types through varargs. 845 switch (VAK) { 846 case VAK_ValidInCXX11: 847 DiagRuntimeBehavior( 848 E->getBeginLoc(), nullptr, 849 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 850 LLVM_FALLTHROUGH; 851 case VAK_Valid: 852 if (Ty->isRecordType()) { 853 // This is unlikely to be what the user intended. If the class has a 854 // 'c_str' member function, the user probably meant to call that. 855 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 856 PDiag(diag::warn_pass_class_arg_to_vararg) 857 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 858 } 859 break; 860 861 case VAK_Undefined: 862 case VAK_MSVCUndefined: 863 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 864 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 865 << getLangOpts().CPlusPlus11 << Ty << CT); 866 break; 867 868 case VAK_Invalid: 869 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 870 Diag(E->getBeginLoc(), 871 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 872 << Ty << CT; 873 else if (Ty->isObjCObjectType()) 874 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 875 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 876 << Ty << CT); 877 else 878 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 879 << isa<InitListExpr>(E) << Ty << CT; 880 break; 881 } 882 } 883 884 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 885 /// will create a trap if the resulting type is not a POD type. 886 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 887 FunctionDecl *FDecl) { 888 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 889 // Strip the unbridged-cast placeholder expression off, if applicable. 890 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 891 (CT == VariadicMethod || 892 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 893 E = stripARCUnbridgedCast(E); 894 895 // Otherwise, do normal placeholder checking. 896 } else { 897 ExprResult ExprRes = CheckPlaceholderExpr(E); 898 if (ExprRes.isInvalid()) 899 return ExprError(); 900 E = ExprRes.get(); 901 } 902 } 903 904 ExprResult ExprRes = DefaultArgumentPromotion(E); 905 if (ExprRes.isInvalid()) 906 return ExprError(); 907 E = ExprRes.get(); 908 909 // Diagnostics regarding non-POD argument types are 910 // emitted along with format string checking in Sema::CheckFunctionCall(). 911 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 912 // Turn this into a trap. 913 CXXScopeSpec SS; 914 SourceLocation TemplateKWLoc; 915 UnqualifiedId Name; 916 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 917 E->getBeginLoc()); 918 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 919 Name, true, false); 920 if (TrapFn.isInvalid()) 921 return ExprError(); 922 923 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 924 None, E->getEndLoc()); 925 if (Call.isInvalid()) 926 return ExprError(); 927 928 ExprResult Comma = 929 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 930 if (Comma.isInvalid()) 931 return ExprError(); 932 return Comma.get(); 933 } 934 935 if (!getLangOpts().CPlusPlus && 936 RequireCompleteType(E->getExprLoc(), E->getType(), 937 diag::err_call_incomplete_argument)) 938 return ExprError(); 939 940 return E; 941 } 942 943 /// Converts an integer to complex float type. Helper function of 944 /// UsualArithmeticConversions() 945 /// 946 /// \return false if the integer expression is an integer type and is 947 /// successfully converted to the complex type. 948 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 949 ExprResult &ComplexExpr, 950 QualType IntTy, 951 QualType ComplexTy, 952 bool SkipCast) { 953 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 954 if (SkipCast) return false; 955 if (IntTy->isIntegerType()) { 956 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 957 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 958 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 959 CK_FloatingRealToComplex); 960 } else { 961 assert(IntTy->isComplexIntegerType()); 962 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 963 CK_IntegralComplexToFloatingComplex); 964 } 965 return false; 966 } 967 968 /// Handle arithmetic conversion with complex types. Helper function of 969 /// UsualArithmeticConversions() 970 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 971 ExprResult &RHS, QualType LHSType, 972 QualType RHSType, 973 bool IsCompAssign) { 974 // if we have an integer operand, the result is the complex type. 975 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 976 /*skipCast*/false)) 977 return LHSType; 978 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 979 /*skipCast*/IsCompAssign)) 980 return RHSType; 981 982 // This handles complex/complex, complex/float, or float/complex. 983 // When both operands are complex, the shorter operand is converted to the 984 // type of the longer, and that is the type of the result. This corresponds 985 // to what is done when combining two real floating-point operands. 986 // The fun begins when size promotion occur across type domains. 987 // From H&S 6.3.4: When one operand is complex and the other is a real 988 // floating-point type, the less precise type is converted, within it's 989 // real or complex domain, to the precision of the other type. For example, 990 // when combining a "long double" with a "double _Complex", the 991 // "double _Complex" is promoted to "long double _Complex". 992 993 // Compute the rank of the two types, regardless of whether they are complex. 994 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 995 996 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 997 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 998 QualType LHSElementType = 999 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1000 QualType RHSElementType = 1001 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1002 1003 QualType ResultType = S.Context.getComplexType(LHSElementType); 1004 if (Order < 0) { 1005 // Promote the precision of the LHS if not an assignment. 1006 ResultType = S.Context.getComplexType(RHSElementType); 1007 if (!IsCompAssign) { 1008 if (LHSComplexType) 1009 LHS = 1010 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1011 else 1012 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1013 } 1014 } else if (Order > 0) { 1015 // Promote the precision of the RHS. 1016 if (RHSComplexType) 1017 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1018 else 1019 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1020 } 1021 return ResultType; 1022 } 1023 1024 /// Handle arithmetic conversion from integer to float. Helper function 1025 /// of UsualArithmeticConversions() 1026 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1027 ExprResult &IntExpr, 1028 QualType FloatTy, QualType IntTy, 1029 bool ConvertFloat, bool ConvertInt) { 1030 if (IntTy->isIntegerType()) { 1031 if (ConvertInt) 1032 // Convert intExpr to the lhs floating point type. 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1034 CK_IntegralToFloating); 1035 return FloatTy; 1036 } 1037 1038 // Convert both sides to the appropriate complex float. 1039 assert(IntTy->isComplexIntegerType()); 1040 QualType result = S.Context.getComplexType(FloatTy); 1041 1042 // _Complex int -> _Complex float 1043 if (ConvertInt) 1044 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1045 CK_IntegralComplexToFloatingComplex); 1046 1047 // float -> _Complex float 1048 if (ConvertFloat) 1049 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1050 CK_FloatingRealToComplex); 1051 1052 return result; 1053 } 1054 1055 /// Handle arithmethic conversion with floating point types. Helper 1056 /// function of UsualArithmeticConversions() 1057 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1058 ExprResult &RHS, QualType LHSType, 1059 QualType RHSType, bool IsCompAssign) { 1060 bool LHSFloat = LHSType->isRealFloatingType(); 1061 bool RHSFloat = RHSType->isRealFloatingType(); 1062 1063 // If we have two real floating types, convert the smaller operand 1064 // to the bigger result. 1065 if (LHSFloat && RHSFloat) { 1066 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1067 if (order > 0) { 1068 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1069 return LHSType; 1070 } 1071 1072 assert(order < 0 && "illegal float comparison"); 1073 if (!IsCompAssign) 1074 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1075 return RHSType; 1076 } 1077 1078 if (LHSFloat) { 1079 // Half FP has to be promoted to float unless it is natively supported 1080 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1081 LHSType = S.Context.FloatTy; 1082 1083 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1084 /*convertFloat=*/!IsCompAssign, 1085 /*convertInt=*/ true); 1086 } 1087 assert(RHSFloat); 1088 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1089 /*convertInt=*/ true, 1090 /*convertFloat=*/!IsCompAssign); 1091 } 1092 1093 /// Diagnose attempts to convert between __float128 and long double if 1094 /// there is no support for such conversion. Helper function of 1095 /// UsualArithmeticConversions(). 1096 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1097 QualType RHSType) { 1098 /* No issue converting if at least one of the types is not a floating point 1099 type or the two types have the same rank. 1100 */ 1101 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1102 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1103 return false; 1104 1105 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1106 "The remaining types must be floating point types."); 1107 1108 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1109 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1110 1111 QualType LHSElemType = LHSComplex ? 1112 LHSComplex->getElementType() : LHSType; 1113 QualType RHSElemType = RHSComplex ? 1114 RHSComplex->getElementType() : RHSType; 1115 1116 // No issue if the two types have the same representation 1117 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1118 &S.Context.getFloatTypeSemantics(RHSElemType)) 1119 return false; 1120 1121 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1122 RHSElemType == S.Context.LongDoubleTy); 1123 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1124 RHSElemType == S.Context.Float128Ty); 1125 1126 // We've handled the situation where __float128 and long double have the same 1127 // representation. We allow all conversions for all possible long double types 1128 // except PPC's double double. 1129 return Float128AndLongDouble && 1130 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1131 &llvm::APFloat::PPCDoubleDouble()); 1132 } 1133 1134 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1135 1136 namespace { 1137 /// These helper callbacks are placed in an anonymous namespace to 1138 /// permit their use as function template parameters. 1139 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1140 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1141 } 1142 1143 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1144 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1145 CK_IntegralComplexCast); 1146 } 1147 } 1148 1149 /// Handle integer arithmetic conversions. Helper function of 1150 /// UsualArithmeticConversions() 1151 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1152 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1153 ExprResult &RHS, QualType LHSType, 1154 QualType RHSType, bool IsCompAssign) { 1155 // The rules for this case are in C99 6.3.1.8 1156 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1157 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1158 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1159 if (LHSSigned == RHSSigned) { 1160 // Same signedness; use the higher-ranked type 1161 if (order >= 0) { 1162 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1163 return LHSType; 1164 } else if (!IsCompAssign) 1165 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1166 return RHSType; 1167 } else if (order != (LHSSigned ? 1 : -1)) { 1168 // The unsigned type has greater than or equal rank to the 1169 // signed type, so use the unsigned type 1170 if (RHSSigned) { 1171 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1172 return LHSType; 1173 } else if (!IsCompAssign) 1174 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1175 return RHSType; 1176 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1177 // The two types are different widths; if we are here, that 1178 // means the signed type is larger than the unsigned type, so 1179 // use the signed type. 1180 if (LHSSigned) { 1181 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1182 return LHSType; 1183 } else if (!IsCompAssign) 1184 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1185 return RHSType; 1186 } else { 1187 // The signed type is higher-ranked than the unsigned type, 1188 // but isn't actually any bigger (like unsigned int and long 1189 // on most 32-bit systems). Use the unsigned type corresponding 1190 // to the signed type. 1191 QualType result = 1192 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1193 RHS = (*doRHSCast)(S, RHS.get(), result); 1194 if (!IsCompAssign) 1195 LHS = (*doLHSCast)(S, LHS.get(), result); 1196 return result; 1197 } 1198 } 1199 1200 /// Handle conversions with GCC complex int extension. Helper function 1201 /// of UsualArithmeticConversions() 1202 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1203 ExprResult &RHS, QualType LHSType, 1204 QualType RHSType, 1205 bool IsCompAssign) { 1206 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1207 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1208 1209 if (LHSComplexInt && RHSComplexInt) { 1210 QualType LHSEltType = LHSComplexInt->getElementType(); 1211 QualType RHSEltType = RHSComplexInt->getElementType(); 1212 QualType ScalarType = 1213 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1214 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1215 1216 return S.Context.getComplexType(ScalarType); 1217 } 1218 1219 if (LHSComplexInt) { 1220 QualType LHSEltType = LHSComplexInt->getElementType(); 1221 QualType ScalarType = 1222 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1223 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1224 QualType ComplexType = S.Context.getComplexType(ScalarType); 1225 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1226 CK_IntegralRealToComplex); 1227 1228 return ComplexType; 1229 } 1230 1231 assert(RHSComplexInt); 1232 1233 QualType RHSEltType = RHSComplexInt->getElementType(); 1234 QualType ScalarType = 1235 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1236 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1237 QualType ComplexType = S.Context.getComplexType(ScalarType); 1238 1239 if (!IsCompAssign) 1240 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1241 CK_IntegralRealToComplex); 1242 return ComplexType; 1243 } 1244 1245 /// UsualArithmeticConversions - Performs various conversions that are common to 1246 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1247 /// routine returns the first non-arithmetic type found. The client is 1248 /// responsible for emitting appropriate error diagnostics. 1249 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1250 bool IsCompAssign) { 1251 if (!IsCompAssign) { 1252 LHS = UsualUnaryConversions(LHS.get()); 1253 if (LHS.isInvalid()) 1254 return QualType(); 1255 } 1256 1257 RHS = UsualUnaryConversions(RHS.get()); 1258 if (RHS.isInvalid()) 1259 return QualType(); 1260 1261 // For conversion purposes, we ignore any qualifiers. 1262 // For example, "const float" and "float" are equivalent. 1263 QualType LHSType = 1264 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1265 QualType RHSType = 1266 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1267 1268 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1269 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1270 LHSType = AtomicLHS->getValueType(); 1271 1272 // If both types are identical, no conversion is needed. 1273 if (LHSType == RHSType) 1274 return LHSType; 1275 1276 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1277 // The caller can deal with this (e.g. pointer + int). 1278 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1279 return QualType(); 1280 1281 // Apply unary and bitfield promotions to the LHS's type. 1282 QualType LHSUnpromotedType = LHSType; 1283 if (LHSType->isPromotableIntegerType()) 1284 LHSType = Context.getPromotedIntegerType(LHSType); 1285 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1286 if (!LHSBitfieldPromoteTy.isNull()) 1287 LHSType = LHSBitfieldPromoteTy; 1288 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1289 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1290 1291 // If both types are identical, no conversion is needed. 1292 if (LHSType == RHSType) 1293 return LHSType; 1294 1295 // At this point, we have two different arithmetic types. 1296 1297 // Diagnose attempts to convert between __float128 and long double where 1298 // such conversions currently can't be handled. 1299 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1300 return QualType(); 1301 1302 // Handle complex types first (C99 6.3.1.8p1). 1303 if (LHSType->isComplexType() || RHSType->isComplexType()) 1304 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1305 IsCompAssign); 1306 1307 // Now handle "real" floating types (i.e. float, double, long double). 1308 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1309 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1310 IsCompAssign); 1311 1312 // Handle GCC complex int extension. 1313 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1314 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1315 IsCompAssign); 1316 1317 // Finally, we have two differing integer types. 1318 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1319 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1320 } 1321 1322 1323 //===----------------------------------------------------------------------===// 1324 // Semantic Analysis for various Expression Types 1325 //===----------------------------------------------------------------------===// 1326 1327 1328 ExprResult 1329 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1330 SourceLocation DefaultLoc, 1331 SourceLocation RParenLoc, 1332 Expr *ControllingExpr, 1333 ArrayRef<ParsedType> ArgTypes, 1334 ArrayRef<Expr *> ArgExprs) { 1335 unsigned NumAssocs = ArgTypes.size(); 1336 assert(NumAssocs == ArgExprs.size()); 1337 1338 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1339 for (unsigned i = 0; i < NumAssocs; ++i) { 1340 if (ArgTypes[i]) 1341 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1342 else 1343 Types[i] = nullptr; 1344 } 1345 1346 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1347 ControllingExpr, 1348 llvm::makeArrayRef(Types, NumAssocs), 1349 ArgExprs); 1350 delete [] Types; 1351 return ER; 1352 } 1353 1354 ExprResult 1355 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1356 SourceLocation DefaultLoc, 1357 SourceLocation RParenLoc, 1358 Expr *ControllingExpr, 1359 ArrayRef<TypeSourceInfo *> Types, 1360 ArrayRef<Expr *> Exprs) { 1361 unsigned NumAssocs = Types.size(); 1362 assert(NumAssocs == Exprs.size()); 1363 1364 // Decay and strip qualifiers for the controlling expression type, and handle 1365 // placeholder type replacement. See committee discussion from WG14 DR423. 1366 { 1367 EnterExpressionEvaluationContext Unevaluated( 1368 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1369 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1370 if (R.isInvalid()) 1371 return ExprError(); 1372 ControllingExpr = R.get(); 1373 } 1374 1375 // The controlling expression is an unevaluated operand, so side effects are 1376 // likely unintended. 1377 if (!inTemplateInstantiation() && 1378 ControllingExpr->HasSideEffects(Context, false)) 1379 Diag(ControllingExpr->getExprLoc(), 1380 diag::warn_side_effects_unevaluated_context); 1381 1382 bool TypeErrorFound = false, 1383 IsResultDependent = ControllingExpr->isTypeDependent(), 1384 ContainsUnexpandedParameterPack 1385 = ControllingExpr->containsUnexpandedParameterPack(); 1386 1387 for (unsigned i = 0; i < NumAssocs; ++i) { 1388 if (Exprs[i]->containsUnexpandedParameterPack()) 1389 ContainsUnexpandedParameterPack = true; 1390 1391 if (Types[i]) { 1392 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1393 ContainsUnexpandedParameterPack = true; 1394 1395 if (Types[i]->getType()->isDependentType()) { 1396 IsResultDependent = true; 1397 } else { 1398 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1399 // complete object type other than a variably modified type." 1400 unsigned D = 0; 1401 if (Types[i]->getType()->isIncompleteType()) 1402 D = diag::err_assoc_type_incomplete; 1403 else if (!Types[i]->getType()->isObjectType()) 1404 D = diag::err_assoc_type_nonobject; 1405 else if (Types[i]->getType()->isVariablyModifiedType()) 1406 D = diag::err_assoc_type_variably_modified; 1407 1408 if (D != 0) { 1409 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1410 << Types[i]->getTypeLoc().getSourceRange() 1411 << Types[i]->getType(); 1412 TypeErrorFound = true; 1413 } 1414 1415 // C11 6.5.1.1p2 "No two generic associations in the same generic 1416 // selection shall specify compatible types." 1417 for (unsigned j = i+1; j < NumAssocs; ++j) 1418 if (Types[j] && !Types[j]->getType()->isDependentType() && 1419 Context.typesAreCompatible(Types[i]->getType(), 1420 Types[j]->getType())) { 1421 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1422 diag::err_assoc_compatible_types) 1423 << Types[j]->getTypeLoc().getSourceRange() 1424 << Types[j]->getType() 1425 << Types[i]->getType(); 1426 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1427 diag::note_compat_assoc) 1428 << Types[i]->getTypeLoc().getSourceRange() 1429 << Types[i]->getType(); 1430 TypeErrorFound = true; 1431 } 1432 } 1433 } 1434 } 1435 if (TypeErrorFound) 1436 return ExprError(); 1437 1438 // If we determined that the generic selection is result-dependent, don't 1439 // try to compute the result expression. 1440 if (IsResultDependent) 1441 return new (Context) GenericSelectionExpr( 1442 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1443 ContainsUnexpandedParameterPack); 1444 1445 SmallVector<unsigned, 1> CompatIndices; 1446 unsigned DefaultIndex = -1U; 1447 for (unsigned i = 0; i < NumAssocs; ++i) { 1448 if (!Types[i]) 1449 DefaultIndex = i; 1450 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1451 Types[i]->getType())) 1452 CompatIndices.push_back(i); 1453 } 1454 1455 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1456 // type compatible with at most one of the types named in its generic 1457 // association list." 1458 if (CompatIndices.size() > 1) { 1459 // We strip parens here because the controlling expression is typically 1460 // parenthesized in macro definitions. 1461 ControllingExpr = ControllingExpr->IgnoreParens(); 1462 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1463 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1464 << (unsigned)CompatIndices.size(); 1465 for (unsigned I : CompatIndices) { 1466 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1467 diag::note_compat_assoc) 1468 << Types[I]->getTypeLoc().getSourceRange() 1469 << Types[I]->getType(); 1470 } 1471 return ExprError(); 1472 } 1473 1474 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1475 // its controlling expression shall have type compatible with exactly one of 1476 // the types named in its generic association list." 1477 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1478 // We strip parens here because the controlling expression is typically 1479 // parenthesized in macro definitions. 1480 ControllingExpr = ControllingExpr->IgnoreParens(); 1481 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1482 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1483 return ExprError(); 1484 } 1485 1486 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1487 // type name that is compatible with the type of the controlling expression, 1488 // then the result expression of the generic selection is the expression 1489 // in that generic association. Otherwise, the result expression of the 1490 // generic selection is the expression in the default generic association." 1491 unsigned ResultIndex = 1492 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1493 1494 return new (Context) GenericSelectionExpr( 1495 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1496 ContainsUnexpandedParameterPack, ResultIndex); 1497 } 1498 1499 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1500 /// location of the token and the offset of the ud-suffix within it. 1501 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1502 unsigned Offset) { 1503 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1504 S.getLangOpts()); 1505 } 1506 1507 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1508 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1509 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1510 IdentifierInfo *UDSuffix, 1511 SourceLocation UDSuffixLoc, 1512 ArrayRef<Expr*> Args, 1513 SourceLocation LitEndLoc) { 1514 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1515 1516 QualType ArgTy[2]; 1517 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1518 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1519 if (ArgTy[ArgIdx]->isArrayType()) 1520 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1521 } 1522 1523 DeclarationName OpName = 1524 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1525 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1526 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1527 1528 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1529 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1530 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1531 /*AllowStringTemplate*/ false, 1532 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1533 return ExprError(); 1534 1535 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1536 } 1537 1538 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1539 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1540 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1541 /// multiple tokens. However, the common case is that StringToks points to one 1542 /// string. 1543 /// 1544 ExprResult 1545 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1546 assert(!StringToks.empty() && "Must have at least one string!"); 1547 1548 StringLiteralParser Literal(StringToks, PP); 1549 if (Literal.hadError) 1550 return ExprError(); 1551 1552 SmallVector<SourceLocation, 4> StringTokLocs; 1553 for (const Token &Tok : StringToks) 1554 StringTokLocs.push_back(Tok.getLocation()); 1555 1556 QualType CharTy = Context.CharTy; 1557 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1558 if (Literal.isWide()) { 1559 CharTy = Context.getWideCharType(); 1560 Kind = StringLiteral::Wide; 1561 } else if (Literal.isUTF8()) { 1562 if (getLangOpts().Char8) 1563 CharTy = Context.Char8Ty; 1564 Kind = StringLiteral::UTF8; 1565 } else if (Literal.isUTF16()) { 1566 CharTy = Context.Char16Ty; 1567 Kind = StringLiteral::UTF16; 1568 } else if (Literal.isUTF32()) { 1569 CharTy = Context.Char32Ty; 1570 Kind = StringLiteral::UTF32; 1571 } else if (Literal.isPascal()) { 1572 CharTy = Context.UnsignedCharTy; 1573 } 1574 1575 // Warn on initializing an array of char from a u8 string literal; this 1576 // becomes ill-formed in C++2a. 1577 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1578 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1579 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1580 1581 // Create removals for all 'u8' prefixes in the string literal(s). This 1582 // ensures C++2a compatibility (but may change the program behavior when 1583 // built by non-Clang compilers for which the execution character set is 1584 // not always UTF-8). 1585 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1586 SourceLocation RemovalDiagLoc; 1587 for (const Token &Tok : StringToks) { 1588 if (Tok.getKind() == tok::utf8_string_literal) { 1589 if (RemovalDiagLoc.isInvalid()) 1590 RemovalDiagLoc = Tok.getLocation(); 1591 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1592 Tok.getLocation(), 1593 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1594 getSourceManager(), getLangOpts()))); 1595 } 1596 } 1597 Diag(RemovalDiagLoc, RemovalDiag); 1598 } 1599 1600 1601 QualType CharTyConst = CharTy; 1602 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1603 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1604 CharTyConst.addConst(); 1605 1606 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1607 1608 // Get an array type for the string, according to C99 6.4.5. This includes 1609 // the nul terminator character as well as the string length for pascal 1610 // strings. 1611 QualType StrTy = Context.getConstantArrayType( 1612 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1613 ArrayType::Normal, 0); 1614 1615 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1616 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1617 Kind, Literal.Pascal, StrTy, 1618 &StringTokLocs[0], 1619 StringTokLocs.size()); 1620 if (Literal.getUDSuffix().empty()) 1621 return Lit; 1622 1623 // We're building a user-defined literal. 1624 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1625 SourceLocation UDSuffixLoc = 1626 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1627 Literal.getUDSuffixOffset()); 1628 1629 // Make sure we're allowed user-defined literals here. 1630 if (!UDLScope) 1631 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1632 1633 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1634 // operator "" X (str, len) 1635 QualType SizeType = Context.getSizeType(); 1636 1637 DeclarationName OpName = 1638 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1639 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1640 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1641 1642 QualType ArgTy[] = { 1643 Context.getArrayDecayedType(StrTy), SizeType 1644 }; 1645 1646 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1647 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1648 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1649 /*AllowStringTemplate*/ true, 1650 /*DiagnoseMissing*/ true)) { 1651 1652 case LOLR_Cooked: { 1653 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1654 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1655 StringTokLocs[0]); 1656 Expr *Args[] = { Lit, LenArg }; 1657 1658 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1659 } 1660 1661 case LOLR_StringTemplate: { 1662 TemplateArgumentListInfo ExplicitArgs; 1663 1664 unsigned CharBits = Context.getIntWidth(CharTy); 1665 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1666 llvm::APSInt Value(CharBits, CharIsUnsigned); 1667 1668 TemplateArgument TypeArg(CharTy); 1669 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1670 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1671 1672 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1673 Value = Lit->getCodeUnit(I); 1674 TemplateArgument Arg(Context, Value, CharTy); 1675 TemplateArgumentLocInfo ArgInfo; 1676 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1677 } 1678 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1679 &ExplicitArgs); 1680 } 1681 case LOLR_Raw: 1682 case LOLR_Template: 1683 case LOLR_ErrorNoDiagnostic: 1684 llvm_unreachable("unexpected literal operator lookup result"); 1685 case LOLR_Error: 1686 return ExprError(); 1687 } 1688 llvm_unreachable("unexpected literal operator lookup result"); 1689 } 1690 1691 ExprResult 1692 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1693 SourceLocation Loc, 1694 const CXXScopeSpec *SS) { 1695 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1696 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1697 } 1698 1699 /// BuildDeclRefExpr - Build an expression that references a 1700 /// declaration that does not require a closure capture. 1701 ExprResult 1702 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1703 const DeclarationNameInfo &NameInfo, 1704 const CXXScopeSpec *SS, NamedDecl *FoundD, 1705 const TemplateArgumentListInfo *TemplateArgs) { 1706 bool RefersToCapturedVariable = 1707 isa<VarDecl>(D) && 1708 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1709 1710 DeclRefExpr *E; 1711 if (isa<VarTemplateSpecializationDecl>(D)) { 1712 VarTemplateSpecializationDecl *VarSpec = 1713 cast<VarTemplateSpecializationDecl>(D); 1714 1715 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1716 : NestedNameSpecifierLoc(), 1717 VarSpec->getTemplateKeywordLoc(), D, 1718 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1719 FoundD, TemplateArgs); 1720 } else { 1721 assert(!TemplateArgs && "No template arguments for non-variable" 1722 " template specialization references"); 1723 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1724 : NestedNameSpecifierLoc(), 1725 SourceLocation(), D, RefersToCapturedVariable, 1726 NameInfo, Ty, VK, FoundD); 1727 } 1728 1729 MarkDeclRefReferenced(E); 1730 1731 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1732 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1733 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1734 getCurFunction()->recordUseOfWeak(E); 1735 1736 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1737 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1738 FD = IFD->getAnonField(); 1739 if (FD) { 1740 UnusedPrivateFields.remove(FD); 1741 // Just in case we're building an illegal pointer-to-member. 1742 if (FD->isBitField()) 1743 E->setObjectKind(OK_BitField); 1744 } 1745 1746 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1747 // designates a bit-field. 1748 if (auto *BD = dyn_cast<BindingDecl>(D)) 1749 if (auto *BE = BD->getBinding()) 1750 E->setObjectKind(BE->getObjectKind()); 1751 1752 return E; 1753 } 1754 1755 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1756 /// possibly a list of template arguments. 1757 /// 1758 /// If this produces template arguments, it is permitted to call 1759 /// DecomposeTemplateName. 1760 /// 1761 /// This actually loses a lot of source location information for 1762 /// non-standard name kinds; we should consider preserving that in 1763 /// some way. 1764 void 1765 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1766 TemplateArgumentListInfo &Buffer, 1767 DeclarationNameInfo &NameInfo, 1768 const TemplateArgumentListInfo *&TemplateArgs) { 1769 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1770 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1771 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1772 1773 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1774 Id.TemplateId->NumArgs); 1775 translateTemplateArguments(TemplateArgsPtr, Buffer); 1776 1777 TemplateName TName = Id.TemplateId->Template.get(); 1778 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1779 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1780 TemplateArgs = &Buffer; 1781 } else { 1782 NameInfo = GetNameFromUnqualifiedId(Id); 1783 TemplateArgs = nullptr; 1784 } 1785 } 1786 1787 static void emitEmptyLookupTypoDiagnostic( 1788 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1789 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1790 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1791 DeclContext *Ctx = 1792 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1793 if (!TC) { 1794 // Emit a special diagnostic for failed member lookups. 1795 // FIXME: computing the declaration context might fail here (?) 1796 if (Ctx) 1797 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1798 << SS.getRange(); 1799 else 1800 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1801 return; 1802 } 1803 1804 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1805 bool DroppedSpecifier = 1806 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1807 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1808 ? diag::note_implicit_param_decl 1809 : diag::note_previous_decl; 1810 if (!Ctx) 1811 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1812 SemaRef.PDiag(NoteID)); 1813 else 1814 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1815 << Typo << Ctx << DroppedSpecifier 1816 << SS.getRange(), 1817 SemaRef.PDiag(NoteID)); 1818 } 1819 1820 /// Diagnose an empty lookup. 1821 /// 1822 /// \return false if new lookup candidates were found 1823 bool 1824 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1825 std::unique_ptr<CorrectionCandidateCallback> CCC, 1826 TemplateArgumentListInfo *ExplicitTemplateArgs, 1827 ArrayRef<Expr *> Args, TypoExpr **Out) { 1828 DeclarationName Name = R.getLookupName(); 1829 1830 unsigned diagnostic = diag::err_undeclared_var_use; 1831 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1832 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1833 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1834 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1835 diagnostic = diag::err_undeclared_use; 1836 diagnostic_suggest = diag::err_undeclared_use_suggest; 1837 } 1838 1839 // If the original lookup was an unqualified lookup, fake an 1840 // unqualified lookup. This is useful when (for example) the 1841 // original lookup would not have found something because it was a 1842 // dependent name. 1843 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1844 while (DC) { 1845 if (isa<CXXRecordDecl>(DC)) { 1846 LookupQualifiedName(R, DC); 1847 1848 if (!R.empty()) { 1849 // Don't give errors about ambiguities in this lookup. 1850 R.suppressDiagnostics(); 1851 1852 // During a default argument instantiation the CurContext points 1853 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1854 // function parameter list, hence add an explicit check. 1855 bool isDefaultArgument = 1856 !CodeSynthesisContexts.empty() && 1857 CodeSynthesisContexts.back().Kind == 1858 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1859 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1860 bool isInstance = CurMethod && 1861 CurMethod->isInstance() && 1862 DC == CurMethod->getParent() && !isDefaultArgument; 1863 1864 // Give a code modification hint to insert 'this->'. 1865 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1866 // Actually quite difficult! 1867 if (getLangOpts().MSVCCompat) 1868 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1869 if (isInstance) { 1870 Diag(R.getNameLoc(), diagnostic) << Name 1871 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1872 CheckCXXThisCapture(R.getNameLoc()); 1873 } else { 1874 Diag(R.getNameLoc(), diagnostic) << Name; 1875 } 1876 1877 // Do we really want to note all of these? 1878 for (NamedDecl *D : R) 1879 Diag(D->getLocation(), diag::note_dependent_var_use); 1880 1881 // Return true if we are inside a default argument instantiation 1882 // and the found name refers to an instance member function, otherwise 1883 // the function calling DiagnoseEmptyLookup will try to create an 1884 // implicit member call and this is wrong for default argument. 1885 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1886 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1887 return true; 1888 } 1889 1890 // Tell the callee to try to recover. 1891 return false; 1892 } 1893 1894 R.clear(); 1895 } 1896 1897 // In Microsoft mode, if we are performing lookup from within a friend 1898 // function definition declared at class scope then we must set 1899 // DC to the lexical parent to be able to search into the parent 1900 // class. 1901 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1902 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1903 DC->getLexicalParent()->isRecord()) 1904 DC = DC->getLexicalParent(); 1905 else 1906 DC = DC->getParent(); 1907 } 1908 1909 // We didn't find anything, so try to correct for a typo. 1910 TypoCorrection Corrected; 1911 if (S && Out) { 1912 SourceLocation TypoLoc = R.getNameLoc(); 1913 assert(!ExplicitTemplateArgs && 1914 "Diagnosing an empty lookup with explicit template args!"); 1915 *Out = CorrectTypoDelayed( 1916 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1917 [=](const TypoCorrection &TC) { 1918 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1919 diagnostic, diagnostic_suggest); 1920 }, 1921 nullptr, CTK_ErrorRecovery); 1922 if (*Out) 1923 return true; 1924 } else if (S && (Corrected = 1925 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1926 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1927 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1928 bool DroppedSpecifier = 1929 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1930 R.setLookupName(Corrected.getCorrection()); 1931 1932 bool AcceptableWithRecovery = false; 1933 bool AcceptableWithoutRecovery = false; 1934 NamedDecl *ND = Corrected.getFoundDecl(); 1935 if (ND) { 1936 if (Corrected.isOverloaded()) { 1937 OverloadCandidateSet OCS(R.getNameLoc(), 1938 OverloadCandidateSet::CSK_Normal); 1939 OverloadCandidateSet::iterator Best; 1940 for (NamedDecl *CD : Corrected) { 1941 if (FunctionTemplateDecl *FTD = 1942 dyn_cast<FunctionTemplateDecl>(CD)) 1943 AddTemplateOverloadCandidate( 1944 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1945 Args, OCS); 1946 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1947 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1948 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1949 Args, OCS); 1950 } 1951 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1952 case OR_Success: 1953 ND = Best->FoundDecl; 1954 Corrected.setCorrectionDecl(ND); 1955 break; 1956 default: 1957 // FIXME: Arbitrarily pick the first declaration for the note. 1958 Corrected.setCorrectionDecl(ND); 1959 break; 1960 } 1961 } 1962 R.addDecl(ND); 1963 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1964 CXXRecordDecl *Record = nullptr; 1965 if (Corrected.getCorrectionSpecifier()) { 1966 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1967 Record = Ty->getAsCXXRecordDecl(); 1968 } 1969 if (!Record) 1970 Record = cast<CXXRecordDecl>( 1971 ND->getDeclContext()->getRedeclContext()); 1972 R.setNamingClass(Record); 1973 } 1974 1975 auto *UnderlyingND = ND->getUnderlyingDecl(); 1976 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1977 isa<FunctionTemplateDecl>(UnderlyingND); 1978 // FIXME: If we ended up with a typo for a type name or 1979 // Objective-C class name, we're in trouble because the parser 1980 // is in the wrong place to recover. Suggest the typo 1981 // correction, but don't make it a fix-it since we're not going 1982 // to recover well anyway. 1983 AcceptableWithoutRecovery = 1984 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1985 } else { 1986 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1987 // because we aren't able to recover. 1988 AcceptableWithoutRecovery = true; 1989 } 1990 1991 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1992 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1993 ? diag::note_implicit_param_decl 1994 : diag::note_previous_decl; 1995 if (SS.isEmpty()) 1996 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1997 PDiag(NoteID), AcceptableWithRecovery); 1998 else 1999 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2000 << Name << computeDeclContext(SS, false) 2001 << DroppedSpecifier << SS.getRange(), 2002 PDiag(NoteID), AcceptableWithRecovery); 2003 2004 // Tell the callee whether to try to recover. 2005 return !AcceptableWithRecovery; 2006 } 2007 } 2008 R.clear(); 2009 2010 // Emit a special diagnostic for failed member lookups. 2011 // FIXME: computing the declaration context might fail here (?) 2012 if (!SS.isEmpty()) { 2013 Diag(R.getNameLoc(), diag::err_no_member) 2014 << Name << computeDeclContext(SS, false) 2015 << SS.getRange(); 2016 return true; 2017 } 2018 2019 // Give up, we can't recover. 2020 Diag(R.getNameLoc(), diagnostic) << Name; 2021 return true; 2022 } 2023 2024 /// In Microsoft mode, if we are inside a template class whose parent class has 2025 /// dependent base classes, and we can't resolve an unqualified identifier, then 2026 /// assume the identifier is a member of a dependent base class. We can only 2027 /// recover successfully in static methods, instance methods, and other contexts 2028 /// where 'this' is available. This doesn't precisely match MSVC's 2029 /// instantiation model, but it's close enough. 2030 static Expr * 2031 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2032 DeclarationNameInfo &NameInfo, 2033 SourceLocation TemplateKWLoc, 2034 const TemplateArgumentListInfo *TemplateArgs) { 2035 // Only try to recover from lookup into dependent bases in static methods or 2036 // contexts where 'this' is available. 2037 QualType ThisType = S.getCurrentThisType(); 2038 const CXXRecordDecl *RD = nullptr; 2039 if (!ThisType.isNull()) 2040 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2041 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2042 RD = MD->getParent(); 2043 if (!RD || !RD->hasAnyDependentBases()) 2044 return nullptr; 2045 2046 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2047 // is available, suggest inserting 'this->' as a fixit. 2048 SourceLocation Loc = NameInfo.getLoc(); 2049 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2050 DB << NameInfo.getName() << RD; 2051 2052 if (!ThisType.isNull()) { 2053 DB << FixItHint::CreateInsertion(Loc, "this->"); 2054 return CXXDependentScopeMemberExpr::Create( 2055 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2056 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2057 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2058 } 2059 2060 // Synthesize a fake NNS that points to the derived class. This will 2061 // perform name lookup during template instantiation. 2062 CXXScopeSpec SS; 2063 auto *NNS = 2064 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2065 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2066 return DependentScopeDeclRefExpr::Create( 2067 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2068 TemplateArgs); 2069 } 2070 2071 ExprResult 2072 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2073 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2074 bool HasTrailingLParen, bool IsAddressOfOperand, 2075 std::unique_ptr<CorrectionCandidateCallback> CCC, 2076 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2077 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2078 "cannot be direct & operand and have a trailing lparen"); 2079 if (SS.isInvalid()) 2080 return ExprError(); 2081 2082 TemplateArgumentListInfo TemplateArgsBuffer; 2083 2084 // Decompose the UnqualifiedId into the following data. 2085 DeclarationNameInfo NameInfo; 2086 const TemplateArgumentListInfo *TemplateArgs; 2087 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2088 2089 DeclarationName Name = NameInfo.getName(); 2090 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2091 SourceLocation NameLoc = NameInfo.getLoc(); 2092 2093 if (II && II->isEditorPlaceholder()) { 2094 // FIXME: When typed placeholders are supported we can create a typed 2095 // placeholder expression node. 2096 return ExprError(); 2097 } 2098 2099 // C++ [temp.dep.expr]p3: 2100 // An id-expression is type-dependent if it contains: 2101 // -- an identifier that was declared with a dependent type, 2102 // (note: handled after lookup) 2103 // -- a template-id that is dependent, 2104 // (note: handled in BuildTemplateIdExpr) 2105 // -- a conversion-function-id that specifies a dependent type, 2106 // -- a nested-name-specifier that contains a class-name that 2107 // names a dependent type. 2108 // Determine whether this is a member of an unknown specialization; 2109 // we need to handle these differently. 2110 bool DependentID = false; 2111 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2112 Name.getCXXNameType()->isDependentType()) { 2113 DependentID = true; 2114 } else if (SS.isSet()) { 2115 if (DeclContext *DC = computeDeclContext(SS, false)) { 2116 if (RequireCompleteDeclContext(SS, DC)) 2117 return ExprError(); 2118 } else { 2119 DependentID = true; 2120 } 2121 } 2122 2123 if (DependentID) 2124 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2125 IsAddressOfOperand, TemplateArgs); 2126 2127 // Perform the required lookup. 2128 LookupResult R(*this, NameInfo, 2129 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2130 ? LookupObjCImplicitSelfParam 2131 : LookupOrdinaryName); 2132 if (TemplateKWLoc.isValid() || TemplateArgs) { 2133 // Lookup the template name again to correctly establish the context in 2134 // which it was found. This is really unfortunate as we already did the 2135 // lookup to determine that it was a template name in the first place. If 2136 // this becomes a performance hit, we can work harder to preserve those 2137 // results until we get here but it's likely not worth it. 2138 bool MemberOfUnknownSpecialization; 2139 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2140 MemberOfUnknownSpecialization, TemplateKWLoc)) 2141 return ExprError(); 2142 2143 if (MemberOfUnknownSpecialization || 2144 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2145 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2146 IsAddressOfOperand, TemplateArgs); 2147 } else { 2148 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2149 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2150 2151 // If the result might be in a dependent base class, this is a dependent 2152 // id-expression. 2153 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2154 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2155 IsAddressOfOperand, TemplateArgs); 2156 2157 // If this reference is in an Objective-C method, then we need to do 2158 // some special Objective-C lookup, too. 2159 if (IvarLookupFollowUp) { 2160 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2161 if (E.isInvalid()) 2162 return ExprError(); 2163 2164 if (Expr *Ex = E.getAs<Expr>()) 2165 return Ex; 2166 } 2167 } 2168 2169 if (R.isAmbiguous()) 2170 return ExprError(); 2171 2172 // This could be an implicitly declared function reference (legal in C90, 2173 // extension in C99, forbidden in C++). 2174 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2175 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2176 if (D) R.addDecl(D); 2177 } 2178 2179 // Determine whether this name might be a candidate for 2180 // argument-dependent lookup. 2181 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2182 2183 if (R.empty() && !ADL) { 2184 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2185 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2186 TemplateKWLoc, TemplateArgs)) 2187 return E; 2188 } 2189 2190 // Don't diagnose an empty lookup for inline assembly. 2191 if (IsInlineAsmIdentifier) 2192 return ExprError(); 2193 2194 // If this name wasn't predeclared and if this is not a function 2195 // call, diagnose the problem. 2196 TypoExpr *TE = nullptr; 2197 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2198 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2199 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2200 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2201 "Typo correction callback misconfigured"); 2202 if (CCC) { 2203 // Make sure the callback knows what the typo being diagnosed is. 2204 CCC->setTypoName(II); 2205 if (SS.isValid()) 2206 CCC->setTypoNNS(SS.getScopeRep()); 2207 } 2208 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2209 // a template name, but we happen to have always already looked up the name 2210 // before we get here if it must be a template name. 2211 if (DiagnoseEmptyLookup(S, SS, R, 2212 CCC ? std::move(CCC) : std::move(DefaultValidator), 2213 nullptr, None, &TE)) { 2214 if (TE && KeywordReplacement) { 2215 auto &State = getTypoExprState(TE); 2216 auto BestTC = State.Consumer->getNextCorrection(); 2217 if (BestTC.isKeyword()) { 2218 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2219 if (State.DiagHandler) 2220 State.DiagHandler(BestTC); 2221 KeywordReplacement->startToken(); 2222 KeywordReplacement->setKind(II->getTokenID()); 2223 KeywordReplacement->setIdentifierInfo(II); 2224 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2225 // Clean up the state associated with the TypoExpr, since it has 2226 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2227 clearDelayedTypo(TE); 2228 // Signal that a correction to a keyword was performed by returning a 2229 // valid-but-null ExprResult. 2230 return (Expr*)nullptr; 2231 } 2232 State.Consumer->resetCorrectionStream(); 2233 } 2234 return TE ? TE : ExprError(); 2235 } 2236 2237 assert(!R.empty() && 2238 "DiagnoseEmptyLookup returned false but added no results"); 2239 2240 // If we found an Objective-C instance variable, let 2241 // LookupInObjCMethod build the appropriate expression to 2242 // reference the ivar. 2243 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2244 R.clear(); 2245 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2246 // In a hopelessly buggy code, Objective-C instance variable 2247 // lookup fails and no expression will be built to reference it. 2248 if (!E.isInvalid() && !E.get()) 2249 return ExprError(); 2250 return E; 2251 } 2252 } 2253 2254 // This is guaranteed from this point on. 2255 assert(!R.empty() || ADL); 2256 2257 // Check whether this might be a C++ implicit instance member access. 2258 // C++ [class.mfct.non-static]p3: 2259 // When an id-expression that is not part of a class member access 2260 // syntax and not used to form a pointer to member is used in the 2261 // body of a non-static member function of class X, if name lookup 2262 // resolves the name in the id-expression to a non-static non-type 2263 // member of some class C, the id-expression is transformed into a 2264 // class member access expression using (*this) as the 2265 // postfix-expression to the left of the . operator. 2266 // 2267 // But we don't actually need to do this for '&' operands if R 2268 // resolved to a function or overloaded function set, because the 2269 // expression is ill-formed if it actually works out to be a 2270 // non-static member function: 2271 // 2272 // C++ [expr.ref]p4: 2273 // Otherwise, if E1.E2 refers to a non-static member function. . . 2274 // [t]he expression can be used only as the left-hand operand of a 2275 // member function call. 2276 // 2277 // There are other safeguards against such uses, but it's important 2278 // to get this right here so that we don't end up making a 2279 // spuriously dependent expression if we're inside a dependent 2280 // instance method. 2281 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2282 bool MightBeImplicitMember; 2283 if (!IsAddressOfOperand) 2284 MightBeImplicitMember = true; 2285 else if (!SS.isEmpty()) 2286 MightBeImplicitMember = false; 2287 else if (R.isOverloadedResult()) 2288 MightBeImplicitMember = false; 2289 else if (R.isUnresolvableResult()) 2290 MightBeImplicitMember = true; 2291 else 2292 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2293 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2294 isa<MSPropertyDecl>(R.getFoundDecl()); 2295 2296 if (MightBeImplicitMember) 2297 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2298 R, TemplateArgs, S); 2299 } 2300 2301 if (TemplateArgs || TemplateKWLoc.isValid()) { 2302 2303 // In C++1y, if this is a variable template id, then check it 2304 // in BuildTemplateIdExpr(). 2305 // The single lookup result must be a variable template declaration. 2306 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2307 Id.TemplateId->Kind == TNK_Var_template) { 2308 assert(R.getAsSingle<VarTemplateDecl>() && 2309 "There should only be one declaration found."); 2310 } 2311 2312 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2313 } 2314 2315 return BuildDeclarationNameExpr(SS, R, ADL); 2316 } 2317 2318 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2319 /// declaration name, generally during template instantiation. 2320 /// There's a large number of things which don't need to be done along 2321 /// this path. 2322 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2323 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2324 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2325 DeclContext *DC = computeDeclContext(SS, false); 2326 if (!DC) 2327 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2328 NameInfo, /*TemplateArgs=*/nullptr); 2329 2330 if (RequireCompleteDeclContext(SS, DC)) 2331 return ExprError(); 2332 2333 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2334 LookupQualifiedName(R, DC); 2335 2336 if (R.isAmbiguous()) 2337 return ExprError(); 2338 2339 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2340 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2341 NameInfo, /*TemplateArgs=*/nullptr); 2342 2343 if (R.empty()) { 2344 Diag(NameInfo.getLoc(), diag::err_no_member) 2345 << NameInfo.getName() << DC << SS.getRange(); 2346 return ExprError(); 2347 } 2348 2349 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2350 // Diagnose a missing typename if this resolved unambiguously to a type in 2351 // a dependent context. If we can recover with a type, downgrade this to 2352 // a warning in Microsoft compatibility mode. 2353 unsigned DiagID = diag::err_typename_missing; 2354 if (RecoveryTSI && getLangOpts().MSVCCompat) 2355 DiagID = diag::ext_typename_missing; 2356 SourceLocation Loc = SS.getBeginLoc(); 2357 auto D = Diag(Loc, DiagID); 2358 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2359 << SourceRange(Loc, NameInfo.getEndLoc()); 2360 2361 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2362 // context. 2363 if (!RecoveryTSI) 2364 return ExprError(); 2365 2366 // Only issue the fixit if we're prepared to recover. 2367 D << FixItHint::CreateInsertion(Loc, "typename "); 2368 2369 // Recover by pretending this was an elaborated type. 2370 QualType Ty = Context.getTypeDeclType(TD); 2371 TypeLocBuilder TLB; 2372 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2373 2374 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2375 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2376 QTL.setElaboratedKeywordLoc(SourceLocation()); 2377 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2378 2379 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2380 2381 return ExprEmpty(); 2382 } 2383 2384 // Defend against this resolving to an implicit member access. We usually 2385 // won't get here if this might be a legitimate a class member (we end up in 2386 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2387 // a pointer-to-member or in an unevaluated context in C++11. 2388 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2389 return BuildPossibleImplicitMemberExpr(SS, 2390 /*TemplateKWLoc=*/SourceLocation(), 2391 R, /*TemplateArgs=*/nullptr, S); 2392 2393 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2394 } 2395 2396 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2397 /// detected that we're currently inside an ObjC method. Perform some 2398 /// additional lookup. 2399 /// 2400 /// Ideally, most of this would be done by lookup, but there's 2401 /// actually quite a lot of extra work involved. 2402 /// 2403 /// Returns a null sentinel to indicate trivial success. 2404 ExprResult 2405 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2406 IdentifierInfo *II, bool AllowBuiltinCreation) { 2407 SourceLocation Loc = Lookup.getNameLoc(); 2408 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2409 2410 // Check for error condition which is already reported. 2411 if (!CurMethod) 2412 return ExprError(); 2413 2414 // There are two cases to handle here. 1) scoped lookup could have failed, 2415 // in which case we should look for an ivar. 2) scoped lookup could have 2416 // found a decl, but that decl is outside the current instance method (i.e. 2417 // a global variable). In these two cases, we do a lookup for an ivar with 2418 // this name, if the lookup sucedes, we replace it our current decl. 2419 2420 // If we're in a class method, we don't normally want to look for 2421 // ivars. But if we don't find anything else, and there's an 2422 // ivar, that's an error. 2423 bool IsClassMethod = CurMethod->isClassMethod(); 2424 2425 bool LookForIvars; 2426 if (Lookup.empty()) 2427 LookForIvars = true; 2428 else if (IsClassMethod) 2429 LookForIvars = false; 2430 else 2431 LookForIvars = (Lookup.isSingleResult() && 2432 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2433 ObjCInterfaceDecl *IFace = nullptr; 2434 if (LookForIvars) { 2435 IFace = CurMethod->getClassInterface(); 2436 ObjCInterfaceDecl *ClassDeclared; 2437 ObjCIvarDecl *IV = nullptr; 2438 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2439 // Diagnose using an ivar in a class method. 2440 if (IsClassMethod) 2441 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2442 << IV->getDeclName()); 2443 2444 // If we're referencing an invalid decl, just return this as a silent 2445 // error node. The error diagnostic was already emitted on the decl. 2446 if (IV->isInvalidDecl()) 2447 return ExprError(); 2448 2449 // Check if referencing a field with __attribute__((deprecated)). 2450 if (DiagnoseUseOfDecl(IV, Loc)) 2451 return ExprError(); 2452 2453 // Diagnose the use of an ivar outside of the declaring class. 2454 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2455 !declaresSameEntity(ClassDeclared, IFace) && 2456 !getLangOpts().DebuggerSupport) 2457 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2458 2459 // FIXME: This should use a new expr for a direct reference, don't 2460 // turn this into Self->ivar, just return a BareIVarExpr or something. 2461 IdentifierInfo &II = Context.Idents.get("self"); 2462 UnqualifiedId SelfName; 2463 SelfName.setIdentifier(&II, SourceLocation()); 2464 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2465 CXXScopeSpec SelfScopeSpec; 2466 SourceLocation TemplateKWLoc; 2467 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2468 SelfName, false, false); 2469 if (SelfExpr.isInvalid()) 2470 return ExprError(); 2471 2472 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2473 if (SelfExpr.isInvalid()) 2474 return ExprError(); 2475 2476 MarkAnyDeclReferenced(Loc, IV, true); 2477 2478 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2479 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2480 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2481 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2482 2483 ObjCIvarRefExpr *Result = new (Context) 2484 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2485 IV->getLocation(), SelfExpr.get(), true, true); 2486 2487 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2488 if (!isUnevaluatedContext() && 2489 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2490 getCurFunction()->recordUseOfWeak(Result); 2491 } 2492 if (getLangOpts().ObjCAutoRefCount) { 2493 if (CurContext->isClosure()) 2494 Diag(Loc, diag::warn_implicitly_retains_self) 2495 << FixItHint::CreateInsertion(Loc, "self->"); 2496 } 2497 2498 return Result; 2499 } 2500 } else if (CurMethod->isInstanceMethod()) { 2501 // We should warn if a local variable hides an ivar. 2502 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2503 ObjCInterfaceDecl *ClassDeclared; 2504 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2505 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2506 declaresSameEntity(IFace, ClassDeclared)) 2507 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2508 } 2509 } 2510 } else if (Lookup.isSingleResult() && 2511 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2512 // If accessing a stand-alone ivar in a class method, this is an error. 2513 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2514 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2515 << IV->getDeclName()); 2516 } 2517 2518 if (Lookup.empty() && II && AllowBuiltinCreation) { 2519 // FIXME. Consolidate this with similar code in LookupName. 2520 if (unsigned BuiltinID = II->getBuiltinID()) { 2521 if (!(getLangOpts().CPlusPlus && 2522 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2523 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2524 S, Lookup.isForRedeclaration(), 2525 Lookup.getNameLoc()); 2526 if (D) Lookup.addDecl(D); 2527 } 2528 } 2529 } 2530 // Sentinel value saying that we didn't do anything special. 2531 return ExprResult((Expr *)nullptr); 2532 } 2533 2534 /// Cast a base object to a member's actual type. 2535 /// 2536 /// Logically this happens in three phases: 2537 /// 2538 /// * First we cast from the base type to the naming class. 2539 /// The naming class is the class into which we were looking 2540 /// when we found the member; it's the qualifier type if a 2541 /// qualifier was provided, and otherwise it's the base type. 2542 /// 2543 /// * Next we cast from the naming class to the declaring class. 2544 /// If the member we found was brought into a class's scope by 2545 /// a using declaration, this is that class; otherwise it's 2546 /// the class declaring the member. 2547 /// 2548 /// * Finally we cast from the declaring class to the "true" 2549 /// declaring class of the member. This conversion does not 2550 /// obey access control. 2551 ExprResult 2552 Sema::PerformObjectMemberConversion(Expr *From, 2553 NestedNameSpecifier *Qualifier, 2554 NamedDecl *FoundDecl, 2555 NamedDecl *Member) { 2556 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2557 if (!RD) 2558 return From; 2559 2560 QualType DestRecordType; 2561 QualType DestType; 2562 QualType FromRecordType; 2563 QualType FromType = From->getType(); 2564 bool PointerConversions = false; 2565 if (isa<FieldDecl>(Member)) { 2566 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2567 2568 if (FromType->getAs<PointerType>()) { 2569 DestType = Context.getPointerType(DestRecordType); 2570 FromRecordType = FromType->getPointeeType(); 2571 PointerConversions = true; 2572 } else { 2573 DestType = DestRecordType; 2574 FromRecordType = FromType; 2575 } 2576 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2577 if (Method->isStatic()) 2578 return From; 2579 2580 DestType = Method->getThisType(Context); 2581 DestRecordType = DestType->getPointeeType(); 2582 2583 if (FromType->getAs<PointerType>()) { 2584 FromRecordType = FromType->getPointeeType(); 2585 PointerConversions = true; 2586 } else { 2587 FromRecordType = FromType; 2588 DestType = DestRecordType; 2589 } 2590 } else { 2591 // No conversion necessary. 2592 return From; 2593 } 2594 2595 if (DestType->isDependentType() || FromType->isDependentType()) 2596 return From; 2597 2598 // If the unqualified types are the same, no conversion is necessary. 2599 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2600 return From; 2601 2602 SourceRange FromRange = From->getSourceRange(); 2603 SourceLocation FromLoc = FromRange.getBegin(); 2604 2605 ExprValueKind VK = From->getValueKind(); 2606 2607 // C++ [class.member.lookup]p8: 2608 // [...] Ambiguities can often be resolved by qualifying a name with its 2609 // class name. 2610 // 2611 // If the member was a qualified name and the qualified referred to a 2612 // specific base subobject type, we'll cast to that intermediate type 2613 // first and then to the object in which the member is declared. That allows 2614 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2615 // 2616 // class Base { public: int x; }; 2617 // class Derived1 : public Base { }; 2618 // class Derived2 : public Base { }; 2619 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2620 // 2621 // void VeryDerived::f() { 2622 // x = 17; // error: ambiguous base subobjects 2623 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2624 // } 2625 if (Qualifier && Qualifier->getAsType()) { 2626 QualType QType = QualType(Qualifier->getAsType(), 0); 2627 assert(QType->isRecordType() && "lookup done with non-record type"); 2628 2629 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2630 2631 // In C++98, the qualifier type doesn't actually have to be a base 2632 // type of the object type, in which case we just ignore it. 2633 // Otherwise build the appropriate casts. 2634 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2635 CXXCastPath BasePath; 2636 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2637 FromLoc, FromRange, &BasePath)) 2638 return ExprError(); 2639 2640 if (PointerConversions) 2641 QType = Context.getPointerType(QType); 2642 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2643 VK, &BasePath).get(); 2644 2645 FromType = QType; 2646 FromRecordType = QRecordType; 2647 2648 // If the qualifier type was the same as the destination type, 2649 // we're done. 2650 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2651 return From; 2652 } 2653 } 2654 2655 bool IgnoreAccess = false; 2656 2657 // If we actually found the member through a using declaration, cast 2658 // down to the using declaration's type. 2659 // 2660 // Pointer equality is fine here because only one declaration of a 2661 // class ever has member declarations. 2662 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2663 assert(isa<UsingShadowDecl>(FoundDecl)); 2664 QualType URecordType = Context.getTypeDeclType( 2665 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2666 2667 // We only need to do this if the naming-class to declaring-class 2668 // conversion is non-trivial. 2669 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2670 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2671 CXXCastPath BasePath; 2672 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2673 FromLoc, FromRange, &BasePath)) 2674 return ExprError(); 2675 2676 QualType UType = URecordType; 2677 if (PointerConversions) 2678 UType = Context.getPointerType(UType); 2679 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2680 VK, &BasePath).get(); 2681 FromType = UType; 2682 FromRecordType = URecordType; 2683 } 2684 2685 // We don't do access control for the conversion from the 2686 // declaring class to the true declaring class. 2687 IgnoreAccess = true; 2688 } 2689 2690 CXXCastPath BasePath; 2691 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2692 FromLoc, FromRange, &BasePath, 2693 IgnoreAccess)) 2694 return ExprError(); 2695 2696 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2697 VK, &BasePath); 2698 } 2699 2700 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2701 const LookupResult &R, 2702 bool HasTrailingLParen) { 2703 // Only when used directly as the postfix-expression of a call. 2704 if (!HasTrailingLParen) 2705 return false; 2706 2707 // Never if a scope specifier was provided. 2708 if (SS.isSet()) 2709 return false; 2710 2711 // Only in C++ or ObjC++. 2712 if (!getLangOpts().CPlusPlus) 2713 return false; 2714 2715 // Turn off ADL when we find certain kinds of declarations during 2716 // normal lookup: 2717 for (NamedDecl *D : R) { 2718 // C++0x [basic.lookup.argdep]p3: 2719 // -- a declaration of a class member 2720 // Since using decls preserve this property, we check this on the 2721 // original decl. 2722 if (D->isCXXClassMember()) 2723 return false; 2724 2725 // C++0x [basic.lookup.argdep]p3: 2726 // -- a block-scope function declaration that is not a 2727 // using-declaration 2728 // NOTE: we also trigger this for function templates (in fact, we 2729 // don't check the decl type at all, since all other decl types 2730 // turn off ADL anyway). 2731 if (isa<UsingShadowDecl>(D)) 2732 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2733 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2734 return false; 2735 2736 // C++0x [basic.lookup.argdep]p3: 2737 // -- a declaration that is neither a function or a function 2738 // template 2739 // And also for builtin functions. 2740 if (isa<FunctionDecl>(D)) { 2741 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2742 2743 // But also builtin functions. 2744 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2745 return false; 2746 } else if (!isa<FunctionTemplateDecl>(D)) 2747 return false; 2748 } 2749 2750 return true; 2751 } 2752 2753 2754 /// Diagnoses obvious problems with the use of the given declaration 2755 /// as an expression. This is only actually called for lookups that 2756 /// were not overloaded, and it doesn't promise that the declaration 2757 /// will in fact be used. 2758 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2759 if (D->isInvalidDecl()) 2760 return true; 2761 2762 if (isa<TypedefNameDecl>(D)) { 2763 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2764 return true; 2765 } 2766 2767 if (isa<ObjCInterfaceDecl>(D)) { 2768 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2769 return true; 2770 } 2771 2772 if (isa<NamespaceDecl>(D)) { 2773 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2774 return true; 2775 } 2776 2777 return false; 2778 } 2779 2780 // Certain multiversion types should be treated as overloaded even when there is 2781 // only one result. 2782 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2783 assert(R.isSingleResult() && "Expected only a single result"); 2784 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2785 return FD && 2786 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2787 } 2788 2789 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2790 LookupResult &R, bool NeedsADL, 2791 bool AcceptInvalidDecl) { 2792 // If this is a single, fully-resolved result and we don't need ADL, 2793 // just build an ordinary singleton decl ref. 2794 if (!NeedsADL && R.isSingleResult() && 2795 !R.getAsSingle<FunctionTemplateDecl>() && 2796 !ShouldLookupResultBeMultiVersionOverload(R)) 2797 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2798 R.getRepresentativeDecl(), nullptr, 2799 AcceptInvalidDecl); 2800 2801 // We only need to check the declaration if there's exactly one 2802 // result, because in the overloaded case the results can only be 2803 // functions and function templates. 2804 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2805 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2806 return ExprError(); 2807 2808 // Otherwise, just build an unresolved lookup expression. Suppress 2809 // any lookup-related diagnostics; we'll hash these out later, when 2810 // we've picked a target. 2811 R.suppressDiagnostics(); 2812 2813 UnresolvedLookupExpr *ULE 2814 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2815 SS.getWithLocInContext(Context), 2816 R.getLookupNameInfo(), 2817 NeedsADL, R.isOverloadedResult(), 2818 R.begin(), R.end()); 2819 2820 return ULE; 2821 } 2822 2823 static void 2824 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2825 ValueDecl *var, DeclContext *DC); 2826 2827 /// Complete semantic analysis for a reference to the given declaration. 2828 ExprResult Sema::BuildDeclarationNameExpr( 2829 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2830 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2831 bool AcceptInvalidDecl) { 2832 assert(D && "Cannot refer to a NULL declaration"); 2833 assert(!isa<FunctionTemplateDecl>(D) && 2834 "Cannot refer unambiguously to a function template"); 2835 2836 SourceLocation Loc = NameInfo.getLoc(); 2837 if (CheckDeclInExpr(*this, Loc, D)) 2838 return ExprError(); 2839 2840 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2841 // Specifically diagnose references to class templates that are missing 2842 // a template argument list. 2843 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2844 return ExprError(); 2845 } 2846 2847 // Make sure that we're referring to a value. 2848 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2849 if (!VD) { 2850 Diag(Loc, diag::err_ref_non_value) 2851 << D << SS.getRange(); 2852 Diag(D->getLocation(), diag::note_declared_at); 2853 return ExprError(); 2854 } 2855 2856 // Check whether this declaration can be used. Note that we suppress 2857 // this check when we're going to perform argument-dependent lookup 2858 // on this function name, because this might not be the function 2859 // that overload resolution actually selects. 2860 if (DiagnoseUseOfDecl(VD, Loc)) 2861 return ExprError(); 2862 2863 // Only create DeclRefExpr's for valid Decl's. 2864 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2865 return ExprError(); 2866 2867 // Handle members of anonymous structs and unions. If we got here, 2868 // and the reference is to a class member indirect field, then this 2869 // must be the subject of a pointer-to-member expression. 2870 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2871 if (!indirectField->isCXXClassMember()) 2872 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2873 indirectField); 2874 2875 { 2876 QualType type = VD->getType(); 2877 if (type.isNull()) 2878 return ExprError(); 2879 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2880 // C++ [except.spec]p17: 2881 // An exception-specification is considered to be needed when: 2882 // - in an expression, the function is the unique lookup result or 2883 // the selected member of a set of overloaded functions. 2884 ResolveExceptionSpec(Loc, FPT); 2885 type = VD->getType(); 2886 } 2887 ExprValueKind valueKind = VK_RValue; 2888 2889 switch (D->getKind()) { 2890 // Ignore all the non-ValueDecl kinds. 2891 #define ABSTRACT_DECL(kind) 2892 #define VALUE(type, base) 2893 #define DECL(type, base) \ 2894 case Decl::type: 2895 #include "clang/AST/DeclNodes.inc" 2896 llvm_unreachable("invalid value decl kind"); 2897 2898 // These shouldn't make it here. 2899 case Decl::ObjCAtDefsField: 2900 case Decl::ObjCIvar: 2901 llvm_unreachable("forming non-member reference to ivar?"); 2902 2903 // Enum constants are always r-values and never references. 2904 // Unresolved using declarations are dependent. 2905 case Decl::EnumConstant: 2906 case Decl::UnresolvedUsingValue: 2907 case Decl::OMPDeclareReduction: 2908 valueKind = VK_RValue; 2909 break; 2910 2911 // Fields and indirect fields that got here must be for 2912 // pointer-to-member expressions; we just call them l-values for 2913 // internal consistency, because this subexpression doesn't really 2914 // exist in the high-level semantics. 2915 case Decl::Field: 2916 case Decl::IndirectField: 2917 assert(getLangOpts().CPlusPlus && 2918 "building reference to field in C?"); 2919 2920 // These can't have reference type in well-formed programs, but 2921 // for internal consistency we do this anyway. 2922 type = type.getNonReferenceType(); 2923 valueKind = VK_LValue; 2924 break; 2925 2926 // Non-type template parameters are either l-values or r-values 2927 // depending on the type. 2928 case Decl::NonTypeTemplateParm: { 2929 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2930 type = reftype->getPointeeType(); 2931 valueKind = VK_LValue; // even if the parameter is an r-value reference 2932 break; 2933 } 2934 2935 // For non-references, we need to strip qualifiers just in case 2936 // the template parameter was declared as 'const int' or whatever. 2937 valueKind = VK_RValue; 2938 type = type.getUnqualifiedType(); 2939 break; 2940 } 2941 2942 case Decl::Var: 2943 case Decl::VarTemplateSpecialization: 2944 case Decl::VarTemplatePartialSpecialization: 2945 case Decl::Decomposition: 2946 case Decl::OMPCapturedExpr: 2947 // In C, "extern void blah;" is valid and is an r-value. 2948 if (!getLangOpts().CPlusPlus && 2949 !type.hasQualifiers() && 2950 type->isVoidType()) { 2951 valueKind = VK_RValue; 2952 break; 2953 } 2954 LLVM_FALLTHROUGH; 2955 2956 case Decl::ImplicitParam: 2957 case Decl::ParmVar: { 2958 // These are always l-values. 2959 valueKind = VK_LValue; 2960 type = type.getNonReferenceType(); 2961 2962 // FIXME: Does the addition of const really only apply in 2963 // potentially-evaluated contexts? Since the variable isn't actually 2964 // captured in an unevaluated context, it seems that the answer is no. 2965 if (!isUnevaluatedContext()) { 2966 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2967 if (!CapturedType.isNull()) 2968 type = CapturedType; 2969 } 2970 2971 break; 2972 } 2973 2974 case Decl::Binding: { 2975 // These are always lvalues. 2976 valueKind = VK_LValue; 2977 type = type.getNonReferenceType(); 2978 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2979 // decides how that's supposed to work. 2980 auto *BD = cast<BindingDecl>(VD); 2981 if (BD->getDeclContext()->isFunctionOrMethod() && 2982 BD->getDeclContext() != CurContext) 2983 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2984 break; 2985 } 2986 2987 case Decl::Function: { 2988 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2989 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2990 type = Context.BuiltinFnTy; 2991 valueKind = VK_RValue; 2992 break; 2993 } 2994 } 2995 2996 const FunctionType *fty = type->castAs<FunctionType>(); 2997 2998 // If we're referring to a function with an __unknown_anytype 2999 // result type, make the entire expression __unknown_anytype. 3000 if (fty->getReturnType() == Context.UnknownAnyTy) { 3001 type = Context.UnknownAnyTy; 3002 valueKind = VK_RValue; 3003 break; 3004 } 3005 3006 // Functions are l-values in C++. 3007 if (getLangOpts().CPlusPlus) { 3008 valueKind = VK_LValue; 3009 break; 3010 } 3011 3012 // C99 DR 316 says that, if a function type comes from a 3013 // function definition (without a prototype), that type is only 3014 // used for checking compatibility. Therefore, when referencing 3015 // the function, we pretend that we don't have the full function 3016 // type. 3017 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3018 isa<FunctionProtoType>(fty)) 3019 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3020 fty->getExtInfo()); 3021 3022 // Functions are r-values in C. 3023 valueKind = VK_RValue; 3024 break; 3025 } 3026 3027 case Decl::CXXDeductionGuide: 3028 llvm_unreachable("building reference to deduction guide"); 3029 3030 case Decl::MSProperty: 3031 valueKind = VK_LValue; 3032 break; 3033 3034 case Decl::CXXMethod: 3035 // If we're referring to a method with an __unknown_anytype 3036 // result type, make the entire expression __unknown_anytype. 3037 // This should only be possible with a type written directly. 3038 if (const FunctionProtoType *proto 3039 = dyn_cast<FunctionProtoType>(VD->getType())) 3040 if (proto->getReturnType() == Context.UnknownAnyTy) { 3041 type = Context.UnknownAnyTy; 3042 valueKind = VK_RValue; 3043 break; 3044 } 3045 3046 // C++ methods are l-values if static, r-values if non-static. 3047 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3048 valueKind = VK_LValue; 3049 break; 3050 } 3051 LLVM_FALLTHROUGH; 3052 3053 case Decl::CXXConversion: 3054 case Decl::CXXDestructor: 3055 case Decl::CXXConstructor: 3056 valueKind = VK_RValue; 3057 break; 3058 } 3059 3060 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3061 TemplateArgs); 3062 } 3063 } 3064 3065 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3066 SmallString<32> &Target) { 3067 Target.resize(CharByteWidth * (Source.size() + 1)); 3068 char *ResultPtr = &Target[0]; 3069 const llvm::UTF8 *ErrorPtr; 3070 bool success = 3071 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3072 (void)success; 3073 assert(success); 3074 Target.resize(ResultPtr - &Target[0]); 3075 } 3076 3077 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3078 PredefinedExpr::IdentKind IK) { 3079 // Pick the current block, lambda, captured statement or function. 3080 Decl *currentDecl = nullptr; 3081 if (const BlockScopeInfo *BSI = getCurBlock()) 3082 currentDecl = BSI->TheDecl; 3083 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3084 currentDecl = LSI->CallOperator; 3085 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3086 currentDecl = CSI->TheCapturedDecl; 3087 else 3088 currentDecl = getCurFunctionOrMethodDecl(); 3089 3090 if (!currentDecl) { 3091 Diag(Loc, diag::ext_predef_outside_function); 3092 currentDecl = Context.getTranslationUnitDecl(); 3093 } 3094 3095 QualType ResTy; 3096 StringLiteral *SL = nullptr; 3097 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3098 ResTy = Context.DependentTy; 3099 else { 3100 // Pre-defined identifiers are of type char[x], where x is the length of 3101 // the string. 3102 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3103 unsigned Length = Str.length(); 3104 3105 llvm::APInt LengthI(32, Length + 1); 3106 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3107 ResTy = 3108 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3109 SmallString<32> RawChars; 3110 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3111 Str, RawChars); 3112 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3113 /*IndexTypeQuals*/ 0); 3114 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3115 /*Pascal*/ false, ResTy, Loc); 3116 } else { 3117 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3118 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3119 /*IndexTypeQuals*/ 0); 3120 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3121 /*Pascal*/ false, ResTy, Loc); 3122 } 3123 } 3124 3125 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3126 } 3127 3128 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3129 PredefinedExpr::IdentKind IK; 3130 3131 switch (Kind) { 3132 default: llvm_unreachable("Unknown simple primary expr!"); 3133 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3134 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3135 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3136 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3137 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3138 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3139 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3140 } 3141 3142 return BuildPredefinedExpr(Loc, IK); 3143 } 3144 3145 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3146 SmallString<16> CharBuffer; 3147 bool Invalid = false; 3148 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3149 if (Invalid) 3150 return ExprError(); 3151 3152 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3153 PP, Tok.getKind()); 3154 if (Literal.hadError()) 3155 return ExprError(); 3156 3157 QualType Ty; 3158 if (Literal.isWide()) 3159 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3160 else if (Literal.isUTF8() && getLangOpts().Char8) 3161 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3162 else if (Literal.isUTF16()) 3163 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3164 else if (Literal.isUTF32()) 3165 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3166 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3167 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3168 else 3169 Ty = Context.CharTy; // 'x' -> char in C++ 3170 3171 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3172 if (Literal.isWide()) 3173 Kind = CharacterLiteral::Wide; 3174 else if (Literal.isUTF16()) 3175 Kind = CharacterLiteral::UTF16; 3176 else if (Literal.isUTF32()) 3177 Kind = CharacterLiteral::UTF32; 3178 else if (Literal.isUTF8()) 3179 Kind = CharacterLiteral::UTF8; 3180 3181 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3182 Tok.getLocation()); 3183 3184 if (Literal.getUDSuffix().empty()) 3185 return Lit; 3186 3187 // We're building a user-defined literal. 3188 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3189 SourceLocation UDSuffixLoc = 3190 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3191 3192 // Make sure we're allowed user-defined literals here. 3193 if (!UDLScope) 3194 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3195 3196 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3197 // operator "" X (ch) 3198 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3199 Lit, Tok.getLocation()); 3200 } 3201 3202 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3203 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3204 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3205 Context.IntTy, Loc); 3206 } 3207 3208 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3209 QualType Ty, SourceLocation Loc) { 3210 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3211 3212 using llvm::APFloat; 3213 APFloat Val(Format); 3214 3215 APFloat::opStatus result = Literal.GetFloatValue(Val); 3216 3217 // Overflow is always an error, but underflow is only an error if 3218 // we underflowed to zero (APFloat reports denormals as underflow). 3219 if ((result & APFloat::opOverflow) || 3220 ((result & APFloat::opUnderflow) && Val.isZero())) { 3221 unsigned diagnostic; 3222 SmallString<20> buffer; 3223 if (result & APFloat::opOverflow) { 3224 diagnostic = diag::warn_float_overflow; 3225 APFloat::getLargest(Format).toString(buffer); 3226 } else { 3227 diagnostic = diag::warn_float_underflow; 3228 APFloat::getSmallest(Format).toString(buffer); 3229 } 3230 3231 S.Diag(Loc, diagnostic) 3232 << Ty 3233 << StringRef(buffer.data(), buffer.size()); 3234 } 3235 3236 bool isExact = (result == APFloat::opOK); 3237 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3238 } 3239 3240 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3241 assert(E && "Invalid expression"); 3242 3243 if (E->isValueDependent()) 3244 return false; 3245 3246 QualType QT = E->getType(); 3247 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3248 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3249 return true; 3250 } 3251 3252 llvm::APSInt ValueAPS; 3253 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3254 3255 if (R.isInvalid()) 3256 return true; 3257 3258 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3259 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3260 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3261 << ValueAPS.toString(10) << ValueIsPositive; 3262 return true; 3263 } 3264 3265 return false; 3266 } 3267 3268 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3269 // Fast path for a single digit (which is quite common). A single digit 3270 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3271 if (Tok.getLength() == 1) { 3272 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3273 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3274 } 3275 3276 SmallString<128> SpellingBuffer; 3277 // NumericLiteralParser wants to overread by one character. Add padding to 3278 // the buffer in case the token is copied to the buffer. If getSpelling() 3279 // returns a StringRef to the memory buffer, it should have a null char at 3280 // the EOF, so it is also safe. 3281 SpellingBuffer.resize(Tok.getLength() + 1); 3282 3283 // Get the spelling of the token, which eliminates trigraphs, etc. 3284 bool Invalid = false; 3285 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3286 if (Invalid) 3287 return ExprError(); 3288 3289 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3290 if (Literal.hadError) 3291 return ExprError(); 3292 3293 if (Literal.hasUDSuffix()) { 3294 // We're building a user-defined literal. 3295 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3296 SourceLocation UDSuffixLoc = 3297 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3298 3299 // Make sure we're allowed user-defined literals here. 3300 if (!UDLScope) 3301 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3302 3303 QualType CookedTy; 3304 if (Literal.isFloatingLiteral()) { 3305 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3306 // long double, the literal is treated as a call of the form 3307 // operator "" X (f L) 3308 CookedTy = Context.LongDoubleTy; 3309 } else { 3310 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3311 // unsigned long long, the literal is treated as a call of the form 3312 // operator "" X (n ULL) 3313 CookedTy = Context.UnsignedLongLongTy; 3314 } 3315 3316 DeclarationName OpName = 3317 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3318 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3319 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3320 3321 SourceLocation TokLoc = Tok.getLocation(); 3322 3323 // Perform literal operator lookup to determine if we're building a raw 3324 // literal or a cooked one. 3325 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3326 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3327 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3328 /*AllowStringTemplate*/ false, 3329 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3330 case LOLR_ErrorNoDiagnostic: 3331 // Lookup failure for imaginary constants isn't fatal, there's still the 3332 // GNU extension producing _Complex types. 3333 break; 3334 case LOLR_Error: 3335 return ExprError(); 3336 case LOLR_Cooked: { 3337 Expr *Lit; 3338 if (Literal.isFloatingLiteral()) { 3339 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3340 } else { 3341 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3342 if (Literal.GetIntegerValue(ResultVal)) 3343 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3344 << /* Unsigned */ 1; 3345 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3346 Tok.getLocation()); 3347 } 3348 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3349 } 3350 3351 case LOLR_Raw: { 3352 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3353 // literal is treated as a call of the form 3354 // operator "" X ("n") 3355 unsigned Length = Literal.getUDSuffixOffset(); 3356 QualType StrTy = Context.getConstantArrayType( 3357 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3358 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3359 Expr *Lit = StringLiteral::Create( 3360 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3361 /*Pascal*/false, StrTy, &TokLoc, 1); 3362 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3363 } 3364 3365 case LOLR_Template: { 3366 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3367 // template), L is treated as a call fo the form 3368 // operator "" X <'c1', 'c2', ... 'ck'>() 3369 // where n is the source character sequence c1 c2 ... ck. 3370 TemplateArgumentListInfo ExplicitArgs; 3371 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3372 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3373 llvm::APSInt Value(CharBits, CharIsUnsigned); 3374 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3375 Value = TokSpelling[I]; 3376 TemplateArgument Arg(Context, Value, Context.CharTy); 3377 TemplateArgumentLocInfo ArgInfo; 3378 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3379 } 3380 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3381 &ExplicitArgs); 3382 } 3383 case LOLR_StringTemplate: 3384 llvm_unreachable("unexpected literal operator lookup result"); 3385 } 3386 } 3387 3388 Expr *Res; 3389 3390 if (Literal.isFixedPointLiteral()) { 3391 QualType Ty; 3392 3393 if (Literal.isAccum) { 3394 if (Literal.isHalf) { 3395 Ty = Context.ShortAccumTy; 3396 } else if (Literal.isLong) { 3397 Ty = Context.LongAccumTy; 3398 } else { 3399 Ty = Context.AccumTy; 3400 } 3401 } else if (Literal.isFract) { 3402 if (Literal.isHalf) { 3403 Ty = Context.ShortFractTy; 3404 } else if (Literal.isLong) { 3405 Ty = Context.LongFractTy; 3406 } else { 3407 Ty = Context.FractTy; 3408 } 3409 } 3410 3411 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3412 3413 bool isSigned = !Literal.isUnsigned; 3414 unsigned scale = Context.getFixedPointScale(Ty); 3415 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3416 3417 llvm::APInt Val(bit_width, 0, isSigned); 3418 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3419 bool ValIsZero = Val.isNullValue() && !Overflowed; 3420 3421 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3422 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3423 // Clause 6.4.4 - The value of a constant shall be in the range of 3424 // representable values for its type, with exception for constants of a 3425 // fract type with a value of exactly 1; such a constant shall denote 3426 // the maximal value for the type. 3427 --Val; 3428 else if (Val.ugt(MaxVal) || Overflowed) 3429 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3430 3431 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3432 Tok.getLocation(), scale); 3433 } else if (Literal.isFloatingLiteral()) { 3434 QualType Ty; 3435 if (Literal.isHalf){ 3436 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3437 Ty = Context.HalfTy; 3438 else { 3439 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3440 return ExprError(); 3441 } 3442 } else if (Literal.isFloat) 3443 Ty = Context.FloatTy; 3444 else if (Literal.isLong) 3445 Ty = Context.LongDoubleTy; 3446 else if (Literal.isFloat16) 3447 Ty = Context.Float16Ty; 3448 else if (Literal.isFloat128) 3449 Ty = Context.Float128Ty; 3450 else 3451 Ty = Context.DoubleTy; 3452 3453 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3454 3455 if (Ty == Context.DoubleTy) { 3456 if (getLangOpts().SinglePrecisionConstants) { 3457 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3458 if (BTy->getKind() != BuiltinType::Float) { 3459 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3460 } 3461 } else if (getLangOpts().OpenCL && 3462 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3463 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3464 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3465 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3466 } 3467 } 3468 } else if (!Literal.isIntegerLiteral()) { 3469 return ExprError(); 3470 } else { 3471 QualType Ty; 3472 3473 // 'long long' is a C99 or C++11 feature. 3474 if (!getLangOpts().C99 && Literal.isLongLong) { 3475 if (getLangOpts().CPlusPlus) 3476 Diag(Tok.getLocation(), 3477 getLangOpts().CPlusPlus11 ? 3478 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3479 else 3480 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3481 } 3482 3483 // Get the value in the widest-possible width. 3484 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3485 llvm::APInt ResultVal(MaxWidth, 0); 3486 3487 if (Literal.GetIntegerValue(ResultVal)) { 3488 // If this value didn't fit into uintmax_t, error and force to ull. 3489 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3490 << /* Unsigned */ 1; 3491 Ty = Context.UnsignedLongLongTy; 3492 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3493 "long long is not intmax_t?"); 3494 } else { 3495 // If this value fits into a ULL, try to figure out what else it fits into 3496 // according to the rules of C99 6.4.4.1p5. 3497 3498 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3499 // be an unsigned int. 3500 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3501 3502 // Check from smallest to largest, picking the smallest type we can. 3503 unsigned Width = 0; 3504 3505 // Microsoft specific integer suffixes are explicitly sized. 3506 if (Literal.MicrosoftInteger) { 3507 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3508 Width = 8; 3509 Ty = Context.CharTy; 3510 } else { 3511 Width = Literal.MicrosoftInteger; 3512 Ty = Context.getIntTypeForBitwidth(Width, 3513 /*Signed=*/!Literal.isUnsigned); 3514 } 3515 } 3516 3517 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3518 // Are int/unsigned possibilities? 3519 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3520 3521 // Does it fit in a unsigned int? 3522 if (ResultVal.isIntN(IntSize)) { 3523 // Does it fit in a signed int? 3524 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3525 Ty = Context.IntTy; 3526 else if (AllowUnsigned) 3527 Ty = Context.UnsignedIntTy; 3528 Width = IntSize; 3529 } 3530 } 3531 3532 // Are long/unsigned long possibilities? 3533 if (Ty.isNull() && !Literal.isLongLong) { 3534 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3535 3536 // Does it fit in a unsigned long? 3537 if (ResultVal.isIntN(LongSize)) { 3538 // Does it fit in a signed long? 3539 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3540 Ty = Context.LongTy; 3541 else if (AllowUnsigned) 3542 Ty = Context.UnsignedLongTy; 3543 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3544 // is compatible. 3545 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3546 const unsigned LongLongSize = 3547 Context.getTargetInfo().getLongLongWidth(); 3548 Diag(Tok.getLocation(), 3549 getLangOpts().CPlusPlus 3550 ? Literal.isLong 3551 ? diag::warn_old_implicitly_unsigned_long_cxx 3552 : /*C++98 UB*/ diag:: 3553 ext_old_implicitly_unsigned_long_cxx 3554 : diag::warn_old_implicitly_unsigned_long) 3555 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3556 : /*will be ill-formed*/ 1); 3557 Ty = Context.UnsignedLongTy; 3558 } 3559 Width = LongSize; 3560 } 3561 } 3562 3563 // Check long long if needed. 3564 if (Ty.isNull()) { 3565 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3566 3567 // Does it fit in a unsigned long long? 3568 if (ResultVal.isIntN(LongLongSize)) { 3569 // Does it fit in a signed long long? 3570 // To be compatible with MSVC, hex integer literals ending with the 3571 // LL or i64 suffix are always signed in Microsoft mode. 3572 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3573 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3574 Ty = Context.LongLongTy; 3575 else if (AllowUnsigned) 3576 Ty = Context.UnsignedLongLongTy; 3577 Width = LongLongSize; 3578 } 3579 } 3580 3581 // If we still couldn't decide a type, we probably have something that 3582 // does not fit in a signed long long, but has no U suffix. 3583 if (Ty.isNull()) { 3584 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3585 Ty = Context.UnsignedLongLongTy; 3586 Width = Context.getTargetInfo().getLongLongWidth(); 3587 } 3588 3589 if (ResultVal.getBitWidth() != Width) 3590 ResultVal = ResultVal.trunc(Width); 3591 } 3592 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3593 } 3594 3595 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3596 if (Literal.isImaginary) { 3597 Res = new (Context) ImaginaryLiteral(Res, 3598 Context.getComplexType(Res->getType())); 3599 3600 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3601 } 3602 return Res; 3603 } 3604 3605 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3606 assert(E && "ActOnParenExpr() missing expr"); 3607 return new (Context) ParenExpr(L, R, E); 3608 } 3609 3610 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3611 SourceLocation Loc, 3612 SourceRange ArgRange) { 3613 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3614 // scalar or vector data type argument..." 3615 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3616 // type (C99 6.2.5p18) or void. 3617 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3618 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3619 << T << ArgRange; 3620 return true; 3621 } 3622 3623 assert((T->isVoidType() || !T->isIncompleteType()) && 3624 "Scalar types should always be complete"); 3625 return false; 3626 } 3627 3628 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3629 SourceLocation Loc, 3630 SourceRange ArgRange, 3631 UnaryExprOrTypeTrait TraitKind) { 3632 // Invalid types must be hard errors for SFINAE in C++. 3633 if (S.LangOpts.CPlusPlus) 3634 return true; 3635 3636 // C99 6.5.3.4p1: 3637 if (T->isFunctionType() && 3638 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3639 TraitKind == UETT_PreferredAlignOf)) { 3640 // sizeof(function)/alignof(function) is allowed as an extension. 3641 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3642 << TraitKind << ArgRange; 3643 return false; 3644 } 3645 3646 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3647 // this is an error (OpenCL v1.1 s6.3.k) 3648 if (T->isVoidType()) { 3649 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3650 : diag::ext_sizeof_alignof_void_type; 3651 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3652 return false; 3653 } 3654 3655 return true; 3656 } 3657 3658 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3659 SourceLocation Loc, 3660 SourceRange ArgRange, 3661 UnaryExprOrTypeTrait TraitKind) { 3662 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3663 // runtime doesn't allow it. 3664 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3665 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3666 << T << (TraitKind == UETT_SizeOf) 3667 << ArgRange; 3668 return true; 3669 } 3670 3671 return false; 3672 } 3673 3674 /// Check whether E is a pointer from a decayed array type (the decayed 3675 /// pointer type is equal to T) and emit a warning if it is. 3676 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3677 Expr *E) { 3678 // Don't warn if the operation changed the type. 3679 if (T != E->getType()) 3680 return; 3681 3682 // Now look for array decays. 3683 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3684 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3685 return; 3686 3687 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3688 << ICE->getType() 3689 << ICE->getSubExpr()->getType(); 3690 } 3691 3692 /// Check the constraints on expression operands to unary type expression 3693 /// and type traits. 3694 /// 3695 /// Completes any types necessary and validates the constraints on the operand 3696 /// expression. The logic mostly mirrors the type-based overload, but may modify 3697 /// the expression as it completes the type for that expression through template 3698 /// instantiation, etc. 3699 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3700 UnaryExprOrTypeTrait ExprKind) { 3701 QualType ExprTy = E->getType(); 3702 assert(!ExprTy->isReferenceType()); 3703 3704 if (ExprKind == UETT_VecStep) 3705 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3706 E->getSourceRange()); 3707 3708 // Whitelist some types as extensions 3709 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3710 E->getSourceRange(), ExprKind)) 3711 return false; 3712 3713 // 'alignof' applied to an expression only requires the base element type of 3714 // the expression to be complete. 'sizeof' requires the expression's type to 3715 // be complete (and will attempt to complete it if it's an array of unknown 3716 // bound). 3717 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3718 if (RequireCompleteType(E->getExprLoc(), 3719 Context.getBaseElementType(E->getType()), 3720 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3721 E->getSourceRange())) 3722 return true; 3723 } else { 3724 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3725 ExprKind, E->getSourceRange())) 3726 return true; 3727 } 3728 3729 // Completing the expression's type may have changed it. 3730 ExprTy = E->getType(); 3731 assert(!ExprTy->isReferenceType()); 3732 3733 if (ExprTy->isFunctionType()) { 3734 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3735 << ExprKind << E->getSourceRange(); 3736 return true; 3737 } 3738 3739 // The operand for sizeof and alignof is in an unevaluated expression context, 3740 // so side effects could result in unintended consequences. 3741 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3742 ExprKind == UETT_PreferredAlignOf) && 3743 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3744 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3745 3746 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3747 E->getSourceRange(), ExprKind)) 3748 return true; 3749 3750 if (ExprKind == UETT_SizeOf) { 3751 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3752 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3753 QualType OType = PVD->getOriginalType(); 3754 QualType Type = PVD->getType(); 3755 if (Type->isPointerType() && OType->isArrayType()) { 3756 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3757 << Type << OType; 3758 Diag(PVD->getLocation(), diag::note_declared_at); 3759 } 3760 } 3761 } 3762 3763 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3764 // decays into a pointer and returns an unintended result. This is most 3765 // likely a typo for "sizeof(array) op x". 3766 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3767 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3768 BO->getLHS()); 3769 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3770 BO->getRHS()); 3771 } 3772 } 3773 3774 return false; 3775 } 3776 3777 /// Check the constraints on operands to unary expression and type 3778 /// traits. 3779 /// 3780 /// This will complete any types necessary, and validate the various constraints 3781 /// on those operands. 3782 /// 3783 /// The UsualUnaryConversions() function is *not* called by this routine. 3784 /// C99 6.3.2.1p[2-4] all state: 3785 /// Except when it is the operand of the sizeof operator ... 3786 /// 3787 /// C++ [expr.sizeof]p4 3788 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3789 /// standard conversions are not applied to the operand of sizeof. 3790 /// 3791 /// This policy is followed for all of the unary trait expressions. 3792 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3793 SourceLocation OpLoc, 3794 SourceRange ExprRange, 3795 UnaryExprOrTypeTrait ExprKind) { 3796 if (ExprType->isDependentType()) 3797 return false; 3798 3799 // C++ [expr.sizeof]p2: 3800 // When applied to a reference or a reference type, the result 3801 // is the size of the referenced type. 3802 // C++11 [expr.alignof]p3: 3803 // When alignof is applied to a reference type, the result 3804 // shall be the alignment of the referenced type. 3805 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3806 ExprType = Ref->getPointeeType(); 3807 3808 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3809 // When alignof or _Alignof is applied to an array type, the result 3810 // is the alignment of the element type. 3811 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3812 ExprKind == UETT_OpenMPRequiredSimdAlign) 3813 ExprType = Context.getBaseElementType(ExprType); 3814 3815 if (ExprKind == UETT_VecStep) 3816 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3817 3818 // Whitelist some types as extensions 3819 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3820 ExprKind)) 3821 return false; 3822 3823 if (RequireCompleteType(OpLoc, ExprType, 3824 diag::err_sizeof_alignof_incomplete_type, 3825 ExprKind, ExprRange)) 3826 return true; 3827 3828 if (ExprType->isFunctionType()) { 3829 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3830 << ExprKind << ExprRange; 3831 return true; 3832 } 3833 3834 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3835 ExprKind)) 3836 return true; 3837 3838 return false; 3839 } 3840 3841 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3842 E = E->IgnoreParens(); 3843 3844 // Cannot know anything else if the expression is dependent. 3845 if (E->isTypeDependent()) 3846 return false; 3847 3848 if (E->getObjectKind() == OK_BitField) { 3849 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3850 << 1 << E->getSourceRange(); 3851 return true; 3852 } 3853 3854 ValueDecl *D = nullptr; 3855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3856 D = DRE->getDecl(); 3857 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3858 D = ME->getMemberDecl(); 3859 } 3860 3861 // If it's a field, require the containing struct to have a 3862 // complete definition so that we can compute the layout. 3863 // 3864 // This can happen in C++11 onwards, either by naming the member 3865 // in a way that is not transformed into a member access expression 3866 // (in an unevaluated operand, for instance), or by naming the member 3867 // in a trailing-return-type. 3868 // 3869 // For the record, since __alignof__ on expressions is a GCC 3870 // extension, GCC seems to permit this but always gives the 3871 // nonsensical answer 0. 3872 // 3873 // We don't really need the layout here --- we could instead just 3874 // directly check for all the appropriate alignment-lowing 3875 // attributes --- but that would require duplicating a lot of 3876 // logic that just isn't worth duplicating for such a marginal 3877 // use-case. 3878 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3879 // Fast path this check, since we at least know the record has a 3880 // definition if we can find a member of it. 3881 if (!FD->getParent()->isCompleteDefinition()) { 3882 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3883 << E->getSourceRange(); 3884 return true; 3885 } 3886 3887 // Otherwise, if it's a field, and the field doesn't have 3888 // reference type, then it must have a complete type (or be a 3889 // flexible array member, which we explicitly want to 3890 // white-list anyway), which makes the following checks trivial. 3891 if (!FD->getType()->isReferenceType()) 3892 return false; 3893 } 3894 3895 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3896 } 3897 3898 bool Sema::CheckVecStepExpr(Expr *E) { 3899 E = E->IgnoreParens(); 3900 3901 // Cannot know anything else if the expression is dependent. 3902 if (E->isTypeDependent()) 3903 return false; 3904 3905 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3906 } 3907 3908 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3909 CapturingScopeInfo *CSI) { 3910 assert(T->isVariablyModifiedType()); 3911 assert(CSI != nullptr); 3912 3913 // We're going to walk down into the type and look for VLA expressions. 3914 do { 3915 const Type *Ty = T.getTypePtr(); 3916 switch (Ty->getTypeClass()) { 3917 #define TYPE(Class, Base) 3918 #define ABSTRACT_TYPE(Class, Base) 3919 #define NON_CANONICAL_TYPE(Class, Base) 3920 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3921 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3922 #include "clang/AST/TypeNodes.def" 3923 T = QualType(); 3924 break; 3925 // These types are never variably-modified. 3926 case Type::Builtin: 3927 case Type::Complex: 3928 case Type::Vector: 3929 case Type::ExtVector: 3930 case Type::Record: 3931 case Type::Enum: 3932 case Type::Elaborated: 3933 case Type::TemplateSpecialization: 3934 case Type::ObjCObject: 3935 case Type::ObjCInterface: 3936 case Type::ObjCObjectPointer: 3937 case Type::ObjCTypeParam: 3938 case Type::Pipe: 3939 llvm_unreachable("type class is never variably-modified!"); 3940 case Type::Adjusted: 3941 T = cast<AdjustedType>(Ty)->getOriginalType(); 3942 break; 3943 case Type::Decayed: 3944 T = cast<DecayedType>(Ty)->getPointeeType(); 3945 break; 3946 case Type::Pointer: 3947 T = cast<PointerType>(Ty)->getPointeeType(); 3948 break; 3949 case Type::BlockPointer: 3950 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3951 break; 3952 case Type::LValueReference: 3953 case Type::RValueReference: 3954 T = cast<ReferenceType>(Ty)->getPointeeType(); 3955 break; 3956 case Type::MemberPointer: 3957 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3958 break; 3959 case Type::ConstantArray: 3960 case Type::IncompleteArray: 3961 // Losing element qualification here is fine. 3962 T = cast<ArrayType>(Ty)->getElementType(); 3963 break; 3964 case Type::VariableArray: { 3965 // Losing element qualification here is fine. 3966 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3967 3968 // Unknown size indication requires no size computation. 3969 // Otherwise, evaluate and record it. 3970 if (auto Size = VAT->getSizeExpr()) { 3971 if (!CSI->isVLATypeCaptured(VAT)) { 3972 RecordDecl *CapRecord = nullptr; 3973 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3974 CapRecord = LSI->Lambda; 3975 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3976 CapRecord = CRSI->TheRecordDecl; 3977 } 3978 if (CapRecord) { 3979 auto ExprLoc = Size->getExprLoc(); 3980 auto SizeType = Context.getSizeType(); 3981 // Build the non-static data member. 3982 auto Field = 3983 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3984 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3985 /*BW*/ nullptr, /*Mutable*/ false, 3986 /*InitStyle*/ ICIS_NoInit); 3987 Field->setImplicit(true); 3988 Field->setAccess(AS_private); 3989 Field->setCapturedVLAType(VAT); 3990 CapRecord->addDecl(Field); 3991 3992 CSI->addVLATypeCapture(ExprLoc, SizeType); 3993 } 3994 } 3995 } 3996 T = VAT->getElementType(); 3997 break; 3998 } 3999 case Type::FunctionProto: 4000 case Type::FunctionNoProto: 4001 T = cast<FunctionType>(Ty)->getReturnType(); 4002 break; 4003 case Type::Paren: 4004 case Type::TypeOf: 4005 case Type::UnaryTransform: 4006 case Type::Attributed: 4007 case Type::SubstTemplateTypeParm: 4008 case Type::PackExpansion: 4009 // Keep walking after single level desugaring. 4010 T = T.getSingleStepDesugaredType(Context); 4011 break; 4012 case Type::Typedef: 4013 T = cast<TypedefType>(Ty)->desugar(); 4014 break; 4015 case Type::Decltype: 4016 T = cast<DecltypeType>(Ty)->desugar(); 4017 break; 4018 case Type::Auto: 4019 case Type::DeducedTemplateSpecialization: 4020 T = cast<DeducedType>(Ty)->getDeducedType(); 4021 break; 4022 case Type::TypeOfExpr: 4023 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4024 break; 4025 case Type::Atomic: 4026 T = cast<AtomicType>(Ty)->getValueType(); 4027 break; 4028 } 4029 } while (!T.isNull() && T->isVariablyModifiedType()); 4030 } 4031 4032 /// Build a sizeof or alignof expression given a type operand. 4033 ExprResult 4034 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4035 SourceLocation OpLoc, 4036 UnaryExprOrTypeTrait ExprKind, 4037 SourceRange R) { 4038 if (!TInfo) 4039 return ExprError(); 4040 4041 QualType T = TInfo->getType(); 4042 4043 if (!T->isDependentType() && 4044 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4045 return ExprError(); 4046 4047 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4048 if (auto *TT = T->getAs<TypedefType>()) { 4049 for (auto I = FunctionScopes.rbegin(), 4050 E = std::prev(FunctionScopes.rend()); 4051 I != E; ++I) { 4052 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4053 if (CSI == nullptr) 4054 break; 4055 DeclContext *DC = nullptr; 4056 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4057 DC = LSI->CallOperator; 4058 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4059 DC = CRSI->TheCapturedDecl; 4060 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4061 DC = BSI->TheDecl; 4062 if (DC) { 4063 if (DC->containsDecl(TT->getDecl())) 4064 break; 4065 captureVariablyModifiedType(Context, T, CSI); 4066 } 4067 } 4068 } 4069 } 4070 4071 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4072 return new (Context) UnaryExprOrTypeTraitExpr( 4073 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4074 } 4075 4076 /// Build a sizeof or alignof expression given an expression 4077 /// operand. 4078 ExprResult 4079 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4080 UnaryExprOrTypeTrait ExprKind) { 4081 ExprResult PE = CheckPlaceholderExpr(E); 4082 if (PE.isInvalid()) 4083 return ExprError(); 4084 4085 E = PE.get(); 4086 4087 // Verify that the operand is valid. 4088 bool isInvalid = false; 4089 if (E->isTypeDependent()) { 4090 // Delay type-checking for type-dependent expressions. 4091 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4092 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4093 } else if (ExprKind == UETT_VecStep) { 4094 isInvalid = CheckVecStepExpr(E); 4095 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4096 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4097 isInvalid = true; 4098 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4099 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4100 isInvalid = true; 4101 } else { 4102 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4103 } 4104 4105 if (isInvalid) 4106 return ExprError(); 4107 4108 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4109 PE = TransformToPotentiallyEvaluated(E); 4110 if (PE.isInvalid()) return ExprError(); 4111 E = PE.get(); 4112 } 4113 4114 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4115 return new (Context) UnaryExprOrTypeTraitExpr( 4116 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4117 } 4118 4119 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4120 /// expr and the same for @c alignof and @c __alignof 4121 /// Note that the ArgRange is invalid if isType is false. 4122 ExprResult 4123 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4124 UnaryExprOrTypeTrait ExprKind, bool IsType, 4125 void *TyOrEx, SourceRange ArgRange) { 4126 // If error parsing type, ignore. 4127 if (!TyOrEx) return ExprError(); 4128 4129 if (IsType) { 4130 TypeSourceInfo *TInfo; 4131 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4132 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4133 } 4134 4135 Expr *ArgEx = (Expr *)TyOrEx; 4136 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4137 return Result; 4138 } 4139 4140 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4141 bool IsReal) { 4142 if (V.get()->isTypeDependent()) 4143 return S.Context.DependentTy; 4144 4145 // _Real and _Imag are only l-values for normal l-values. 4146 if (V.get()->getObjectKind() != OK_Ordinary) { 4147 V = S.DefaultLvalueConversion(V.get()); 4148 if (V.isInvalid()) 4149 return QualType(); 4150 } 4151 4152 // These operators return the element type of a complex type. 4153 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4154 return CT->getElementType(); 4155 4156 // Otherwise they pass through real integer and floating point types here. 4157 if (V.get()->getType()->isArithmeticType()) 4158 return V.get()->getType(); 4159 4160 // Test for placeholders. 4161 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4162 if (PR.isInvalid()) return QualType(); 4163 if (PR.get() != V.get()) { 4164 V = PR; 4165 return CheckRealImagOperand(S, V, Loc, IsReal); 4166 } 4167 4168 // Reject anything else. 4169 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4170 << (IsReal ? "__real" : "__imag"); 4171 return QualType(); 4172 } 4173 4174 4175 4176 ExprResult 4177 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4178 tok::TokenKind Kind, Expr *Input) { 4179 UnaryOperatorKind Opc; 4180 switch (Kind) { 4181 default: llvm_unreachable("Unknown unary op!"); 4182 case tok::plusplus: Opc = UO_PostInc; break; 4183 case tok::minusminus: Opc = UO_PostDec; break; 4184 } 4185 4186 // Since this might is a postfix expression, get rid of ParenListExprs. 4187 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4188 if (Result.isInvalid()) return ExprError(); 4189 Input = Result.get(); 4190 4191 return BuildUnaryOp(S, OpLoc, Opc, Input); 4192 } 4193 4194 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4195 /// 4196 /// \return true on error 4197 static bool checkArithmeticOnObjCPointer(Sema &S, 4198 SourceLocation opLoc, 4199 Expr *op) { 4200 assert(op->getType()->isObjCObjectPointerType()); 4201 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4202 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4203 return false; 4204 4205 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4206 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4207 << op->getSourceRange(); 4208 return true; 4209 } 4210 4211 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4212 auto *BaseNoParens = Base->IgnoreParens(); 4213 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4214 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4215 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4216 } 4217 4218 ExprResult 4219 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4220 Expr *idx, SourceLocation rbLoc) { 4221 if (base && !base->getType().isNull() && 4222 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4223 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4224 /*Length=*/nullptr, rbLoc); 4225 4226 // Since this might be a postfix expression, get rid of ParenListExprs. 4227 if (isa<ParenListExpr>(base)) { 4228 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4229 if (result.isInvalid()) return ExprError(); 4230 base = result.get(); 4231 } 4232 4233 // Handle any non-overload placeholder types in the base and index 4234 // expressions. We can't handle overloads here because the other 4235 // operand might be an overloadable type, in which case the overload 4236 // resolution for the operator overload should get the first crack 4237 // at the overload. 4238 bool IsMSPropertySubscript = false; 4239 if (base->getType()->isNonOverloadPlaceholderType()) { 4240 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4241 if (!IsMSPropertySubscript) { 4242 ExprResult result = CheckPlaceholderExpr(base); 4243 if (result.isInvalid()) 4244 return ExprError(); 4245 base = result.get(); 4246 } 4247 } 4248 if (idx->getType()->isNonOverloadPlaceholderType()) { 4249 ExprResult result = CheckPlaceholderExpr(idx); 4250 if (result.isInvalid()) return ExprError(); 4251 idx = result.get(); 4252 } 4253 4254 // Build an unanalyzed expression if either operand is type-dependent. 4255 if (getLangOpts().CPlusPlus && 4256 (base->isTypeDependent() || idx->isTypeDependent())) { 4257 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4258 VK_LValue, OK_Ordinary, rbLoc); 4259 } 4260 4261 // MSDN, property (C++) 4262 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4263 // This attribute can also be used in the declaration of an empty array in a 4264 // class or structure definition. For example: 4265 // __declspec(property(get=GetX, put=PutX)) int x[]; 4266 // The above statement indicates that x[] can be used with one or more array 4267 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4268 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4269 if (IsMSPropertySubscript) { 4270 // Build MS property subscript expression if base is MS property reference 4271 // or MS property subscript. 4272 return new (Context) MSPropertySubscriptExpr( 4273 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4274 } 4275 4276 // Use C++ overloaded-operator rules if either operand has record 4277 // type. The spec says to do this if either type is *overloadable*, 4278 // but enum types can't declare subscript operators or conversion 4279 // operators, so there's nothing interesting for overload resolution 4280 // to do if there aren't any record types involved. 4281 // 4282 // ObjC pointers have their own subscripting logic that is not tied 4283 // to overload resolution and so should not take this path. 4284 if (getLangOpts().CPlusPlus && 4285 (base->getType()->isRecordType() || 4286 (!base->getType()->isObjCObjectPointerType() && 4287 idx->getType()->isRecordType()))) { 4288 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4289 } 4290 4291 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4292 4293 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4294 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4295 4296 return Res; 4297 } 4298 4299 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4300 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4301 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4302 4303 // For expressions like `&(*s).b`, the base is recorded and what should be 4304 // checked. 4305 const MemberExpr *Member = nullptr; 4306 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4307 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4308 4309 LastRecord.PossibleDerefs.erase(StrippedExpr); 4310 } 4311 4312 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4313 QualType ResultTy = E->getType(); 4314 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4315 4316 // Bail if the element is an array since it is not memory access. 4317 if (isa<ArrayType>(ResultTy)) 4318 return; 4319 4320 if (ResultTy->hasAttr(attr::NoDeref)) { 4321 LastRecord.PossibleDerefs.insert(E); 4322 return; 4323 } 4324 4325 // Check if the base type is a pointer to a member access of a struct 4326 // marked with noderef. 4327 const Expr *Base = E->getBase(); 4328 QualType BaseTy = Base->getType(); 4329 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4330 // Not a pointer access 4331 return; 4332 4333 const MemberExpr *Member = nullptr; 4334 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4335 Member->isArrow()) 4336 Base = Member->getBase(); 4337 4338 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4339 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4340 LastRecord.PossibleDerefs.insert(E); 4341 } 4342 } 4343 4344 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4345 Expr *LowerBound, 4346 SourceLocation ColonLoc, Expr *Length, 4347 SourceLocation RBLoc) { 4348 if (Base->getType()->isPlaceholderType() && 4349 !Base->getType()->isSpecificPlaceholderType( 4350 BuiltinType::OMPArraySection)) { 4351 ExprResult Result = CheckPlaceholderExpr(Base); 4352 if (Result.isInvalid()) 4353 return ExprError(); 4354 Base = Result.get(); 4355 } 4356 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4357 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4358 if (Result.isInvalid()) 4359 return ExprError(); 4360 Result = DefaultLvalueConversion(Result.get()); 4361 if (Result.isInvalid()) 4362 return ExprError(); 4363 LowerBound = Result.get(); 4364 } 4365 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4366 ExprResult Result = CheckPlaceholderExpr(Length); 4367 if (Result.isInvalid()) 4368 return ExprError(); 4369 Result = DefaultLvalueConversion(Result.get()); 4370 if (Result.isInvalid()) 4371 return ExprError(); 4372 Length = Result.get(); 4373 } 4374 4375 // Build an unanalyzed expression if either operand is type-dependent. 4376 if (Base->isTypeDependent() || 4377 (LowerBound && 4378 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4379 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4380 return new (Context) 4381 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4382 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4383 } 4384 4385 // Perform default conversions. 4386 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4387 QualType ResultTy; 4388 if (OriginalTy->isAnyPointerType()) { 4389 ResultTy = OriginalTy->getPointeeType(); 4390 } else if (OriginalTy->isArrayType()) { 4391 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4392 } else { 4393 return ExprError( 4394 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4395 << Base->getSourceRange()); 4396 } 4397 // C99 6.5.2.1p1 4398 if (LowerBound) { 4399 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4400 LowerBound); 4401 if (Res.isInvalid()) 4402 return ExprError(Diag(LowerBound->getExprLoc(), 4403 diag::err_omp_typecheck_section_not_integer) 4404 << 0 << LowerBound->getSourceRange()); 4405 LowerBound = Res.get(); 4406 4407 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4408 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4409 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4410 << 0 << LowerBound->getSourceRange(); 4411 } 4412 if (Length) { 4413 auto Res = 4414 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4415 if (Res.isInvalid()) 4416 return ExprError(Diag(Length->getExprLoc(), 4417 diag::err_omp_typecheck_section_not_integer) 4418 << 1 << Length->getSourceRange()); 4419 Length = Res.get(); 4420 4421 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4422 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4423 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4424 << 1 << Length->getSourceRange(); 4425 } 4426 4427 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4428 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4429 // type. Note that functions are not objects, and that (in C99 parlance) 4430 // incomplete types are not object types. 4431 if (ResultTy->isFunctionType()) { 4432 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4433 << ResultTy << Base->getSourceRange(); 4434 return ExprError(); 4435 } 4436 4437 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4438 diag::err_omp_section_incomplete_type, Base)) 4439 return ExprError(); 4440 4441 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4442 Expr::EvalResult Result; 4443 if (LowerBound->EvaluateAsInt(Result, Context)) { 4444 // OpenMP 4.5, [2.4 Array Sections] 4445 // The array section must be a subset of the original array. 4446 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4447 if (LowerBoundValue.isNegative()) { 4448 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4449 << LowerBound->getSourceRange(); 4450 return ExprError(); 4451 } 4452 } 4453 } 4454 4455 if (Length) { 4456 Expr::EvalResult Result; 4457 if (Length->EvaluateAsInt(Result, Context)) { 4458 // OpenMP 4.5, [2.4 Array Sections] 4459 // The length must evaluate to non-negative integers. 4460 llvm::APSInt LengthValue = Result.Val.getInt(); 4461 if (LengthValue.isNegative()) { 4462 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4463 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4464 << Length->getSourceRange(); 4465 return ExprError(); 4466 } 4467 } 4468 } else if (ColonLoc.isValid() && 4469 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4470 !OriginalTy->isVariableArrayType()))) { 4471 // OpenMP 4.5, [2.4 Array Sections] 4472 // When the size of the array dimension is not known, the length must be 4473 // specified explicitly. 4474 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4475 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4476 return ExprError(); 4477 } 4478 4479 if (!Base->getType()->isSpecificPlaceholderType( 4480 BuiltinType::OMPArraySection)) { 4481 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4482 if (Result.isInvalid()) 4483 return ExprError(); 4484 Base = Result.get(); 4485 } 4486 return new (Context) 4487 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4488 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4489 } 4490 4491 ExprResult 4492 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4493 Expr *Idx, SourceLocation RLoc) { 4494 Expr *LHSExp = Base; 4495 Expr *RHSExp = Idx; 4496 4497 ExprValueKind VK = VK_LValue; 4498 ExprObjectKind OK = OK_Ordinary; 4499 4500 // Per C++ core issue 1213, the result is an xvalue if either operand is 4501 // a non-lvalue array, and an lvalue otherwise. 4502 if (getLangOpts().CPlusPlus11) { 4503 for (auto *Op : {LHSExp, RHSExp}) { 4504 Op = Op->IgnoreImplicit(); 4505 if (Op->getType()->isArrayType() && !Op->isLValue()) 4506 VK = VK_XValue; 4507 } 4508 } 4509 4510 // Perform default conversions. 4511 if (!LHSExp->getType()->getAs<VectorType>()) { 4512 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4513 if (Result.isInvalid()) 4514 return ExprError(); 4515 LHSExp = Result.get(); 4516 } 4517 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4518 if (Result.isInvalid()) 4519 return ExprError(); 4520 RHSExp = Result.get(); 4521 4522 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4523 4524 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4525 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4526 // in the subscript position. As a result, we need to derive the array base 4527 // and index from the expression types. 4528 Expr *BaseExpr, *IndexExpr; 4529 QualType ResultType; 4530 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4531 BaseExpr = LHSExp; 4532 IndexExpr = RHSExp; 4533 ResultType = Context.DependentTy; 4534 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4535 BaseExpr = LHSExp; 4536 IndexExpr = RHSExp; 4537 ResultType = PTy->getPointeeType(); 4538 } else if (const ObjCObjectPointerType *PTy = 4539 LHSTy->getAs<ObjCObjectPointerType>()) { 4540 BaseExpr = LHSExp; 4541 IndexExpr = RHSExp; 4542 4543 // Use custom logic if this should be the pseudo-object subscript 4544 // expression. 4545 if (!LangOpts.isSubscriptPointerArithmetic()) 4546 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4547 nullptr); 4548 4549 ResultType = PTy->getPointeeType(); 4550 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4551 // Handle the uncommon case of "123[Ptr]". 4552 BaseExpr = RHSExp; 4553 IndexExpr = LHSExp; 4554 ResultType = PTy->getPointeeType(); 4555 } else if (const ObjCObjectPointerType *PTy = 4556 RHSTy->getAs<ObjCObjectPointerType>()) { 4557 // Handle the uncommon case of "123[Ptr]". 4558 BaseExpr = RHSExp; 4559 IndexExpr = LHSExp; 4560 ResultType = PTy->getPointeeType(); 4561 if (!LangOpts.isSubscriptPointerArithmetic()) { 4562 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4563 << ResultType << BaseExpr->getSourceRange(); 4564 return ExprError(); 4565 } 4566 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4567 BaseExpr = LHSExp; // vectors: V[123] 4568 IndexExpr = RHSExp; 4569 // We apply C++ DR1213 to vector subscripting too. 4570 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4571 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4572 if (Materialized.isInvalid()) 4573 return ExprError(); 4574 LHSExp = Materialized.get(); 4575 } 4576 VK = LHSExp->getValueKind(); 4577 if (VK != VK_RValue) 4578 OK = OK_VectorComponent; 4579 4580 ResultType = VTy->getElementType(); 4581 QualType BaseType = BaseExpr->getType(); 4582 Qualifiers BaseQuals = BaseType.getQualifiers(); 4583 Qualifiers MemberQuals = ResultType.getQualifiers(); 4584 Qualifiers Combined = BaseQuals + MemberQuals; 4585 if (Combined != MemberQuals) 4586 ResultType = Context.getQualifiedType(ResultType, Combined); 4587 } else if (LHSTy->isArrayType()) { 4588 // If we see an array that wasn't promoted by 4589 // DefaultFunctionArrayLvalueConversion, it must be an array that 4590 // wasn't promoted because of the C90 rule that doesn't 4591 // allow promoting non-lvalue arrays. Warn, then 4592 // force the promotion here. 4593 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4594 << LHSExp->getSourceRange(); 4595 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4596 CK_ArrayToPointerDecay).get(); 4597 LHSTy = LHSExp->getType(); 4598 4599 BaseExpr = LHSExp; 4600 IndexExpr = RHSExp; 4601 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4602 } else if (RHSTy->isArrayType()) { 4603 // Same as previous, except for 123[f().a] case 4604 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4605 << RHSExp->getSourceRange(); 4606 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4607 CK_ArrayToPointerDecay).get(); 4608 RHSTy = RHSExp->getType(); 4609 4610 BaseExpr = RHSExp; 4611 IndexExpr = LHSExp; 4612 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4613 } else { 4614 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4615 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4616 } 4617 // C99 6.5.2.1p1 4618 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4619 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4620 << IndexExpr->getSourceRange()); 4621 4622 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4623 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4624 && !IndexExpr->isTypeDependent()) 4625 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4626 4627 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4628 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4629 // type. Note that Functions are not objects, and that (in C99 parlance) 4630 // incomplete types are not object types. 4631 if (ResultType->isFunctionType()) { 4632 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4633 << ResultType << BaseExpr->getSourceRange(); 4634 return ExprError(); 4635 } 4636 4637 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4638 // GNU extension: subscripting on pointer to void 4639 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4640 << BaseExpr->getSourceRange(); 4641 4642 // C forbids expressions of unqualified void type from being l-values. 4643 // See IsCForbiddenLValueType. 4644 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4645 } else if (!ResultType->isDependentType() && 4646 RequireCompleteType(LLoc, ResultType, 4647 diag::err_subscript_incomplete_type, BaseExpr)) 4648 return ExprError(); 4649 4650 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4651 !ResultType.isCForbiddenLValueType()); 4652 4653 return new (Context) 4654 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4655 } 4656 4657 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4658 ParmVarDecl *Param) { 4659 if (Param->hasUnparsedDefaultArg()) { 4660 Diag(CallLoc, 4661 diag::err_use_of_default_argument_to_function_declared_later) << 4662 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4663 Diag(UnparsedDefaultArgLocs[Param], 4664 diag::note_default_argument_declared_here); 4665 return true; 4666 } 4667 4668 if (Param->hasUninstantiatedDefaultArg()) { 4669 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4670 4671 EnterExpressionEvaluationContext EvalContext( 4672 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4673 4674 // Instantiate the expression. 4675 // 4676 // FIXME: Pass in a correct Pattern argument, otherwise 4677 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4678 // 4679 // template<typename T> 4680 // struct A { 4681 // static int FooImpl(); 4682 // 4683 // template<typename Tp> 4684 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4685 // // template argument list [[T], [Tp]], should be [[Tp]]. 4686 // friend A<Tp> Foo(int a); 4687 // }; 4688 // 4689 // template<typename T> 4690 // A<T> Foo(int a = A<T>::FooImpl()); 4691 MultiLevelTemplateArgumentList MutiLevelArgList 4692 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4693 4694 InstantiatingTemplate Inst(*this, CallLoc, Param, 4695 MutiLevelArgList.getInnermost()); 4696 if (Inst.isInvalid()) 4697 return true; 4698 if (Inst.isAlreadyInstantiating()) { 4699 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4700 Param->setInvalidDecl(); 4701 return true; 4702 } 4703 4704 ExprResult Result; 4705 { 4706 // C++ [dcl.fct.default]p5: 4707 // The names in the [default argument] expression are bound, and 4708 // the semantic constraints are checked, at the point where the 4709 // default argument expression appears. 4710 ContextRAII SavedContext(*this, FD); 4711 LocalInstantiationScope Local(*this); 4712 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4713 /*DirectInit*/false); 4714 } 4715 if (Result.isInvalid()) 4716 return true; 4717 4718 // Check the expression as an initializer for the parameter. 4719 InitializedEntity Entity 4720 = InitializedEntity::InitializeParameter(Context, Param); 4721 InitializationKind Kind = InitializationKind::CreateCopy( 4722 Param->getLocation(), 4723 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4724 Expr *ResultE = Result.getAs<Expr>(); 4725 4726 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4727 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4728 if (Result.isInvalid()) 4729 return true; 4730 4731 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4732 Param->getOuterLocStart()); 4733 if (Result.isInvalid()) 4734 return true; 4735 4736 // Remember the instantiated default argument. 4737 Param->setDefaultArg(Result.getAs<Expr>()); 4738 if (ASTMutationListener *L = getASTMutationListener()) { 4739 L->DefaultArgumentInstantiated(Param); 4740 } 4741 } 4742 4743 // If the default argument expression is not set yet, we are building it now. 4744 if (!Param->hasInit()) { 4745 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4746 Param->setInvalidDecl(); 4747 return true; 4748 } 4749 4750 // If the default expression creates temporaries, we need to 4751 // push them to the current stack of expression temporaries so they'll 4752 // be properly destroyed. 4753 // FIXME: We should really be rebuilding the default argument with new 4754 // bound temporaries; see the comment in PR5810. 4755 // We don't need to do that with block decls, though, because 4756 // blocks in default argument expression can never capture anything. 4757 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4758 // Set the "needs cleanups" bit regardless of whether there are 4759 // any explicit objects. 4760 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4761 4762 // Append all the objects to the cleanup list. Right now, this 4763 // should always be a no-op, because blocks in default argument 4764 // expressions should never be able to capture anything. 4765 assert(!Init->getNumObjects() && 4766 "default argument expression has capturing blocks?"); 4767 } 4768 4769 // We already type-checked the argument, so we know it works. 4770 // Just mark all of the declarations in this potentially-evaluated expression 4771 // as being "referenced". 4772 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4773 /*SkipLocalVariables=*/true); 4774 return false; 4775 } 4776 4777 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4778 FunctionDecl *FD, ParmVarDecl *Param) { 4779 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4780 return ExprError(); 4781 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4782 } 4783 4784 Sema::VariadicCallType 4785 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4786 Expr *Fn) { 4787 if (Proto && Proto->isVariadic()) { 4788 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4789 return VariadicConstructor; 4790 else if (Fn && Fn->getType()->isBlockPointerType()) 4791 return VariadicBlock; 4792 else if (FDecl) { 4793 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4794 if (Method->isInstance()) 4795 return VariadicMethod; 4796 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4797 return VariadicMethod; 4798 return VariadicFunction; 4799 } 4800 return VariadicDoesNotApply; 4801 } 4802 4803 namespace { 4804 class FunctionCallCCC : public FunctionCallFilterCCC { 4805 public: 4806 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4807 unsigned NumArgs, MemberExpr *ME) 4808 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4809 FunctionName(FuncName) {} 4810 4811 bool ValidateCandidate(const TypoCorrection &candidate) override { 4812 if (!candidate.getCorrectionSpecifier() || 4813 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4814 return false; 4815 } 4816 4817 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4818 } 4819 4820 private: 4821 const IdentifierInfo *const FunctionName; 4822 }; 4823 } 4824 4825 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4826 FunctionDecl *FDecl, 4827 ArrayRef<Expr *> Args) { 4828 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4829 DeclarationName FuncName = FDecl->getDeclName(); 4830 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4831 4832 if (TypoCorrection Corrected = S.CorrectTypo( 4833 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4834 S.getScopeForContext(S.CurContext), nullptr, 4835 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4836 Args.size(), ME), 4837 Sema::CTK_ErrorRecovery)) { 4838 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4839 if (Corrected.isOverloaded()) { 4840 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4841 OverloadCandidateSet::iterator Best; 4842 for (NamedDecl *CD : Corrected) { 4843 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4844 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4845 OCS); 4846 } 4847 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4848 case OR_Success: 4849 ND = Best->FoundDecl; 4850 Corrected.setCorrectionDecl(ND); 4851 break; 4852 default: 4853 break; 4854 } 4855 } 4856 ND = ND->getUnderlyingDecl(); 4857 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4858 return Corrected; 4859 } 4860 } 4861 return TypoCorrection(); 4862 } 4863 4864 /// ConvertArgumentsForCall - Converts the arguments specified in 4865 /// Args/NumArgs to the parameter types of the function FDecl with 4866 /// function prototype Proto. Call is the call expression itself, and 4867 /// Fn is the function expression. For a C++ member function, this 4868 /// routine does not attempt to convert the object argument. Returns 4869 /// true if the call is ill-formed. 4870 bool 4871 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4872 FunctionDecl *FDecl, 4873 const FunctionProtoType *Proto, 4874 ArrayRef<Expr *> Args, 4875 SourceLocation RParenLoc, 4876 bool IsExecConfig) { 4877 // Bail out early if calling a builtin with custom typechecking. 4878 if (FDecl) 4879 if (unsigned ID = FDecl->getBuiltinID()) 4880 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4881 return false; 4882 4883 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4884 // assignment, to the types of the corresponding parameter, ... 4885 unsigned NumParams = Proto->getNumParams(); 4886 bool Invalid = false; 4887 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4888 unsigned FnKind = Fn->getType()->isBlockPointerType() 4889 ? 1 /* block */ 4890 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4891 : 0 /* function */); 4892 4893 // If too few arguments are available (and we don't have default 4894 // arguments for the remaining parameters), don't make the call. 4895 if (Args.size() < NumParams) { 4896 if (Args.size() < MinArgs) { 4897 TypoCorrection TC; 4898 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4899 unsigned diag_id = 4900 MinArgs == NumParams && !Proto->isVariadic() 4901 ? diag::err_typecheck_call_too_few_args_suggest 4902 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4903 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4904 << static_cast<unsigned>(Args.size()) 4905 << TC.getCorrectionRange()); 4906 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4907 Diag(RParenLoc, 4908 MinArgs == NumParams && !Proto->isVariadic() 4909 ? diag::err_typecheck_call_too_few_args_one 4910 : diag::err_typecheck_call_too_few_args_at_least_one) 4911 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4912 else 4913 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4914 ? diag::err_typecheck_call_too_few_args 4915 : diag::err_typecheck_call_too_few_args_at_least) 4916 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4917 << Fn->getSourceRange(); 4918 4919 // Emit the location of the prototype. 4920 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4921 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4922 4923 return true; 4924 } 4925 // We reserve space for the default arguments when we create 4926 // the call expression, before calling ConvertArgumentsForCall. 4927 assert((Call->getNumArgs() == NumParams) && 4928 "We should have reserved space for the default arguments before!"); 4929 } 4930 4931 // If too many are passed and not variadic, error on the extras and drop 4932 // them. 4933 if (Args.size() > NumParams) { 4934 if (!Proto->isVariadic()) { 4935 TypoCorrection TC; 4936 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4937 unsigned diag_id = 4938 MinArgs == NumParams && !Proto->isVariadic() 4939 ? diag::err_typecheck_call_too_many_args_suggest 4940 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4941 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4942 << static_cast<unsigned>(Args.size()) 4943 << TC.getCorrectionRange()); 4944 } else if (NumParams == 1 && FDecl && 4945 FDecl->getParamDecl(0)->getDeclName()) 4946 Diag(Args[NumParams]->getBeginLoc(), 4947 MinArgs == NumParams 4948 ? diag::err_typecheck_call_too_many_args_one 4949 : diag::err_typecheck_call_too_many_args_at_most_one) 4950 << FnKind << FDecl->getParamDecl(0) 4951 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4952 << SourceRange(Args[NumParams]->getBeginLoc(), 4953 Args.back()->getEndLoc()); 4954 else 4955 Diag(Args[NumParams]->getBeginLoc(), 4956 MinArgs == NumParams 4957 ? diag::err_typecheck_call_too_many_args 4958 : diag::err_typecheck_call_too_many_args_at_most) 4959 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4960 << Fn->getSourceRange() 4961 << SourceRange(Args[NumParams]->getBeginLoc(), 4962 Args.back()->getEndLoc()); 4963 4964 // Emit the location of the prototype. 4965 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4966 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4967 4968 // This deletes the extra arguments. 4969 Call->shrinkNumArgs(NumParams); 4970 return true; 4971 } 4972 } 4973 SmallVector<Expr *, 8> AllArgs; 4974 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4975 4976 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4977 AllArgs, CallType); 4978 if (Invalid) 4979 return true; 4980 unsigned TotalNumArgs = AllArgs.size(); 4981 for (unsigned i = 0; i < TotalNumArgs; ++i) 4982 Call->setArg(i, AllArgs[i]); 4983 4984 return false; 4985 } 4986 4987 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4988 const FunctionProtoType *Proto, 4989 unsigned FirstParam, ArrayRef<Expr *> Args, 4990 SmallVectorImpl<Expr *> &AllArgs, 4991 VariadicCallType CallType, bool AllowExplicit, 4992 bool IsListInitialization) { 4993 unsigned NumParams = Proto->getNumParams(); 4994 bool Invalid = false; 4995 size_t ArgIx = 0; 4996 // Continue to check argument types (even if we have too few/many args). 4997 for (unsigned i = FirstParam; i < NumParams; i++) { 4998 QualType ProtoArgType = Proto->getParamType(i); 4999 5000 Expr *Arg; 5001 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5002 if (ArgIx < Args.size()) { 5003 Arg = Args[ArgIx++]; 5004 5005 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5006 diag::err_call_incomplete_argument, Arg)) 5007 return true; 5008 5009 // Strip the unbridged-cast placeholder expression off, if applicable. 5010 bool CFAudited = false; 5011 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5012 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5013 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5014 Arg = stripARCUnbridgedCast(Arg); 5015 else if (getLangOpts().ObjCAutoRefCount && 5016 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5017 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5018 CFAudited = true; 5019 5020 if (Proto->getExtParameterInfo(i).isNoEscape()) 5021 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5022 BE->getBlockDecl()->setDoesNotEscape(); 5023 5024 InitializedEntity Entity = 5025 Param ? InitializedEntity::InitializeParameter(Context, Param, 5026 ProtoArgType) 5027 : InitializedEntity::InitializeParameter( 5028 Context, ProtoArgType, Proto->isParamConsumed(i)); 5029 5030 // Remember that parameter belongs to a CF audited API. 5031 if (CFAudited) 5032 Entity.setParameterCFAudited(); 5033 5034 ExprResult ArgE = PerformCopyInitialization( 5035 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5036 if (ArgE.isInvalid()) 5037 return true; 5038 5039 Arg = ArgE.getAs<Expr>(); 5040 } else { 5041 assert(Param && "can't use default arguments without a known callee"); 5042 5043 ExprResult ArgExpr = 5044 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5045 if (ArgExpr.isInvalid()) 5046 return true; 5047 5048 Arg = ArgExpr.getAs<Expr>(); 5049 } 5050 5051 // Check for array bounds violations for each argument to the call. This 5052 // check only triggers warnings when the argument isn't a more complex Expr 5053 // with its own checking, such as a BinaryOperator. 5054 CheckArrayAccess(Arg); 5055 5056 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5057 CheckStaticArrayArgument(CallLoc, Param, Arg); 5058 5059 AllArgs.push_back(Arg); 5060 } 5061 5062 // If this is a variadic call, handle args passed through "...". 5063 if (CallType != VariadicDoesNotApply) { 5064 // Assume that extern "C" functions with variadic arguments that 5065 // return __unknown_anytype aren't *really* variadic. 5066 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5067 FDecl->isExternC()) { 5068 for (Expr *A : Args.slice(ArgIx)) { 5069 QualType paramType; // ignored 5070 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5071 Invalid |= arg.isInvalid(); 5072 AllArgs.push_back(arg.get()); 5073 } 5074 5075 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5076 } else { 5077 for (Expr *A : Args.slice(ArgIx)) { 5078 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5079 Invalid |= Arg.isInvalid(); 5080 AllArgs.push_back(Arg.get()); 5081 } 5082 } 5083 5084 // Check for array bounds violations. 5085 for (Expr *A : Args.slice(ArgIx)) 5086 CheckArrayAccess(A); 5087 } 5088 return Invalid; 5089 } 5090 5091 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5092 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5093 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5094 TL = DTL.getOriginalLoc(); 5095 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5096 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5097 << ATL.getLocalSourceRange(); 5098 } 5099 5100 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5101 /// array parameter, check that it is non-null, and that if it is formed by 5102 /// array-to-pointer decay, the underlying array is sufficiently large. 5103 /// 5104 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5105 /// array type derivation, then for each call to the function, the value of the 5106 /// corresponding actual argument shall provide access to the first element of 5107 /// an array with at least as many elements as specified by the size expression. 5108 void 5109 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5110 ParmVarDecl *Param, 5111 const Expr *ArgExpr) { 5112 // Static array parameters are not supported in C++. 5113 if (!Param || getLangOpts().CPlusPlus) 5114 return; 5115 5116 QualType OrigTy = Param->getOriginalType(); 5117 5118 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5119 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5120 return; 5121 5122 if (ArgExpr->isNullPointerConstant(Context, 5123 Expr::NPC_NeverValueDependent)) { 5124 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5125 DiagnoseCalleeStaticArrayParam(*this, Param); 5126 return; 5127 } 5128 5129 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5130 if (!CAT) 5131 return; 5132 5133 const ConstantArrayType *ArgCAT = 5134 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5135 if (!ArgCAT) 5136 return; 5137 5138 if (ArgCAT->getSize().ult(CAT->getSize())) { 5139 Diag(CallLoc, diag::warn_static_array_too_small) 5140 << ArgExpr->getSourceRange() 5141 << (unsigned) ArgCAT->getSize().getZExtValue() 5142 << (unsigned) CAT->getSize().getZExtValue(); 5143 DiagnoseCalleeStaticArrayParam(*this, Param); 5144 } 5145 } 5146 5147 /// Given a function expression of unknown-any type, try to rebuild it 5148 /// to have a function type. 5149 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5150 5151 /// Is the given type a placeholder that we need to lower out 5152 /// immediately during argument processing? 5153 static bool isPlaceholderToRemoveAsArg(QualType type) { 5154 // Placeholders are never sugared. 5155 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5156 if (!placeholder) return false; 5157 5158 switch (placeholder->getKind()) { 5159 // Ignore all the non-placeholder types. 5160 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5161 case BuiltinType::Id: 5162 #include "clang/Basic/OpenCLImageTypes.def" 5163 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5164 case BuiltinType::Id: 5165 #include "clang/Basic/OpenCLExtensionTypes.def" 5166 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5167 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5168 #include "clang/AST/BuiltinTypes.def" 5169 return false; 5170 5171 // We cannot lower out overload sets; they might validly be resolved 5172 // by the call machinery. 5173 case BuiltinType::Overload: 5174 return false; 5175 5176 // Unbridged casts in ARC can be handled in some call positions and 5177 // should be left in place. 5178 case BuiltinType::ARCUnbridgedCast: 5179 return false; 5180 5181 // Pseudo-objects should be converted as soon as possible. 5182 case BuiltinType::PseudoObject: 5183 return true; 5184 5185 // The debugger mode could theoretically but currently does not try 5186 // to resolve unknown-typed arguments based on known parameter types. 5187 case BuiltinType::UnknownAny: 5188 return true; 5189 5190 // These are always invalid as call arguments and should be reported. 5191 case BuiltinType::BoundMember: 5192 case BuiltinType::BuiltinFn: 5193 case BuiltinType::OMPArraySection: 5194 return true; 5195 5196 } 5197 llvm_unreachable("bad builtin type kind"); 5198 } 5199 5200 /// Check an argument list for placeholders that we won't try to 5201 /// handle later. 5202 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5203 // Apply this processing to all the arguments at once instead of 5204 // dying at the first failure. 5205 bool hasInvalid = false; 5206 for (size_t i = 0, e = args.size(); i != e; i++) { 5207 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5208 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5209 if (result.isInvalid()) hasInvalid = true; 5210 else args[i] = result.get(); 5211 } else if (hasInvalid) { 5212 (void)S.CorrectDelayedTyposInExpr(args[i]); 5213 } 5214 } 5215 return hasInvalid; 5216 } 5217 5218 /// If a builtin function has a pointer argument with no explicit address 5219 /// space, then it should be able to accept a pointer to any address 5220 /// space as input. In order to do this, we need to replace the 5221 /// standard builtin declaration with one that uses the same address space 5222 /// as the call. 5223 /// 5224 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5225 /// it does not contain any pointer arguments without 5226 /// an address space qualifer. Otherwise the rewritten 5227 /// FunctionDecl is returned. 5228 /// TODO: Handle pointer return types. 5229 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5230 const FunctionDecl *FDecl, 5231 MultiExprArg ArgExprs) { 5232 5233 QualType DeclType = FDecl->getType(); 5234 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5235 5236 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5237 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5238 return nullptr; 5239 5240 bool NeedsNewDecl = false; 5241 unsigned i = 0; 5242 SmallVector<QualType, 8> OverloadParams; 5243 5244 for (QualType ParamType : FT->param_types()) { 5245 5246 // Convert array arguments to pointer to simplify type lookup. 5247 ExprResult ArgRes = 5248 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5249 if (ArgRes.isInvalid()) 5250 return nullptr; 5251 Expr *Arg = ArgRes.get(); 5252 QualType ArgType = Arg->getType(); 5253 if (!ParamType->isPointerType() || 5254 ParamType.getQualifiers().hasAddressSpace() || 5255 !ArgType->isPointerType() || 5256 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5257 OverloadParams.push_back(ParamType); 5258 continue; 5259 } 5260 5261 QualType PointeeType = ParamType->getPointeeType(); 5262 if (PointeeType.getQualifiers().hasAddressSpace()) 5263 continue; 5264 5265 NeedsNewDecl = true; 5266 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5267 5268 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5269 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5270 } 5271 5272 if (!NeedsNewDecl) 5273 return nullptr; 5274 5275 FunctionProtoType::ExtProtoInfo EPI; 5276 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5277 OverloadParams, EPI); 5278 DeclContext *Parent = Context.getTranslationUnitDecl(); 5279 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5280 FDecl->getLocation(), 5281 FDecl->getLocation(), 5282 FDecl->getIdentifier(), 5283 OverloadTy, 5284 /*TInfo=*/nullptr, 5285 SC_Extern, false, 5286 /*hasPrototype=*/true); 5287 SmallVector<ParmVarDecl*, 16> Params; 5288 FT = cast<FunctionProtoType>(OverloadTy); 5289 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5290 QualType ParamType = FT->getParamType(i); 5291 ParmVarDecl *Parm = 5292 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5293 SourceLocation(), nullptr, ParamType, 5294 /*TInfo=*/nullptr, SC_None, nullptr); 5295 Parm->setScopeInfo(0, i); 5296 Params.push_back(Parm); 5297 } 5298 OverloadDecl->setParams(Params); 5299 return OverloadDecl; 5300 } 5301 5302 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5303 FunctionDecl *Callee, 5304 MultiExprArg ArgExprs) { 5305 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5306 // similar attributes) really don't like it when functions are called with an 5307 // invalid number of args. 5308 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5309 /*PartialOverloading=*/false) && 5310 !Callee->isVariadic()) 5311 return; 5312 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5313 return; 5314 5315 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5316 S.Diag(Fn->getBeginLoc(), 5317 isa<CXXMethodDecl>(Callee) 5318 ? diag::err_ovl_no_viable_member_function_in_call 5319 : diag::err_ovl_no_viable_function_in_call) 5320 << Callee << Callee->getSourceRange(); 5321 S.Diag(Callee->getLocation(), 5322 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5323 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5324 return; 5325 } 5326 } 5327 5328 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5329 const UnresolvedMemberExpr *const UME, Sema &S) { 5330 5331 const auto GetFunctionLevelDCIfCXXClass = 5332 [](Sema &S) -> const CXXRecordDecl * { 5333 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5334 if (!DC || !DC->getParent()) 5335 return nullptr; 5336 5337 // If the call to some member function was made from within a member 5338 // function body 'M' return return 'M's parent. 5339 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5340 return MD->getParent()->getCanonicalDecl(); 5341 // else the call was made from within a default member initializer of a 5342 // class, so return the class. 5343 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5344 return RD->getCanonicalDecl(); 5345 return nullptr; 5346 }; 5347 // If our DeclContext is neither a member function nor a class (in the 5348 // case of a lambda in a default member initializer), we can't have an 5349 // enclosing 'this'. 5350 5351 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5352 if (!CurParentClass) 5353 return false; 5354 5355 // The naming class for implicit member functions call is the class in which 5356 // name lookup starts. 5357 const CXXRecordDecl *const NamingClass = 5358 UME->getNamingClass()->getCanonicalDecl(); 5359 assert(NamingClass && "Must have naming class even for implicit access"); 5360 5361 // If the unresolved member functions were found in a 'naming class' that is 5362 // related (either the same or derived from) to the class that contains the 5363 // member function that itself contained the implicit member access. 5364 5365 return CurParentClass == NamingClass || 5366 CurParentClass->isDerivedFrom(NamingClass); 5367 } 5368 5369 static void 5370 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5371 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5372 5373 if (!UME) 5374 return; 5375 5376 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5377 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5378 // already been captured, or if this is an implicit member function call (if 5379 // it isn't, an attempt to capture 'this' should already have been made). 5380 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5381 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5382 return; 5383 5384 // Check if the naming class in which the unresolved members were found is 5385 // related (same as or is a base of) to the enclosing class. 5386 5387 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5388 return; 5389 5390 5391 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5392 // If the enclosing function is not dependent, then this lambda is 5393 // capture ready, so if we can capture this, do so. 5394 if (!EnclosingFunctionCtx->isDependentContext()) { 5395 // If the current lambda and all enclosing lambdas can capture 'this' - 5396 // then go ahead and capture 'this' (since our unresolved overload set 5397 // contains at least one non-static member function). 5398 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5399 S.CheckCXXThisCapture(CallLoc); 5400 } else if (S.CurContext->isDependentContext()) { 5401 // ... since this is an implicit member reference, that might potentially 5402 // involve a 'this' capture, mark 'this' for potential capture in 5403 // enclosing lambdas. 5404 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5405 CurLSI->addPotentialThisCapture(CallLoc); 5406 } 5407 } 5408 5409 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5410 /// This provides the location of the left/right parens and a list of comma 5411 /// locations. 5412 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5413 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5414 Expr *ExecConfig, bool IsExecConfig) { 5415 // Since this might be a postfix expression, get rid of ParenListExprs. 5416 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5417 if (Result.isInvalid()) return ExprError(); 5418 Fn = Result.get(); 5419 5420 if (checkArgsForPlaceholders(*this, ArgExprs)) 5421 return ExprError(); 5422 5423 if (getLangOpts().CPlusPlus) { 5424 // If this is a pseudo-destructor expression, build the call immediately. 5425 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5426 if (!ArgExprs.empty()) { 5427 // Pseudo-destructor calls should not have any arguments. 5428 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5429 << FixItHint::CreateRemoval( 5430 SourceRange(ArgExprs.front()->getBeginLoc(), 5431 ArgExprs.back()->getEndLoc())); 5432 } 5433 5434 return new (Context) 5435 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5436 } 5437 if (Fn->getType() == Context.PseudoObjectTy) { 5438 ExprResult result = CheckPlaceholderExpr(Fn); 5439 if (result.isInvalid()) return ExprError(); 5440 Fn = result.get(); 5441 } 5442 5443 // Determine whether this is a dependent call inside a C++ template, 5444 // in which case we won't do any semantic analysis now. 5445 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5446 if (ExecConfig) { 5447 return new (Context) CUDAKernelCallExpr( 5448 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5449 Context.DependentTy, VK_RValue, RParenLoc); 5450 } else { 5451 5452 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5453 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5454 Fn->getBeginLoc()); 5455 5456 return new (Context) CallExpr( 5457 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5458 } 5459 } 5460 5461 // Determine whether this is a call to an object (C++ [over.call.object]). 5462 if (Fn->getType()->isRecordType()) 5463 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5464 RParenLoc); 5465 5466 if (Fn->getType() == Context.UnknownAnyTy) { 5467 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5468 if (result.isInvalid()) return ExprError(); 5469 Fn = result.get(); 5470 } 5471 5472 if (Fn->getType() == Context.BoundMemberTy) { 5473 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5474 RParenLoc); 5475 } 5476 } 5477 5478 // Check for overloaded calls. This can happen even in C due to extensions. 5479 if (Fn->getType() == Context.OverloadTy) { 5480 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5481 5482 // We aren't supposed to apply this logic if there's an '&' involved. 5483 if (!find.HasFormOfMemberPointer) { 5484 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5485 return new (Context) CallExpr( 5486 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5487 OverloadExpr *ovl = find.Expression; 5488 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5489 return BuildOverloadedCallExpr( 5490 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5491 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5492 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5493 RParenLoc); 5494 } 5495 } 5496 5497 // If we're directly calling a function, get the appropriate declaration. 5498 if (Fn->getType() == Context.UnknownAnyTy) { 5499 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5500 if (result.isInvalid()) return ExprError(); 5501 Fn = result.get(); 5502 } 5503 5504 Expr *NakedFn = Fn->IgnoreParens(); 5505 5506 bool CallingNDeclIndirectly = false; 5507 NamedDecl *NDecl = nullptr; 5508 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5509 if (UnOp->getOpcode() == UO_AddrOf) { 5510 CallingNDeclIndirectly = true; 5511 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5512 } 5513 } 5514 5515 if (isa<DeclRefExpr>(NakedFn)) { 5516 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5517 5518 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5519 if (FDecl && FDecl->getBuiltinID()) { 5520 // Rewrite the function decl for this builtin by replacing parameters 5521 // with no explicit address space with the address space of the arguments 5522 // in ArgExprs. 5523 if ((FDecl = 5524 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5525 NDecl = FDecl; 5526 Fn = DeclRefExpr::Create( 5527 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5528 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5529 } 5530 } 5531 } else if (isa<MemberExpr>(NakedFn)) 5532 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5533 5534 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5535 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5536 FD, /*Complain=*/true, Fn->getBeginLoc())) 5537 return ExprError(); 5538 5539 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5540 return ExprError(); 5541 5542 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5543 } 5544 5545 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5546 ExecConfig, IsExecConfig); 5547 } 5548 5549 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5550 /// 5551 /// __builtin_astype( value, dst type ) 5552 /// 5553 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5554 SourceLocation BuiltinLoc, 5555 SourceLocation RParenLoc) { 5556 ExprValueKind VK = VK_RValue; 5557 ExprObjectKind OK = OK_Ordinary; 5558 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5559 QualType SrcTy = E->getType(); 5560 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5561 return ExprError(Diag(BuiltinLoc, 5562 diag::err_invalid_astype_of_different_size) 5563 << DstTy 5564 << SrcTy 5565 << E->getSourceRange()); 5566 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5567 } 5568 5569 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5570 /// provided arguments. 5571 /// 5572 /// __builtin_convertvector( value, dst type ) 5573 /// 5574 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5575 SourceLocation BuiltinLoc, 5576 SourceLocation RParenLoc) { 5577 TypeSourceInfo *TInfo; 5578 GetTypeFromParser(ParsedDestTy, &TInfo); 5579 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5580 } 5581 5582 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5583 /// i.e. an expression not of \p OverloadTy. The expression should 5584 /// unary-convert to an expression of function-pointer or 5585 /// block-pointer type. 5586 /// 5587 /// \param NDecl the declaration being called, if available 5588 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5589 SourceLocation LParenLoc, 5590 ArrayRef<Expr *> Args, 5591 SourceLocation RParenLoc, Expr *Config, 5592 bool IsExecConfig, ADLCallKind UsesADL) { 5593 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5594 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5595 5596 // Functions with 'interrupt' attribute cannot be called directly. 5597 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5598 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5599 return ExprError(); 5600 } 5601 5602 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5603 // so there's some risk when calling out to non-interrupt handler functions 5604 // that the callee might not preserve them. This is easy to diagnose here, 5605 // but can be very challenging to debug. 5606 if (auto *Caller = getCurFunctionDecl()) 5607 if (Caller->hasAttr<ARMInterruptAttr>()) { 5608 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5609 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5610 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5611 } 5612 5613 // Promote the function operand. 5614 // We special-case function promotion here because we only allow promoting 5615 // builtin functions to function pointers in the callee of a call. 5616 ExprResult Result; 5617 QualType ResultTy; 5618 if (BuiltinID && 5619 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5620 // Extract the return type from the (builtin) function pointer type. 5621 // FIXME Several builtins still have setType in 5622 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5623 // Builtins.def to ensure they are correct before removing setType calls. 5624 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5625 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5626 ResultTy = FDecl->getCallResultType(); 5627 } else { 5628 Result = CallExprUnaryConversions(Fn); 5629 ResultTy = Context.BoolTy; 5630 } 5631 if (Result.isInvalid()) 5632 return ExprError(); 5633 Fn = Result.get(); 5634 5635 // Check for a valid function type, but only if it is not a builtin which 5636 // requires custom type checking. These will be handled by 5637 // CheckBuiltinFunctionCall below just after creation of the call expression. 5638 const FunctionType *FuncT = nullptr; 5639 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5640 retry: 5641 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5642 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5643 // have type pointer to function". 5644 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5645 if (!FuncT) 5646 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5647 << Fn->getType() << Fn->getSourceRange()); 5648 } else if (const BlockPointerType *BPT = 5649 Fn->getType()->getAs<BlockPointerType>()) { 5650 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5651 } else { 5652 // Handle calls to expressions of unknown-any type. 5653 if (Fn->getType() == Context.UnknownAnyTy) { 5654 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5655 if (rewrite.isInvalid()) return ExprError(); 5656 Fn = rewrite.get(); 5657 goto retry; 5658 } 5659 5660 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5661 << Fn->getType() << Fn->getSourceRange()); 5662 } 5663 } 5664 5665 // Get the number of parameters in the function prototype, if any. 5666 // We will allocate space for max(Args.size(), NumParams) arguments 5667 // in the call expression. 5668 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5669 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5670 5671 CallExpr *TheCall; 5672 if (Config) { 5673 assert(UsesADL == ADLCallKind::NotADL && 5674 "CUDAKernelCallExpr should not use ADL"); 5675 TheCall = new (Context) 5676 CUDAKernelCallExpr(Context, Fn, cast<CallExpr>(Config), Args, ResultTy, 5677 VK_RValue, RParenLoc, NumParams); 5678 } else { 5679 TheCall = new (Context) CallExpr(Context, Fn, Args, ResultTy, VK_RValue, 5680 RParenLoc, NumParams, UsesADL); 5681 } 5682 5683 if (!getLangOpts().CPlusPlus) { 5684 // C cannot always handle TypoExpr nodes in builtin calls and direct 5685 // function calls as their argument checking don't necessarily handle 5686 // dependent types properly, so make sure any TypoExprs have been 5687 // dealt with. 5688 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5689 if (!Result.isUsable()) return ExprError(); 5690 TheCall = dyn_cast<CallExpr>(Result.get()); 5691 if (!TheCall) return Result; 5692 // TheCall at this point has max(Args.size(), NumParams) arguments, 5693 // with extra arguments nulled. We don't want to introduce nulled 5694 // arguments in Args and so we only take the first Args.size() arguments. 5695 Args = llvm::makeArrayRef(TheCall->getArgs(), Args.size()); 5696 } 5697 5698 // Bail out early if calling a builtin with custom type checking. 5699 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5700 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5701 5702 if (getLangOpts().CUDA) { 5703 if (Config) { 5704 // CUDA: Kernel calls must be to global functions 5705 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5706 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5707 << FDecl << Fn->getSourceRange()); 5708 5709 // CUDA: Kernel function must have 'void' return type 5710 if (!FuncT->getReturnType()->isVoidType()) 5711 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5712 << Fn->getType() << Fn->getSourceRange()); 5713 } else { 5714 // CUDA: Calls to global functions must be configured 5715 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5716 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5717 << FDecl << Fn->getSourceRange()); 5718 } 5719 } 5720 5721 // Check for a valid return type 5722 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5723 FDecl)) 5724 return ExprError(); 5725 5726 // We know the result type of the call, set it. 5727 TheCall->setType(FuncT->getCallResultType(Context)); 5728 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5729 5730 if (Proto) { 5731 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5732 IsExecConfig)) 5733 return ExprError(); 5734 } else { 5735 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5736 5737 if (FDecl) { 5738 // Check if we have too few/too many template arguments, based 5739 // on our knowledge of the function definition. 5740 const FunctionDecl *Def = nullptr; 5741 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5742 Proto = Def->getType()->getAs<FunctionProtoType>(); 5743 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5744 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5745 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5746 } 5747 5748 // If the function we're calling isn't a function prototype, but we have 5749 // a function prototype from a prior declaratiom, use that prototype. 5750 if (!FDecl->hasPrototype()) 5751 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5752 } 5753 5754 // Promote the arguments (C99 6.5.2.2p6). 5755 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5756 Expr *Arg = Args[i]; 5757 5758 if (Proto && i < Proto->getNumParams()) { 5759 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5760 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5761 ExprResult ArgE = 5762 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5763 if (ArgE.isInvalid()) 5764 return true; 5765 5766 Arg = ArgE.getAs<Expr>(); 5767 5768 } else { 5769 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5770 5771 if (ArgE.isInvalid()) 5772 return true; 5773 5774 Arg = ArgE.getAs<Expr>(); 5775 } 5776 5777 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5778 diag::err_call_incomplete_argument, Arg)) 5779 return ExprError(); 5780 5781 TheCall->setArg(i, Arg); 5782 } 5783 } 5784 5785 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5786 if (!Method->isStatic()) 5787 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5788 << Fn->getSourceRange()); 5789 5790 // Check for sentinels 5791 if (NDecl) 5792 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5793 5794 // Do special checking on direct calls to functions. 5795 if (FDecl) { 5796 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5797 return ExprError(); 5798 5799 if (BuiltinID) 5800 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5801 } else if (NDecl) { 5802 if (CheckPointerCall(NDecl, TheCall, Proto)) 5803 return ExprError(); 5804 } else { 5805 if (CheckOtherCall(TheCall, Proto)) 5806 return ExprError(); 5807 } 5808 5809 return MaybeBindToTemporary(TheCall); 5810 } 5811 5812 ExprResult 5813 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5814 SourceLocation RParenLoc, Expr *InitExpr) { 5815 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5816 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5817 5818 TypeSourceInfo *TInfo; 5819 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5820 if (!TInfo) 5821 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5822 5823 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5824 } 5825 5826 ExprResult 5827 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5828 SourceLocation RParenLoc, Expr *LiteralExpr) { 5829 QualType literalType = TInfo->getType(); 5830 5831 if (literalType->isArrayType()) { 5832 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5833 diag::err_illegal_decl_array_incomplete_type, 5834 SourceRange(LParenLoc, 5835 LiteralExpr->getSourceRange().getEnd()))) 5836 return ExprError(); 5837 if (literalType->isVariableArrayType()) 5838 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5839 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5840 } else if (!literalType->isDependentType() && 5841 RequireCompleteType(LParenLoc, literalType, 5842 diag::err_typecheck_decl_incomplete_type, 5843 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5844 return ExprError(); 5845 5846 InitializedEntity Entity 5847 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5848 InitializationKind Kind 5849 = InitializationKind::CreateCStyleCast(LParenLoc, 5850 SourceRange(LParenLoc, RParenLoc), 5851 /*InitList=*/true); 5852 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5853 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5854 &literalType); 5855 if (Result.isInvalid()) 5856 return ExprError(); 5857 LiteralExpr = Result.get(); 5858 5859 bool isFileScope = !CurContext->isFunctionOrMethod(); 5860 5861 // In C, compound literals are l-values for some reason. 5862 // For GCC compatibility, in C++, file-scope array compound literals with 5863 // constant initializers are also l-values, and compound literals are 5864 // otherwise prvalues. 5865 // 5866 // (GCC also treats C++ list-initialized file-scope array prvalues with 5867 // constant initializers as l-values, but that's non-conforming, so we don't 5868 // follow it there.) 5869 // 5870 // FIXME: It would be better to handle the lvalue cases as materializing and 5871 // lifetime-extending a temporary object, but our materialized temporaries 5872 // representation only supports lifetime extension from a variable, not "out 5873 // of thin air". 5874 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5875 // is bound to the result of applying array-to-pointer decay to the compound 5876 // literal. 5877 // FIXME: GCC supports compound literals of reference type, which should 5878 // obviously have a value kind derived from the kind of reference involved. 5879 ExprValueKind VK = 5880 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5881 ? VK_RValue 5882 : VK_LValue; 5883 5884 if (isFileScope) 5885 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 5886 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 5887 Expr *Init = ILE->getInit(i); 5888 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 5889 } 5890 5891 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5892 VK, LiteralExpr, isFileScope); 5893 if (isFileScope) { 5894 if (!LiteralExpr->isTypeDependent() && 5895 !LiteralExpr->isValueDependent() && 5896 !literalType->isDependentType()) // C99 6.5.2.5p3 5897 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5898 return ExprError(); 5899 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5900 literalType.getAddressSpace() != LangAS::Default) { 5901 // Embedded-C extensions to C99 6.5.2.5: 5902 // "If the compound literal occurs inside the body of a function, the 5903 // type name shall not be qualified by an address-space qualifier." 5904 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5905 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5906 return ExprError(); 5907 } 5908 5909 return MaybeBindToTemporary(E); 5910 } 5911 5912 ExprResult 5913 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5914 SourceLocation RBraceLoc) { 5915 // Immediately handle non-overload placeholders. Overloads can be 5916 // resolved contextually, but everything else here can't. 5917 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5918 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5919 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5920 5921 // Ignore failures; dropping the entire initializer list because 5922 // of one failure would be terrible for indexing/etc. 5923 if (result.isInvalid()) continue; 5924 5925 InitArgList[I] = result.get(); 5926 } 5927 } 5928 5929 // Semantic analysis for initializers is done by ActOnDeclarator() and 5930 // CheckInitializer() - it requires knowledge of the object being initialized. 5931 5932 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5933 RBraceLoc); 5934 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5935 return E; 5936 } 5937 5938 /// Do an explicit extend of the given block pointer if we're in ARC. 5939 void Sema::maybeExtendBlockObject(ExprResult &E) { 5940 assert(E.get()->getType()->isBlockPointerType()); 5941 assert(E.get()->isRValue()); 5942 5943 // Only do this in an r-value context. 5944 if (!getLangOpts().ObjCAutoRefCount) return; 5945 5946 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5947 CK_ARCExtendBlockObject, E.get(), 5948 /*base path*/ nullptr, VK_RValue); 5949 Cleanup.setExprNeedsCleanups(true); 5950 } 5951 5952 /// Prepare a conversion of the given expression to an ObjC object 5953 /// pointer type. 5954 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5955 QualType type = E.get()->getType(); 5956 if (type->isObjCObjectPointerType()) { 5957 return CK_BitCast; 5958 } else if (type->isBlockPointerType()) { 5959 maybeExtendBlockObject(E); 5960 return CK_BlockPointerToObjCPointerCast; 5961 } else { 5962 assert(type->isPointerType()); 5963 return CK_CPointerToObjCPointerCast; 5964 } 5965 } 5966 5967 /// Prepares for a scalar cast, performing all the necessary stages 5968 /// except the final cast and returning the kind required. 5969 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5970 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5971 // Also, callers should have filtered out the invalid cases with 5972 // pointers. Everything else should be possible. 5973 5974 QualType SrcTy = Src.get()->getType(); 5975 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5976 return CK_NoOp; 5977 5978 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5979 case Type::STK_MemberPointer: 5980 llvm_unreachable("member pointer type in C"); 5981 5982 case Type::STK_CPointer: 5983 case Type::STK_BlockPointer: 5984 case Type::STK_ObjCObjectPointer: 5985 switch (DestTy->getScalarTypeKind()) { 5986 case Type::STK_CPointer: { 5987 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5988 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5989 if (SrcAS != DestAS) 5990 return CK_AddressSpaceConversion; 5991 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 5992 return CK_NoOp; 5993 return CK_BitCast; 5994 } 5995 case Type::STK_BlockPointer: 5996 return (SrcKind == Type::STK_BlockPointer 5997 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5998 case Type::STK_ObjCObjectPointer: 5999 if (SrcKind == Type::STK_ObjCObjectPointer) 6000 return CK_BitCast; 6001 if (SrcKind == Type::STK_CPointer) 6002 return CK_CPointerToObjCPointerCast; 6003 maybeExtendBlockObject(Src); 6004 return CK_BlockPointerToObjCPointerCast; 6005 case Type::STK_Bool: 6006 return CK_PointerToBoolean; 6007 case Type::STK_Integral: 6008 return CK_PointerToIntegral; 6009 case Type::STK_Floating: 6010 case Type::STK_FloatingComplex: 6011 case Type::STK_IntegralComplex: 6012 case Type::STK_MemberPointer: 6013 case Type::STK_FixedPoint: 6014 llvm_unreachable("illegal cast from pointer"); 6015 } 6016 llvm_unreachable("Should have returned before this"); 6017 6018 case Type::STK_FixedPoint: 6019 switch (DestTy->getScalarTypeKind()) { 6020 case Type::STK_FixedPoint: 6021 return CK_FixedPointCast; 6022 case Type::STK_Bool: 6023 return CK_FixedPointToBoolean; 6024 case Type::STK_Integral: 6025 case Type::STK_Floating: 6026 case Type::STK_IntegralComplex: 6027 case Type::STK_FloatingComplex: 6028 Diag(Src.get()->getExprLoc(), 6029 diag::err_unimplemented_conversion_with_fixed_point_type) 6030 << DestTy; 6031 return CK_IntegralCast; 6032 case Type::STK_CPointer: 6033 case Type::STK_ObjCObjectPointer: 6034 case Type::STK_BlockPointer: 6035 case Type::STK_MemberPointer: 6036 llvm_unreachable("illegal cast to pointer type"); 6037 } 6038 llvm_unreachable("Should have returned before this"); 6039 6040 case Type::STK_Bool: // casting from bool is like casting from an integer 6041 case Type::STK_Integral: 6042 switch (DestTy->getScalarTypeKind()) { 6043 case Type::STK_CPointer: 6044 case Type::STK_ObjCObjectPointer: 6045 case Type::STK_BlockPointer: 6046 if (Src.get()->isNullPointerConstant(Context, 6047 Expr::NPC_ValueDependentIsNull)) 6048 return CK_NullToPointer; 6049 return CK_IntegralToPointer; 6050 case Type::STK_Bool: 6051 return CK_IntegralToBoolean; 6052 case Type::STK_Integral: 6053 return CK_IntegralCast; 6054 case Type::STK_Floating: 6055 return CK_IntegralToFloating; 6056 case Type::STK_IntegralComplex: 6057 Src = ImpCastExprToType(Src.get(), 6058 DestTy->castAs<ComplexType>()->getElementType(), 6059 CK_IntegralCast); 6060 return CK_IntegralRealToComplex; 6061 case Type::STK_FloatingComplex: 6062 Src = ImpCastExprToType(Src.get(), 6063 DestTy->castAs<ComplexType>()->getElementType(), 6064 CK_IntegralToFloating); 6065 return CK_FloatingRealToComplex; 6066 case Type::STK_MemberPointer: 6067 llvm_unreachable("member pointer type in C"); 6068 case Type::STK_FixedPoint: 6069 Diag(Src.get()->getExprLoc(), 6070 diag::err_unimplemented_conversion_with_fixed_point_type) 6071 << SrcTy; 6072 return CK_IntegralCast; 6073 } 6074 llvm_unreachable("Should have returned before this"); 6075 6076 case Type::STK_Floating: 6077 switch (DestTy->getScalarTypeKind()) { 6078 case Type::STK_Floating: 6079 return CK_FloatingCast; 6080 case Type::STK_Bool: 6081 return CK_FloatingToBoolean; 6082 case Type::STK_Integral: 6083 return CK_FloatingToIntegral; 6084 case Type::STK_FloatingComplex: 6085 Src = ImpCastExprToType(Src.get(), 6086 DestTy->castAs<ComplexType>()->getElementType(), 6087 CK_FloatingCast); 6088 return CK_FloatingRealToComplex; 6089 case Type::STK_IntegralComplex: 6090 Src = ImpCastExprToType(Src.get(), 6091 DestTy->castAs<ComplexType>()->getElementType(), 6092 CK_FloatingToIntegral); 6093 return CK_IntegralRealToComplex; 6094 case Type::STK_CPointer: 6095 case Type::STK_ObjCObjectPointer: 6096 case Type::STK_BlockPointer: 6097 llvm_unreachable("valid float->pointer cast?"); 6098 case Type::STK_MemberPointer: 6099 llvm_unreachable("member pointer type in C"); 6100 case Type::STK_FixedPoint: 6101 Diag(Src.get()->getExprLoc(), 6102 diag::err_unimplemented_conversion_with_fixed_point_type) 6103 << SrcTy; 6104 return CK_IntegralCast; 6105 } 6106 llvm_unreachable("Should have returned before this"); 6107 6108 case Type::STK_FloatingComplex: 6109 switch (DestTy->getScalarTypeKind()) { 6110 case Type::STK_FloatingComplex: 6111 return CK_FloatingComplexCast; 6112 case Type::STK_IntegralComplex: 6113 return CK_FloatingComplexToIntegralComplex; 6114 case Type::STK_Floating: { 6115 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6116 if (Context.hasSameType(ET, DestTy)) 6117 return CK_FloatingComplexToReal; 6118 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6119 return CK_FloatingCast; 6120 } 6121 case Type::STK_Bool: 6122 return CK_FloatingComplexToBoolean; 6123 case Type::STK_Integral: 6124 Src = ImpCastExprToType(Src.get(), 6125 SrcTy->castAs<ComplexType>()->getElementType(), 6126 CK_FloatingComplexToReal); 6127 return CK_FloatingToIntegral; 6128 case Type::STK_CPointer: 6129 case Type::STK_ObjCObjectPointer: 6130 case Type::STK_BlockPointer: 6131 llvm_unreachable("valid complex float->pointer cast?"); 6132 case Type::STK_MemberPointer: 6133 llvm_unreachable("member pointer type in C"); 6134 case Type::STK_FixedPoint: 6135 Diag(Src.get()->getExprLoc(), 6136 diag::err_unimplemented_conversion_with_fixed_point_type) 6137 << SrcTy; 6138 return CK_IntegralCast; 6139 } 6140 llvm_unreachable("Should have returned before this"); 6141 6142 case Type::STK_IntegralComplex: 6143 switch (DestTy->getScalarTypeKind()) { 6144 case Type::STK_FloatingComplex: 6145 return CK_IntegralComplexToFloatingComplex; 6146 case Type::STK_IntegralComplex: 6147 return CK_IntegralComplexCast; 6148 case Type::STK_Integral: { 6149 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6150 if (Context.hasSameType(ET, DestTy)) 6151 return CK_IntegralComplexToReal; 6152 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6153 return CK_IntegralCast; 6154 } 6155 case Type::STK_Bool: 6156 return CK_IntegralComplexToBoolean; 6157 case Type::STK_Floating: 6158 Src = ImpCastExprToType(Src.get(), 6159 SrcTy->castAs<ComplexType>()->getElementType(), 6160 CK_IntegralComplexToReal); 6161 return CK_IntegralToFloating; 6162 case Type::STK_CPointer: 6163 case Type::STK_ObjCObjectPointer: 6164 case Type::STK_BlockPointer: 6165 llvm_unreachable("valid complex int->pointer cast?"); 6166 case Type::STK_MemberPointer: 6167 llvm_unreachable("member pointer type in C"); 6168 case Type::STK_FixedPoint: 6169 Diag(Src.get()->getExprLoc(), 6170 diag::err_unimplemented_conversion_with_fixed_point_type) 6171 << SrcTy; 6172 return CK_IntegralCast; 6173 } 6174 llvm_unreachable("Should have returned before this"); 6175 } 6176 6177 llvm_unreachable("Unhandled scalar cast"); 6178 } 6179 6180 static bool breakDownVectorType(QualType type, uint64_t &len, 6181 QualType &eltType) { 6182 // Vectors are simple. 6183 if (const VectorType *vecType = type->getAs<VectorType>()) { 6184 len = vecType->getNumElements(); 6185 eltType = vecType->getElementType(); 6186 assert(eltType->isScalarType()); 6187 return true; 6188 } 6189 6190 // We allow lax conversion to and from non-vector types, but only if 6191 // they're real types (i.e. non-complex, non-pointer scalar types). 6192 if (!type->isRealType()) return false; 6193 6194 len = 1; 6195 eltType = type; 6196 return true; 6197 } 6198 6199 /// Are the two types lax-compatible vector types? That is, given 6200 /// that one of them is a vector, do they have equal storage sizes, 6201 /// where the storage size is the number of elements times the element 6202 /// size? 6203 /// 6204 /// This will also return false if either of the types is neither a 6205 /// vector nor a real type. 6206 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6207 assert(destTy->isVectorType() || srcTy->isVectorType()); 6208 6209 // Disallow lax conversions between scalars and ExtVectors (these 6210 // conversions are allowed for other vector types because common headers 6211 // depend on them). Most scalar OP ExtVector cases are handled by the 6212 // splat path anyway, which does what we want (convert, not bitcast). 6213 // What this rules out for ExtVectors is crazy things like char4*float. 6214 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6215 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6216 6217 uint64_t srcLen, destLen; 6218 QualType srcEltTy, destEltTy; 6219 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6220 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6221 6222 // ASTContext::getTypeSize will return the size rounded up to a 6223 // power of 2, so instead of using that, we need to use the raw 6224 // element size multiplied by the element count. 6225 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6226 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6227 6228 return (srcLen * srcEltSize == destLen * destEltSize); 6229 } 6230 6231 /// Is this a legal conversion between two types, one of which is 6232 /// known to be a vector type? 6233 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6234 assert(destTy->isVectorType() || srcTy->isVectorType()); 6235 6236 if (!Context.getLangOpts().LaxVectorConversions) 6237 return false; 6238 return areLaxCompatibleVectorTypes(srcTy, destTy); 6239 } 6240 6241 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6242 CastKind &Kind) { 6243 assert(VectorTy->isVectorType() && "Not a vector type!"); 6244 6245 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6246 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6247 return Diag(R.getBegin(), 6248 Ty->isVectorType() ? 6249 diag::err_invalid_conversion_between_vectors : 6250 diag::err_invalid_conversion_between_vector_and_integer) 6251 << VectorTy << Ty << R; 6252 } else 6253 return Diag(R.getBegin(), 6254 diag::err_invalid_conversion_between_vector_and_scalar) 6255 << VectorTy << Ty << R; 6256 6257 Kind = CK_BitCast; 6258 return false; 6259 } 6260 6261 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6262 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6263 6264 if (DestElemTy == SplattedExpr->getType()) 6265 return SplattedExpr; 6266 6267 assert(DestElemTy->isFloatingType() || 6268 DestElemTy->isIntegralOrEnumerationType()); 6269 6270 CastKind CK; 6271 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6272 // OpenCL requires that we convert `true` boolean expressions to -1, but 6273 // only when splatting vectors. 6274 if (DestElemTy->isFloatingType()) { 6275 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6276 // in two steps: boolean to signed integral, then to floating. 6277 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6278 CK_BooleanToSignedIntegral); 6279 SplattedExpr = CastExprRes.get(); 6280 CK = CK_IntegralToFloating; 6281 } else { 6282 CK = CK_BooleanToSignedIntegral; 6283 } 6284 } else { 6285 ExprResult CastExprRes = SplattedExpr; 6286 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6287 if (CastExprRes.isInvalid()) 6288 return ExprError(); 6289 SplattedExpr = CastExprRes.get(); 6290 } 6291 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6292 } 6293 6294 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6295 Expr *CastExpr, CastKind &Kind) { 6296 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6297 6298 QualType SrcTy = CastExpr->getType(); 6299 6300 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6301 // an ExtVectorType. 6302 // In OpenCL, casts between vectors of different types are not allowed. 6303 // (See OpenCL 6.2). 6304 if (SrcTy->isVectorType()) { 6305 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6306 (getLangOpts().OpenCL && 6307 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6308 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6309 << DestTy << SrcTy << R; 6310 return ExprError(); 6311 } 6312 Kind = CK_BitCast; 6313 return CastExpr; 6314 } 6315 6316 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6317 // conversion will take place first from scalar to elt type, and then 6318 // splat from elt type to vector. 6319 if (SrcTy->isPointerType()) 6320 return Diag(R.getBegin(), 6321 diag::err_invalid_conversion_between_vector_and_scalar) 6322 << DestTy << SrcTy << R; 6323 6324 Kind = CK_VectorSplat; 6325 return prepareVectorSplat(DestTy, CastExpr); 6326 } 6327 6328 ExprResult 6329 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6330 Declarator &D, ParsedType &Ty, 6331 SourceLocation RParenLoc, Expr *CastExpr) { 6332 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6333 "ActOnCastExpr(): missing type or expr"); 6334 6335 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6336 if (D.isInvalidType()) 6337 return ExprError(); 6338 6339 if (getLangOpts().CPlusPlus) { 6340 // Check that there are no default arguments (C++ only). 6341 CheckExtraCXXDefaultArguments(D); 6342 } else { 6343 // Make sure any TypoExprs have been dealt with. 6344 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6345 if (!Res.isUsable()) 6346 return ExprError(); 6347 CastExpr = Res.get(); 6348 } 6349 6350 checkUnusedDeclAttributes(D); 6351 6352 QualType castType = castTInfo->getType(); 6353 Ty = CreateParsedType(castType, castTInfo); 6354 6355 bool isVectorLiteral = false; 6356 6357 // Check for an altivec or OpenCL literal, 6358 // i.e. all the elements are integer constants. 6359 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6360 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6361 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6362 && castType->isVectorType() && (PE || PLE)) { 6363 if (PLE && PLE->getNumExprs() == 0) { 6364 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6365 return ExprError(); 6366 } 6367 if (PE || PLE->getNumExprs() == 1) { 6368 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6369 if (!E->getType()->isVectorType()) 6370 isVectorLiteral = true; 6371 } 6372 else 6373 isVectorLiteral = true; 6374 } 6375 6376 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6377 // then handle it as such. 6378 if (isVectorLiteral) 6379 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6380 6381 // If the Expr being casted is a ParenListExpr, handle it specially. 6382 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6383 // sequence of BinOp comma operators. 6384 if (isa<ParenListExpr>(CastExpr)) { 6385 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6386 if (Result.isInvalid()) return ExprError(); 6387 CastExpr = Result.get(); 6388 } 6389 6390 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6391 !getSourceManager().isInSystemMacro(LParenLoc)) 6392 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6393 6394 CheckTollFreeBridgeCast(castType, CastExpr); 6395 6396 CheckObjCBridgeRelatedCast(castType, CastExpr); 6397 6398 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6399 6400 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6401 } 6402 6403 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6404 SourceLocation RParenLoc, Expr *E, 6405 TypeSourceInfo *TInfo) { 6406 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6407 "Expected paren or paren list expression"); 6408 6409 Expr **exprs; 6410 unsigned numExprs; 6411 Expr *subExpr; 6412 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6413 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6414 LiteralLParenLoc = PE->getLParenLoc(); 6415 LiteralRParenLoc = PE->getRParenLoc(); 6416 exprs = PE->getExprs(); 6417 numExprs = PE->getNumExprs(); 6418 } else { // isa<ParenExpr> by assertion at function entrance 6419 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6420 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6421 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6422 exprs = &subExpr; 6423 numExprs = 1; 6424 } 6425 6426 QualType Ty = TInfo->getType(); 6427 assert(Ty->isVectorType() && "Expected vector type"); 6428 6429 SmallVector<Expr *, 8> initExprs; 6430 const VectorType *VTy = Ty->getAs<VectorType>(); 6431 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6432 6433 // '(...)' form of vector initialization in AltiVec: the number of 6434 // initializers must be one or must match the size of the vector. 6435 // If a single value is specified in the initializer then it will be 6436 // replicated to all the components of the vector 6437 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6438 // The number of initializers must be one or must match the size of the 6439 // vector. If a single value is specified in the initializer then it will 6440 // be replicated to all the components of the vector 6441 if (numExprs == 1) { 6442 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6443 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6444 if (Literal.isInvalid()) 6445 return ExprError(); 6446 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6447 PrepareScalarCast(Literal, ElemTy)); 6448 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6449 } 6450 else if (numExprs < numElems) { 6451 Diag(E->getExprLoc(), 6452 diag::err_incorrect_number_of_vector_initializers); 6453 return ExprError(); 6454 } 6455 else 6456 initExprs.append(exprs, exprs + numExprs); 6457 } 6458 else { 6459 // For OpenCL, when the number of initializers is a single value, 6460 // it will be replicated to all components of the vector. 6461 if (getLangOpts().OpenCL && 6462 VTy->getVectorKind() == VectorType::GenericVector && 6463 numExprs == 1) { 6464 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6465 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6466 if (Literal.isInvalid()) 6467 return ExprError(); 6468 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6469 PrepareScalarCast(Literal, ElemTy)); 6470 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6471 } 6472 6473 initExprs.append(exprs, exprs + numExprs); 6474 } 6475 // FIXME: This means that pretty-printing the final AST will produce curly 6476 // braces instead of the original commas. 6477 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6478 initExprs, LiteralRParenLoc); 6479 initE->setType(Ty); 6480 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6481 } 6482 6483 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6484 /// the ParenListExpr into a sequence of comma binary operators. 6485 ExprResult 6486 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6487 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6488 if (!E) 6489 return OrigExpr; 6490 6491 ExprResult Result(E->getExpr(0)); 6492 6493 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6494 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6495 E->getExpr(i)); 6496 6497 if (Result.isInvalid()) return ExprError(); 6498 6499 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6500 } 6501 6502 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6503 SourceLocation R, 6504 MultiExprArg Val) { 6505 return ParenListExpr::Create(Context, L, Val, R); 6506 } 6507 6508 /// Emit a specialized diagnostic when one expression is a null pointer 6509 /// constant and the other is not a pointer. Returns true if a diagnostic is 6510 /// emitted. 6511 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6512 SourceLocation QuestionLoc) { 6513 Expr *NullExpr = LHSExpr; 6514 Expr *NonPointerExpr = RHSExpr; 6515 Expr::NullPointerConstantKind NullKind = 6516 NullExpr->isNullPointerConstant(Context, 6517 Expr::NPC_ValueDependentIsNotNull); 6518 6519 if (NullKind == Expr::NPCK_NotNull) { 6520 NullExpr = RHSExpr; 6521 NonPointerExpr = LHSExpr; 6522 NullKind = 6523 NullExpr->isNullPointerConstant(Context, 6524 Expr::NPC_ValueDependentIsNotNull); 6525 } 6526 6527 if (NullKind == Expr::NPCK_NotNull) 6528 return false; 6529 6530 if (NullKind == Expr::NPCK_ZeroExpression) 6531 return false; 6532 6533 if (NullKind == Expr::NPCK_ZeroLiteral) { 6534 // In this case, check to make sure that we got here from a "NULL" 6535 // string in the source code. 6536 NullExpr = NullExpr->IgnoreParenImpCasts(); 6537 SourceLocation loc = NullExpr->getExprLoc(); 6538 if (!findMacroSpelling(loc, "NULL")) 6539 return false; 6540 } 6541 6542 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6543 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6544 << NonPointerExpr->getType() << DiagType 6545 << NonPointerExpr->getSourceRange(); 6546 return true; 6547 } 6548 6549 /// Return false if the condition expression is valid, true otherwise. 6550 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6551 QualType CondTy = Cond->getType(); 6552 6553 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6554 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6555 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6556 << CondTy << Cond->getSourceRange(); 6557 return true; 6558 } 6559 6560 // C99 6.5.15p2 6561 if (CondTy->isScalarType()) return false; 6562 6563 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6564 << CondTy << Cond->getSourceRange(); 6565 return true; 6566 } 6567 6568 /// Handle when one or both operands are void type. 6569 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6570 ExprResult &RHS) { 6571 Expr *LHSExpr = LHS.get(); 6572 Expr *RHSExpr = RHS.get(); 6573 6574 if (!LHSExpr->getType()->isVoidType()) 6575 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6576 << RHSExpr->getSourceRange(); 6577 if (!RHSExpr->getType()->isVoidType()) 6578 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6579 << LHSExpr->getSourceRange(); 6580 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6581 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6582 return S.Context.VoidTy; 6583 } 6584 6585 /// Return false if the NullExpr can be promoted to PointerTy, 6586 /// true otherwise. 6587 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6588 QualType PointerTy) { 6589 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6590 !NullExpr.get()->isNullPointerConstant(S.Context, 6591 Expr::NPC_ValueDependentIsNull)) 6592 return true; 6593 6594 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6595 return false; 6596 } 6597 6598 /// Checks compatibility between two pointers and return the resulting 6599 /// type. 6600 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6601 ExprResult &RHS, 6602 SourceLocation Loc) { 6603 QualType LHSTy = LHS.get()->getType(); 6604 QualType RHSTy = RHS.get()->getType(); 6605 6606 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6607 // Two identical pointers types are always compatible. 6608 return LHSTy; 6609 } 6610 6611 QualType lhptee, rhptee; 6612 6613 // Get the pointee types. 6614 bool IsBlockPointer = false; 6615 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6616 lhptee = LHSBTy->getPointeeType(); 6617 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6618 IsBlockPointer = true; 6619 } else { 6620 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6621 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6622 } 6623 6624 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6625 // differently qualified versions of compatible types, the result type is 6626 // a pointer to an appropriately qualified version of the composite 6627 // type. 6628 6629 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6630 // clause doesn't make sense for our extensions. E.g. address space 2 should 6631 // be incompatible with address space 3: they may live on different devices or 6632 // anything. 6633 Qualifiers lhQual = lhptee.getQualifiers(); 6634 Qualifiers rhQual = rhptee.getQualifiers(); 6635 6636 LangAS ResultAddrSpace = LangAS::Default; 6637 LangAS LAddrSpace = lhQual.getAddressSpace(); 6638 LangAS RAddrSpace = rhQual.getAddressSpace(); 6639 6640 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6641 // spaces is disallowed. 6642 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6643 ResultAddrSpace = LAddrSpace; 6644 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6645 ResultAddrSpace = RAddrSpace; 6646 else { 6647 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6648 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6649 << RHS.get()->getSourceRange(); 6650 return QualType(); 6651 } 6652 6653 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6654 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6655 lhQual.removeCVRQualifiers(); 6656 rhQual.removeCVRQualifiers(); 6657 6658 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6659 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6660 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6661 // qual types are compatible iff 6662 // * corresponded types are compatible 6663 // * CVR qualifiers are equal 6664 // * address spaces are equal 6665 // Thus for conditional operator we merge CVR and address space unqualified 6666 // pointees and if there is a composite type we return a pointer to it with 6667 // merged qualifiers. 6668 LHSCastKind = 6669 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6670 RHSCastKind = 6671 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6672 lhQual.removeAddressSpace(); 6673 rhQual.removeAddressSpace(); 6674 6675 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6676 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6677 6678 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6679 6680 if (CompositeTy.isNull()) { 6681 // In this situation, we assume void* type. No especially good 6682 // reason, but this is what gcc does, and we do have to pick 6683 // to get a consistent AST. 6684 QualType incompatTy; 6685 incompatTy = S.Context.getPointerType( 6686 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6687 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6688 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6689 6690 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6691 // for casts between types with incompatible address space qualifiers. 6692 // For the following code the compiler produces casts between global and 6693 // local address spaces of the corresponded innermost pointees: 6694 // local int *global *a; 6695 // global int *global *b; 6696 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6697 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6698 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6699 << RHS.get()->getSourceRange(); 6700 6701 return incompatTy; 6702 } 6703 6704 // The pointer types are compatible. 6705 // In case of OpenCL ResultTy should have the address space qualifier 6706 // which is a superset of address spaces of both the 2nd and the 3rd 6707 // operands of the conditional operator. 6708 QualType ResultTy = [&, ResultAddrSpace]() { 6709 if (S.getLangOpts().OpenCL) { 6710 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6711 CompositeQuals.setAddressSpace(ResultAddrSpace); 6712 return S.Context 6713 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6714 .withCVRQualifiers(MergedCVRQual); 6715 } 6716 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6717 }(); 6718 if (IsBlockPointer) 6719 ResultTy = S.Context.getBlockPointerType(ResultTy); 6720 else 6721 ResultTy = S.Context.getPointerType(ResultTy); 6722 6723 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6724 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6725 return ResultTy; 6726 } 6727 6728 /// Return the resulting type when the operands are both block pointers. 6729 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6730 ExprResult &LHS, 6731 ExprResult &RHS, 6732 SourceLocation Loc) { 6733 QualType LHSTy = LHS.get()->getType(); 6734 QualType RHSTy = RHS.get()->getType(); 6735 6736 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6737 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6738 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6739 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6740 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6741 return destType; 6742 } 6743 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6744 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6745 << RHS.get()->getSourceRange(); 6746 return QualType(); 6747 } 6748 6749 // We have 2 block pointer types. 6750 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6751 } 6752 6753 /// Return the resulting type when the operands are both pointers. 6754 static QualType 6755 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6756 ExprResult &RHS, 6757 SourceLocation Loc) { 6758 // get the pointer types 6759 QualType LHSTy = LHS.get()->getType(); 6760 QualType RHSTy = RHS.get()->getType(); 6761 6762 // get the "pointed to" types 6763 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6764 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6765 6766 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6767 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6768 // Figure out necessary qualifiers (C99 6.5.15p6) 6769 QualType destPointee 6770 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6771 QualType destType = S.Context.getPointerType(destPointee); 6772 // Add qualifiers if necessary. 6773 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6774 // Promote to void*. 6775 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6776 return destType; 6777 } 6778 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6779 QualType destPointee 6780 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6781 QualType destType = S.Context.getPointerType(destPointee); 6782 // Add qualifiers if necessary. 6783 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6784 // Promote to void*. 6785 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6786 return destType; 6787 } 6788 6789 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6790 } 6791 6792 /// Return false if the first expression is not an integer and the second 6793 /// expression is not a pointer, true otherwise. 6794 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6795 Expr* PointerExpr, SourceLocation Loc, 6796 bool IsIntFirstExpr) { 6797 if (!PointerExpr->getType()->isPointerType() || 6798 !Int.get()->getType()->isIntegerType()) 6799 return false; 6800 6801 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6802 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6803 6804 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6805 << Expr1->getType() << Expr2->getType() 6806 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6807 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6808 CK_IntegralToPointer); 6809 return true; 6810 } 6811 6812 /// Simple conversion between integer and floating point types. 6813 /// 6814 /// Used when handling the OpenCL conditional operator where the 6815 /// condition is a vector while the other operands are scalar. 6816 /// 6817 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6818 /// types are either integer or floating type. Between the two 6819 /// operands, the type with the higher rank is defined as the "result 6820 /// type". The other operand needs to be promoted to the same type. No 6821 /// other type promotion is allowed. We cannot use 6822 /// UsualArithmeticConversions() for this purpose, since it always 6823 /// promotes promotable types. 6824 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6825 ExprResult &RHS, 6826 SourceLocation QuestionLoc) { 6827 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6828 if (LHS.isInvalid()) 6829 return QualType(); 6830 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6831 if (RHS.isInvalid()) 6832 return QualType(); 6833 6834 // For conversion purposes, we ignore any qualifiers. 6835 // For example, "const float" and "float" are equivalent. 6836 QualType LHSType = 6837 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6838 QualType RHSType = 6839 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6840 6841 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6842 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6843 << LHSType << LHS.get()->getSourceRange(); 6844 return QualType(); 6845 } 6846 6847 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6848 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6849 << RHSType << RHS.get()->getSourceRange(); 6850 return QualType(); 6851 } 6852 6853 // If both types are identical, no conversion is needed. 6854 if (LHSType == RHSType) 6855 return LHSType; 6856 6857 // Now handle "real" floating types (i.e. float, double, long double). 6858 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6859 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6860 /*IsCompAssign = */ false); 6861 6862 // Finally, we have two differing integer types. 6863 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6864 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6865 } 6866 6867 /// Convert scalar operands to a vector that matches the 6868 /// condition in length. 6869 /// 6870 /// Used when handling the OpenCL conditional operator where the 6871 /// condition is a vector while the other operands are scalar. 6872 /// 6873 /// We first compute the "result type" for the scalar operands 6874 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6875 /// into a vector of that type where the length matches the condition 6876 /// vector type. s6.11.6 requires that the element types of the result 6877 /// and the condition must have the same number of bits. 6878 static QualType 6879 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6880 QualType CondTy, SourceLocation QuestionLoc) { 6881 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6882 if (ResTy.isNull()) return QualType(); 6883 6884 const VectorType *CV = CondTy->getAs<VectorType>(); 6885 assert(CV); 6886 6887 // Determine the vector result type 6888 unsigned NumElements = CV->getNumElements(); 6889 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6890 6891 // Ensure that all types have the same number of bits 6892 if (S.Context.getTypeSize(CV->getElementType()) 6893 != S.Context.getTypeSize(ResTy)) { 6894 // Since VectorTy is created internally, it does not pretty print 6895 // with an OpenCL name. Instead, we just print a description. 6896 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6897 SmallString<64> Str; 6898 llvm::raw_svector_ostream OS(Str); 6899 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6900 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6901 << CondTy << OS.str(); 6902 return QualType(); 6903 } 6904 6905 // Convert operands to the vector result type 6906 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6907 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6908 6909 return VectorTy; 6910 } 6911 6912 /// Return false if this is a valid OpenCL condition vector 6913 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6914 SourceLocation QuestionLoc) { 6915 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6916 // integral type. 6917 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6918 assert(CondTy); 6919 QualType EleTy = CondTy->getElementType(); 6920 if (EleTy->isIntegerType()) return false; 6921 6922 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6923 << Cond->getType() << Cond->getSourceRange(); 6924 return true; 6925 } 6926 6927 /// Return false if the vector condition type and the vector 6928 /// result type are compatible. 6929 /// 6930 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6931 /// number of elements, and their element types have the same number 6932 /// of bits. 6933 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6934 SourceLocation QuestionLoc) { 6935 const VectorType *CV = CondTy->getAs<VectorType>(); 6936 const VectorType *RV = VecResTy->getAs<VectorType>(); 6937 assert(CV && RV); 6938 6939 if (CV->getNumElements() != RV->getNumElements()) { 6940 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6941 << CondTy << VecResTy; 6942 return true; 6943 } 6944 6945 QualType CVE = CV->getElementType(); 6946 QualType RVE = RV->getElementType(); 6947 6948 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6949 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6950 << CondTy << VecResTy; 6951 return true; 6952 } 6953 6954 return false; 6955 } 6956 6957 /// Return the resulting type for the conditional operator in 6958 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6959 /// s6.3.i) when the condition is a vector type. 6960 static QualType 6961 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6962 ExprResult &LHS, ExprResult &RHS, 6963 SourceLocation QuestionLoc) { 6964 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6965 if (Cond.isInvalid()) 6966 return QualType(); 6967 QualType CondTy = Cond.get()->getType(); 6968 6969 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6970 return QualType(); 6971 6972 // If either operand is a vector then find the vector type of the 6973 // result as specified in OpenCL v1.1 s6.3.i. 6974 if (LHS.get()->getType()->isVectorType() || 6975 RHS.get()->getType()->isVectorType()) { 6976 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6977 /*isCompAssign*/false, 6978 /*AllowBothBool*/true, 6979 /*AllowBoolConversions*/false); 6980 if (VecResTy.isNull()) return QualType(); 6981 // The result type must match the condition type as specified in 6982 // OpenCL v1.1 s6.11.6. 6983 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6984 return QualType(); 6985 return VecResTy; 6986 } 6987 6988 // Both operands are scalar. 6989 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6990 } 6991 6992 /// Return true if the Expr is block type 6993 static bool checkBlockType(Sema &S, const Expr *E) { 6994 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6995 QualType Ty = CE->getCallee()->getType(); 6996 if (Ty->isBlockPointerType()) { 6997 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6998 return true; 6999 } 7000 } 7001 return false; 7002 } 7003 7004 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7005 /// In that case, LHS = cond. 7006 /// C99 6.5.15 7007 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7008 ExprResult &RHS, ExprValueKind &VK, 7009 ExprObjectKind &OK, 7010 SourceLocation QuestionLoc) { 7011 7012 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7013 if (!LHSResult.isUsable()) return QualType(); 7014 LHS = LHSResult; 7015 7016 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7017 if (!RHSResult.isUsable()) return QualType(); 7018 RHS = RHSResult; 7019 7020 // C++ is sufficiently different to merit its own checker. 7021 if (getLangOpts().CPlusPlus) 7022 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7023 7024 VK = VK_RValue; 7025 OK = OK_Ordinary; 7026 7027 // The OpenCL operator with a vector condition is sufficiently 7028 // different to merit its own checker. 7029 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7030 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7031 7032 // First, check the condition. 7033 Cond = UsualUnaryConversions(Cond.get()); 7034 if (Cond.isInvalid()) 7035 return QualType(); 7036 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7037 return QualType(); 7038 7039 // Now check the two expressions. 7040 if (LHS.get()->getType()->isVectorType() || 7041 RHS.get()->getType()->isVectorType()) 7042 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7043 /*AllowBothBool*/true, 7044 /*AllowBoolConversions*/false); 7045 7046 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7047 if (LHS.isInvalid() || RHS.isInvalid()) 7048 return QualType(); 7049 7050 QualType LHSTy = LHS.get()->getType(); 7051 QualType RHSTy = RHS.get()->getType(); 7052 7053 // Diagnose attempts to convert between __float128 and long double where 7054 // such conversions currently can't be handled. 7055 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7056 Diag(QuestionLoc, 7057 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7059 return QualType(); 7060 } 7061 7062 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7063 // selection operator (?:). 7064 if (getLangOpts().OpenCL && 7065 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7066 return QualType(); 7067 } 7068 7069 // If both operands have arithmetic type, do the usual arithmetic conversions 7070 // to find a common type: C99 6.5.15p3,5. 7071 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7072 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7073 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7074 7075 return ResTy; 7076 } 7077 7078 // If both operands are the same structure or union type, the result is that 7079 // type. 7080 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7081 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7082 if (LHSRT->getDecl() == RHSRT->getDecl()) 7083 // "If both the operands have structure or union type, the result has 7084 // that type." This implies that CV qualifiers are dropped. 7085 return LHSTy.getUnqualifiedType(); 7086 // FIXME: Type of conditional expression must be complete in C mode. 7087 } 7088 7089 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7090 // The following || allows only one side to be void (a GCC-ism). 7091 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7092 return checkConditionalVoidType(*this, LHS, RHS); 7093 } 7094 7095 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7096 // the type of the other operand." 7097 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7098 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7099 7100 // All objective-c pointer type analysis is done here. 7101 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7102 QuestionLoc); 7103 if (LHS.isInvalid() || RHS.isInvalid()) 7104 return QualType(); 7105 if (!compositeType.isNull()) 7106 return compositeType; 7107 7108 7109 // Handle block pointer types. 7110 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7111 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7112 QuestionLoc); 7113 7114 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7115 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7116 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7117 QuestionLoc); 7118 7119 // GCC compatibility: soften pointer/integer mismatch. Note that 7120 // null pointers have been filtered out by this point. 7121 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7122 /*isIntFirstExpr=*/true)) 7123 return RHSTy; 7124 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7125 /*isIntFirstExpr=*/false)) 7126 return LHSTy; 7127 7128 // Emit a better diagnostic if one of the expressions is a null pointer 7129 // constant and the other is not a pointer type. In this case, the user most 7130 // likely forgot to take the address of the other expression. 7131 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7132 return QualType(); 7133 7134 // Otherwise, the operands are not compatible. 7135 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7136 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7137 << RHS.get()->getSourceRange(); 7138 return QualType(); 7139 } 7140 7141 /// FindCompositeObjCPointerType - Helper method to find composite type of 7142 /// two objective-c pointer types of the two input expressions. 7143 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7144 SourceLocation QuestionLoc) { 7145 QualType LHSTy = LHS.get()->getType(); 7146 QualType RHSTy = RHS.get()->getType(); 7147 7148 // Handle things like Class and struct objc_class*. Here we case the result 7149 // to the pseudo-builtin, because that will be implicitly cast back to the 7150 // redefinition type if an attempt is made to access its fields. 7151 if (LHSTy->isObjCClassType() && 7152 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7153 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7154 return LHSTy; 7155 } 7156 if (RHSTy->isObjCClassType() && 7157 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7158 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7159 return RHSTy; 7160 } 7161 // And the same for struct objc_object* / id 7162 if (LHSTy->isObjCIdType() && 7163 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7164 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7165 return LHSTy; 7166 } 7167 if (RHSTy->isObjCIdType() && 7168 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7169 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7170 return RHSTy; 7171 } 7172 // And the same for struct objc_selector* / SEL 7173 if (Context.isObjCSelType(LHSTy) && 7174 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7175 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7176 return LHSTy; 7177 } 7178 if (Context.isObjCSelType(RHSTy) && 7179 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7180 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7181 return RHSTy; 7182 } 7183 // Check constraints for Objective-C object pointers types. 7184 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7185 7186 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7187 // Two identical object pointer types are always compatible. 7188 return LHSTy; 7189 } 7190 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7191 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7192 QualType compositeType = LHSTy; 7193 7194 // If both operands are interfaces and either operand can be 7195 // assigned to the other, use that type as the composite 7196 // type. This allows 7197 // xxx ? (A*) a : (B*) b 7198 // where B is a subclass of A. 7199 // 7200 // Additionally, as for assignment, if either type is 'id' 7201 // allow silent coercion. Finally, if the types are 7202 // incompatible then make sure to use 'id' as the composite 7203 // type so the result is acceptable for sending messages to. 7204 7205 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7206 // It could return the composite type. 7207 if (!(compositeType = 7208 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7209 // Nothing more to do. 7210 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7211 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7212 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7213 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7214 } else if ((LHSTy->isObjCQualifiedIdType() || 7215 RHSTy->isObjCQualifiedIdType()) && 7216 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7217 // Need to handle "id<xx>" explicitly. 7218 // GCC allows qualified id and any Objective-C type to devolve to 7219 // id. Currently localizing to here until clear this should be 7220 // part of ObjCQualifiedIdTypesAreCompatible. 7221 compositeType = Context.getObjCIdType(); 7222 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7223 compositeType = Context.getObjCIdType(); 7224 } else { 7225 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7226 << LHSTy << RHSTy 7227 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7228 QualType incompatTy = Context.getObjCIdType(); 7229 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7230 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7231 return incompatTy; 7232 } 7233 // The object pointer types are compatible. 7234 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7235 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7236 return compositeType; 7237 } 7238 // Check Objective-C object pointer types and 'void *' 7239 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7240 if (getLangOpts().ObjCAutoRefCount) { 7241 // ARC forbids the implicit conversion of object pointers to 'void *', 7242 // so these types are not compatible. 7243 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7244 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7245 LHS = RHS = true; 7246 return QualType(); 7247 } 7248 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7249 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7250 QualType destPointee 7251 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7252 QualType destType = Context.getPointerType(destPointee); 7253 // Add qualifiers if necessary. 7254 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7255 // Promote to void*. 7256 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7257 return destType; 7258 } 7259 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7260 if (getLangOpts().ObjCAutoRefCount) { 7261 // ARC forbids the implicit conversion of object pointers to 'void *', 7262 // so these types are not compatible. 7263 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7265 LHS = RHS = true; 7266 return QualType(); 7267 } 7268 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7269 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7270 QualType destPointee 7271 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7272 QualType destType = Context.getPointerType(destPointee); 7273 // Add qualifiers if necessary. 7274 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7275 // Promote to void*. 7276 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7277 return destType; 7278 } 7279 return QualType(); 7280 } 7281 7282 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7283 /// ParenRange in parentheses. 7284 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7285 const PartialDiagnostic &Note, 7286 SourceRange ParenRange) { 7287 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7288 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7289 EndLoc.isValid()) { 7290 Self.Diag(Loc, Note) 7291 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7292 << FixItHint::CreateInsertion(EndLoc, ")"); 7293 } else { 7294 // We can't display the parentheses, so just show the bare note. 7295 Self.Diag(Loc, Note) << ParenRange; 7296 } 7297 } 7298 7299 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7300 return BinaryOperator::isAdditiveOp(Opc) || 7301 BinaryOperator::isMultiplicativeOp(Opc) || 7302 BinaryOperator::isShiftOp(Opc); 7303 } 7304 7305 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7306 /// expression, either using a built-in or overloaded operator, 7307 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7308 /// expression. 7309 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7310 Expr **RHSExprs) { 7311 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7312 E = E->IgnoreImpCasts(); 7313 E = E->IgnoreConversionOperator(); 7314 E = E->IgnoreImpCasts(); 7315 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7316 E = MTE->GetTemporaryExpr(); 7317 E = E->IgnoreImpCasts(); 7318 } 7319 7320 // Built-in binary operator. 7321 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7322 if (IsArithmeticOp(OP->getOpcode())) { 7323 *Opcode = OP->getOpcode(); 7324 *RHSExprs = OP->getRHS(); 7325 return true; 7326 } 7327 } 7328 7329 // Overloaded operator. 7330 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7331 if (Call->getNumArgs() != 2) 7332 return false; 7333 7334 // Make sure this is really a binary operator that is safe to pass into 7335 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7336 OverloadedOperatorKind OO = Call->getOperator(); 7337 if (OO < OO_Plus || OO > OO_Arrow || 7338 OO == OO_PlusPlus || OO == OO_MinusMinus) 7339 return false; 7340 7341 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7342 if (IsArithmeticOp(OpKind)) { 7343 *Opcode = OpKind; 7344 *RHSExprs = Call->getArg(1); 7345 return true; 7346 } 7347 } 7348 7349 return false; 7350 } 7351 7352 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7353 /// or is a logical expression such as (x==y) which has int type, but is 7354 /// commonly interpreted as boolean. 7355 static bool ExprLooksBoolean(Expr *E) { 7356 E = E->IgnoreParenImpCasts(); 7357 7358 if (E->getType()->isBooleanType()) 7359 return true; 7360 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7361 return OP->isComparisonOp() || OP->isLogicalOp(); 7362 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7363 return OP->getOpcode() == UO_LNot; 7364 if (E->getType()->isPointerType()) 7365 return true; 7366 // FIXME: What about overloaded operator calls returning "unspecified boolean 7367 // type"s (commonly pointer-to-members)? 7368 7369 return false; 7370 } 7371 7372 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7373 /// and binary operator are mixed in a way that suggests the programmer assumed 7374 /// the conditional operator has higher precedence, for example: 7375 /// "int x = a + someBinaryCondition ? 1 : 2". 7376 static void DiagnoseConditionalPrecedence(Sema &Self, 7377 SourceLocation OpLoc, 7378 Expr *Condition, 7379 Expr *LHSExpr, 7380 Expr *RHSExpr) { 7381 BinaryOperatorKind CondOpcode; 7382 Expr *CondRHS; 7383 7384 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7385 return; 7386 if (!ExprLooksBoolean(CondRHS)) 7387 return; 7388 7389 // The condition is an arithmetic binary expression, with a right- 7390 // hand side that looks boolean, so warn. 7391 7392 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7393 << Condition->getSourceRange() 7394 << BinaryOperator::getOpcodeStr(CondOpcode); 7395 7396 SuggestParentheses( 7397 Self, OpLoc, 7398 Self.PDiag(diag::note_precedence_silence) 7399 << BinaryOperator::getOpcodeStr(CondOpcode), 7400 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7401 7402 SuggestParentheses(Self, OpLoc, 7403 Self.PDiag(diag::note_precedence_conditional_first), 7404 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7405 } 7406 7407 /// Compute the nullability of a conditional expression. 7408 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7409 QualType LHSTy, QualType RHSTy, 7410 ASTContext &Ctx) { 7411 if (!ResTy->isAnyPointerType()) 7412 return ResTy; 7413 7414 auto GetNullability = [&Ctx](QualType Ty) { 7415 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7416 if (Kind) 7417 return *Kind; 7418 return NullabilityKind::Unspecified; 7419 }; 7420 7421 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7422 NullabilityKind MergedKind; 7423 7424 // Compute nullability of a binary conditional expression. 7425 if (IsBin) { 7426 if (LHSKind == NullabilityKind::NonNull) 7427 MergedKind = NullabilityKind::NonNull; 7428 else 7429 MergedKind = RHSKind; 7430 // Compute nullability of a normal conditional expression. 7431 } else { 7432 if (LHSKind == NullabilityKind::Nullable || 7433 RHSKind == NullabilityKind::Nullable) 7434 MergedKind = NullabilityKind::Nullable; 7435 else if (LHSKind == NullabilityKind::NonNull) 7436 MergedKind = RHSKind; 7437 else if (RHSKind == NullabilityKind::NonNull) 7438 MergedKind = LHSKind; 7439 else 7440 MergedKind = NullabilityKind::Unspecified; 7441 } 7442 7443 // Return if ResTy already has the correct nullability. 7444 if (GetNullability(ResTy) == MergedKind) 7445 return ResTy; 7446 7447 // Strip all nullability from ResTy. 7448 while (ResTy->getNullability(Ctx)) 7449 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7450 7451 // Create a new AttributedType with the new nullability kind. 7452 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7453 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7454 } 7455 7456 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7457 /// in the case of a the GNU conditional expr extension. 7458 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7459 SourceLocation ColonLoc, 7460 Expr *CondExpr, Expr *LHSExpr, 7461 Expr *RHSExpr) { 7462 if (!getLangOpts().CPlusPlus) { 7463 // C cannot handle TypoExpr nodes in the condition because it 7464 // doesn't handle dependent types properly, so make sure any TypoExprs have 7465 // been dealt with before checking the operands. 7466 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7467 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7468 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7469 7470 if (!CondResult.isUsable()) 7471 return ExprError(); 7472 7473 if (LHSExpr) { 7474 if (!LHSResult.isUsable()) 7475 return ExprError(); 7476 } 7477 7478 if (!RHSResult.isUsable()) 7479 return ExprError(); 7480 7481 CondExpr = CondResult.get(); 7482 LHSExpr = LHSResult.get(); 7483 RHSExpr = RHSResult.get(); 7484 } 7485 7486 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7487 // was the condition. 7488 OpaqueValueExpr *opaqueValue = nullptr; 7489 Expr *commonExpr = nullptr; 7490 if (!LHSExpr) { 7491 commonExpr = CondExpr; 7492 // Lower out placeholder types first. This is important so that we don't 7493 // try to capture a placeholder. This happens in few cases in C++; such 7494 // as Objective-C++'s dictionary subscripting syntax. 7495 if (commonExpr->hasPlaceholderType()) { 7496 ExprResult result = CheckPlaceholderExpr(commonExpr); 7497 if (!result.isUsable()) return ExprError(); 7498 commonExpr = result.get(); 7499 } 7500 // We usually want to apply unary conversions *before* saving, except 7501 // in the special case of a C++ l-value conditional. 7502 if (!(getLangOpts().CPlusPlus 7503 && !commonExpr->isTypeDependent() 7504 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7505 && commonExpr->isGLValue() 7506 && commonExpr->isOrdinaryOrBitFieldObject() 7507 && RHSExpr->isOrdinaryOrBitFieldObject() 7508 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7509 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7510 if (commonRes.isInvalid()) 7511 return ExprError(); 7512 commonExpr = commonRes.get(); 7513 } 7514 7515 // If the common expression is a class or array prvalue, materialize it 7516 // so that we can safely refer to it multiple times. 7517 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7518 commonExpr->getType()->isArrayType())) { 7519 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7520 if (MatExpr.isInvalid()) 7521 return ExprError(); 7522 commonExpr = MatExpr.get(); 7523 } 7524 7525 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7526 commonExpr->getType(), 7527 commonExpr->getValueKind(), 7528 commonExpr->getObjectKind(), 7529 commonExpr); 7530 LHSExpr = CondExpr = opaqueValue; 7531 } 7532 7533 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7534 ExprValueKind VK = VK_RValue; 7535 ExprObjectKind OK = OK_Ordinary; 7536 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7537 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7538 VK, OK, QuestionLoc); 7539 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7540 RHS.isInvalid()) 7541 return ExprError(); 7542 7543 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7544 RHS.get()); 7545 7546 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7547 7548 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7549 Context); 7550 7551 if (!commonExpr) 7552 return new (Context) 7553 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7554 RHS.get(), result, VK, OK); 7555 7556 return new (Context) BinaryConditionalOperator( 7557 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7558 ColonLoc, result, VK, OK); 7559 } 7560 7561 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7562 // being closely modeled after the C99 spec:-). The odd characteristic of this 7563 // routine is it effectively iqnores the qualifiers on the top level pointee. 7564 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7565 // FIXME: add a couple examples in this comment. 7566 static Sema::AssignConvertType 7567 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7568 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7569 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7570 7571 // get the "pointed to" type (ignoring qualifiers at the top level) 7572 const Type *lhptee, *rhptee; 7573 Qualifiers lhq, rhq; 7574 std::tie(lhptee, lhq) = 7575 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7576 std::tie(rhptee, rhq) = 7577 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7578 7579 Sema::AssignConvertType ConvTy = Sema::Compatible; 7580 7581 // C99 6.5.16.1p1: This following citation is common to constraints 7582 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7583 // qualifiers of the type *pointed to* by the right; 7584 7585 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7586 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7587 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7588 // Ignore lifetime for further calculation. 7589 lhq.removeObjCLifetime(); 7590 rhq.removeObjCLifetime(); 7591 } 7592 7593 if (!lhq.compatiblyIncludes(rhq)) { 7594 // Treat address-space mismatches as fatal. TODO: address subspaces 7595 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7596 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7597 7598 // It's okay to add or remove GC or lifetime qualifiers when converting to 7599 // and from void*. 7600 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7601 .compatiblyIncludes( 7602 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7603 && (lhptee->isVoidType() || rhptee->isVoidType())) 7604 ; // keep old 7605 7606 // Treat lifetime mismatches as fatal. 7607 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7608 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7609 7610 // For GCC/MS compatibility, other qualifier mismatches are treated 7611 // as still compatible in C. 7612 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7613 } 7614 7615 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7616 // incomplete type and the other is a pointer to a qualified or unqualified 7617 // version of void... 7618 if (lhptee->isVoidType()) { 7619 if (rhptee->isIncompleteOrObjectType()) 7620 return ConvTy; 7621 7622 // As an extension, we allow cast to/from void* to function pointer. 7623 assert(rhptee->isFunctionType()); 7624 return Sema::FunctionVoidPointer; 7625 } 7626 7627 if (rhptee->isVoidType()) { 7628 if (lhptee->isIncompleteOrObjectType()) 7629 return ConvTy; 7630 7631 // As an extension, we allow cast to/from void* to function pointer. 7632 assert(lhptee->isFunctionType()); 7633 return Sema::FunctionVoidPointer; 7634 } 7635 7636 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7637 // unqualified versions of compatible types, ... 7638 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7639 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7640 // Check if the pointee types are compatible ignoring the sign. 7641 // We explicitly check for char so that we catch "char" vs 7642 // "unsigned char" on systems where "char" is unsigned. 7643 if (lhptee->isCharType()) 7644 ltrans = S.Context.UnsignedCharTy; 7645 else if (lhptee->hasSignedIntegerRepresentation()) 7646 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7647 7648 if (rhptee->isCharType()) 7649 rtrans = S.Context.UnsignedCharTy; 7650 else if (rhptee->hasSignedIntegerRepresentation()) 7651 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7652 7653 if (ltrans == rtrans) { 7654 // Types are compatible ignoring the sign. Qualifier incompatibility 7655 // takes priority over sign incompatibility because the sign 7656 // warning can be disabled. 7657 if (ConvTy != Sema::Compatible) 7658 return ConvTy; 7659 7660 return Sema::IncompatiblePointerSign; 7661 } 7662 7663 // If we are a multi-level pointer, it's possible that our issue is simply 7664 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7665 // the eventual target type is the same and the pointers have the same 7666 // level of indirection, this must be the issue. 7667 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7668 do { 7669 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7670 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7671 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7672 7673 if (lhptee == rhptee) 7674 return Sema::IncompatibleNestedPointerQualifiers; 7675 } 7676 7677 // General pointer incompatibility takes priority over qualifiers. 7678 return Sema::IncompatiblePointer; 7679 } 7680 if (!S.getLangOpts().CPlusPlus && 7681 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7682 return Sema::IncompatiblePointer; 7683 return ConvTy; 7684 } 7685 7686 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7687 /// block pointer types are compatible or whether a block and normal pointer 7688 /// are compatible. It is more restrict than comparing two function pointer 7689 // types. 7690 static Sema::AssignConvertType 7691 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7692 QualType RHSType) { 7693 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7694 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7695 7696 QualType lhptee, rhptee; 7697 7698 // get the "pointed to" type (ignoring qualifiers at the top level) 7699 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7700 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7701 7702 // In C++, the types have to match exactly. 7703 if (S.getLangOpts().CPlusPlus) 7704 return Sema::IncompatibleBlockPointer; 7705 7706 Sema::AssignConvertType ConvTy = Sema::Compatible; 7707 7708 // For blocks we enforce that qualifiers are identical. 7709 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7710 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7711 if (S.getLangOpts().OpenCL) { 7712 LQuals.removeAddressSpace(); 7713 RQuals.removeAddressSpace(); 7714 } 7715 if (LQuals != RQuals) 7716 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7717 7718 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7719 // assignment. 7720 // The current behavior is similar to C++ lambdas. A block might be 7721 // assigned to a variable iff its return type and parameters are compatible 7722 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7723 // an assignment. Presumably it should behave in way that a function pointer 7724 // assignment does in C, so for each parameter and return type: 7725 // * CVR and address space of LHS should be a superset of CVR and address 7726 // space of RHS. 7727 // * unqualified types should be compatible. 7728 if (S.getLangOpts().OpenCL) { 7729 if (!S.Context.typesAreBlockPointerCompatible( 7730 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7731 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7732 return Sema::IncompatibleBlockPointer; 7733 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7734 return Sema::IncompatibleBlockPointer; 7735 7736 return ConvTy; 7737 } 7738 7739 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7740 /// for assignment compatibility. 7741 static Sema::AssignConvertType 7742 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7743 QualType RHSType) { 7744 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7745 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7746 7747 if (LHSType->isObjCBuiltinType()) { 7748 // Class is not compatible with ObjC object pointers. 7749 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7750 !RHSType->isObjCQualifiedClassType()) 7751 return Sema::IncompatiblePointer; 7752 return Sema::Compatible; 7753 } 7754 if (RHSType->isObjCBuiltinType()) { 7755 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7756 !LHSType->isObjCQualifiedClassType()) 7757 return Sema::IncompatiblePointer; 7758 return Sema::Compatible; 7759 } 7760 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7761 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7762 7763 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7764 // make an exception for id<P> 7765 !LHSType->isObjCQualifiedIdType()) 7766 return Sema::CompatiblePointerDiscardsQualifiers; 7767 7768 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7769 return Sema::Compatible; 7770 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7771 return Sema::IncompatibleObjCQualifiedId; 7772 return Sema::IncompatiblePointer; 7773 } 7774 7775 Sema::AssignConvertType 7776 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7777 QualType LHSType, QualType RHSType) { 7778 // Fake up an opaque expression. We don't actually care about what 7779 // cast operations are required, so if CheckAssignmentConstraints 7780 // adds casts to this they'll be wasted, but fortunately that doesn't 7781 // usually happen on valid code. 7782 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7783 ExprResult RHSPtr = &RHSExpr; 7784 CastKind K; 7785 7786 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7787 } 7788 7789 /// This helper function returns true if QT is a vector type that has element 7790 /// type ElementType. 7791 static bool isVector(QualType QT, QualType ElementType) { 7792 if (const VectorType *VT = QT->getAs<VectorType>()) 7793 return VT->getElementType() == ElementType; 7794 return false; 7795 } 7796 7797 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7798 /// has code to accommodate several GCC extensions when type checking 7799 /// pointers. Here are some objectionable examples that GCC considers warnings: 7800 /// 7801 /// int a, *pint; 7802 /// short *pshort; 7803 /// struct foo *pfoo; 7804 /// 7805 /// pint = pshort; // warning: assignment from incompatible pointer type 7806 /// a = pint; // warning: assignment makes integer from pointer without a cast 7807 /// pint = a; // warning: assignment makes pointer from integer without a cast 7808 /// pint = pfoo; // warning: assignment from incompatible pointer type 7809 /// 7810 /// As a result, the code for dealing with pointers is more complex than the 7811 /// C99 spec dictates. 7812 /// 7813 /// Sets 'Kind' for any result kind except Incompatible. 7814 Sema::AssignConvertType 7815 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7816 CastKind &Kind, bool ConvertRHS) { 7817 QualType RHSType = RHS.get()->getType(); 7818 QualType OrigLHSType = LHSType; 7819 7820 // Get canonical types. We're not formatting these types, just comparing 7821 // them. 7822 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7823 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7824 7825 // Common case: no conversion required. 7826 if (LHSType == RHSType) { 7827 Kind = CK_NoOp; 7828 return Compatible; 7829 } 7830 7831 // If we have an atomic type, try a non-atomic assignment, then just add an 7832 // atomic qualification step. 7833 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7834 Sema::AssignConvertType result = 7835 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7836 if (result != Compatible) 7837 return result; 7838 if (Kind != CK_NoOp && ConvertRHS) 7839 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7840 Kind = CK_NonAtomicToAtomic; 7841 return Compatible; 7842 } 7843 7844 // If the left-hand side is a reference type, then we are in a 7845 // (rare!) case where we've allowed the use of references in C, 7846 // e.g., as a parameter type in a built-in function. In this case, 7847 // just make sure that the type referenced is compatible with the 7848 // right-hand side type. The caller is responsible for adjusting 7849 // LHSType so that the resulting expression does not have reference 7850 // type. 7851 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7852 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7853 Kind = CK_LValueBitCast; 7854 return Compatible; 7855 } 7856 return Incompatible; 7857 } 7858 7859 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7860 // to the same ExtVector type. 7861 if (LHSType->isExtVectorType()) { 7862 if (RHSType->isExtVectorType()) 7863 return Incompatible; 7864 if (RHSType->isArithmeticType()) { 7865 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7866 if (ConvertRHS) 7867 RHS = prepareVectorSplat(LHSType, RHS.get()); 7868 Kind = CK_VectorSplat; 7869 return Compatible; 7870 } 7871 } 7872 7873 // Conversions to or from vector type. 7874 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7875 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7876 // Allow assignments of an AltiVec vector type to an equivalent GCC 7877 // vector type and vice versa 7878 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7879 Kind = CK_BitCast; 7880 return Compatible; 7881 } 7882 7883 // If we are allowing lax vector conversions, and LHS and RHS are both 7884 // vectors, the total size only needs to be the same. This is a bitcast; 7885 // no bits are changed but the result type is different. 7886 if (isLaxVectorConversion(RHSType, LHSType)) { 7887 Kind = CK_BitCast; 7888 return IncompatibleVectors; 7889 } 7890 } 7891 7892 // When the RHS comes from another lax conversion (e.g. binops between 7893 // scalars and vectors) the result is canonicalized as a vector. When the 7894 // LHS is also a vector, the lax is allowed by the condition above. Handle 7895 // the case where LHS is a scalar. 7896 if (LHSType->isScalarType()) { 7897 const VectorType *VecType = RHSType->getAs<VectorType>(); 7898 if (VecType && VecType->getNumElements() == 1 && 7899 isLaxVectorConversion(RHSType, LHSType)) { 7900 ExprResult *VecExpr = &RHS; 7901 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7902 Kind = CK_BitCast; 7903 return Compatible; 7904 } 7905 } 7906 7907 return Incompatible; 7908 } 7909 7910 // Diagnose attempts to convert between __float128 and long double where 7911 // such conversions currently can't be handled. 7912 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7913 return Incompatible; 7914 7915 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7916 // discards the imaginary part. 7917 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7918 !LHSType->getAs<ComplexType>()) 7919 return Incompatible; 7920 7921 // Arithmetic conversions. 7922 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7923 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7924 if (ConvertRHS) 7925 Kind = PrepareScalarCast(RHS, LHSType); 7926 return Compatible; 7927 } 7928 7929 // Conversions to normal pointers. 7930 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7931 // U* -> T* 7932 if (isa<PointerType>(RHSType)) { 7933 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7934 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7935 if (AddrSpaceL != AddrSpaceR) 7936 Kind = CK_AddressSpaceConversion; 7937 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 7938 Kind = CK_NoOp; 7939 else 7940 Kind = CK_BitCast; 7941 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7942 } 7943 7944 // int -> T* 7945 if (RHSType->isIntegerType()) { 7946 Kind = CK_IntegralToPointer; // FIXME: null? 7947 return IntToPointer; 7948 } 7949 7950 // C pointers are not compatible with ObjC object pointers, 7951 // with two exceptions: 7952 if (isa<ObjCObjectPointerType>(RHSType)) { 7953 // - conversions to void* 7954 if (LHSPointer->getPointeeType()->isVoidType()) { 7955 Kind = CK_BitCast; 7956 return Compatible; 7957 } 7958 7959 // - conversions from 'Class' to the redefinition type 7960 if (RHSType->isObjCClassType() && 7961 Context.hasSameType(LHSType, 7962 Context.getObjCClassRedefinitionType())) { 7963 Kind = CK_BitCast; 7964 return Compatible; 7965 } 7966 7967 Kind = CK_BitCast; 7968 return IncompatiblePointer; 7969 } 7970 7971 // U^ -> void* 7972 if (RHSType->getAs<BlockPointerType>()) { 7973 if (LHSPointer->getPointeeType()->isVoidType()) { 7974 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7975 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7976 ->getPointeeType() 7977 .getAddressSpace(); 7978 Kind = 7979 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7980 return Compatible; 7981 } 7982 } 7983 7984 return Incompatible; 7985 } 7986 7987 // Conversions to block pointers. 7988 if (isa<BlockPointerType>(LHSType)) { 7989 // U^ -> T^ 7990 if (RHSType->isBlockPointerType()) { 7991 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7992 ->getPointeeType() 7993 .getAddressSpace(); 7994 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7995 ->getPointeeType() 7996 .getAddressSpace(); 7997 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7998 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7999 } 8000 8001 // int or null -> T^ 8002 if (RHSType->isIntegerType()) { 8003 Kind = CK_IntegralToPointer; // FIXME: null 8004 return IntToBlockPointer; 8005 } 8006 8007 // id -> T^ 8008 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8009 Kind = CK_AnyPointerToBlockPointerCast; 8010 return Compatible; 8011 } 8012 8013 // void* -> T^ 8014 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8015 if (RHSPT->getPointeeType()->isVoidType()) { 8016 Kind = CK_AnyPointerToBlockPointerCast; 8017 return Compatible; 8018 } 8019 8020 return Incompatible; 8021 } 8022 8023 // Conversions to Objective-C pointers. 8024 if (isa<ObjCObjectPointerType>(LHSType)) { 8025 // A* -> B* 8026 if (RHSType->isObjCObjectPointerType()) { 8027 Kind = CK_BitCast; 8028 Sema::AssignConvertType result = 8029 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8030 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8031 result == Compatible && 8032 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8033 result = IncompatibleObjCWeakRef; 8034 return result; 8035 } 8036 8037 // int or null -> A* 8038 if (RHSType->isIntegerType()) { 8039 Kind = CK_IntegralToPointer; // FIXME: null 8040 return IntToPointer; 8041 } 8042 8043 // In general, C pointers are not compatible with ObjC object pointers, 8044 // with two exceptions: 8045 if (isa<PointerType>(RHSType)) { 8046 Kind = CK_CPointerToObjCPointerCast; 8047 8048 // - conversions from 'void*' 8049 if (RHSType->isVoidPointerType()) { 8050 return Compatible; 8051 } 8052 8053 // - conversions to 'Class' from its redefinition type 8054 if (LHSType->isObjCClassType() && 8055 Context.hasSameType(RHSType, 8056 Context.getObjCClassRedefinitionType())) { 8057 return Compatible; 8058 } 8059 8060 return IncompatiblePointer; 8061 } 8062 8063 // Only under strict condition T^ is compatible with an Objective-C pointer. 8064 if (RHSType->isBlockPointerType() && 8065 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8066 if (ConvertRHS) 8067 maybeExtendBlockObject(RHS); 8068 Kind = CK_BlockPointerToObjCPointerCast; 8069 return Compatible; 8070 } 8071 8072 return Incompatible; 8073 } 8074 8075 // Conversions from pointers that are not covered by the above. 8076 if (isa<PointerType>(RHSType)) { 8077 // T* -> _Bool 8078 if (LHSType == Context.BoolTy) { 8079 Kind = CK_PointerToBoolean; 8080 return Compatible; 8081 } 8082 8083 // T* -> int 8084 if (LHSType->isIntegerType()) { 8085 Kind = CK_PointerToIntegral; 8086 return PointerToInt; 8087 } 8088 8089 return Incompatible; 8090 } 8091 8092 // Conversions from Objective-C pointers that are not covered by the above. 8093 if (isa<ObjCObjectPointerType>(RHSType)) { 8094 // T* -> _Bool 8095 if (LHSType == Context.BoolTy) { 8096 Kind = CK_PointerToBoolean; 8097 return Compatible; 8098 } 8099 8100 // T* -> int 8101 if (LHSType->isIntegerType()) { 8102 Kind = CK_PointerToIntegral; 8103 return PointerToInt; 8104 } 8105 8106 return Incompatible; 8107 } 8108 8109 // struct A -> struct B 8110 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8111 if (Context.typesAreCompatible(LHSType, RHSType)) { 8112 Kind = CK_NoOp; 8113 return Compatible; 8114 } 8115 } 8116 8117 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8118 Kind = CK_IntToOCLSampler; 8119 return Compatible; 8120 } 8121 8122 return Incompatible; 8123 } 8124 8125 /// Constructs a transparent union from an expression that is 8126 /// used to initialize the transparent union. 8127 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8128 ExprResult &EResult, QualType UnionType, 8129 FieldDecl *Field) { 8130 // Build an initializer list that designates the appropriate member 8131 // of the transparent union. 8132 Expr *E = EResult.get(); 8133 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8134 E, SourceLocation()); 8135 Initializer->setType(UnionType); 8136 Initializer->setInitializedFieldInUnion(Field); 8137 8138 // Build a compound literal constructing a value of the transparent 8139 // union type from this initializer list. 8140 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8141 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8142 VK_RValue, Initializer, false); 8143 } 8144 8145 Sema::AssignConvertType 8146 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8147 ExprResult &RHS) { 8148 QualType RHSType = RHS.get()->getType(); 8149 8150 // If the ArgType is a Union type, we want to handle a potential 8151 // transparent_union GCC extension. 8152 const RecordType *UT = ArgType->getAsUnionType(); 8153 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8154 return Incompatible; 8155 8156 // The field to initialize within the transparent union. 8157 RecordDecl *UD = UT->getDecl(); 8158 FieldDecl *InitField = nullptr; 8159 // It's compatible if the expression matches any of the fields. 8160 for (auto *it : UD->fields()) { 8161 if (it->getType()->isPointerType()) { 8162 // If the transparent union contains a pointer type, we allow: 8163 // 1) void pointer 8164 // 2) null pointer constant 8165 if (RHSType->isPointerType()) 8166 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8167 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8168 InitField = it; 8169 break; 8170 } 8171 8172 if (RHS.get()->isNullPointerConstant(Context, 8173 Expr::NPC_ValueDependentIsNull)) { 8174 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8175 CK_NullToPointer); 8176 InitField = it; 8177 break; 8178 } 8179 } 8180 8181 CastKind Kind; 8182 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8183 == Compatible) { 8184 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8185 InitField = it; 8186 break; 8187 } 8188 } 8189 8190 if (!InitField) 8191 return Incompatible; 8192 8193 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8194 return Compatible; 8195 } 8196 8197 Sema::AssignConvertType 8198 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8199 bool Diagnose, 8200 bool DiagnoseCFAudited, 8201 bool ConvertRHS) { 8202 // We need to be able to tell the caller whether we diagnosed a problem, if 8203 // they ask us to issue diagnostics. 8204 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8205 8206 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8207 // we can't avoid *all* modifications at the moment, so we need some somewhere 8208 // to put the updated value. 8209 ExprResult LocalRHS = CallerRHS; 8210 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8211 8212 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8213 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8214 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8215 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8216 Diag(RHS.get()->getExprLoc(), 8217 diag::warn_noderef_to_dereferenceable_pointer) 8218 << RHS.get()->getSourceRange(); 8219 } 8220 } 8221 } 8222 8223 if (getLangOpts().CPlusPlus) { 8224 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8225 // C++ 5.17p3: If the left operand is not of class type, the 8226 // expression is implicitly converted (C++ 4) to the 8227 // cv-unqualified type of the left operand. 8228 QualType RHSType = RHS.get()->getType(); 8229 if (Diagnose) { 8230 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8231 AA_Assigning); 8232 } else { 8233 ImplicitConversionSequence ICS = 8234 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8235 /*SuppressUserConversions=*/false, 8236 /*AllowExplicit=*/false, 8237 /*InOverloadResolution=*/false, 8238 /*CStyle=*/false, 8239 /*AllowObjCWritebackConversion=*/false); 8240 if (ICS.isFailure()) 8241 return Incompatible; 8242 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8243 ICS, AA_Assigning); 8244 } 8245 if (RHS.isInvalid()) 8246 return Incompatible; 8247 Sema::AssignConvertType result = Compatible; 8248 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8249 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8250 result = IncompatibleObjCWeakRef; 8251 return result; 8252 } 8253 8254 // FIXME: Currently, we fall through and treat C++ classes like C 8255 // structures. 8256 // FIXME: We also fall through for atomics; not sure what should 8257 // happen there, though. 8258 } else if (RHS.get()->getType() == Context.OverloadTy) { 8259 // As a set of extensions to C, we support overloading on functions. These 8260 // functions need to be resolved here. 8261 DeclAccessPair DAP; 8262 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8263 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8264 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8265 else 8266 return Incompatible; 8267 } 8268 8269 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8270 // a null pointer constant. 8271 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8272 LHSType->isBlockPointerType()) && 8273 RHS.get()->isNullPointerConstant(Context, 8274 Expr::NPC_ValueDependentIsNull)) { 8275 if (Diagnose || ConvertRHS) { 8276 CastKind Kind; 8277 CXXCastPath Path; 8278 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8279 /*IgnoreBaseAccess=*/false, Diagnose); 8280 if (ConvertRHS) 8281 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8282 } 8283 return Compatible; 8284 } 8285 8286 // OpenCL queue_t type assignment. 8287 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8288 Context, Expr::NPC_ValueDependentIsNull)) { 8289 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8290 return Compatible; 8291 } 8292 8293 // This check seems unnatural, however it is necessary to ensure the proper 8294 // conversion of functions/arrays. If the conversion were done for all 8295 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8296 // expressions that suppress this implicit conversion (&, sizeof). 8297 // 8298 // Suppress this for references: C++ 8.5.3p5. 8299 if (!LHSType->isReferenceType()) { 8300 // FIXME: We potentially allocate here even if ConvertRHS is false. 8301 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8302 if (RHS.isInvalid()) 8303 return Incompatible; 8304 } 8305 CastKind Kind; 8306 Sema::AssignConvertType result = 8307 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8308 8309 // C99 6.5.16.1p2: The value of the right operand is converted to the 8310 // type of the assignment expression. 8311 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8312 // so that we can use references in built-in functions even in C. 8313 // The getNonReferenceType() call makes sure that the resulting expression 8314 // does not have reference type. 8315 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8316 QualType Ty = LHSType.getNonLValueExprType(Context); 8317 Expr *E = RHS.get(); 8318 8319 // Check for various Objective-C errors. If we are not reporting 8320 // diagnostics and just checking for errors, e.g., during overload 8321 // resolution, return Incompatible to indicate the failure. 8322 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8323 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8324 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8325 if (!Diagnose) 8326 return Incompatible; 8327 } 8328 if (getLangOpts().ObjC && 8329 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8330 E->getType(), E, Diagnose) || 8331 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8332 if (!Diagnose) 8333 return Incompatible; 8334 // Replace the expression with a corrected version and continue so we 8335 // can find further errors. 8336 RHS = E; 8337 return Compatible; 8338 } 8339 8340 if (ConvertRHS) 8341 RHS = ImpCastExprToType(E, Ty, Kind); 8342 } 8343 8344 return result; 8345 } 8346 8347 namespace { 8348 /// The original operand to an operator, prior to the application of the usual 8349 /// arithmetic conversions and converting the arguments of a builtin operator 8350 /// candidate. 8351 struct OriginalOperand { 8352 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8353 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8354 Op = MTE->GetTemporaryExpr(); 8355 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8356 Op = BTE->getSubExpr(); 8357 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8358 Orig = ICE->getSubExprAsWritten(); 8359 Conversion = ICE->getConversionFunction(); 8360 } 8361 } 8362 8363 QualType getType() const { return Orig->getType(); } 8364 8365 Expr *Orig; 8366 NamedDecl *Conversion; 8367 }; 8368 } 8369 8370 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8371 ExprResult &RHS) { 8372 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8373 8374 Diag(Loc, diag::err_typecheck_invalid_operands) 8375 << OrigLHS.getType() << OrigRHS.getType() 8376 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8377 8378 // If a user-defined conversion was applied to either of the operands prior 8379 // to applying the built-in operator rules, tell the user about it. 8380 if (OrigLHS.Conversion) { 8381 Diag(OrigLHS.Conversion->getLocation(), 8382 diag::note_typecheck_invalid_operands_converted) 8383 << 0 << LHS.get()->getType(); 8384 } 8385 if (OrigRHS.Conversion) { 8386 Diag(OrigRHS.Conversion->getLocation(), 8387 diag::note_typecheck_invalid_operands_converted) 8388 << 1 << RHS.get()->getType(); 8389 } 8390 8391 return QualType(); 8392 } 8393 8394 // Diagnose cases where a scalar was implicitly converted to a vector and 8395 // diagnose the underlying types. Otherwise, diagnose the error 8396 // as invalid vector logical operands for non-C++ cases. 8397 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8398 ExprResult &RHS) { 8399 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8400 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8401 8402 bool LHSNatVec = LHSType->isVectorType(); 8403 bool RHSNatVec = RHSType->isVectorType(); 8404 8405 if (!(LHSNatVec && RHSNatVec)) { 8406 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8407 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8408 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8409 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8410 << Vector->getSourceRange(); 8411 return QualType(); 8412 } 8413 8414 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8415 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8416 << RHS.get()->getSourceRange(); 8417 8418 return QualType(); 8419 } 8420 8421 /// Try to convert a value of non-vector type to a vector type by converting 8422 /// the type to the element type of the vector and then performing a splat. 8423 /// If the language is OpenCL, we only use conversions that promote scalar 8424 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8425 /// for float->int. 8426 /// 8427 /// OpenCL V2.0 6.2.6.p2: 8428 /// An error shall occur if any scalar operand type has greater rank 8429 /// than the type of the vector element. 8430 /// 8431 /// \param scalar - if non-null, actually perform the conversions 8432 /// \return true if the operation fails (but without diagnosing the failure) 8433 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8434 QualType scalarTy, 8435 QualType vectorEltTy, 8436 QualType vectorTy, 8437 unsigned &DiagID) { 8438 // The conversion to apply to the scalar before splatting it, 8439 // if necessary. 8440 CastKind scalarCast = CK_NoOp; 8441 8442 if (vectorEltTy->isIntegralType(S.Context)) { 8443 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8444 (scalarTy->isIntegerType() && 8445 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8446 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8447 return true; 8448 } 8449 if (!scalarTy->isIntegralType(S.Context)) 8450 return true; 8451 scalarCast = CK_IntegralCast; 8452 } else if (vectorEltTy->isRealFloatingType()) { 8453 if (scalarTy->isRealFloatingType()) { 8454 if (S.getLangOpts().OpenCL && 8455 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8456 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8457 return true; 8458 } 8459 scalarCast = CK_FloatingCast; 8460 } 8461 else if (scalarTy->isIntegralType(S.Context)) 8462 scalarCast = CK_IntegralToFloating; 8463 else 8464 return true; 8465 } else { 8466 return true; 8467 } 8468 8469 // Adjust scalar if desired. 8470 if (scalar) { 8471 if (scalarCast != CK_NoOp) 8472 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8473 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8474 } 8475 return false; 8476 } 8477 8478 /// Convert vector E to a vector with the same number of elements but different 8479 /// element type. 8480 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8481 const auto *VecTy = E->getType()->getAs<VectorType>(); 8482 assert(VecTy && "Expression E must be a vector"); 8483 QualType NewVecTy = S.Context.getVectorType(ElementType, 8484 VecTy->getNumElements(), 8485 VecTy->getVectorKind()); 8486 8487 // Look through the implicit cast. Return the subexpression if its type is 8488 // NewVecTy. 8489 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8490 if (ICE->getSubExpr()->getType() == NewVecTy) 8491 return ICE->getSubExpr(); 8492 8493 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8494 return S.ImpCastExprToType(E, NewVecTy, Cast); 8495 } 8496 8497 /// Test if a (constant) integer Int can be casted to another integer type 8498 /// IntTy without losing precision. 8499 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8500 QualType OtherIntTy) { 8501 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8502 8503 // Reject cases where the value of the Int is unknown as that would 8504 // possibly cause truncation, but accept cases where the scalar can be 8505 // demoted without loss of precision. 8506 Expr::EvalResult EVResult; 8507 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8508 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8509 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8510 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8511 8512 if (CstInt) { 8513 // If the scalar is constant and is of a higher order and has more active 8514 // bits that the vector element type, reject it. 8515 llvm::APSInt Result = EVResult.Val.getInt(); 8516 unsigned NumBits = IntSigned 8517 ? (Result.isNegative() ? Result.getMinSignedBits() 8518 : Result.getActiveBits()) 8519 : Result.getActiveBits(); 8520 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8521 return true; 8522 8523 // If the signedness of the scalar type and the vector element type 8524 // differs and the number of bits is greater than that of the vector 8525 // element reject it. 8526 return (IntSigned != OtherIntSigned && 8527 NumBits > S.Context.getIntWidth(OtherIntTy)); 8528 } 8529 8530 // Reject cases where the value of the scalar is not constant and it's 8531 // order is greater than that of the vector element type. 8532 return (Order < 0); 8533 } 8534 8535 /// Test if a (constant) integer Int can be casted to floating point type 8536 /// FloatTy without losing precision. 8537 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8538 QualType FloatTy) { 8539 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8540 8541 // Determine if the integer constant can be expressed as a floating point 8542 // number of the appropriate type. 8543 Expr::EvalResult EVResult; 8544 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8545 8546 uint64_t Bits = 0; 8547 if (CstInt) { 8548 // Reject constants that would be truncated if they were converted to 8549 // the floating point type. Test by simple to/from conversion. 8550 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8551 // could be avoided if there was a convertFromAPInt method 8552 // which could signal back if implicit truncation occurred. 8553 llvm::APSInt Result = EVResult.Val.getInt(); 8554 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8555 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8556 llvm::APFloat::rmTowardZero); 8557 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8558 !IntTy->hasSignedIntegerRepresentation()); 8559 bool Ignored = false; 8560 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8561 &Ignored); 8562 if (Result != ConvertBack) 8563 return true; 8564 } else { 8565 // Reject types that cannot be fully encoded into the mantissa of 8566 // the float. 8567 Bits = S.Context.getTypeSize(IntTy); 8568 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8569 S.Context.getFloatTypeSemantics(FloatTy)); 8570 if (Bits > FloatPrec) 8571 return true; 8572 } 8573 8574 return false; 8575 } 8576 8577 /// Attempt to convert and splat Scalar into a vector whose types matches 8578 /// Vector following GCC conversion rules. The rule is that implicit 8579 /// conversion can occur when Scalar can be casted to match Vector's element 8580 /// type without causing truncation of Scalar. 8581 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8582 ExprResult *Vector) { 8583 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8584 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8585 const VectorType *VT = VectorTy->getAs<VectorType>(); 8586 8587 assert(!isa<ExtVectorType>(VT) && 8588 "ExtVectorTypes should not be handled here!"); 8589 8590 QualType VectorEltTy = VT->getElementType(); 8591 8592 // Reject cases where the vector element type or the scalar element type are 8593 // not integral or floating point types. 8594 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8595 return true; 8596 8597 // The conversion to apply to the scalar before splatting it, 8598 // if necessary. 8599 CastKind ScalarCast = CK_NoOp; 8600 8601 // Accept cases where the vector elements are integers and the scalar is 8602 // an integer. 8603 // FIXME: Notionally if the scalar was a floating point value with a precise 8604 // integral representation, we could cast it to an appropriate integer 8605 // type and then perform the rest of the checks here. GCC will perform 8606 // this conversion in some cases as determined by the input language. 8607 // We should accept it on a language independent basis. 8608 if (VectorEltTy->isIntegralType(S.Context) && 8609 ScalarTy->isIntegralType(S.Context) && 8610 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8611 8612 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8613 return true; 8614 8615 ScalarCast = CK_IntegralCast; 8616 } else if (VectorEltTy->isRealFloatingType()) { 8617 if (ScalarTy->isRealFloatingType()) { 8618 8619 // Reject cases where the scalar type is not a constant and has a higher 8620 // Order than the vector element type. 8621 llvm::APFloat Result(0.0); 8622 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8623 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8624 if (!CstScalar && Order < 0) 8625 return true; 8626 8627 // If the scalar cannot be safely casted to the vector element type, 8628 // reject it. 8629 if (CstScalar) { 8630 bool Truncated = false; 8631 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8632 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8633 if (Truncated) 8634 return true; 8635 } 8636 8637 ScalarCast = CK_FloatingCast; 8638 } else if (ScalarTy->isIntegralType(S.Context)) { 8639 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8640 return true; 8641 8642 ScalarCast = CK_IntegralToFloating; 8643 } else 8644 return true; 8645 } 8646 8647 // Adjust scalar if desired. 8648 if (Scalar) { 8649 if (ScalarCast != CK_NoOp) 8650 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8651 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8652 } 8653 return false; 8654 } 8655 8656 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8657 SourceLocation Loc, bool IsCompAssign, 8658 bool AllowBothBool, 8659 bool AllowBoolConversions) { 8660 if (!IsCompAssign) { 8661 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8662 if (LHS.isInvalid()) 8663 return QualType(); 8664 } 8665 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8666 if (RHS.isInvalid()) 8667 return QualType(); 8668 8669 // For conversion purposes, we ignore any qualifiers. 8670 // For example, "const float" and "float" are equivalent. 8671 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8672 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8673 8674 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8675 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8676 assert(LHSVecType || RHSVecType); 8677 8678 // AltiVec-style "vector bool op vector bool" combinations are allowed 8679 // for some operators but not others. 8680 if (!AllowBothBool && 8681 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8682 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8683 return InvalidOperands(Loc, LHS, RHS); 8684 8685 // If the vector types are identical, return. 8686 if (Context.hasSameType(LHSType, RHSType)) 8687 return LHSType; 8688 8689 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8690 if (LHSVecType && RHSVecType && 8691 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8692 if (isa<ExtVectorType>(LHSVecType)) { 8693 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8694 return LHSType; 8695 } 8696 8697 if (!IsCompAssign) 8698 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8699 return RHSType; 8700 } 8701 8702 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8703 // can be mixed, with the result being the non-bool type. The non-bool 8704 // operand must have integer element type. 8705 if (AllowBoolConversions && LHSVecType && RHSVecType && 8706 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8707 (Context.getTypeSize(LHSVecType->getElementType()) == 8708 Context.getTypeSize(RHSVecType->getElementType()))) { 8709 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8710 LHSVecType->getElementType()->isIntegerType() && 8711 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8712 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8713 return LHSType; 8714 } 8715 if (!IsCompAssign && 8716 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8717 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8718 RHSVecType->getElementType()->isIntegerType()) { 8719 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8720 return RHSType; 8721 } 8722 } 8723 8724 // If there's a vector type and a scalar, try to convert the scalar to 8725 // the vector element type and splat. 8726 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8727 if (!RHSVecType) { 8728 if (isa<ExtVectorType>(LHSVecType)) { 8729 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8730 LHSVecType->getElementType(), LHSType, 8731 DiagID)) 8732 return LHSType; 8733 } else { 8734 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8735 return LHSType; 8736 } 8737 } 8738 if (!LHSVecType) { 8739 if (isa<ExtVectorType>(RHSVecType)) { 8740 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8741 LHSType, RHSVecType->getElementType(), 8742 RHSType, DiagID)) 8743 return RHSType; 8744 } else { 8745 if (LHS.get()->getValueKind() == VK_LValue || 8746 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8747 return RHSType; 8748 } 8749 } 8750 8751 // FIXME: The code below also handles conversion between vectors and 8752 // non-scalars, we should break this down into fine grained specific checks 8753 // and emit proper diagnostics. 8754 QualType VecType = LHSVecType ? LHSType : RHSType; 8755 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8756 QualType OtherType = LHSVecType ? RHSType : LHSType; 8757 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8758 if (isLaxVectorConversion(OtherType, VecType)) { 8759 // If we're allowing lax vector conversions, only the total (data) size 8760 // needs to be the same. For non compound assignment, if one of the types is 8761 // scalar, the result is always the vector type. 8762 if (!IsCompAssign) { 8763 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8764 return VecType; 8765 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8766 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8767 // type. Note that this is already done by non-compound assignments in 8768 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8769 // <1 x T> -> T. The result is also a vector type. 8770 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8771 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8772 ExprResult *RHSExpr = &RHS; 8773 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8774 return VecType; 8775 } 8776 } 8777 8778 // Okay, the expression is invalid. 8779 8780 // If there's a non-vector, non-real operand, diagnose that. 8781 if ((!RHSVecType && !RHSType->isRealType()) || 8782 (!LHSVecType && !LHSType->isRealType())) { 8783 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8784 << LHSType << RHSType 8785 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8786 return QualType(); 8787 } 8788 8789 // OpenCL V1.1 6.2.6.p1: 8790 // If the operands are of more than one vector type, then an error shall 8791 // occur. Implicit conversions between vector types are not permitted, per 8792 // section 6.2.1. 8793 if (getLangOpts().OpenCL && 8794 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8795 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8796 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8797 << RHSType; 8798 return QualType(); 8799 } 8800 8801 8802 // If there is a vector type that is not a ExtVector and a scalar, we reach 8803 // this point if scalar could not be converted to the vector's element type 8804 // without truncation. 8805 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8806 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8807 QualType Scalar = LHSVecType ? RHSType : LHSType; 8808 QualType Vector = LHSVecType ? LHSType : RHSType; 8809 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8810 Diag(Loc, 8811 diag::err_typecheck_vector_not_convertable_implict_truncation) 8812 << ScalarOrVector << Scalar << Vector; 8813 8814 return QualType(); 8815 } 8816 8817 // Otherwise, use the generic diagnostic. 8818 Diag(Loc, DiagID) 8819 << LHSType << RHSType 8820 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8821 return QualType(); 8822 } 8823 8824 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8825 // expression. These are mainly cases where the null pointer is used as an 8826 // integer instead of a pointer. 8827 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8828 SourceLocation Loc, bool IsCompare) { 8829 // The canonical way to check for a GNU null is with isNullPointerConstant, 8830 // but we use a bit of a hack here for speed; this is a relatively 8831 // hot path, and isNullPointerConstant is slow. 8832 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8833 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8834 8835 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8836 8837 // Avoid analyzing cases where the result will either be invalid (and 8838 // diagnosed as such) or entirely valid and not something to warn about. 8839 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8840 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8841 return; 8842 8843 // Comparison operations would not make sense with a null pointer no matter 8844 // what the other expression is. 8845 if (!IsCompare) { 8846 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8847 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8848 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8849 return; 8850 } 8851 8852 // The rest of the operations only make sense with a null pointer 8853 // if the other expression is a pointer. 8854 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8855 NonNullType->canDecayToPointerType()) 8856 return; 8857 8858 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8859 << LHSNull /* LHS is NULL */ << NonNullType 8860 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8861 } 8862 8863 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8864 SourceLocation Loc) { 8865 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 8866 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 8867 if (!LUE || !RUE) 8868 return; 8869 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 8870 RUE->getKind() != UETT_SizeOf) 8871 return; 8872 8873 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 8874 QualType RHSTy; 8875 8876 if (RUE->isArgumentType()) 8877 RHSTy = RUE->getArgumentType(); 8878 else 8879 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 8880 8881 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 8882 return; 8883 if (LHSTy->getPointeeType() != RHSTy) 8884 return; 8885 8886 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 8887 } 8888 8889 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8890 ExprResult &RHS, 8891 SourceLocation Loc, bool IsDiv) { 8892 // Check for division/remainder by zero. 8893 Expr::EvalResult RHSValue; 8894 if (!RHS.get()->isValueDependent() && 8895 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 8896 RHSValue.Val.getInt() == 0) 8897 S.DiagRuntimeBehavior(Loc, RHS.get(), 8898 S.PDiag(diag::warn_remainder_division_by_zero) 8899 << IsDiv << RHS.get()->getSourceRange()); 8900 } 8901 8902 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8903 SourceLocation Loc, 8904 bool IsCompAssign, bool IsDiv) { 8905 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8906 8907 if (LHS.get()->getType()->isVectorType() || 8908 RHS.get()->getType()->isVectorType()) 8909 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8910 /*AllowBothBool*/getLangOpts().AltiVec, 8911 /*AllowBoolConversions*/false); 8912 8913 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8914 if (LHS.isInvalid() || RHS.isInvalid()) 8915 return QualType(); 8916 8917 8918 if (compType.isNull() || !compType->isArithmeticType()) 8919 return InvalidOperands(Loc, LHS, RHS); 8920 if (IsDiv) { 8921 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8922 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 8923 } 8924 return compType; 8925 } 8926 8927 QualType Sema::CheckRemainderOperands( 8928 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8929 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8930 8931 if (LHS.get()->getType()->isVectorType() || 8932 RHS.get()->getType()->isVectorType()) { 8933 if (LHS.get()->getType()->hasIntegerRepresentation() && 8934 RHS.get()->getType()->hasIntegerRepresentation()) 8935 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8936 /*AllowBothBool*/getLangOpts().AltiVec, 8937 /*AllowBoolConversions*/false); 8938 return InvalidOperands(Loc, LHS, RHS); 8939 } 8940 8941 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8942 if (LHS.isInvalid() || RHS.isInvalid()) 8943 return QualType(); 8944 8945 if (compType.isNull() || !compType->isIntegerType()) 8946 return InvalidOperands(Loc, LHS, RHS); 8947 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8948 return compType; 8949 } 8950 8951 /// Diagnose invalid arithmetic on two void pointers. 8952 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8953 Expr *LHSExpr, Expr *RHSExpr) { 8954 S.Diag(Loc, S.getLangOpts().CPlusPlus 8955 ? diag::err_typecheck_pointer_arith_void_type 8956 : diag::ext_gnu_void_ptr) 8957 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8958 << RHSExpr->getSourceRange(); 8959 } 8960 8961 /// Diagnose invalid arithmetic on a void pointer. 8962 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8963 Expr *Pointer) { 8964 S.Diag(Loc, S.getLangOpts().CPlusPlus 8965 ? diag::err_typecheck_pointer_arith_void_type 8966 : diag::ext_gnu_void_ptr) 8967 << 0 /* one pointer */ << Pointer->getSourceRange(); 8968 } 8969 8970 /// Diagnose invalid arithmetic on a null pointer. 8971 /// 8972 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8973 /// idiom, which we recognize as a GNU extension. 8974 /// 8975 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8976 Expr *Pointer, bool IsGNUIdiom) { 8977 if (IsGNUIdiom) 8978 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8979 << Pointer->getSourceRange(); 8980 else 8981 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8982 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8983 } 8984 8985 /// Diagnose invalid arithmetic on two function pointers. 8986 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8987 Expr *LHS, Expr *RHS) { 8988 assert(LHS->getType()->isAnyPointerType()); 8989 assert(RHS->getType()->isAnyPointerType()); 8990 S.Diag(Loc, S.getLangOpts().CPlusPlus 8991 ? diag::err_typecheck_pointer_arith_function_type 8992 : diag::ext_gnu_ptr_func_arith) 8993 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8994 // We only show the second type if it differs from the first. 8995 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8996 RHS->getType()) 8997 << RHS->getType()->getPointeeType() 8998 << LHS->getSourceRange() << RHS->getSourceRange(); 8999 } 9000 9001 /// Diagnose invalid arithmetic on a function pointer. 9002 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9003 Expr *Pointer) { 9004 assert(Pointer->getType()->isAnyPointerType()); 9005 S.Diag(Loc, S.getLangOpts().CPlusPlus 9006 ? diag::err_typecheck_pointer_arith_function_type 9007 : diag::ext_gnu_ptr_func_arith) 9008 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9009 << 0 /* one pointer, so only one type */ 9010 << Pointer->getSourceRange(); 9011 } 9012 9013 /// Emit error if Operand is incomplete pointer type 9014 /// 9015 /// \returns True if pointer has incomplete type 9016 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9017 Expr *Operand) { 9018 QualType ResType = Operand->getType(); 9019 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9020 ResType = ResAtomicType->getValueType(); 9021 9022 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9023 QualType PointeeTy = ResType->getPointeeType(); 9024 return S.RequireCompleteType(Loc, PointeeTy, 9025 diag::err_typecheck_arithmetic_incomplete_type, 9026 PointeeTy, Operand->getSourceRange()); 9027 } 9028 9029 /// Check the validity of an arithmetic pointer operand. 9030 /// 9031 /// If the operand has pointer type, this code will check for pointer types 9032 /// which are invalid in arithmetic operations. These will be diagnosed 9033 /// appropriately, including whether or not the use is supported as an 9034 /// extension. 9035 /// 9036 /// \returns True when the operand is valid to use (even if as an extension). 9037 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9038 Expr *Operand) { 9039 QualType ResType = Operand->getType(); 9040 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9041 ResType = ResAtomicType->getValueType(); 9042 9043 if (!ResType->isAnyPointerType()) return true; 9044 9045 QualType PointeeTy = ResType->getPointeeType(); 9046 if (PointeeTy->isVoidType()) { 9047 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9048 return !S.getLangOpts().CPlusPlus; 9049 } 9050 if (PointeeTy->isFunctionType()) { 9051 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9052 return !S.getLangOpts().CPlusPlus; 9053 } 9054 9055 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9056 9057 return true; 9058 } 9059 9060 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9061 /// operands. 9062 /// 9063 /// This routine will diagnose any invalid arithmetic on pointer operands much 9064 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9065 /// for emitting a single diagnostic even for operations where both LHS and RHS 9066 /// are (potentially problematic) pointers. 9067 /// 9068 /// \returns True when the operand is valid to use (even if as an extension). 9069 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9070 Expr *LHSExpr, Expr *RHSExpr) { 9071 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9072 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9073 if (!isLHSPointer && !isRHSPointer) return true; 9074 9075 QualType LHSPointeeTy, RHSPointeeTy; 9076 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9077 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9078 9079 // if both are pointers check if operation is valid wrt address spaces 9080 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9081 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9082 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9083 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9084 S.Diag(Loc, 9085 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9086 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9087 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9088 return false; 9089 } 9090 } 9091 9092 // Check for arithmetic on pointers to incomplete types. 9093 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9094 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9095 if (isLHSVoidPtr || isRHSVoidPtr) { 9096 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9097 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9098 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9099 9100 return !S.getLangOpts().CPlusPlus; 9101 } 9102 9103 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9104 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9105 if (isLHSFuncPtr || isRHSFuncPtr) { 9106 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9107 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9108 RHSExpr); 9109 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9110 9111 return !S.getLangOpts().CPlusPlus; 9112 } 9113 9114 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9115 return false; 9116 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9117 return false; 9118 9119 return true; 9120 } 9121 9122 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9123 /// literal. 9124 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9125 Expr *LHSExpr, Expr *RHSExpr) { 9126 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9127 Expr* IndexExpr = RHSExpr; 9128 if (!StrExpr) { 9129 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9130 IndexExpr = LHSExpr; 9131 } 9132 9133 bool IsStringPlusInt = StrExpr && 9134 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9135 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9136 return; 9137 9138 Expr::EvalResult Result; 9139 if (IndexExpr->EvaluateAsInt(Result, Self.getASTContext())) { 9140 llvm::APSInt index = Result.Val.getInt(); 9141 unsigned StrLenWithNull = StrExpr->getLength() + 1; 9142 if (index.isNonNegative() && 9143 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 9144 index.isUnsigned())) 9145 return; 9146 } 9147 9148 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9149 Self.Diag(OpLoc, diag::warn_string_plus_int) 9150 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9151 9152 // Only print a fixit for "str" + int, not for int + "str". 9153 if (IndexExpr == RHSExpr) { 9154 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9155 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9156 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9157 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9158 << FixItHint::CreateInsertion(EndLoc, "]"); 9159 } else 9160 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9161 } 9162 9163 /// Emit a warning when adding a char literal to a string. 9164 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9165 Expr *LHSExpr, Expr *RHSExpr) { 9166 const Expr *StringRefExpr = LHSExpr; 9167 const CharacterLiteral *CharExpr = 9168 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9169 9170 if (!CharExpr) { 9171 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9172 StringRefExpr = RHSExpr; 9173 } 9174 9175 if (!CharExpr || !StringRefExpr) 9176 return; 9177 9178 const QualType StringType = StringRefExpr->getType(); 9179 9180 // Return if not a PointerType. 9181 if (!StringType->isAnyPointerType()) 9182 return; 9183 9184 // Return if not a CharacterType. 9185 if (!StringType->getPointeeType()->isAnyCharacterType()) 9186 return; 9187 9188 ASTContext &Ctx = Self.getASTContext(); 9189 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9190 9191 const QualType CharType = CharExpr->getType(); 9192 if (!CharType->isAnyCharacterType() && 9193 CharType->isIntegerType() && 9194 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9195 Self.Diag(OpLoc, diag::warn_string_plus_char) 9196 << DiagRange << Ctx.CharTy; 9197 } else { 9198 Self.Diag(OpLoc, diag::warn_string_plus_char) 9199 << DiagRange << CharExpr->getType(); 9200 } 9201 9202 // Only print a fixit for str + char, not for char + str. 9203 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9204 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9205 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9206 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9207 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9208 << FixItHint::CreateInsertion(EndLoc, "]"); 9209 } else { 9210 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9211 } 9212 } 9213 9214 /// Emit error when two pointers are incompatible. 9215 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9216 Expr *LHSExpr, Expr *RHSExpr) { 9217 assert(LHSExpr->getType()->isAnyPointerType()); 9218 assert(RHSExpr->getType()->isAnyPointerType()); 9219 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9220 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9221 << RHSExpr->getSourceRange(); 9222 } 9223 9224 // C99 6.5.6 9225 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9226 SourceLocation Loc, BinaryOperatorKind Opc, 9227 QualType* CompLHSTy) { 9228 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9229 9230 if (LHS.get()->getType()->isVectorType() || 9231 RHS.get()->getType()->isVectorType()) { 9232 QualType compType = CheckVectorOperands( 9233 LHS, RHS, Loc, CompLHSTy, 9234 /*AllowBothBool*/getLangOpts().AltiVec, 9235 /*AllowBoolConversions*/getLangOpts().ZVector); 9236 if (CompLHSTy) *CompLHSTy = compType; 9237 return compType; 9238 } 9239 9240 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9241 if (LHS.isInvalid() || RHS.isInvalid()) 9242 return QualType(); 9243 9244 // Diagnose "string literal" '+' int and string '+' "char literal". 9245 if (Opc == BO_Add) { 9246 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9247 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9248 } 9249 9250 // handle the common case first (both operands are arithmetic). 9251 if (!compType.isNull() && compType->isArithmeticType()) { 9252 if (CompLHSTy) *CompLHSTy = compType; 9253 return compType; 9254 } 9255 9256 // Type-checking. Ultimately the pointer's going to be in PExp; 9257 // note that we bias towards the LHS being the pointer. 9258 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9259 9260 bool isObjCPointer; 9261 if (PExp->getType()->isPointerType()) { 9262 isObjCPointer = false; 9263 } else if (PExp->getType()->isObjCObjectPointerType()) { 9264 isObjCPointer = true; 9265 } else { 9266 std::swap(PExp, IExp); 9267 if (PExp->getType()->isPointerType()) { 9268 isObjCPointer = false; 9269 } else if (PExp->getType()->isObjCObjectPointerType()) { 9270 isObjCPointer = true; 9271 } else { 9272 return InvalidOperands(Loc, LHS, RHS); 9273 } 9274 } 9275 assert(PExp->getType()->isAnyPointerType()); 9276 9277 if (!IExp->getType()->isIntegerType()) 9278 return InvalidOperands(Loc, LHS, RHS); 9279 9280 // Adding to a null pointer results in undefined behavior. 9281 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9282 Context, Expr::NPC_ValueDependentIsNotNull)) { 9283 // In C++ adding zero to a null pointer is defined. 9284 Expr::EvalResult KnownVal; 9285 if (!getLangOpts().CPlusPlus || 9286 (!IExp->isValueDependent() && 9287 (!IExp->EvaluateAsInt(KnownVal, Context) || 9288 KnownVal.Val.getInt() != 0))) { 9289 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9290 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9291 Context, BO_Add, PExp, IExp); 9292 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9293 } 9294 } 9295 9296 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9297 return QualType(); 9298 9299 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9300 return QualType(); 9301 9302 // Check array bounds for pointer arithemtic 9303 CheckArrayAccess(PExp, IExp); 9304 9305 if (CompLHSTy) { 9306 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9307 if (LHSTy.isNull()) { 9308 LHSTy = LHS.get()->getType(); 9309 if (LHSTy->isPromotableIntegerType()) 9310 LHSTy = Context.getPromotedIntegerType(LHSTy); 9311 } 9312 *CompLHSTy = LHSTy; 9313 } 9314 9315 return PExp->getType(); 9316 } 9317 9318 // C99 6.5.6 9319 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9320 SourceLocation Loc, 9321 QualType* CompLHSTy) { 9322 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9323 9324 if (LHS.get()->getType()->isVectorType() || 9325 RHS.get()->getType()->isVectorType()) { 9326 QualType compType = CheckVectorOperands( 9327 LHS, RHS, Loc, CompLHSTy, 9328 /*AllowBothBool*/getLangOpts().AltiVec, 9329 /*AllowBoolConversions*/getLangOpts().ZVector); 9330 if (CompLHSTy) *CompLHSTy = compType; 9331 return compType; 9332 } 9333 9334 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9335 if (LHS.isInvalid() || RHS.isInvalid()) 9336 return QualType(); 9337 9338 // Enforce type constraints: C99 6.5.6p3. 9339 9340 // Handle the common case first (both operands are arithmetic). 9341 if (!compType.isNull() && compType->isArithmeticType()) { 9342 if (CompLHSTy) *CompLHSTy = compType; 9343 return compType; 9344 } 9345 9346 // Either ptr - int or ptr - ptr. 9347 if (LHS.get()->getType()->isAnyPointerType()) { 9348 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9349 9350 // Diagnose bad cases where we step over interface counts. 9351 if (LHS.get()->getType()->isObjCObjectPointerType() && 9352 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9353 return QualType(); 9354 9355 // The result type of a pointer-int computation is the pointer type. 9356 if (RHS.get()->getType()->isIntegerType()) { 9357 // Subtracting from a null pointer should produce a warning. 9358 // The last argument to the diagnose call says this doesn't match the 9359 // GNU int-to-pointer idiom. 9360 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9361 Expr::NPC_ValueDependentIsNotNull)) { 9362 // In C++ adding zero to a null pointer is defined. 9363 Expr::EvalResult KnownVal; 9364 if (!getLangOpts().CPlusPlus || 9365 (!RHS.get()->isValueDependent() && 9366 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9367 KnownVal.Val.getInt() != 0))) { 9368 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9369 } 9370 } 9371 9372 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9373 return QualType(); 9374 9375 // Check array bounds for pointer arithemtic 9376 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9377 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9378 9379 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9380 return LHS.get()->getType(); 9381 } 9382 9383 // Handle pointer-pointer subtractions. 9384 if (const PointerType *RHSPTy 9385 = RHS.get()->getType()->getAs<PointerType>()) { 9386 QualType rpointee = RHSPTy->getPointeeType(); 9387 9388 if (getLangOpts().CPlusPlus) { 9389 // Pointee types must be the same: C++ [expr.add] 9390 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9391 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9392 } 9393 } else { 9394 // Pointee types must be compatible C99 6.5.6p3 9395 if (!Context.typesAreCompatible( 9396 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9397 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9398 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9399 return QualType(); 9400 } 9401 } 9402 9403 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9404 LHS.get(), RHS.get())) 9405 return QualType(); 9406 9407 // FIXME: Add warnings for nullptr - ptr. 9408 9409 // The pointee type may have zero size. As an extension, a structure or 9410 // union may have zero size or an array may have zero length. In this 9411 // case subtraction does not make sense. 9412 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9413 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9414 if (ElementSize.isZero()) { 9415 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9416 << rpointee.getUnqualifiedType() 9417 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9418 } 9419 } 9420 9421 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9422 return Context.getPointerDiffType(); 9423 } 9424 } 9425 9426 return InvalidOperands(Loc, LHS, RHS); 9427 } 9428 9429 static bool isScopedEnumerationType(QualType T) { 9430 if (const EnumType *ET = T->getAs<EnumType>()) 9431 return ET->getDecl()->isScoped(); 9432 return false; 9433 } 9434 9435 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9436 SourceLocation Loc, BinaryOperatorKind Opc, 9437 QualType LHSType) { 9438 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9439 // so skip remaining warnings as we don't want to modify values within Sema. 9440 if (S.getLangOpts().OpenCL) 9441 return; 9442 9443 // Check right/shifter operand 9444 Expr::EvalResult RHSResult; 9445 if (RHS.get()->isValueDependent() || 9446 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9447 return; 9448 llvm::APSInt Right = RHSResult.Val.getInt(); 9449 9450 if (Right.isNegative()) { 9451 S.DiagRuntimeBehavior(Loc, RHS.get(), 9452 S.PDiag(diag::warn_shift_negative) 9453 << RHS.get()->getSourceRange()); 9454 return; 9455 } 9456 llvm::APInt LeftBits(Right.getBitWidth(), 9457 S.Context.getTypeSize(LHS.get()->getType())); 9458 if (Right.uge(LeftBits)) { 9459 S.DiagRuntimeBehavior(Loc, RHS.get(), 9460 S.PDiag(diag::warn_shift_gt_typewidth) 9461 << RHS.get()->getSourceRange()); 9462 return; 9463 } 9464 if (Opc != BO_Shl) 9465 return; 9466 9467 // When left shifting an ICE which is signed, we can check for overflow which 9468 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9469 // integers have defined behavior modulo one more than the maximum value 9470 // representable in the result type, so never warn for those. 9471 Expr::EvalResult LHSResult; 9472 if (LHS.get()->isValueDependent() || 9473 LHSType->hasUnsignedIntegerRepresentation() || 9474 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9475 return; 9476 llvm::APSInt Left = LHSResult.Val.getInt(); 9477 9478 // If LHS does not have a signed type and non-negative value 9479 // then, the behavior is undefined. Warn about it. 9480 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9481 S.DiagRuntimeBehavior(Loc, LHS.get(), 9482 S.PDiag(diag::warn_shift_lhs_negative) 9483 << LHS.get()->getSourceRange()); 9484 return; 9485 } 9486 9487 llvm::APInt ResultBits = 9488 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9489 if (LeftBits.uge(ResultBits)) 9490 return; 9491 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9492 Result = Result.shl(Right); 9493 9494 // Print the bit representation of the signed integer as an unsigned 9495 // hexadecimal number. 9496 SmallString<40> HexResult; 9497 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9498 9499 // If we are only missing a sign bit, this is less likely to result in actual 9500 // bugs -- if the result is cast back to an unsigned type, it will have the 9501 // expected value. Thus we place this behind a different warning that can be 9502 // turned off separately if needed. 9503 if (LeftBits == ResultBits - 1) { 9504 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9505 << HexResult << LHSType 9506 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9507 return; 9508 } 9509 9510 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9511 << HexResult.str() << Result.getMinSignedBits() << LHSType 9512 << Left.getBitWidth() << LHS.get()->getSourceRange() 9513 << RHS.get()->getSourceRange(); 9514 } 9515 9516 /// Return the resulting type when a vector is shifted 9517 /// by a scalar or vector shift amount. 9518 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9519 SourceLocation Loc, bool IsCompAssign) { 9520 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9521 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9522 !LHS.get()->getType()->isVectorType()) { 9523 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9524 << RHS.get()->getType() << LHS.get()->getType() 9525 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9526 return QualType(); 9527 } 9528 9529 if (!IsCompAssign) { 9530 LHS = S.UsualUnaryConversions(LHS.get()); 9531 if (LHS.isInvalid()) return QualType(); 9532 } 9533 9534 RHS = S.UsualUnaryConversions(RHS.get()); 9535 if (RHS.isInvalid()) return QualType(); 9536 9537 QualType LHSType = LHS.get()->getType(); 9538 // Note that LHS might be a scalar because the routine calls not only in 9539 // OpenCL case. 9540 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9541 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9542 9543 // Note that RHS might not be a vector. 9544 QualType RHSType = RHS.get()->getType(); 9545 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9546 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9547 9548 // The operands need to be integers. 9549 if (!LHSEleType->isIntegerType()) { 9550 S.Diag(Loc, diag::err_typecheck_expect_int) 9551 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9552 return QualType(); 9553 } 9554 9555 if (!RHSEleType->isIntegerType()) { 9556 S.Diag(Loc, diag::err_typecheck_expect_int) 9557 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9558 return QualType(); 9559 } 9560 9561 if (!LHSVecTy) { 9562 assert(RHSVecTy); 9563 if (IsCompAssign) 9564 return RHSType; 9565 if (LHSEleType != RHSEleType) { 9566 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9567 LHSEleType = RHSEleType; 9568 } 9569 QualType VecTy = 9570 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9571 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9572 LHSType = VecTy; 9573 } else if (RHSVecTy) { 9574 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9575 // are applied component-wise. So if RHS is a vector, then ensure 9576 // that the number of elements is the same as LHS... 9577 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9578 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9579 << LHS.get()->getType() << RHS.get()->getType() 9580 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9581 return QualType(); 9582 } 9583 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9584 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9585 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9586 if (LHSBT != RHSBT && 9587 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9588 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9589 << LHS.get()->getType() << RHS.get()->getType() 9590 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9591 } 9592 } 9593 } else { 9594 // ...else expand RHS to match the number of elements in LHS. 9595 QualType VecTy = 9596 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9597 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9598 } 9599 9600 return LHSType; 9601 } 9602 9603 // C99 6.5.7 9604 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9605 SourceLocation Loc, BinaryOperatorKind Opc, 9606 bool IsCompAssign) { 9607 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9608 9609 // Vector shifts promote their scalar inputs to vector type. 9610 if (LHS.get()->getType()->isVectorType() || 9611 RHS.get()->getType()->isVectorType()) { 9612 if (LangOpts.ZVector) { 9613 // The shift operators for the z vector extensions work basically 9614 // like general shifts, except that neither the LHS nor the RHS is 9615 // allowed to be a "vector bool". 9616 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9617 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9618 return InvalidOperands(Loc, LHS, RHS); 9619 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9620 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9621 return InvalidOperands(Loc, LHS, RHS); 9622 } 9623 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9624 } 9625 9626 // Shifts don't perform usual arithmetic conversions, they just do integer 9627 // promotions on each operand. C99 6.5.7p3 9628 9629 // For the LHS, do usual unary conversions, but then reset them away 9630 // if this is a compound assignment. 9631 ExprResult OldLHS = LHS; 9632 LHS = UsualUnaryConversions(LHS.get()); 9633 if (LHS.isInvalid()) 9634 return QualType(); 9635 QualType LHSType = LHS.get()->getType(); 9636 if (IsCompAssign) LHS = OldLHS; 9637 9638 // The RHS is simpler. 9639 RHS = UsualUnaryConversions(RHS.get()); 9640 if (RHS.isInvalid()) 9641 return QualType(); 9642 QualType RHSType = RHS.get()->getType(); 9643 9644 // C99 6.5.7p2: Each of the operands shall have integer type. 9645 if (!LHSType->hasIntegerRepresentation() || 9646 !RHSType->hasIntegerRepresentation()) 9647 return InvalidOperands(Loc, LHS, RHS); 9648 9649 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9650 // hasIntegerRepresentation() above instead of this. 9651 if (isScopedEnumerationType(LHSType) || 9652 isScopedEnumerationType(RHSType)) { 9653 return InvalidOperands(Loc, LHS, RHS); 9654 } 9655 // Sanity-check shift operands 9656 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9657 9658 // "The type of the result is that of the promoted left operand." 9659 return LHSType; 9660 } 9661 9662 /// If two different enums are compared, raise a warning. 9663 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9664 Expr *RHS) { 9665 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9666 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9667 9668 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9669 if (!LHSEnumType) 9670 return; 9671 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9672 if (!RHSEnumType) 9673 return; 9674 9675 // Ignore anonymous enums. 9676 if (!LHSEnumType->getDecl()->getIdentifier() && 9677 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9678 return; 9679 if (!RHSEnumType->getDecl()->getIdentifier() && 9680 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9681 return; 9682 9683 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9684 return; 9685 9686 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9687 << LHSStrippedType << RHSStrippedType 9688 << LHS->getSourceRange() << RHS->getSourceRange(); 9689 } 9690 9691 /// Diagnose bad pointer comparisons. 9692 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9693 ExprResult &LHS, ExprResult &RHS, 9694 bool IsError) { 9695 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9696 : diag::ext_typecheck_comparison_of_distinct_pointers) 9697 << LHS.get()->getType() << RHS.get()->getType() 9698 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9699 } 9700 9701 /// Returns false if the pointers are converted to a composite type, 9702 /// true otherwise. 9703 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9704 ExprResult &LHS, ExprResult &RHS) { 9705 // C++ [expr.rel]p2: 9706 // [...] Pointer conversions (4.10) and qualification 9707 // conversions (4.4) are performed on pointer operands (or on 9708 // a pointer operand and a null pointer constant) to bring 9709 // them to their composite pointer type. [...] 9710 // 9711 // C++ [expr.eq]p1 uses the same notion for (in)equality 9712 // comparisons of pointers. 9713 9714 QualType LHSType = LHS.get()->getType(); 9715 QualType RHSType = RHS.get()->getType(); 9716 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9717 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9718 9719 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9720 if (T.isNull()) { 9721 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9722 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9723 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9724 else 9725 S.InvalidOperands(Loc, LHS, RHS); 9726 return true; 9727 } 9728 9729 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9730 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9731 return false; 9732 } 9733 9734 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9735 ExprResult &LHS, 9736 ExprResult &RHS, 9737 bool IsError) { 9738 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9739 : diag::ext_typecheck_comparison_of_fptr_to_void) 9740 << LHS.get()->getType() << RHS.get()->getType() 9741 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9742 } 9743 9744 static bool isObjCObjectLiteral(ExprResult &E) { 9745 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9746 case Stmt::ObjCArrayLiteralClass: 9747 case Stmt::ObjCDictionaryLiteralClass: 9748 case Stmt::ObjCStringLiteralClass: 9749 case Stmt::ObjCBoxedExprClass: 9750 return true; 9751 default: 9752 // Note that ObjCBoolLiteral is NOT an object literal! 9753 return false; 9754 } 9755 } 9756 9757 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9758 const ObjCObjectPointerType *Type = 9759 LHS->getType()->getAs<ObjCObjectPointerType>(); 9760 9761 // If this is not actually an Objective-C object, bail out. 9762 if (!Type) 9763 return false; 9764 9765 // Get the LHS object's interface type. 9766 QualType InterfaceType = Type->getPointeeType(); 9767 9768 // If the RHS isn't an Objective-C object, bail out. 9769 if (!RHS->getType()->isObjCObjectPointerType()) 9770 return false; 9771 9772 // Try to find the -isEqual: method. 9773 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9774 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9775 InterfaceType, 9776 /*instance=*/true); 9777 if (!Method) { 9778 if (Type->isObjCIdType()) { 9779 // For 'id', just check the global pool. 9780 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9781 /*receiverId=*/true); 9782 } else { 9783 // Check protocols. 9784 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9785 /*instance=*/true); 9786 } 9787 } 9788 9789 if (!Method) 9790 return false; 9791 9792 QualType T = Method->parameters()[0]->getType(); 9793 if (!T->isObjCObjectPointerType()) 9794 return false; 9795 9796 QualType R = Method->getReturnType(); 9797 if (!R->isScalarType()) 9798 return false; 9799 9800 return true; 9801 } 9802 9803 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9804 FromE = FromE->IgnoreParenImpCasts(); 9805 switch (FromE->getStmtClass()) { 9806 default: 9807 break; 9808 case Stmt::ObjCStringLiteralClass: 9809 // "string literal" 9810 return LK_String; 9811 case Stmt::ObjCArrayLiteralClass: 9812 // "array literal" 9813 return LK_Array; 9814 case Stmt::ObjCDictionaryLiteralClass: 9815 // "dictionary literal" 9816 return LK_Dictionary; 9817 case Stmt::BlockExprClass: 9818 return LK_Block; 9819 case Stmt::ObjCBoxedExprClass: { 9820 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9821 switch (Inner->getStmtClass()) { 9822 case Stmt::IntegerLiteralClass: 9823 case Stmt::FloatingLiteralClass: 9824 case Stmt::CharacterLiteralClass: 9825 case Stmt::ObjCBoolLiteralExprClass: 9826 case Stmt::CXXBoolLiteralExprClass: 9827 // "numeric literal" 9828 return LK_Numeric; 9829 case Stmt::ImplicitCastExprClass: { 9830 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9831 // Boolean literals can be represented by implicit casts. 9832 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9833 return LK_Numeric; 9834 break; 9835 } 9836 default: 9837 break; 9838 } 9839 return LK_Boxed; 9840 } 9841 } 9842 return LK_None; 9843 } 9844 9845 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9846 ExprResult &LHS, ExprResult &RHS, 9847 BinaryOperator::Opcode Opc){ 9848 Expr *Literal; 9849 Expr *Other; 9850 if (isObjCObjectLiteral(LHS)) { 9851 Literal = LHS.get(); 9852 Other = RHS.get(); 9853 } else { 9854 Literal = RHS.get(); 9855 Other = LHS.get(); 9856 } 9857 9858 // Don't warn on comparisons against nil. 9859 Other = Other->IgnoreParenCasts(); 9860 if (Other->isNullPointerConstant(S.getASTContext(), 9861 Expr::NPC_ValueDependentIsNotNull)) 9862 return; 9863 9864 // This should be kept in sync with warn_objc_literal_comparison. 9865 // LK_String should always be after the other literals, since it has its own 9866 // warning flag. 9867 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9868 assert(LiteralKind != Sema::LK_Block); 9869 if (LiteralKind == Sema::LK_None) { 9870 llvm_unreachable("Unknown Objective-C object literal kind"); 9871 } 9872 9873 if (LiteralKind == Sema::LK_String) 9874 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9875 << Literal->getSourceRange(); 9876 else 9877 S.Diag(Loc, diag::warn_objc_literal_comparison) 9878 << LiteralKind << Literal->getSourceRange(); 9879 9880 if (BinaryOperator::isEqualityOp(Opc) && 9881 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9882 SourceLocation Start = LHS.get()->getBeginLoc(); 9883 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9884 CharSourceRange OpRange = 9885 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9886 9887 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9888 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9889 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9890 << FixItHint::CreateInsertion(End, "]"); 9891 } 9892 } 9893 9894 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9895 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9896 ExprResult &RHS, SourceLocation Loc, 9897 BinaryOperatorKind Opc) { 9898 // Check that left hand side is !something. 9899 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9900 if (!UO || UO->getOpcode() != UO_LNot) return; 9901 9902 // Only check if the right hand side is non-bool arithmetic type. 9903 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9904 9905 // Make sure that the something in !something is not bool. 9906 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9907 if (SubExpr->isKnownToHaveBooleanValue()) return; 9908 9909 // Emit warning. 9910 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9911 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9912 << Loc << IsBitwiseOp; 9913 9914 // First note suggest !(x < y) 9915 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9916 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9917 FirstClose = S.getLocForEndOfToken(FirstClose); 9918 if (FirstClose.isInvalid()) 9919 FirstOpen = SourceLocation(); 9920 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9921 << IsBitwiseOp 9922 << FixItHint::CreateInsertion(FirstOpen, "(") 9923 << FixItHint::CreateInsertion(FirstClose, ")"); 9924 9925 // Second note suggests (!x) < y 9926 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9927 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9928 SecondClose = S.getLocForEndOfToken(SecondClose); 9929 if (SecondClose.isInvalid()) 9930 SecondOpen = SourceLocation(); 9931 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9932 << FixItHint::CreateInsertion(SecondOpen, "(") 9933 << FixItHint::CreateInsertion(SecondClose, ")"); 9934 } 9935 9936 // Get the decl for a simple expression: a reference to a variable, 9937 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9938 static ValueDecl *getCompareDecl(Expr *E) { 9939 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9940 return DR->getDecl(); 9941 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9942 if (Ivar->isFreeIvar()) 9943 return Ivar->getDecl(); 9944 } 9945 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9946 if (Mem->isImplicitAccess()) 9947 return Mem->getMemberDecl(); 9948 } 9949 return nullptr; 9950 } 9951 9952 /// Diagnose some forms of syntactically-obvious tautological comparison. 9953 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9954 Expr *LHS, Expr *RHS, 9955 BinaryOperatorKind Opc) { 9956 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9957 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9958 9959 QualType LHSType = LHS->getType(); 9960 QualType RHSType = RHS->getType(); 9961 if (LHSType->hasFloatingRepresentation() || 9962 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9963 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9964 S.inTemplateInstantiation()) 9965 return; 9966 9967 // Comparisons between two array types are ill-formed for operator<=>, so 9968 // we shouldn't emit any additional warnings about it. 9969 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9970 return; 9971 9972 // For non-floating point types, check for self-comparisons of the form 9973 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9974 // often indicate logic errors in the program. 9975 // 9976 // NOTE: Don't warn about comparison expressions resulting from macro 9977 // expansion. Also don't warn about comparisons which are only self 9978 // comparisons within a template instantiation. The warnings should catch 9979 // obvious cases in the definition of the template anyways. The idea is to 9980 // warn when the typed comparison operator will always evaluate to the same 9981 // result. 9982 ValueDecl *DL = getCompareDecl(LHSStripped); 9983 ValueDecl *DR = getCompareDecl(RHSStripped); 9984 if (DL && DR && declaresSameEntity(DL, DR)) { 9985 StringRef Result; 9986 switch (Opc) { 9987 case BO_EQ: case BO_LE: case BO_GE: 9988 Result = "true"; 9989 break; 9990 case BO_NE: case BO_LT: case BO_GT: 9991 Result = "false"; 9992 break; 9993 case BO_Cmp: 9994 Result = "'std::strong_ordering::equal'"; 9995 break; 9996 default: 9997 break; 9998 } 9999 S.DiagRuntimeBehavior(Loc, nullptr, 10000 S.PDiag(diag::warn_comparison_always) 10001 << 0 /*self-comparison*/ << !Result.empty() 10002 << Result); 10003 } else if (DL && DR && 10004 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10005 !DL->isWeak() && !DR->isWeak()) { 10006 // What is it always going to evaluate to? 10007 StringRef Result; 10008 switch(Opc) { 10009 case BO_EQ: // e.g. array1 == array2 10010 Result = "false"; 10011 break; 10012 case BO_NE: // e.g. array1 != array2 10013 Result = "true"; 10014 break; 10015 default: // e.g. array1 <= array2 10016 // The best we can say is 'a constant' 10017 break; 10018 } 10019 S.DiagRuntimeBehavior(Loc, nullptr, 10020 S.PDiag(diag::warn_comparison_always) 10021 << 1 /*array comparison*/ 10022 << !Result.empty() << Result); 10023 } 10024 10025 if (isa<CastExpr>(LHSStripped)) 10026 LHSStripped = LHSStripped->IgnoreParenCasts(); 10027 if (isa<CastExpr>(RHSStripped)) 10028 RHSStripped = RHSStripped->IgnoreParenCasts(); 10029 10030 // Warn about comparisons against a string constant (unless the other 10031 // operand is null); the user probably wants strcmp. 10032 Expr *LiteralString = nullptr; 10033 Expr *LiteralStringStripped = nullptr; 10034 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10035 !RHSStripped->isNullPointerConstant(S.Context, 10036 Expr::NPC_ValueDependentIsNull)) { 10037 LiteralString = LHS; 10038 LiteralStringStripped = LHSStripped; 10039 } else if ((isa<StringLiteral>(RHSStripped) || 10040 isa<ObjCEncodeExpr>(RHSStripped)) && 10041 !LHSStripped->isNullPointerConstant(S.Context, 10042 Expr::NPC_ValueDependentIsNull)) { 10043 LiteralString = RHS; 10044 LiteralStringStripped = RHSStripped; 10045 } 10046 10047 if (LiteralString) { 10048 S.DiagRuntimeBehavior(Loc, nullptr, 10049 S.PDiag(diag::warn_stringcompare) 10050 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10051 << LiteralString->getSourceRange()); 10052 } 10053 } 10054 10055 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10056 switch (CK) { 10057 default: { 10058 #ifndef NDEBUG 10059 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10060 << "\n"; 10061 #endif 10062 llvm_unreachable("unhandled cast kind"); 10063 } 10064 case CK_UserDefinedConversion: 10065 return ICK_Identity; 10066 case CK_LValueToRValue: 10067 return ICK_Lvalue_To_Rvalue; 10068 case CK_ArrayToPointerDecay: 10069 return ICK_Array_To_Pointer; 10070 case CK_FunctionToPointerDecay: 10071 return ICK_Function_To_Pointer; 10072 case CK_IntegralCast: 10073 return ICK_Integral_Conversion; 10074 case CK_FloatingCast: 10075 return ICK_Floating_Conversion; 10076 case CK_IntegralToFloating: 10077 case CK_FloatingToIntegral: 10078 return ICK_Floating_Integral; 10079 case CK_IntegralComplexCast: 10080 case CK_FloatingComplexCast: 10081 case CK_FloatingComplexToIntegralComplex: 10082 case CK_IntegralComplexToFloatingComplex: 10083 return ICK_Complex_Conversion; 10084 case CK_FloatingComplexToReal: 10085 case CK_FloatingRealToComplex: 10086 case CK_IntegralComplexToReal: 10087 case CK_IntegralRealToComplex: 10088 return ICK_Complex_Real; 10089 } 10090 } 10091 10092 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10093 QualType FromType, 10094 SourceLocation Loc) { 10095 // Check for a narrowing implicit conversion. 10096 StandardConversionSequence SCS; 10097 SCS.setAsIdentityConversion(); 10098 SCS.setToType(0, FromType); 10099 SCS.setToType(1, ToType); 10100 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10101 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10102 10103 APValue PreNarrowingValue; 10104 QualType PreNarrowingType; 10105 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10106 PreNarrowingType, 10107 /*IgnoreFloatToIntegralConversion*/ true)) { 10108 case NK_Dependent_Narrowing: 10109 // Implicit conversion to a narrower type, but the expression is 10110 // value-dependent so we can't tell whether it's actually narrowing. 10111 case NK_Not_Narrowing: 10112 return false; 10113 10114 case NK_Constant_Narrowing: 10115 // Implicit conversion to a narrower type, and the value is not a constant 10116 // expression. 10117 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10118 << /*Constant*/ 1 10119 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10120 return true; 10121 10122 case NK_Variable_Narrowing: 10123 // Implicit conversion to a narrower type, and the value is not a constant 10124 // expression. 10125 case NK_Type_Narrowing: 10126 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10127 << /*Constant*/ 0 << FromType << ToType; 10128 // TODO: It's not a constant expression, but what if the user intended it 10129 // to be? Can we produce notes to help them figure out why it isn't? 10130 return true; 10131 } 10132 llvm_unreachable("unhandled case in switch"); 10133 } 10134 10135 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10136 ExprResult &LHS, 10137 ExprResult &RHS, 10138 SourceLocation Loc) { 10139 using CCT = ComparisonCategoryType; 10140 10141 QualType LHSType = LHS.get()->getType(); 10142 QualType RHSType = RHS.get()->getType(); 10143 // Dig out the original argument type and expression before implicit casts 10144 // were applied. These are the types/expressions we need to check the 10145 // [expr.spaceship] requirements against. 10146 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10147 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10148 QualType LHSStrippedType = LHSStripped.get()->getType(); 10149 QualType RHSStrippedType = RHSStripped.get()->getType(); 10150 10151 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10152 // other is not, the program is ill-formed. 10153 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10154 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10155 return QualType(); 10156 } 10157 10158 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10159 RHSStrippedType->isEnumeralType(); 10160 if (NumEnumArgs == 1) { 10161 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10162 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10163 if (OtherTy->hasFloatingRepresentation()) { 10164 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10165 return QualType(); 10166 } 10167 } 10168 if (NumEnumArgs == 2) { 10169 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10170 // type E, the operator yields the result of converting the operands 10171 // to the underlying type of E and applying <=> to the converted operands. 10172 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10173 S.InvalidOperands(Loc, LHS, RHS); 10174 return QualType(); 10175 } 10176 QualType IntType = 10177 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10178 assert(IntType->isArithmeticType()); 10179 10180 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10181 // promote the boolean type, and all other promotable integer types, to 10182 // avoid this. 10183 if (IntType->isPromotableIntegerType()) 10184 IntType = S.Context.getPromotedIntegerType(IntType); 10185 10186 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10187 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10188 LHSType = RHSType = IntType; 10189 } 10190 10191 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10192 // usual arithmetic conversions are applied to the operands. 10193 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10194 if (LHS.isInvalid() || RHS.isInvalid()) 10195 return QualType(); 10196 if (Type.isNull()) 10197 return S.InvalidOperands(Loc, LHS, RHS); 10198 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10199 10200 bool HasNarrowing = checkThreeWayNarrowingConversion( 10201 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10202 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10203 RHS.get()->getBeginLoc()); 10204 if (HasNarrowing) 10205 return QualType(); 10206 10207 assert(!Type.isNull() && "composite type for <=> has not been set"); 10208 10209 auto TypeKind = [&]() { 10210 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10211 if (CT->getElementType()->hasFloatingRepresentation()) 10212 return CCT::WeakEquality; 10213 return CCT::StrongEquality; 10214 } 10215 if (Type->isIntegralOrEnumerationType()) 10216 return CCT::StrongOrdering; 10217 if (Type->hasFloatingRepresentation()) 10218 return CCT::PartialOrdering; 10219 llvm_unreachable("other types are unimplemented"); 10220 }(); 10221 10222 return S.CheckComparisonCategoryType(TypeKind, Loc); 10223 } 10224 10225 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10226 ExprResult &RHS, 10227 SourceLocation Loc, 10228 BinaryOperatorKind Opc) { 10229 if (Opc == BO_Cmp) 10230 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10231 10232 // C99 6.5.8p3 / C99 6.5.9p4 10233 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10234 if (LHS.isInvalid() || RHS.isInvalid()) 10235 return QualType(); 10236 if (Type.isNull()) 10237 return S.InvalidOperands(Loc, LHS, RHS); 10238 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10239 10240 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10241 10242 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10243 return S.InvalidOperands(Loc, LHS, RHS); 10244 10245 // Check for comparisons of floating point operands using != and ==. 10246 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10247 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10248 10249 // The result of comparisons is 'bool' in C++, 'int' in C. 10250 return S.Context.getLogicalOperationType(); 10251 } 10252 10253 // C99 6.5.8, C++ [expr.rel] 10254 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10255 SourceLocation Loc, 10256 BinaryOperatorKind Opc) { 10257 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10258 bool IsThreeWay = Opc == BO_Cmp; 10259 auto IsAnyPointerType = [](ExprResult E) { 10260 QualType Ty = E.get()->getType(); 10261 return Ty->isPointerType() || Ty->isMemberPointerType(); 10262 }; 10263 10264 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10265 // type, array-to-pointer, ..., conversions are performed on both operands to 10266 // bring them to their composite type. 10267 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10268 // any type-related checks. 10269 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10270 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10271 if (LHS.isInvalid()) 10272 return QualType(); 10273 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10274 if (RHS.isInvalid()) 10275 return QualType(); 10276 } else { 10277 LHS = DefaultLvalueConversion(LHS.get()); 10278 if (LHS.isInvalid()) 10279 return QualType(); 10280 RHS = DefaultLvalueConversion(RHS.get()); 10281 if (RHS.isInvalid()) 10282 return QualType(); 10283 } 10284 10285 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10286 10287 // Handle vector comparisons separately. 10288 if (LHS.get()->getType()->isVectorType() || 10289 RHS.get()->getType()->isVectorType()) 10290 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10291 10292 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10293 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10294 10295 QualType LHSType = LHS.get()->getType(); 10296 QualType RHSType = RHS.get()->getType(); 10297 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10298 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10299 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10300 10301 const Expr::NullPointerConstantKind LHSNullKind = 10302 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10303 const Expr::NullPointerConstantKind RHSNullKind = 10304 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10305 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10306 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10307 10308 auto computeResultTy = [&]() { 10309 if (Opc != BO_Cmp) 10310 return Context.getLogicalOperationType(); 10311 assert(getLangOpts().CPlusPlus); 10312 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10313 10314 QualType CompositeTy = LHS.get()->getType(); 10315 assert(!CompositeTy->isReferenceType()); 10316 10317 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10318 return CheckComparisonCategoryType(Kind, Loc); 10319 }; 10320 10321 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10322 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10323 // result is of type std::strong_equality 10324 if (CompositeTy->isFunctionPointerType() || 10325 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10326 // FIXME: consider making the function pointer case produce 10327 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10328 // and direction polls 10329 return buildResultTy(ComparisonCategoryType::StrongEquality); 10330 10331 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10332 // pointer type, p <=> q is of type std::strong_ordering. 10333 if (CompositeTy->isPointerType()) { 10334 // P0946R0: Comparisons between a null pointer constant and an object 10335 // pointer result in std::strong_equality 10336 if (LHSIsNull != RHSIsNull) 10337 return buildResultTy(ComparisonCategoryType::StrongEquality); 10338 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10339 } 10340 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10341 // TODO: Extend support for operator<=> to ObjC types. 10342 return InvalidOperands(Loc, LHS, RHS); 10343 }; 10344 10345 10346 if (!IsRelational && LHSIsNull != RHSIsNull) { 10347 bool IsEquality = Opc == BO_EQ; 10348 if (RHSIsNull) 10349 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10350 RHS.get()->getSourceRange()); 10351 else 10352 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10353 LHS.get()->getSourceRange()); 10354 } 10355 10356 if ((LHSType->isIntegerType() && !LHSIsNull) || 10357 (RHSType->isIntegerType() && !RHSIsNull)) { 10358 // Skip normal pointer conversion checks in this case; we have better 10359 // diagnostics for this below. 10360 } else if (getLangOpts().CPlusPlus) { 10361 // Equality comparison of a function pointer to a void pointer is invalid, 10362 // but we allow it as an extension. 10363 // FIXME: If we really want to allow this, should it be part of composite 10364 // pointer type computation so it works in conditionals too? 10365 if (!IsRelational && 10366 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10367 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10368 // This is a gcc extension compatibility comparison. 10369 // In a SFINAE context, we treat this as a hard error to maintain 10370 // conformance with the C++ standard. 10371 diagnoseFunctionPointerToVoidComparison( 10372 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10373 10374 if (isSFINAEContext()) 10375 return QualType(); 10376 10377 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10378 return computeResultTy(); 10379 } 10380 10381 // C++ [expr.eq]p2: 10382 // If at least one operand is a pointer [...] bring them to their 10383 // composite pointer type. 10384 // C++ [expr.spaceship]p6 10385 // If at least one of the operands is of pointer type, [...] bring them 10386 // to their composite pointer type. 10387 // C++ [expr.rel]p2: 10388 // If both operands are pointers, [...] bring them to their composite 10389 // pointer type. 10390 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10391 (IsRelational ? 2 : 1) && 10392 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10393 RHSType->isObjCObjectPointerType()))) { 10394 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10395 return QualType(); 10396 return computeResultTy(); 10397 } 10398 } else if (LHSType->isPointerType() && 10399 RHSType->isPointerType()) { // C99 6.5.8p2 10400 // All of the following pointer-related warnings are GCC extensions, except 10401 // when handling null pointer constants. 10402 QualType LCanPointeeTy = 10403 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10404 QualType RCanPointeeTy = 10405 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10406 10407 // C99 6.5.9p2 and C99 6.5.8p2 10408 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10409 RCanPointeeTy.getUnqualifiedType())) { 10410 // Valid unless a relational comparison of function pointers 10411 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10412 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10413 << LHSType << RHSType << LHS.get()->getSourceRange() 10414 << RHS.get()->getSourceRange(); 10415 } 10416 } else if (!IsRelational && 10417 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10418 // Valid unless comparison between non-null pointer and function pointer 10419 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10420 && !LHSIsNull && !RHSIsNull) 10421 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10422 /*isError*/false); 10423 } else { 10424 // Invalid 10425 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10426 } 10427 if (LCanPointeeTy != RCanPointeeTy) { 10428 // Treat NULL constant as a special case in OpenCL. 10429 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10430 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10431 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10432 Diag(Loc, 10433 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10434 << LHSType << RHSType << 0 /* comparison */ 10435 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10436 } 10437 } 10438 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10439 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10440 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10441 : CK_BitCast; 10442 if (LHSIsNull && !RHSIsNull) 10443 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10444 else 10445 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10446 } 10447 return computeResultTy(); 10448 } 10449 10450 if (getLangOpts().CPlusPlus) { 10451 // C++ [expr.eq]p4: 10452 // Two operands of type std::nullptr_t or one operand of type 10453 // std::nullptr_t and the other a null pointer constant compare equal. 10454 if (!IsRelational && LHSIsNull && RHSIsNull) { 10455 if (LHSType->isNullPtrType()) { 10456 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10457 return computeResultTy(); 10458 } 10459 if (RHSType->isNullPtrType()) { 10460 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10461 return computeResultTy(); 10462 } 10463 } 10464 10465 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10466 // These aren't covered by the composite pointer type rules. 10467 if (!IsRelational && RHSType->isNullPtrType() && 10468 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10469 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10470 return computeResultTy(); 10471 } 10472 if (!IsRelational && LHSType->isNullPtrType() && 10473 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10474 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10475 return computeResultTy(); 10476 } 10477 10478 if (IsRelational && 10479 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10480 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10481 // HACK: Relational comparison of nullptr_t against a pointer type is 10482 // invalid per DR583, but we allow it within std::less<> and friends, 10483 // since otherwise common uses of it break. 10484 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10485 // friends to have std::nullptr_t overload candidates. 10486 DeclContext *DC = CurContext; 10487 if (isa<FunctionDecl>(DC)) 10488 DC = DC->getParent(); 10489 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10490 if (CTSD->isInStdNamespace() && 10491 llvm::StringSwitch<bool>(CTSD->getName()) 10492 .Cases("less", "less_equal", "greater", "greater_equal", true) 10493 .Default(false)) { 10494 if (RHSType->isNullPtrType()) 10495 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10496 else 10497 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10498 return computeResultTy(); 10499 } 10500 } 10501 } 10502 10503 // C++ [expr.eq]p2: 10504 // If at least one operand is a pointer to member, [...] bring them to 10505 // their composite pointer type. 10506 if (!IsRelational && 10507 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10508 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10509 return QualType(); 10510 else 10511 return computeResultTy(); 10512 } 10513 } 10514 10515 // Handle block pointer types. 10516 if (!IsRelational && LHSType->isBlockPointerType() && 10517 RHSType->isBlockPointerType()) { 10518 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10519 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10520 10521 if (!LHSIsNull && !RHSIsNull && 10522 !Context.typesAreCompatible(lpointee, rpointee)) { 10523 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10524 << LHSType << RHSType << LHS.get()->getSourceRange() 10525 << RHS.get()->getSourceRange(); 10526 } 10527 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10528 return computeResultTy(); 10529 } 10530 10531 // Allow block pointers to be compared with null pointer constants. 10532 if (!IsRelational 10533 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10534 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10535 if (!LHSIsNull && !RHSIsNull) { 10536 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10537 ->getPointeeType()->isVoidType()) 10538 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10539 ->getPointeeType()->isVoidType()))) 10540 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10541 << LHSType << RHSType << LHS.get()->getSourceRange() 10542 << RHS.get()->getSourceRange(); 10543 } 10544 if (LHSIsNull && !RHSIsNull) 10545 LHS = ImpCastExprToType(LHS.get(), RHSType, 10546 RHSType->isPointerType() ? CK_BitCast 10547 : CK_AnyPointerToBlockPointerCast); 10548 else 10549 RHS = ImpCastExprToType(RHS.get(), LHSType, 10550 LHSType->isPointerType() ? CK_BitCast 10551 : CK_AnyPointerToBlockPointerCast); 10552 return computeResultTy(); 10553 } 10554 10555 if (LHSType->isObjCObjectPointerType() || 10556 RHSType->isObjCObjectPointerType()) { 10557 const PointerType *LPT = LHSType->getAs<PointerType>(); 10558 const PointerType *RPT = RHSType->getAs<PointerType>(); 10559 if (LPT || RPT) { 10560 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10561 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10562 10563 if (!LPtrToVoid && !RPtrToVoid && 10564 !Context.typesAreCompatible(LHSType, RHSType)) { 10565 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10566 /*isError*/false); 10567 } 10568 if (LHSIsNull && !RHSIsNull) { 10569 Expr *E = LHS.get(); 10570 if (getLangOpts().ObjCAutoRefCount) 10571 CheckObjCConversion(SourceRange(), RHSType, E, 10572 CCK_ImplicitConversion); 10573 LHS = ImpCastExprToType(E, RHSType, 10574 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10575 } 10576 else { 10577 Expr *E = RHS.get(); 10578 if (getLangOpts().ObjCAutoRefCount) 10579 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10580 /*Diagnose=*/true, 10581 /*DiagnoseCFAudited=*/false, Opc); 10582 RHS = ImpCastExprToType(E, LHSType, 10583 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10584 } 10585 return computeResultTy(); 10586 } 10587 if (LHSType->isObjCObjectPointerType() && 10588 RHSType->isObjCObjectPointerType()) { 10589 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10590 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10591 /*isError*/false); 10592 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10593 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10594 10595 if (LHSIsNull && !RHSIsNull) 10596 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10597 else 10598 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10599 return computeResultTy(); 10600 } 10601 10602 if (!IsRelational && LHSType->isBlockPointerType() && 10603 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10604 LHS = ImpCastExprToType(LHS.get(), RHSType, 10605 CK_BlockPointerToObjCPointerCast); 10606 return computeResultTy(); 10607 } else if (!IsRelational && 10608 LHSType->isBlockCompatibleObjCPointerType(Context) && 10609 RHSType->isBlockPointerType()) { 10610 RHS = ImpCastExprToType(RHS.get(), LHSType, 10611 CK_BlockPointerToObjCPointerCast); 10612 return computeResultTy(); 10613 } 10614 } 10615 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10616 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10617 unsigned DiagID = 0; 10618 bool isError = false; 10619 if (LangOpts.DebuggerSupport) { 10620 // Under a debugger, allow the comparison of pointers to integers, 10621 // since users tend to want to compare addresses. 10622 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10623 (RHSIsNull && RHSType->isIntegerType())) { 10624 if (IsRelational) { 10625 isError = getLangOpts().CPlusPlus; 10626 DiagID = 10627 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10628 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10629 } 10630 } else if (getLangOpts().CPlusPlus) { 10631 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10632 isError = true; 10633 } else if (IsRelational) 10634 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10635 else 10636 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10637 10638 if (DiagID) { 10639 Diag(Loc, DiagID) 10640 << LHSType << RHSType << LHS.get()->getSourceRange() 10641 << RHS.get()->getSourceRange(); 10642 if (isError) 10643 return QualType(); 10644 } 10645 10646 if (LHSType->isIntegerType()) 10647 LHS = ImpCastExprToType(LHS.get(), RHSType, 10648 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10649 else 10650 RHS = ImpCastExprToType(RHS.get(), LHSType, 10651 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10652 return computeResultTy(); 10653 } 10654 10655 // Handle block pointers. 10656 if (!IsRelational && RHSIsNull 10657 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10658 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10659 return computeResultTy(); 10660 } 10661 if (!IsRelational && LHSIsNull 10662 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10663 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10664 return computeResultTy(); 10665 } 10666 10667 if (getLangOpts().OpenCLVersion >= 200) { 10668 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10669 return computeResultTy(); 10670 } 10671 10672 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10673 return computeResultTy(); 10674 } 10675 10676 if (LHSIsNull && RHSType->isQueueT()) { 10677 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10678 return computeResultTy(); 10679 } 10680 10681 if (LHSType->isQueueT() && RHSIsNull) { 10682 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10683 return computeResultTy(); 10684 } 10685 } 10686 10687 return InvalidOperands(Loc, LHS, RHS); 10688 } 10689 10690 // Return a signed ext_vector_type that is of identical size and number of 10691 // elements. For floating point vectors, return an integer type of identical 10692 // size and number of elements. In the non ext_vector_type case, search from 10693 // the largest type to the smallest type to avoid cases where long long == long, 10694 // where long gets picked over long long. 10695 QualType Sema::GetSignedVectorType(QualType V) { 10696 const VectorType *VTy = V->getAs<VectorType>(); 10697 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10698 10699 if (isa<ExtVectorType>(VTy)) { 10700 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10701 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10702 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10703 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10704 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10705 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10706 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10707 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10708 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10709 "Unhandled vector element size in vector compare"); 10710 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10711 } 10712 10713 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10714 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10715 VectorType::GenericVector); 10716 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10717 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10718 VectorType::GenericVector); 10719 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10720 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10721 VectorType::GenericVector); 10722 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10723 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10724 VectorType::GenericVector); 10725 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10726 "Unhandled vector element size in vector compare"); 10727 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10728 VectorType::GenericVector); 10729 } 10730 10731 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10732 /// operates on extended vector types. Instead of producing an IntTy result, 10733 /// like a scalar comparison, a vector comparison produces a vector of integer 10734 /// types. 10735 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10736 SourceLocation Loc, 10737 BinaryOperatorKind Opc) { 10738 // Check to make sure we're operating on vectors of the same type and width, 10739 // Allowing one side to be a scalar of element type. 10740 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10741 /*AllowBothBool*/true, 10742 /*AllowBoolConversions*/getLangOpts().ZVector); 10743 if (vType.isNull()) 10744 return vType; 10745 10746 QualType LHSType = LHS.get()->getType(); 10747 10748 // If AltiVec, the comparison results in a numeric type, i.e. 10749 // bool for C++, int for C 10750 if (getLangOpts().AltiVec && 10751 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10752 return Context.getLogicalOperationType(); 10753 10754 // For non-floating point types, check for self-comparisons of the form 10755 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10756 // often indicate logic errors in the program. 10757 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10758 10759 // Check for comparisons of floating point operands using != and ==. 10760 if (BinaryOperator::isEqualityOp(Opc) && 10761 LHSType->hasFloatingRepresentation()) { 10762 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10763 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10764 } 10765 10766 // Return a signed type for the vector. 10767 return GetSignedVectorType(vType); 10768 } 10769 10770 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10771 SourceLocation Loc) { 10772 // Ensure that either both operands are of the same vector type, or 10773 // one operand is of a vector type and the other is of its element type. 10774 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10775 /*AllowBothBool*/true, 10776 /*AllowBoolConversions*/false); 10777 if (vType.isNull()) 10778 return InvalidOperands(Loc, LHS, RHS); 10779 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10780 vType->hasFloatingRepresentation()) 10781 return InvalidOperands(Loc, LHS, RHS); 10782 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10783 // usage of the logical operators && and || with vectors in C. This 10784 // check could be notionally dropped. 10785 if (!getLangOpts().CPlusPlus && 10786 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10787 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10788 10789 return GetSignedVectorType(LHS.get()->getType()); 10790 } 10791 10792 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10793 SourceLocation Loc, 10794 BinaryOperatorKind Opc) { 10795 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10796 10797 bool IsCompAssign = 10798 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10799 10800 if (LHS.get()->getType()->isVectorType() || 10801 RHS.get()->getType()->isVectorType()) { 10802 if (LHS.get()->getType()->hasIntegerRepresentation() && 10803 RHS.get()->getType()->hasIntegerRepresentation()) 10804 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10805 /*AllowBothBool*/true, 10806 /*AllowBoolConversions*/getLangOpts().ZVector); 10807 return InvalidOperands(Loc, LHS, RHS); 10808 } 10809 10810 if (Opc == BO_And) 10811 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10812 10813 ExprResult LHSResult = LHS, RHSResult = RHS; 10814 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10815 IsCompAssign); 10816 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10817 return QualType(); 10818 LHS = LHSResult.get(); 10819 RHS = RHSResult.get(); 10820 10821 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10822 return compType; 10823 return InvalidOperands(Loc, LHS, RHS); 10824 } 10825 10826 // C99 6.5.[13,14] 10827 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10828 SourceLocation Loc, 10829 BinaryOperatorKind Opc) { 10830 // Check vector operands differently. 10831 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10832 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10833 10834 // Diagnose cases where the user write a logical and/or but probably meant a 10835 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10836 // is a constant. 10837 if (LHS.get()->getType()->isIntegerType() && 10838 !LHS.get()->getType()->isBooleanType() && 10839 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10840 // Don't warn in macros or template instantiations. 10841 !Loc.isMacroID() && !inTemplateInstantiation()) { 10842 // If the RHS can be constant folded, and if it constant folds to something 10843 // that isn't 0 or 1 (which indicate a potential logical operation that 10844 // happened to fold to true/false) then warn. 10845 // Parens on the RHS are ignored. 10846 Expr::EvalResult EVResult; 10847 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 10848 llvm::APSInt Result = EVResult.Val.getInt(); 10849 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10850 !RHS.get()->getExprLoc().isMacroID()) || 10851 (Result != 0 && Result != 1)) { 10852 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10853 << RHS.get()->getSourceRange() 10854 << (Opc == BO_LAnd ? "&&" : "||"); 10855 // Suggest replacing the logical operator with the bitwise version 10856 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10857 << (Opc == BO_LAnd ? "&" : "|") 10858 << FixItHint::CreateReplacement(SourceRange( 10859 Loc, getLocForEndOfToken(Loc)), 10860 Opc == BO_LAnd ? "&" : "|"); 10861 if (Opc == BO_LAnd) 10862 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10863 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10864 << FixItHint::CreateRemoval( 10865 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10866 RHS.get()->getEndLoc())); 10867 } 10868 } 10869 } 10870 10871 if (!Context.getLangOpts().CPlusPlus) { 10872 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10873 // not operate on the built-in scalar and vector float types. 10874 if (Context.getLangOpts().OpenCL && 10875 Context.getLangOpts().OpenCLVersion < 120) { 10876 if (LHS.get()->getType()->isFloatingType() || 10877 RHS.get()->getType()->isFloatingType()) 10878 return InvalidOperands(Loc, LHS, RHS); 10879 } 10880 10881 LHS = UsualUnaryConversions(LHS.get()); 10882 if (LHS.isInvalid()) 10883 return QualType(); 10884 10885 RHS = UsualUnaryConversions(RHS.get()); 10886 if (RHS.isInvalid()) 10887 return QualType(); 10888 10889 if (!LHS.get()->getType()->isScalarType() || 10890 !RHS.get()->getType()->isScalarType()) 10891 return InvalidOperands(Loc, LHS, RHS); 10892 10893 return Context.IntTy; 10894 } 10895 10896 // The following is safe because we only use this method for 10897 // non-overloadable operands. 10898 10899 // C++ [expr.log.and]p1 10900 // C++ [expr.log.or]p1 10901 // The operands are both contextually converted to type bool. 10902 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10903 if (LHSRes.isInvalid()) 10904 return InvalidOperands(Loc, LHS, RHS); 10905 LHS = LHSRes; 10906 10907 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10908 if (RHSRes.isInvalid()) 10909 return InvalidOperands(Loc, LHS, RHS); 10910 RHS = RHSRes; 10911 10912 // C++ [expr.log.and]p2 10913 // C++ [expr.log.or]p2 10914 // The result is a bool. 10915 return Context.BoolTy; 10916 } 10917 10918 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10919 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10920 if (!ME) return false; 10921 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10922 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10923 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10924 if (!Base) return false; 10925 return Base->getMethodDecl() != nullptr; 10926 } 10927 10928 /// Is the given expression (which must be 'const') a reference to a 10929 /// variable which was originally non-const, but which has become 10930 /// 'const' due to being captured within a block? 10931 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10932 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10933 assert(E->isLValue() && E->getType().isConstQualified()); 10934 E = E->IgnoreParens(); 10935 10936 // Must be a reference to a declaration from an enclosing scope. 10937 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10938 if (!DRE) return NCCK_None; 10939 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10940 10941 // The declaration must be a variable which is not declared 'const'. 10942 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10943 if (!var) return NCCK_None; 10944 if (var->getType().isConstQualified()) return NCCK_None; 10945 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10946 10947 // Decide whether the first capture was for a block or a lambda. 10948 DeclContext *DC = S.CurContext, *Prev = nullptr; 10949 // Decide whether the first capture was for a block or a lambda. 10950 while (DC) { 10951 // For init-capture, it is possible that the variable belongs to the 10952 // template pattern of the current context. 10953 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10954 if (var->isInitCapture() && 10955 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10956 break; 10957 if (DC == var->getDeclContext()) 10958 break; 10959 Prev = DC; 10960 DC = DC->getParent(); 10961 } 10962 // Unless we have an init-capture, we've gone one step too far. 10963 if (!var->isInitCapture()) 10964 DC = Prev; 10965 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10966 } 10967 10968 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10969 Ty = Ty.getNonReferenceType(); 10970 if (IsDereference && Ty->isPointerType()) 10971 Ty = Ty->getPointeeType(); 10972 return !Ty.isConstQualified(); 10973 } 10974 10975 // Update err_typecheck_assign_const and note_typecheck_assign_const 10976 // when this enum is changed. 10977 enum { 10978 ConstFunction, 10979 ConstVariable, 10980 ConstMember, 10981 ConstMethod, 10982 NestedConstMember, 10983 ConstUnknown, // Keep as last element 10984 }; 10985 10986 /// Emit the "read-only variable not assignable" error and print notes to give 10987 /// more information about why the variable is not assignable, such as pointing 10988 /// to the declaration of a const variable, showing that a method is const, or 10989 /// that the function is returning a const reference. 10990 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10991 SourceLocation Loc) { 10992 SourceRange ExprRange = E->getSourceRange(); 10993 10994 // Only emit one error on the first const found. All other consts will emit 10995 // a note to the error. 10996 bool DiagnosticEmitted = false; 10997 10998 // Track if the current expression is the result of a dereference, and if the 10999 // next checked expression is the result of a dereference. 11000 bool IsDereference = false; 11001 bool NextIsDereference = false; 11002 11003 // Loop to process MemberExpr chains. 11004 while (true) { 11005 IsDereference = NextIsDereference; 11006 11007 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11008 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11009 NextIsDereference = ME->isArrow(); 11010 const ValueDecl *VD = ME->getMemberDecl(); 11011 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11012 // Mutable fields can be modified even if the class is const. 11013 if (Field->isMutable()) { 11014 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11015 break; 11016 } 11017 11018 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11019 if (!DiagnosticEmitted) { 11020 S.Diag(Loc, diag::err_typecheck_assign_const) 11021 << ExprRange << ConstMember << false /*static*/ << Field 11022 << Field->getType(); 11023 DiagnosticEmitted = true; 11024 } 11025 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11026 << ConstMember << false /*static*/ << Field << Field->getType() 11027 << Field->getSourceRange(); 11028 } 11029 E = ME->getBase(); 11030 continue; 11031 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11032 if (VDecl->getType().isConstQualified()) { 11033 if (!DiagnosticEmitted) { 11034 S.Diag(Loc, diag::err_typecheck_assign_const) 11035 << ExprRange << ConstMember << true /*static*/ << VDecl 11036 << VDecl->getType(); 11037 DiagnosticEmitted = true; 11038 } 11039 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11040 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11041 << VDecl->getSourceRange(); 11042 } 11043 // Static fields do not inherit constness from parents. 11044 break; 11045 } 11046 break; // End MemberExpr 11047 } else if (const ArraySubscriptExpr *ASE = 11048 dyn_cast<ArraySubscriptExpr>(E)) { 11049 E = ASE->getBase()->IgnoreParenImpCasts(); 11050 continue; 11051 } else if (const ExtVectorElementExpr *EVE = 11052 dyn_cast<ExtVectorElementExpr>(E)) { 11053 E = EVE->getBase()->IgnoreParenImpCasts(); 11054 continue; 11055 } 11056 break; 11057 } 11058 11059 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11060 // Function calls 11061 const FunctionDecl *FD = CE->getDirectCallee(); 11062 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11063 if (!DiagnosticEmitted) { 11064 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11065 << ConstFunction << FD; 11066 DiagnosticEmitted = true; 11067 } 11068 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11069 diag::note_typecheck_assign_const) 11070 << ConstFunction << FD << FD->getReturnType() 11071 << FD->getReturnTypeSourceRange(); 11072 } 11073 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11074 // Point to variable declaration. 11075 if (const ValueDecl *VD = DRE->getDecl()) { 11076 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11077 if (!DiagnosticEmitted) { 11078 S.Diag(Loc, diag::err_typecheck_assign_const) 11079 << ExprRange << ConstVariable << VD << VD->getType(); 11080 DiagnosticEmitted = true; 11081 } 11082 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11083 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11084 } 11085 } 11086 } else if (isa<CXXThisExpr>(E)) { 11087 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11088 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11089 if (MD->isConst()) { 11090 if (!DiagnosticEmitted) { 11091 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11092 << ConstMethod << MD; 11093 DiagnosticEmitted = true; 11094 } 11095 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11096 << ConstMethod << MD << MD->getSourceRange(); 11097 } 11098 } 11099 } 11100 } 11101 11102 if (DiagnosticEmitted) 11103 return; 11104 11105 // Can't determine a more specific message, so display the generic error. 11106 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11107 } 11108 11109 enum OriginalExprKind { 11110 OEK_Variable, 11111 OEK_Member, 11112 OEK_LValue 11113 }; 11114 11115 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11116 const RecordType *Ty, 11117 SourceLocation Loc, SourceRange Range, 11118 OriginalExprKind OEK, 11119 bool &DiagnosticEmitted) { 11120 std::vector<const RecordType *> RecordTypeList; 11121 RecordTypeList.push_back(Ty); 11122 unsigned NextToCheckIndex = 0; 11123 // We walk the record hierarchy breadth-first to ensure that we print 11124 // diagnostics in field nesting order. 11125 while (RecordTypeList.size() > NextToCheckIndex) { 11126 bool IsNested = NextToCheckIndex > 0; 11127 for (const FieldDecl *Field : 11128 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11129 // First, check every field for constness. 11130 QualType FieldTy = Field->getType(); 11131 if (FieldTy.isConstQualified()) { 11132 if (!DiagnosticEmitted) { 11133 S.Diag(Loc, diag::err_typecheck_assign_const) 11134 << Range << NestedConstMember << OEK << VD 11135 << IsNested << Field; 11136 DiagnosticEmitted = true; 11137 } 11138 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11139 << NestedConstMember << IsNested << Field 11140 << FieldTy << Field->getSourceRange(); 11141 } 11142 11143 // Then we append it to the list to check next in order. 11144 FieldTy = FieldTy.getCanonicalType(); 11145 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11146 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11147 RecordTypeList.push_back(FieldRecTy); 11148 } 11149 } 11150 ++NextToCheckIndex; 11151 } 11152 } 11153 11154 /// Emit an error for the case where a record we are trying to assign to has a 11155 /// const-qualified field somewhere in its hierarchy. 11156 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11157 SourceLocation Loc) { 11158 QualType Ty = E->getType(); 11159 assert(Ty->isRecordType() && "lvalue was not record?"); 11160 SourceRange Range = E->getSourceRange(); 11161 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11162 bool DiagEmitted = false; 11163 11164 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11165 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11166 Range, OEK_Member, DiagEmitted); 11167 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11168 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11169 Range, OEK_Variable, DiagEmitted); 11170 else 11171 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11172 Range, OEK_LValue, DiagEmitted); 11173 if (!DiagEmitted) 11174 DiagnoseConstAssignment(S, E, Loc); 11175 } 11176 11177 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11178 /// emit an error and return true. If so, return false. 11179 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11180 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11181 11182 S.CheckShadowingDeclModification(E, Loc); 11183 11184 SourceLocation OrigLoc = Loc; 11185 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11186 &Loc); 11187 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11188 IsLV = Expr::MLV_InvalidMessageExpression; 11189 if (IsLV == Expr::MLV_Valid) 11190 return false; 11191 11192 unsigned DiagID = 0; 11193 bool NeedType = false; 11194 switch (IsLV) { // C99 6.5.16p2 11195 case Expr::MLV_ConstQualified: 11196 // Use a specialized diagnostic when we're assigning to an object 11197 // from an enclosing function or block. 11198 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11199 if (NCCK == NCCK_Block) 11200 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11201 else 11202 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11203 break; 11204 } 11205 11206 // In ARC, use some specialized diagnostics for occasions where we 11207 // infer 'const'. These are always pseudo-strong variables. 11208 if (S.getLangOpts().ObjCAutoRefCount) { 11209 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11210 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11211 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11212 11213 // Use the normal diagnostic if it's pseudo-__strong but the 11214 // user actually wrote 'const'. 11215 if (var->isARCPseudoStrong() && 11216 (!var->getTypeSourceInfo() || 11217 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11218 // There are two pseudo-strong cases: 11219 // - self 11220 ObjCMethodDecl *method = S.getCurMethodDecl(); 11221 if (method && var == method->getSelfDecl()) 11222 DiagID = method->isClassMethod() 11223 ? diag::err_typecheck_arc_assign_self_class_method 11224 : diag::err_typecheck_arc_assign_self; 11225 11226 // - fast enumeration variables 11227 else 11228 DiagID = diag::err_typecheck_arr_assign_enumeration; 11229 11230 SourceRange Assign; 11231 if (Loc != OrigLoc) 11232 Assign = SourceRange(OrigLoc, OrigLoc); 11233 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11234 // We need to preserve the AST regardless, so migration tool 11235 // can do its job. 11236 return false; 11237 } 11238 } 11239 } 11240 11241 // If none of the special cases above are triggered, then this is a 11242 // simple const assignment. 11243 if (DiagID == 0) { 11244 DiagnoseConstAssignment(S, E, Loc); 11245 return true; 11246 } 11247 11248 break; 11249 case Expr::MLV_ConstAddrSpace: 11250 DiagnoseConstAssignment(S, E, Loc); 11251 return true; 11252 case Expr::MLV_ConstQualifiedField: 11253 DiagnoseRecursiveConstFields(S, E, Loc); 11254 return true; 11255 case Expr::MLV_ArrayType: 11256 case Expr::MLV_ArrayTemporary: 11257 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11258 NeedType = true; 11259 break; 11260 case Expr::MLV_NotObjectType: 11261 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11262 NeedType = true; 11263 break; 11264 case Expr::MLV_LValueCast: 11265 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11266 break; 11267 case Expr::MLV_Valid: 11268 llvm_unreachable("did not take early return for MLV_Valid"); 11269 case Expr::MLV_InvalidExpression: 11270 case Expr::MLV_MemberFunction: 11271 case Expr::MLV_ClassTemporary: 11272 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11273 break; 11274 case Expr::MLV_IncompleteType: 11275 case Expr::MLV_IncompleteVoidType: 11276 return S.RequireCompleteType(Loc, E->getType(), 11277 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11278 case Expr::MLV_DuplicateVectorComponents: 11279 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11280 break; 11281 case Expr::MLV_NoSetterProperty: 11282 llvm_unreachable("readonly properties should be processed differently"); 11283 case Expr::MLV_InvalidMessageExpression: 11284 DiagID = diag::err_readonly_message_assignment; 11285 break; 11286 case Expr::MLV_SubObjCPropertySetting: 11287 DiagID = diag::err_no_subobject_property_setting; 11288 break; 11289 } 11290 11291 SourceRange Assign; 11292 if (Loc != OrigLoc) 11293 Assign = SourceRange(OrigLoc, OrigLoc); 11294 if (NeedType) 11295 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11296 else 11297 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11298 return true; 11299 } 11300 11301 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11302 SourceLocation Loc, 11303 Sema &Sema) { 11304 if (Sema.inTemplateInstantiation()) 11305 return; 11306 if (Sema.isUnevaluatedContext()) 11307 return; 11308 if (Loc.isInvalid() || Loc.isMacroID()) 11309 return; 11310 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11311 return; 11312 11313 // C / C++ fields 11314 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11315 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11316 if (ML && MR) { 11317 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11318 return; 11319 const ValueDecl *LHSDecl = 11320 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11321 const ValueDecl *RHSDecl = 11322 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11323 if (LHSDecl != RHSDecl) 11324 return; 11325 if (LHSDecl->getType().isVolatileQualified()) 11326 return; 11327 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11328 if (RefTy->getPointeeType().isVolatileQualified()) 11329 return; 11330 11331 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11332 } 11333 11334 // Objective-C instance variables 11335 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11336 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11337 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11338 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11339 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11340 if (RL && RR && RL->getDecl() == RR->getDecl()) 11341 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11342 } 11343 } 11344 11345 // C99 6.5.16.1 11346 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11347 SourceLocation Loc, 11348 QualType CompoundType) { 11349 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11350 11351 // Verify that LHS is a modifiable lvalue, and emit error if not. 11352 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11353 return QualType(); 11354 11355 QualType LHSType = LHSExpr->getType(); 11356 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11357 CompoundType; 11358 // OpenCL v1.2 s6.1.1.1 p2: 11359 // The half data type can only be used to declare a pointer to a buffer that 11360 // contains half values 11361 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11362 LHSType->isHalfType()) { 11363 Diag(Loc, diag::err_opencl_half_load_store) << 1 11364 << LHSType.getUnqualifiedType(); 11365 return QualType(); 11366 } 11367 11368 AssignConvertType ConvTy; 11369 if (CompoundType.isNull()) { 11370 Expr *RHSCheck = RHS.get(); 11371 11372 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11373 11374 QualType LHSTy(LHSType); 11375 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11376 if (RHS.isInvalid()) 11377 return QualType(); 11378 // Special case of NSObject attributes on c-style pointer types. 11379 if (ConvTy == IncompatiblePointer && 11380 ((Context.isObjCNSObjectType(LHSType) && 11381 RHSType->isObjCObjectPointerType()) || 11382 (Context.isObjCNSObjectType(RHSType) && 11383 LHSType->isObjCObjectPointerType()))) 11384 ConvTy = Compatible; 11385 11386 if (ConvTy == Compatible && 11387 LHSType->isObjCObjectType()) 11388 Diag(Loc, diag::err_objc_object_assignment) 11389 << LHSType; 11390 11391 // If the RHS is a unary plus or minus, check to see if they = and + are 11392 // right next to each other. If so, the user may have typo'd "x =+ 4" 11393 // instead of "x += 4". 11394 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11395 RHSCheck = ICE->getSubExpr(); 11396 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11397 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11398 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11399 // Only if the two operators are exactly adjacent. 11400 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11401 // And there is a space or other character before the subexpr of the 11402 // unary +/-. We don't want to warn on "x=-1". 11403 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11404 UO->getSubExpr()->getBeginLoc().isFileID()) { 11405 Diag(Loc, diag::warn_not_compound_assign) 11406 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11407 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11408 } 11409 } 11410 11411 if (ConvTy == Compatible) { 11412 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11413 // Warn about retain cycles where a block captures the LHS, but 11414 // not if the LHS is a simple variable into which the block is 11415 // being stored...unless that variable can be captured by reference! 11416 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11417 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11418 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11419 checkRetainCycles(LHSExpr, RHS.get()); 11420 } 11421 11422 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11423 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11424 // It is safe to assign a weak reference into a strong variable. 11425 // Although this code can still have problems: 11426 // id x = self.weakProp; 11427 // id y = self.weakProp; 11428 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11429 // paths through the function. This should be revisited if 11430 // -Wrepeated-use-of-weak is made flow-sensitive. 11431 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11432 // variable, which will be valid for the current autorelease scope. 11433 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11434 RHS.get()->getBeginLoc())) 11435 getCurFunction()->markSafeWeakUse(RHS.get()); 11436 11437 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11438 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11439 } 11440 } 11441 } else { 11442 // Compound assignment "x += y" 11443 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11444 } 11445 11446 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11447 RHS.get(), AA_Assigning)) 11448 return QualType(); 11449 11450 CheckForNullPointerDereference(*this, LHSExpr); 11451 11452 // C99 6.5.16p3: The type of an assignment expression is the type of the 11453 // left operand unless the left operand has qualified type, in which case 11454 // it is the unqualified version of the type of the left operand. 11455 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11456 // is converted to the type of the assignment expression (above). 11457 // C++ 5.17p1: the type of the assignment expression is that of its left 11458 // operand. 11459 return (getLangOpts().CPlusPlus 11460 ? LHSType : LHSType.getUnqualifiedType()); 11461 } 11462 11463 // Only ignore explicit casts to void. 11464 static bool IgnoreCommaOperand(const Expr *E) { 11465 E = E->IgnoreParens(); 11466 11467 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11468 if (CE->getCastKind() == CK_ToVoid) { 11469 return true; 11470 } 11471 11472 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11473 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11474 CE->getSubExpr()->getType()->isDependentType()) { 11475 return true; 11476 } 11477 } 11478 11479 return false; 11480 } 11481 11482 // Look for instances where it is likely the comma operator is confused with 11483 // another operator. There is a whitelist of acceptable expressions for the 11484 // left hand side of the comma operator, otherwise emit a warning. 11485 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11486 // No warnings in macros 11487 if (Loc.isMacroID()) 11488 return; 11489 11490 // Don't warn in template instantiations. 11491 if (inTemplateInstantiation()) 11492 return; 11493 11494 // Scope isn't fine-grained enough to whitelist the specific cases, so 11495 // instead, skip more than needed, then call back into here with the 11496 // CommaVisitor in SemaStmt.cpp. 11497 // The whitelisted locations are the initialization and increment portions 11498 // of a for loop. The additional checks are on the condition of 11499 // if statements, do/while loops, and for loops. 11500 // Differences in scope flags for C89 mode requires the extra logic. 11501 const unsigned ForIncrementFlags = 11502 getLangOpts().C99 || getLangOpts().CPlusPlus 11503 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11504 : Scope::ContinueScope | Scope::BreakScope; 11505 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11506 const unsigned ScopeFlags = getCurScope()->getFlags(); 11507 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11508 (ScopeFlags & ForInitFlags) == ForInitFlags) 11509 return; 11510 11511 // If there are multiple comma operators used together, get the RHS of the 11512 // of the comma operator as the LHS. 11513 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11514 if (BO->getOpcode() != BO_Comma) 11515 break; 11516 LHS = BO->getRHS(); 11517 } 11518 11519 // Only allow some expressions on LHS to not warn. 11520 if (IgnoreCommaOperand(LHS)) 11521 return; 11522 11523 Diag(Loc, diag::warn_comma_operator); 11524 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11525 << LHS->getSourceRange() 11526 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11527 LangOpts.CPlusPlus ? "static_cast<void>(" 11528 : "(void)(") 11529 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11530 ")"); 11531 } 11532 11533 // C99 6.5.17 11534 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11535 SourceLocation Loc) { 11536 LHS = S.CheckPlaceholderExpr(LHS.get()); 11537 RHS = S.CheckPlaceholderExpr(RHS.get()); 11538 if (LHS.isInvalid() || RHS.isInvalid()) 11539 return QualType(); 11540 11541 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11542 // operands, but not unary promotions. 11543 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11544 11545 // So we treat the LHS as a ignored value, and in C++ we allow the 11546 // containing site to determine what should be done with the RHS. 11547 LHS = S.IgnoredValueConversions(LHS.get()); 11548 if (LHS.isInvalid()) 11549 return QualType(); 11550 11551 S.DiagnoseUnusedExprResult(LHS.get()); 11552 11553 if (!S.getLangOpts().CPlusPlus) { 11554 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11555 if (RHS.isInvalid()) 11556 return QualType(); 11557 if (!RHS.get()->getType()->isVoidType()) 11558 S.RequireCompleteType(Loc, RHS.get()->getType(), 11559 diag::err_incomplete_type); 11560 } 11561 11562 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11563 S.DiagnoseCommaOperator(LHS.get(), Loc); 11564 11565 return RHS.get()->getType(); 11566 } 11567 11568 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11569 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11570 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11571 ExprValueKind &VK, 11572 ExprObjectKind &OK, 11573 SourceLocation OpLoc, 11574 bool IsInc, bool IsPrefix) { 11575 if (Op->isTypeDependent()) 11576 return S.Context.DependentTy; 11577 11578 QualType ResType = Op->getType(); 11579 // Atomic types can be used for increment / decrement where the non-atomic 11580 // versions can, so ignore the _Atomic() specifier for the purpose of 11581 // checking. 11582 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11583 ResType = ResAtomicType->getValueType(); 11584 11585 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11586 11587 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11588 // Decrement of bool is not allowed. 11589 if (!IsInc) { 11590 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11591 return QualType(); 11592 } 11593 // Increment of bool sets it to true, but is deprecated. 11594 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11595 : diag::warn_increment_bool) 11596 << Op->getSourceRange(); 11597 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11598 // Error on enum increments and decrements in C++ mode 11599 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11600 return QualType(); 11601 } else if (ResType->isRealType()) { 11602 // OK! 11603 } else if (ResType->isPointerType()) { 11604 // C99 6.5.2.4p2, 6.5.6p2 11605 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11606 return QualType(); 11607 } else if (ResType->isObjCObjectPointerType()) { 11608 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11609 // Otherwise, we just need a complete type. 11610 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11611 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11612 return QualType(); 11613 } else if (ResType->isAnyComplexType()) { 11614 // C99 does not support ++/-- on complex types, we allow as an extension. 11615 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11616 << ResType << Op->getSourceRange(); 11617 } else if (ResType->isPlaceholderType()) { 11618 ExprResult PR = S.CheckPlaceholderExpr(Op); 11619 if (PR.isInvalid()) return QualType(); 11620 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11621 IsInc, IsPrefix); 11622 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11623 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11624 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11625 (ResType->getAs<VectorType>()->getVectorKind() != 11626 VectorType::AltiVecBool)) { 11627 // The z vector extensions allow ++ and -- for non-bool vectors. 11628 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11629 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11630 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11631 } else { 11632 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11633 << ResType << int(IsInc) << Op->getSourceRange(); 11634 return QualType(); 11635 } 11636 // At this point, we know we have a real, complex or pointer type. 11637 // Now make sure the operand is a modifiable lvalue. 11638 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11639 return QualType(); 11640 // In C++, a prefix increment is the same type as the operand. Otherwise 11641 // (in C or with postfix), the increment is the unqualified type of the 11642 // operand. 11643 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11644 VK = VK_LValue; 11645 OK = Op->getObjectKind(); 11646 return ResType; 11647 } else { 11648 VK = VK_RValue; 11649 return ResType.getUnqualifiedType(); 11650 } 11651 } 11652 11653 11654 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11655 /// This routine allows us to typecheck complex/recursive expressions 11656 /// where the declaration is needed for type checking. We only need to 11657 /// handle cases when the expression references a function designator 11658 /// or is an lvalue. Here are some examples: 11659 /// - &(x) => x 11660 /// - &*****f => f for f a function designator. 11661 /// - &s.xx => s 11662 /// - &s.zz[1].yy -> s, if zz is an array 11663 /// - *(x + 1) -> x, if x is an array 11664 /// - &"123"[2] -> 0 11665 /// - & __real__ x -> x 11666 static ValueDecl *getPrimaryDecl(Expr *E) { 11667 switch (E->getStmtClass()) { 11668 case Stmt::DeclRefExprClass: 11669 return cast<DeclRefExpr>(E)->getDecl(); 11670 case Stmt::MemberExprClass: 11671 // If this is an arrow operator, the address is an offset from 11672 // the base's value, so the object the base refers to is 11673 // irrelevant. 11674 if (cast<MemberExpr>(E)->isArrow()) 11675 return nullptr; 11676 // Otherwise, the expression refers to a part of the base 11677 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11678 case Stmt::ArraySubscriptExprClass: { 11679 // FIXME: This code shouldn't be necessary! We should catch the implicit 11680 // promotion of register arrays earlier. 11681 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11682 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11683 if (ICE->getSubExpr()->getType()->isArrayType()) 11684 return getPrimaryDecl(ICE->getSubExpr()); 11685 } 11686 return nullptr; 11687 } 11688 case Stmt::UnaryOperatorClass: { 11689 UnaryOperator *UO = cast<UnaryOperator>(E); 11690 11691 switch(UO->getOpcode()) { 11692 case UO_Real: 11693 case UO_Imag: 11694 case UO_Extension: 11695 return getPrimaryDecl(UO->getSubExpr()); 11696 default: 11697 return nullptr; 11698 } 11699 } 11700 case Stmt::ParenExprClass: 11701 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11702 case Stmt::ImplicitCastExprClass: 11703 // If the result of an implicit cast is an l-value, we care about 11704 // the sub-expression; otherwise, the result here doesn't matter. 11705 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11706 default: 11707 return nullptr; 11708 } 11709 } 11710 11711 namespace { 11712 enum { 11713 AO_Bit_Field = 0, 11714 AO_Vector_Element = 1, 11715 AO_Property_Expansion = 2, 11716 AO_Register_Variable = 3, 11717 AO_No_Error = 4 11718 }; 11719 } 11720 /// Diagnose invalid operand for address of operations. 11721 /// 11722 /// \param Type The type of operand which cannot have its address taken. 11723 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11724 Expr *E, unsigned Type) { 11725 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11726 } 11727 11728 /// CheckAddressOfOperand - The operand of & must be either a function 11729 /// designator or an lvalue designating an object. If it is an lvalue, the 11730 /// object cannot be declared with storage class register or be a bit field. 11731 /// Note: The usual conversions are *not* applied to the operand of the & 11732 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11733 /// In C++, the operand might be an overloaded function name, in which case 11734 /// we allow the '&' but retain the overloaded-function type. 11735 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11736 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11737 if (PTy->getKind() == BuiltinType::Overload) { 11738 Expr *E = OrigOp.get()->IgnoreParens(); 11739 if (!isa<OverloadExpr>(E)) { 11740 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11741 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11742 << OrigOp.get()->getSourceRange(); 11743 return QualType(); 11744 } 11745 11746 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11747 if (isa<UnresolvedMemberExpr>(Ovl)) 11748 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11749 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11750 << OrigOp.get()->getSourceRange(); 11751 return QualType(); 11752 } 11753 11754 return Context.OverloadTy; 11755 } 11756 11757 if (PTy->getKind() == BuiltinType::UnknownAny) 11758 return Context.UnknownAnyTy; 11759 11760 if (PTy->getKind() == BuiltinType::BoundMember) { 11761 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11762 << OrigOp.get()->getSourceRange(); 11763 return QualType(); 11764 } 11765 11766 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11767 if (OrigOp.isInvalid()) return QualType(); 11768 } 11769 11770 if (OrigOp.get()->isTypeDependent()) 11771 return Context.DependentTy; 11772 11773 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11774 11775 // Make sure to ignore parentheses in subsequent checks 11776 Expr *op = OrigOp.get()->IgnoreParens(); 11777 11778 // In OpenCL captures for blocks called as lambda functions 11779 // are located in the private address space. Blocks used in 11780 // enqueue_kernel can be located in a different address space 11781 // depending on a vendor implementation. Thus preventing 11782 // taking an address of the capture to avoid invalid AS casts. 11783 if (LangOpts.OpenCL) { 11784 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11785 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11786 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11787 return QualType(); 11788 } 11789 } 11790 11791 if (getLangOpts().C99) { 11792 // Implement C99-only parts of addressof rules. 11793 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11794 if (uOp->getOpcode() == UO_Deref) 11795 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11796 // (assuming the deref expression is valid). 11797 return uOp->getSubExpr()->getType(); 11798 } 11799 // Technically, there should be a check for array subscript 11800 // expressions here, but the result of one is always an lvalue anyway. 11801 } 11802 ValueDecl *dcl = getPrimaryDecl(op); 11803 11804 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11805 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11806 op->getBeginLoc())) 11807 return QualType(); 11808 11809 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11810 unsigned AddressOfError = AO_No_Error; 11811 11812 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11813 bool sfinae = (bool)isSFINAEContext(); 11814 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11815 : diag::ext_typecheck_addrof_temporary) 11816 << op->getType() << op->getSourceRange(); 11817 if (sfinae) 11818 return QualType(); 11819 // Materialize the temporary as an lvalue so that we can take its address. 11820 OrigOp = op = 11821 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11822 } else if (isa<ObjCSelectorExpr>(op)) { 11823 return Context.getPointerType(op->getType()); 11824 } else if (lval == Expr::LV_MemberFunction) { 11825 // If it's an instance method, make a member pointer. 11826 // The expression must have exactly the form &A::foo. 11827 11828 // If the underlying expression isn't a decl ref, give up. 11829 if (!isa<DeclRefExpr>(op)) { 11830 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11831 << OrigOp.get()->getSourceRange(); 11832 return QualType(); 11833 } 11834 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11835 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11836 11837 // The id-expression was parenthesized. 11838 if (OrigOp.get() != DRE) { 11839 Diag(OpLoc, diag::err_parens_pointer_member_function) 11840 << OrigOp.get()->getSourceRange(); 11841 11842 // The method was named without a qualifier. 11843 } else if (!DRE->getQualifier()) { 11844 if (MD->getParent()->getName().empty()) 11845 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11846 << op->getSourceRange(); 11847 else { 11848 SmallString<32> Str; 11849 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11850 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11851 << op->getSourceRange() 11852 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11853 } 11854 } 11855 11856 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11857 if (isa<CXXDestructorDecl>(MD)) 11858 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11859 11860 QualType MPTy = Context.getMemberPointerType( 11861 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11862 // Under the MS ABI, lock down the inheritance model now. 11863 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11864 (void)isCompleteType(OpLoc, MPTy); 11865 return MPTy; 11866 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11867 // C99 6.5.3.2p1 11868 // The operand must be either an l-value or a function designator 11869 if (!op->getType()->isFunctionType()) { 11870 // Use a special diagnostic for loads from property references. 11871 if (isa<PseudoObjectExpr>(op)) { 11872 AddressOfError = AO_Property_Expansion; 11873 } else { 11874 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11875 << op->getType() << op->getSourceRange(); 11876 return QualType(); 11877 } 11878 } 11879 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11880 // The operand cannot be a bit-field 11881 AddressOfError = AO_Bit_Field; 11882 } else if (op->getObjectKind() == OK_VectorComponent) { 11883 // The operand cannot be an element of a vector 11884 AddressOfError = AO_Vector_Element; 11885 } else if (dcl) { // C99 6.5.3.2p1 11886 // We have an lvalue with a decl. Make sure the decl is not declared 11887 // with the register storage-class specifier. 11888 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11889 // in C++ it is not error to take address of a register 11890 // variable (c++03 7.1.1P3) 11891 if (vd->getStorageClass() == SC_Register && 11892 !getLangOpts().CPlusPlus) { 11893 AddressOfError = AO_Register_Variable; 11894 } 11895 } else if (isa<MSPropertyDecl>(dcl)) { 11896 AddressOfError = AO_Property_Expansion; 11897 } else if (isa<FunctionTemplateDecl>(dcl)) { 11898 return Context.OverloadTy; 11899 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11900 // Okay: we can take the address of a field. 11901 // Could be a pointer to member, though, if there is an explicit 11902 // scope qualifier for the class. 11903 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11904 DeclContext *Ctx = dcl->getDeclContext(); 11905 if (Ctx && Ctx->isRecord()) { 11906 if (dcl->getType()->isReferenceType()) { 11907 Diag(OpLoc, 11908 diag::err_cannot_form_pointer_to_member_of_reference_type) 11909 << dcl->getDeclName() << dcl->getType(); 11910 return QualType(); 11911 } 11912 11913 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11914 Ctx = Ctx->getParent(); 11915 11916 QualType MPTy = Context.getMemberPointerType( 11917 op->getType(), 11918 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11919 // Under the MS ABI, lock down the inheritance model now. 11920 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11921 (void)isCompleteType(OpLoc, MPTy); 11922 return MPTy; 11923 } 11924 } 11925 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11926 !isa<BindingDecl>(dcl)) 11927 llvm_unreachable("Unknown/unexpected decl type"); 11928 } 11929 11930 if (AddressOfError != AO_No_Error) { 11931 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11932 return QualType(); 11933 } 11934 11935 if (lval == Expr::LV_IncompleteVoidType) { 11936 // Taking the address of a void variable is technically illegal, but we 11937 // allow it in cases which are otherwise valid. 11938 // Example: "extern void x; void* y = &x;". 11939 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11940 } 11941 11942 // If the operand has type "type", the result has type "pointer to type". 11943 if (op->getType()->isObjCObjectType()) 11944 return Context.getObjCObjectPointerType(op->getType()); 11945 11946 CheckAddressOfPackedMember(op); 11947 11948 return Context.getPointerType(op->getType()); 11949 } 11950 11951 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11952 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11953 if (!DRE) 11954 return; 11955 const Decl *D = DRE->getDecl(); 11956 if (!D) 11957 return; 11958 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11959 if (!Param) 11960 return; 11961 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11962 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11963 return; 11964 if (FunctionScopeInfo *FD = S.getCurFunction()) 11965 if (!FD->ModifiedNonNullParams.count(Param)) 11966 FD->ModifiedNonNullParams.insert(Param); 11967 } 11968 11969 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11970 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11971 SourceLocation OpLoc) { 11972 if (Op->isTypeDependent()) 11973 return S.Context.DependentTy; 11974 11975 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11976 if (ConvResult.isInvalid()) 11977 return QualType(); 11978 Op = ConvResult.get(); 11979 QualType OpTy = Op->getType(); 11980 QualType Result; 11981 11982 if (isa<CXXReinterpretCastExpr>(Op)) { 11983 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11984 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11985 Op->getSourceRange()); 11986 } 11987 11988 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11989 { 11990 Result = PT->getPointeeType(); 11991 } 11992 else if (const ObjCObjectPointerType *OPT = 11993 OpTy->getAs<ObjCObjectPointerType>()) 11994 Result = OPT->getPointeeType(); 11995 else { 11996 ExprResult PR = S.CheckPlaceholderExpr(Op); 11997 if (PR.isInvalid()) return QualType(); 11998 if (PR.get() != Op) 11999 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12000 } 12001 12002 if (Result.isNull()) { 12003 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12004 << OpTy << Op->getSourceRange(); 12005 return QualType(); 12006 } 12007 12008 // Note that per both C89 and C99, indirection is always legal, even if Result 12009 // is an incomplete type or void. It would be possible to warn about 12010 // dereferencing a void pointer, but it's completely well-defined, and such a 12011 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12012 // for pointers to 'void' but is fine for any other pointer type: 12013 // 12014 // C++ [expr.unary.op]p1: 12015 // [...] the expression to which [the unary * operator] is applied shall 12016 // be a pointer to an object type, or a pointer to a function type 12017 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12018 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12019 << OpTy << Op->getSourceRange(); 12020 12021 // Dereferences are usually l-values... 12022 VK = VK_LValue; 12023 12024 // ...except that certain expressions are never l-values in C. 12025 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12026 VK = VK_RValue; 12027 12028 return Result; 12029 } 12030 12031 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12032 BinaryOperatorKind Opc; 12033 switch (Kind) { 12034 default: llvm_unreachable("Unknown binop!"); 12035 case tok::periodstar: Opc = BO_PtrMemD; break; 12036 case tok::arrowstar: Opc = BO_PtrMemI; break; 12037 case tok::star: Opc = BO_Mul; break; 12038 case tok::slash: Opc = BO_Div; break; 12039 case tok::percent: Opc = BO_Rem; break; 12040 case tok::plus: Opc = BO_Add; break; 12041 case tok::minus: Opc = BO_Sub; break; 12042 case tok::lessless: Opc = BO_Shl; break; 12043 case tok::greatergreater: Opc = BO_Shr; break; 12044 case tok::lessequal: Opc = BO_LE; break; 12045 case tok::less: Opc = BO_LT; break; 12046 case tok::greaterequal: Opc = BO_GE; break; 12047 case tok::greater: Opc = BO_GT; break; 12048 case tok::exclaimequal: Opc = BO_NE; break; 12049 case tok::equalequal: Opc = BO_EQ; break; 12050 case tok::spaceship: Opc = BO_Cmp; break; 12051 case tok::amp: Opc = BO_And; break; 12052 case tok::caret: Opc = BO_Xor; break; 12053 case tok::pipe: Opc = BO_Or; break; 12054 case tok::ampamp: Opc = BO_LAnd; break; 12055 case tok::pipepipe: Opc = BO_LOr; break; 12056 case tok::equal: Opc = BO_Assign; break; 12057 case tok::starequal: Opc = BO_MulAssign; break; 12058 case tok::slashequal: Opc = BO_DivAssign; break; 12059 case tok::percentequal: Opc = BO_RemAssign; break; 12060 case tok::plusequal: Opc = BO_AddAssign; break; 12061 case tok::minusequal: Opc = BO_SubAssign; break; 12062 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12063 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12064 case tok::ampequal: Opc = BO_AndAssign; break; 12065 case tok::caretequal: Opc = BO_XorAssign; break; 12066 case tok::pipeequal: Opc = BO_OrAssign; break; 12067 case tok::comma: Opc = BO_Comma; break; 12068 } 12069 return Opc; 12070 } 12071 12072 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12073 tok::TokenKind Kind) { 12074 UnaryOperatorKind Opc; 12075 switch (Kind) { 12076 default: llvm_unreachable("Unknown unary op!"); 12077 case tok::plusplus: Opc = UO_PreInc; break; 12078 case tok::minusminus: Opc = UO_PreDec; break; 12079 case tok::amp: Opc = UO_AddrOf; break; 12080 case tok::star: Opc = UO_Deref; break; 12081 case tok::plus: Opc = UO_Plus; break; 12082 case tok::minus: Opc = UO_Minus; break; 12083 case tok::tilde: Opc = UO_Not; break; 12084 case tok::exclaim: Opc = UO_LNot; break; 12085 case tok::kw___real: Opc = UO_Real; break; 12086 case tok::kw___imag: Opc = UO_Imag; break; 12087 case tok::kw___extension__: Opc = UO_Extension; break; 12088 } 12089 return Opc; 12090 } 12091 12092 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12093 /// This warning suppressed in the event of macro expansions. 12094 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12095 SourceLocation OpLoc, bool IsBuiltin) { 12096 if (S.inTemplateInstantiation()) 12097 return; 12098 if (S.isUnevaluatedContext()) 12099 return; 12100 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12101 return; 12102 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12103 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12104 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12105 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12106 if (!LHSDeclRef || !RHSDeclRef || 12107 LHSDeclRef->getLocation().isMacroID() || 12108 RHSDeclRef->getLocation().isMacroID()) 12109 return; 12110 const ValueDecl *LHSDecl = 12111 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12112 const ValueDecl *RHSDecl = 12113 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12114 if (LHSDecl != RHSDecl) 12115 return; 12116 if (LHSDecl->getType().isVolatileQualified()) 12117 return; 12118 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12119 if (RefTy->getPointeeType().isVolatileQualified()) 12120 return; 12121 12122 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12123 : diag::warn_self_assignment_overloaded) 12124 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12125 << RHSExpr->getSourceRange(); 12126 } 12127 12128 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12129 /// is usually indicative of introspection within the Objective-C pointer. 12130 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12131 SourceLocation OpLoc) { 12132 if (!S.getLangOpts().ObjC) 12133 return; 12134 12135 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12136 const Expr *LHS = L.get(); 12137 const Expr *RHS = R.get(); 12138 12139 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12140 ObjCPointerExpr = LHS; 12141 OtherExpr = RHS; 12142 } 12143 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12144 ObjCPointerExpr = RHS; 12145 OtherExpr = LHS; 12146 } 12147 12148 // This warning is deliberately made very specific to reduce false 12149 // positives with logic that uses '&' for hashing. This logic mainly 12150 // looks for code trying to introspect into tagged pointers, which 12151 // code should generally never do. 12152 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12153 unsigned Diag = diag::warn_objc_pointer_masking; 12154 // Determine if we are introspecting the result of performSelectorXXX. 12155 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12156 // Special case messages to -performSelector and friends, which 12157 // can return non-pointer values boxed in a pointer value. 12158 // Some clients may wish to silence warnings in this subcase. 12159 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12160 Selector S = ME->getSelector(); 12161 StringRef SelArg0 = S.getNameForSlot(0); 12162 if (SelArg0.startswith("performSelector")) 12163 Diag = diag::warn_objc_pointer_masking_performSelector; 12164 } 12165 12166 S.Diag(OpLoc, Diag) 12167 << ObjCPointerExpr->getSourceRange(); 12168 } 12169 } 12170 12171 static NamedDecl *getDeclFromExpr(Expr *E) { 12172 if (!E) 12173 return nullptr; 12174 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12175 return DRE->getDecl(); 12176 if (auto *ME = dyn_cast<MemberExpr>(E)) 12177 return ME->getMemberDecl(); 12178 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12179 return IRE->getDecl(); 12180 return nullptr; 12181 } 12182 12183 // This helper function promotes a binary operator's operands (which are of a 12184 // half vector type) to a vector of floats and then truncates the result to 12185 // a vector of either half or short. 12186 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12187 BinaryOperatorKind Opc, QualType ResultTy, 12188 ExprValueKind VK, ExprObjectKind OK, 12189 bool IsCompAssign, SourceLocation OpLoc, 12190 FPOptions FPFeatures) { 12191 auto &Context = S.getASTContext(); 12192 assert((isVector(ResultTy, Context.HalfTy) || 12193 isVector(ResultTy, Context.ShortTy)) && 12194 "Result must be a vector of half or short"); 12195 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12196 isVector(RHS.get()->getType(), Context.HalfTy) && 12197 "both operands expected to be a half vector"); 12198 12199 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12200 QualType BinOpResTy = RHS.get()->getType(); 12201 12202 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12203 // change BinOpResTy to a vector of ints. 12204 if (isVector(ResultTy, Context.ShortTy)) 12205 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12206 12207 if (IsCompAssign) 12208 return new (Context) CompoundAssignOperator( 12209 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12210 OpLoc, FPFeatures); 12211 12212 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12213 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12214 VK, OK, OpLoc, FPFeatures); 12215 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12216 } 12217 12218 static std::pair<ExprResult, ExprResult> 12219 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12220 Expr *RHSExpr) { 12221 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12222 if (!S.getLangOpts().CPlusPlus) { 12223 // C cannot handle TypoExpr nodes on either side of a binop because it 12224 // doesn't handle dependent types properly, so make sure any TypoExprs have 12225 // been dealt with before checking the operands. 12226 LHS = S.CorrectDelayedTyposInExpr(LHS); 12227 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12228 if (Opc != BO_Assign) 12229 return ExprResult(E); 12230 // Avoid correcting the RHS to the same Expr as the LHS. 12231 Decl *D = getDeclFromExpr(E); 12232 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12233 }); 12234 } 12235 return std::make_pair(LHS, RHS); 12236 } 12237 12238 /// Returns true if conversion between vectors of halfs and vectors of floats 12239 /// is needed. 12240 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12241 QualType SrcType) { 12242 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12243 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12244 isVector(SrcType, Ctx.HalfTy); 12245 } 12246 12247 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12248 /// operator @p Opc at location @c TokLoc. This routine only supports 12249 /// built-in operations; ActOnBinOp handles overloaded operators. 12250 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12251 BinaryOperatorKind Opc, 12252 Expr *LHSExpr, Expr *RHSExpr) { 12253 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12254 // The syntax only allows initializer lists on the RHS of assignment, 12255 // so we don't need to worry about accepting invalid code for 12256 // non-assignment operators. 12257 // C++11 5.17p9: 12258 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12259 // of x = {} is x = T(). 12260 InitializationKind Kind = InitializationKind::CreateDirectList( 12261 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12262 InitializedEntity Entity = 12263 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12264 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12265 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12266 if (Init.isInvalid()) 12267 return Init; 12268 RHSExpr = Init.get(); 12269 } 12270 12271 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12272 QualType ResultTy; // Result type of the binary operator. 12273 // The following two variables are used for compound assignment operators 12274 QualType CompLHSTy; // Type of LHS after promotions for computation 12275 QualType CompResultTy; // Type of computation result 12276 ExprValueKind VK = VK_RValue; 12277 ExprObjectKind OK = OK_Ordinary; 12278 bool ConvertHalfVec = false; 12279 12280 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12281 if (!LHS.isUsable() || !RHS.isUsable()) 12282 return ExprError(); 12283 12284 if (getLangOpts().OpenCL) { 12285 QualType LHSTy = LHSExpr->getType(); 12286 QualType RHSTy = RHSExpr->getType(); 12287 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12288 // the ATOMIC_VAR_INIT macro. 12289 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12290 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12291 if (BO_Assign == Opc) 12292 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12293 else 12294 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12295 return ExprError(); 12296 } 12297 12298 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12299 // only with a builtin functions and therefore should be disallowed here. 12300 if (LHSTy->isImageType() || RHSTy->isImageType() || 12301 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12302 LHSTy->isPipeType() || RHSTy->isPipeType() || 12303 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12304 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12305 return ExprError(); 12306 } 12307 } 12308 12309 switch (Opc) { 12310 case BO_Assign: 12311 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12312 if (getLangOpts().CPlusPlus && 12313 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12314 VK = LHS.get()->getValueKind(); 12315 OK = LHS.get()->getObjectKind(); 12316 } 12317 if (!ResultTy.isNull()) { 12318 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12319 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12320 } 12321 RecordModifiableNonNullParam(*this, LHS.get()); 12322 break; 12323 case BO_PtrMemD: 12324 case BO_PtrMemI: 12325 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12326 Opc == BO_PtrMemI); 12327 break; 12328 case BO_Mul: 12329 case BO_Div: 12330 ConvertHalfVec = true; 12331 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12332 Opc == BO_Div); 12333 break; 12334 case BO_Rem: 12335 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12336 break; 12337 case BO_Add: 12338 ConvertHalfVec = true; 12339 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12340 break; 12341 case BO_Sub: 12342 ConvertHalfVec = true; 12343 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12344 break; 12345 case BO_Shl: 12346 case BO_Shr: 12347 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12348 break; 12349 case BO_LE: 12350 case BO_LT: 12351 case BO_GE: 12352 case BO_GT: 12353 ConvertHalfVec = true; 12354 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12355 break; 12356 case BO_EQ: 12357 case BO_NE: 12358 ConvertHalfVec = true; 12359 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12360 break; 12361 case BO_Cmp: 12362 ConvertHalfVec = true; 12363 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12364 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12365 break; 12366 case BO_And: 12367 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12368 LLVM_FALLTHROUGH; 12369 case BO_Xor: 12370 case BO_Or: 12371 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12372 break; 12373 case BO_LAnd: 12374 case BO_LOr: 12375 ConvertHalfVec = true; 12376 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12377 break; 12378 case BO_MulAssign: 12379 case BO_DivAssign: 12380 ConvertHalfVec = true; 12381 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12382 Opc == BO_DivAssign); 12383 CompLHSTy = CompResultTy; 12384 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12385 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12386 break; 12387 case BO_RemAssign: 12388 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12389 CompLHSTy = CompResultTy; 12390 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12391 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12392 break; 12393 case BO_AddAssign: 12394 ConvertHalfVec = true; 12395 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12396 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12397 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12398 break; 12399 case BO_SubAssign: 12400 ConvertHalfVec = true; 12401 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12402 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12403 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12404 break; 12405 case BO_ShlAssign: 12406 case BO_ShrAssign: 12407 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12408 CompLHSTy = CompResultTy; 12409 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12410 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12411 break; 12412 case BO_AndAssign: 12413 case BO_OrAssign: // fallthrough 12414 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12415 LLVM_FALLTHROUGH; 12416 case BO_XorAssign: 12417 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12418 CompLHSTy = CompResultTy; 12419 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12420 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12421 break; 12422 case BO_Comma: 12423 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12424 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12425 VK = RHS.get()->getValueKind(); 12426 OK = RHS.get()->getObjectKind(); 12427 } 12428 break; 12429 } 12430 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12431 return ExprError(); 12432 12433 // Some of the binary operations require promoting operands of half vector to 12434 // float vectors and truncating the result back to half vector. For now, we do 12435 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12436 // arm64). 12437 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12438 isVector(LHS.get()->getType(), Context.HalfTy) && 12439 "both sides are half vectors or neither sides are"); 12440 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12441 LHS.get()->getType()); 12442 12443 // Check for array bounds violations for both sides of the BinaryOperator 12444 CheckArrayAccess(LHS.get()); 12445 CheckArrayAccess(RHS.get()); 12446 12447 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12448 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12449 &Context.Idents.get("object_setClass"), 12450 SourceLocation(), LookupOrdinaryName); 12451 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12452 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12453 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12454 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12455 "object_setClass(") 12456 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12457 ",") 12458 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12459 } 12460 else 12461 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12462 } 12463 else if (const ObjCIvarRefExpr *OIRE = 12464 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12465 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12466 12467 // Opc is not a compound assignment if CompResultTy is null. 12468 if (CompResultTy.isNull()) { 12469 if (ConvertHalfVec) 12470 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12471 OpLoc, FPFeatures); 12472 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12473 OK, OpLoc, FPFeatures); 12474 } 12475 12476 // Handle compound assignments. 12477 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12478 OK_ObjCProperty) { 12479 VK = VK_LValue; 12480 OK = LHS.get()->getObjectKind(); 12481 } 12482 12483 if (ConvertHalfVec) 12484 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12485 OpLoc, FPFeatures); 12486 12487 return new (Context) CompoundAssignOperator( 12488 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12489 OpLoc, FPFeatures); 12490 } 12491 12492 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12493 /// operators are mixed in a way that suggests that the programmer forgot that 12494 /// comparison operators have higher precedence. The most typical example of 12495 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12496 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12497 SourceLocation OpLoc, Expr *LHSExpr, 12498 Expr *RHSExpr) { 12499 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12500 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12501 12502 // Check that one of the sides is a comparison operator and the other isn't. 12503 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12504 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12505 if (isLeftComp == isRightComp) 12506 return; 12507 12508 // Bitwise operations are sometimes used as eager logical ops. 12509 // Don't diagnose this. 12510 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12511 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12512 if (isLeftBitwise || isRightBitwise) 12513 return; 12514 12515 SourceRange DiagRange = isLeftComp 12516 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12517 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12518 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12519 SourceRange ParensRange = 12520 isLeftComp 12521 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12522 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12523 12524 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12525 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12526 SuggestParentheses(Self, OpLoc, 12527 Self.PDiag(diag::note_precedence_silence) << OpStr, 12528 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12529 SuggestParentheses(Self, OpLoc, 12530 Self.PDiag(diag::note_precedence_bitwise_first) 12531 << BinaryOperator::getOpcodeStr(Opc), 12532 ParensRange); 12533 } 12534 12535 /// It accepts a '&&' expr that is inside a '||' one. 12536 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12537 /// in parentheses. 12538 static void 12539 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12540 BinaryOperator *Bop) { 12541 assert(Bop->getOpcode() == BO_LAnd); 12542 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12543 << Bop->getSourceRange() << OpLoc; 12544 SuggestParentheses(Self, Bop->getOperatorLoc(), 12545 Self.PDiag(diag::note_precedence_silence) 12546 << Bop->getOpcodeStr(), 12547 Bop->getSourceRange()); 12548 } 12549 12550 /// Returns true if the given expression can be evaluated as a constant 12551 /// 'true'. 12552 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12553 bool Res; 12554 return !E->isValueDependent() && 12555 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12556 } 12557 12558 /// Returns true if the given expression can be evaluated as a constant 12559 /// 'false'. 12560 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12561 bool Res; 12562 return !E->isValueDependent() && 12563 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12564 } 12565 12566 /// Look for '&&' in the left hand of a '||' expr. 12567 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12568 Expr *LHSExpr, Expr *RHSExpr) { 12569 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12570 if (Bop->getOpcode() == BO_LAnd) { 12571 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12572 if (EvaluatesAsFalse(S, RHSExpr)) 12573 return; 12574 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12575 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12576 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12577 } else if (Bop->getOpcode() == BO_LOr) { 12578 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12579 // If it's "a || b && 1 || c" we didn't warn earlier for 12580 // "a || b && 1", but warn now. 12581 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12582 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12583 } 12584 } 12585 } 12586 } 12587 12588 /// Look for '&&' in the right hand of a '||' expr. 12589 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12590 Expr *LHSExpr, Expr *RHSExpr) { 12591 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12592 if (Bop->getOpcode() == BO_LAnd) { 12593 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12594 if (EvaluatesAsFalse(S, LHSExpr)) 12595 return; 12596 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12597 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12598 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12599 } 12600 } 12601 } 12602 12603 /// Look for bitwise op in the left or right hand of a bitwise op with 12604 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12605 /// the '&' expression in parentheses. 12606 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12607 SourceLocation OpLoc, Expr *SubExpr) { 12608 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12609 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12610 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12611 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12612 << Bop->getSourceRange() << OpLoc; 12613 SuggestParentheses(S, Bop->getOperatorLoc(), 12614 S.PDiag(diag::note_precedence_silence) 12615 << Bop->getOpcodeStr(), 12616 Bop->getSourceRange()); 12617 } 12618 } 12619 } 12620 12621 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12622 Expr *SubExpr, StringRef Shift) { 12623 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12624 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12625 StringRef Op = Bop->getOpcodeStr(); 12626 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12627 << Bop->getSourceRange() << OpLoc << Shift << Op; 12628 SuggestParentheses(S, Bop->getOperatorLoc(), 12629 S.PDiag(diag::note_precedence_silence) << Op, 12630 Bop->getSourceRange()); 12631 } 12632 } 12633 } 12634 12635 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12636 Expr *LHSExpr, Expr *RHSExpr) { 12637 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12638 if (!OCE) 12639 return; 12640 12641 FunctionDecl *FD = OCE->getDirectCallee(); 12642 if (!FD || !FD->isOverloadedOperator()) 12643 return; 12644 12645 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12646 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12647 return; 12648 12649 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12650 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12651 << (Kind == OO_LessLess); 12652 SuggestParentheses(S, OCE->getOperatorLoc(), 12653 S.PDiag(diag::note_precedence_silence) 12654 << (Kind == OO_LessLess ? "<<" : ">>"), 12655 OCE->getSourceRange()); 12656 SuggestParentheses( 12657 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12658 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12659 } 12660 12661 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12662 /// precedence. 12663 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12664 SourceLocation OpLoc, Expr *LHSExpr, 12665 Expr *RHSExpr){ 12666 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12667 if (BinaryOperator::isBitwiseOp(Opc)) 12668 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12669 12670 // Diagnose "arg1 & arg2 | arg3" 12671 if ((Opc == BO_Or || Opc == BO_Xor) && 12672 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12673 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12674 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12675 } 12676 12677 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12678 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12679 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12680 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12681 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12682 } 12683 12684 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12685 || Opc == BO_Shr) { 12686 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12687 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12688 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12689 } 12690 12691 // Warn on overloaded shift operators and comparisons, such as: 12692 // cout << 5 == 4; 12693 if (BinaryOperator::isComparisonOp(Opc)) 12694 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12695 } 12696 12697 // Binary Operators. 'Tok' is the token for the operator. 12698 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12699 tok::TokenKind Kind, 12700 Expr *LHSExpr, Expr *RHSExpr) { 12701 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12702 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12703 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12704 12705 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12706 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12707 12708 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12709 } 12710 12711 /// Build an overloaded binary operator expression in the given scope. 12712 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12713 BinaryOperatorKind Opc, 12714 Expr *LHS, Expr *RHS) { 12715 switch (Opc) { 12716 case BO_Assign: 12717 case BO_DivAssign: 12718 case BO_RemAssign: 12719 case BO_SubAssign: 12720 case BO_AndAssign: 12721 case BO_OrAssign: 12722 case BO_XorAssign: 12723 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12724 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12725 break; 12726 default: 12727 break; 12728 } 12729 12730 // Find all of the overloaded operators visible from this 12731 // point. We perform both an operator-name lookup from the local 12732 // scope and an argument-dependent lookup based on the types of 12733 // the arguments. 12734 UnresolvedSet<16> Functions; 12735 OverloadedOperatorKind OverOp 12736 = BinaryOperator::getOverloadedOperator(Opc); 12737 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12738 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12739 RHS->getType(), Functions); 12740 12741 // Build the (potentially-overloaded, potentially-dependent) 12742 // binary operation. 12743 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12744 } 12745 12746 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12747 BinaryOperatorKind Opc, 12748 Expr *LHSExpr, Expr *RHSExpr) { 12749 ExprResult LHS, RHS; 12750 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12751 if (!LHS.isUsable() || !RHS.isUsable()) 12752 return ExprError(); 12753 LHSExpr = LHS.get(); 12754 RHSExpr = RHS.get(); 12755 12756 // We want to end up calling one of checkPseudoObjectAssignment 12757 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12758 // both expressions are overloadable or either is type-dependent), 12759 // or CreateBuiltinBinOp (in any other case). We also want to get 12760 // any placeholder types out of the way. 12761 12762 // Handle pseudo-objects in the LHS. 12763 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12764 // Assignments with a pseudo-object l-value need special analysis. 12765 if (pty->getKind() == BuiltinType::PseudoObject && 12766 BinaryOperator::isAssignmentOp(Opc)) 12767 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12768 12769 // Don't resolve overloads if the other type is overloadable. 12770 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12771 // We can't actually test that if we still have a placeholder, 12772 // though. Fortunately, none of the exceptions we see in that 12773 // code below are valid when the LHS is an overload set. Note 12774 // that an overload set can be dependently-typed, but it never 12775 // instantiates to having an overloadable type. 12776 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12777 if (resolvedRHS.isInvalid()) return ExprError(); 12778 RHSExpr = resolvedRHS.get(); 12779 12780 if (RHSExpr->isTypeDependent() || 12781 RHSExpr->getType()->isOverloadableType()) 12782 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12783 } 12784 12785 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12786 // template, diagnose the missing 'template' keyword instead of diagnosing 12787 // an invalid use of a bound member function. 12788 // 12789 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12790 // to C++1z [over.over]/1.4, but we already checked for that case above. 12791 if (Opc == BO_LT && inTemplateInstantiation() && 12792 (pty->getKind() == BuiltinType::BoundMember || 12793 pty->getKind() == BuiltinType::Overload)) { 12794 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12795 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12796 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12797 return isa<FunctionTemplateDecl>(ND); 12798 })) { 12799 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12800 : OE->getNameLoc(), 12801 diag::err_template_kw_missing) 12802 << OE->getName().getAsString() << ""; 12803 return ExprError(); 12804 } 12805 } 12806 12807 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12808 if (LHS.isInvalid()) return ExprError(); 12809 LHSExpr = LHS.get(); 12810 } 12811 12812 // Handle pseudo-objects in the RHS. 12813 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12814 // An overload in the RHS can potentially be resolved by the type 12815 // being assigned to. 12816 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12817 if (getLangOpts().CPlusPlus && 12818 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12819 LHSExpr->getType()->isOverloadableType())) 12820 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12821 12822 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12823 } 12824 12825 // Don't resolve overloads if the other type is overloadable. 12826 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12827 LHSExpr->getType()->isOverloadableType()) 12828 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12829 12830 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12831 if (!resolvedRHS.isUsable()) return ExprError(); 12832 RHSExpr = resolvedRHS.get(); 12833 } 12834 12835 if (getLangOpts().CPlusPlus) { 12836 // If either expression is type-dependent, always build an 12837 // overloaded op. 12838 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12839 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12840 12841 // Otherwise, build an overloaded op if either expression has an 12842 // overloadable type. 12843 if (LHSExpr->getType()->isOverloadableType() || 12844 RHSExpr->getType()->isOverloadableType()) 12845 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12846 } 12847 12848 // Build a built-in binary operation. 12849 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12850 } 12851 12852 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12853 if (T.isNull() || T->isDependentType()) 12854 return false; 12855 12856 if (!T->isPromotableIntegerType()) 12857 return true; 12858 12859 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12860 } 12861 12862 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12863 UnaryOperatorKind Opc, 12864 Expr *InputExpr) { 12865 ExprResult Input = InputExpr; 12866 ExprValueKind VK = VK_RValue; 12867 ExprObjectKind OK = OK_Ordinary; 12868 QualType resultType; 12869 bool CanOverflow = false; 12870 12871 bool ConvertHalfVec = false; 12872 if (getLangOpts().OpenCL) { 12873 QualType Ty = InputExpr->getType(); 12874 // The only legal unary operation for atomics is '&'. 12875 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12876 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12877 // only with a builtin functions and therefore should be disallowed here. 12878 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12879 || Ty->isBlockPointerType())) { 12880 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12881 << InputExpr->getType() 12882 << Input.get()->getSourceRange()); 12883 } 12884 } 12885 switch (Opc) { 12886 case UO_PreInc: 12887 case UO_PreDec: 12888 case UO_PostInc: 12889 case UO_PostDec: 12890 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12891 OpLoc, 12892 Opc == UO_PreInc || 12893 Opc == UO_PostInc, 12894 Opc == UO_PreInc || 12895 Opc == UO_PreDec); 12896 CanOverflow = isOverflowingIntegerType(Context, resultType); 12897 break; 12898 case UO_AddrOf: 12899 resultType = CheckAddressOfOperand(Input, OpLoc); 12900 CheckAddressOfNoDeref(InputExpr); 12901 RecordModifiableNonNullParam(*this, InputExpr); 12902 break; 12903 case UO_Deref: { 12904 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12905 if (Input.isInvalid()) return ExprError(); 12906 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12907 break; 12908 } 12909 case UO_Plus: 12910 case UO_Minus: 12911 CanOverflow = Opc == UO_Minus && 12912 isOverflowingIntegerType(Context, Input.get()->getType()); 12913 Input = UsualUnaryConversions(Input.get()); 12914 if (Input.isInvalid()) return ExprError(); 12915 // Unary plus and minus require promoting an operand of half vector to a 12916 // float vector and truncating the result back to a half vector. For now, we 12917 // do this only when HalfArgsAndReturns is set (that is, when the target is 12918 // arm or arm64). 12919 ConvertHalfVec = 12920 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12921 12922 // If the operand is a half vector, promote it to a float vector. 12923 if (ConvertHalfVec) 12924 Input = convertVector(Input.get(), Context.FloatTy, *this); 12925 resultType = Input.get()->getType(); 12926 if (resultType->isDependentType()) 12927 break; 12928 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12929 break; 12930 else if (resultType->isVectorType() && 12931 // The z vector extensions don't allow + or - with bool vectors. 12932 (!Context.getLangOpts().ZVector || 12933 resultType->getAs<VectorType>()->getVectorKind() != 12934 VectorType::AltiVecBool)) 12935 break; 12936 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12937 Opc == UO_Plus && 12938 resultType->isPointerType()) 12939 break; 12940 12941 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12942 << resultType << Input.get()->getSourceRange()); 12943 12944 case UO_Not: // bitwise complement 12945 Input = UsualUnaryConversions(Input.get()); 12946 if (Input.isInvalid()) 12947 return ExprError(); 12948 resultType = Input.get()->getType(); 12949 12950 if (resultType->isDependentType()) 12951 break; 12952 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12953 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12954 // C99 does not support '~' for complex conjugation. 12955 Diag(OpLoc, diag::ext_integer_complement_complex) 12956 << resultType << Input.get()->getSourceRange(); 12957 else if (resultType->hasIntegerRepresentation()) 12958 break; 12959 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12960 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12961 // on vector float types. 12962 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12963 if (!T->isIntegerType()) 12964 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12965 << resultType << Input.get()->getSourceRange()); 12966 } else { 12967 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12968 << resultType << Input.get()->getSourceRange()); 12969 } 12970 break; 12971 12972 case UO_LNot: // logical negation 12973 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12974 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12975 if (Input.isInvalid()) return ExprError(); 12976 resultType = Input.get()->getType(); 12977 12978 // Though we still have to promote half FP to float... 12979 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12980 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12981 resultType = Context.FloatTy; 12982 } 12983 12984 if (resultType->isDependentType()) 12985 break; 12986 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12987 // C99 6.5.3.3p1: ok, fallthrough; 12988 if (Context.getLangOpts().CPlusPlus) { 12989 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12990 // operand contextually converted to bool. 12991 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12992 ScalarTypeToBooleanCastKind(resultType)); 12993 } else if (Context.getLangOpts().OpenCL && 12994 Context.getLangOpts().OpenCLVersion < 120) { 12995 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12996 // operate on scalar float types. 12997 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12998 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12999 << resultType << Input.get()->getSourceRange()); 13000 } 13001 } else if (resultType->isExtVectorType()) { 13002 if (Context.getLangOpts().OpenCL && 13003 Context.getLangOpts().OpenCLVersion < 120) { 13004 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13005 // operate on vector float types. 13006 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13007 if (!T->isIntegerType()) 13008 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13009 << resultType << Input.get()->getSourceRange()); 13010 } 13011 // Vector logical not returns the signed variant of the operand type. 13012 resultType = GetSignedVectorType(resultType); 13013 break; 13014 } else { 13015 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13016 // type in C++. We should allow that here too. 13017 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13018 << resultType << Input.get()->getSourceRange()); 13019 } 13020 13021 // LNot always has type int. C99 6.5.3.3p5. 13022 // In C++, it's bool. C++ 5.3.1p8 13023 resultType = Context.getLogicalOperationType(); 13024 break; 13025 case UO_Real: 13026 case UO_Imag: 13027 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13028 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13029 // complex l-values to ordinary l-values and all other values to r-values. 13030 if (Input.isInvalid()) return ExprError(); 13031 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13032 if (Input.get()->getValueKind() != VK_RValue && 13033 Input.get()->getObjectKind() == OK_Ordinary) 13034 VK = Input.get()->getValueKind(); 13035 } else if (!getLangOpts().CPlusPlus) { 13036 // In C, a volatile scalar is read by __imag. In C++, it is not. 13037 Input = DefaultLvalueConversion(Input.get()); 13038 } 13039 break; 13040 case UO_Extension: 13041 resultType = Input.get()->getType(); 13042 VK = Input.get()->getValueKind(); 13043 OK = Input.get()->getObjectKind(); 13044 break; 13045 case UO_Coawait: 13046 // It's unnecessary to represent the pass-through operator co_await in the 13047 // AST; just return the input expression instead. 13048 assert(!Input.get()->getType()->isDependentType() && 13049 "the co_await expression must be non-dependant before " 13050 "building operator co_await"); 13051 return Input; 13052 } 13053 if (resultType.isNull() || Input.isInvalid()) 13054 return ExprError(); 13055 13056 // Check for array bounds violations in the operand of the UnaryOperator, 13057 // except for the '*' and '&' operators that have to be handled specially 13058 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13059 // that are explicitly defined as valid by the standard). 13060 if (Opc != UO_AddrOf && Opc != UO_Deref) 13061 CheckArrayAccess(Input.get()); 13062 13063 auto *UO = new (Context) 13064 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13065 13066 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13067 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13068 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13069 13070 // Convert the result back to a half vector. 13071 if (ConvertHalfVec) 13072 return convertVector(UO, Context.HalfTy, *this); 13073 return UO; 13074 } 13075 13076 /// Determine whether the given expression is a qualified member 13077 /// access expression, of a form that could be turned into a pointer to member 13078 /// with the address-of operator. 13079 bool Sema::isQualifiedMemberAccess(Expr *E) { 13080 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13081 if (!DRE->getQualifier()) 13082 return false; 13083 13084 ValueDecl *VD = DRE->getDecl(); 13085 if (!VD->isCXXClassMember()) 13086 return false; 13087 13088 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13089 return true; 13090 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13091 return Method->isInstance(); 13092 13093 return false; 13094 } 13095 13096 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13097 if (!ULE->getQualifier()) 13098 return false; 13099 13100 for (NamedDecl *D : ULE->decls()) { 13101 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13102 if (Method->isInstance()) 13103 return true; 13104 } else { 13105 // Overload set does not contain methods. 13106 break; 13107 } 13108 } 13109 13110 return false; 13111 } 13112 13113 return false; 13114 } 13115 13116 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13117 UnaryOperatorKind Opc, Expr *Input) { 13118 // First things first: handle placeholders so that the 13119 // overloaded-operator check considers the right type. 13120 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13121 // Increment and decrement of pseudo-object references. 13122 if (pty->getKind() == BuiltinType::PseudoObject && 13123 UnaryOperator::isIncrementDecrementOp(Opc)) 13124 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13125 13126 // extension is always a builtin operator. 13127 if (Opc == UO_Extension) 13128 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13129 13130 // & gets special logic for several kinds of placeholder. 13131 // The builtin code knows what to do. 13132 if (Opc == UO_AddrOf && 13133 (pty->getKind() == BuiltinType::Overload || 13134 pty->getKind() == BuiltinType::UnknownAny || 13135 pty->getKind() == BuiltinType::BoundMember)) 13136 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13137 13138 // Anything else needs to be handled now. 13139 ExprResult Result = CheckPlaceholderExpr(Input); 13140 if (Result.isInvalid()) return ExprError(); 13141 Input = Result.get(); 13142 } 13143 13144 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13145 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13146 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13147 // Find all of the overloaded operators visible from this 13148 // point. We perform both an operator-name lookup from the local 13149 // scope and an argument-dependent lookup based on the types of 13150 // the arguments. 13151 UnresolvedSet<16> Functions; 13152 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13153 if (S && OverOp != OO_None) 13154 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13155 Functions); 13156 13157 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13158 } 13159 13160 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13161 } 13162 13163 // Unary Operators. 'Tok' is the token for the operator. 13164 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13165 tok::TokenKind Op, Expr *Input) { 13166 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13167 } 13168 13169 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13170 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13171 LabelDecl *TheDecl) { 13172 TheDecl->markUsed(Context); 13173 // Create the AST node. The address of a label always has type 'void*'. 13174 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13175 Context.getPointerType(Context.VoidTy)); 13176 } 13177 13178 /// Given the last statement in a statement-expression, check whether 13179 /// the result is a producing expression (like a call to an 13180 /// ns_returns_retained function) and, if so, rebuild it to hoist the 13181 /// release out of the full-expression. Otherwise, return null. 13182 /// Cannot fail. 13183 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 13184 // Should always be wrapped with one of these. 13185 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 13186 if (!cleanups) return nullptr; 13187 13188 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 13189 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 13190 return nullptr; 13191 13192 // Splice out the cast. This shouldn't modify any interesting 13193 // features of the statement. 13194 Expr *producer = cast->getSubExpr(); 13195 assert(producer->getType() == cast->getType()); 13196 assert(producer->getValueKind() == cast->getValueKind()); 13197 cleanups->setSubExpr(producer); 13198 return cleanups; 13199 } 13200 13201 void Sema::ActOnStartStmtExpr() { 13202 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13203 } 13204 13205 void Sema::ActOnStmtExprError() { 13206 // Note that function is also called by TreeTransform when leaving a 13207 // StmtExpr scope without rebuilding anything. 13208 13209 DiscardCleanupsInEvaluationContext(); 13210 PopExpressionEvaluationContext(); 13211 } 13212 13213 ExprResult 13214 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13215 SourceLocation RPLoc) { // "({..})" 13216 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13217 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13218 13219 if (hasAnyUnrecoverableErrorsInThisFunction()) 13220 DiscardCleanupsInEvaluationContext(); 13221 assert(!Cleanup.exprNeedsCleanups() && 13222 "cleanups within StmtExpr not correctly bound!"); 13223 PopExpressionEvaluationContext(); 13224 13225 // FIXME: there are a variety of strange constraints to enforce here, for 13226 // example, it is not possible to goto into a stmt expression apparently. 13227 // More semantic analysis is needed. 13228 13229 // If there are sub-stmts in the compound stmt, take the type of the last one 13230 // as the type of the stmtexpr. 13231 QualType Ty = Context.VoidTy; 13232 bool StmtExprMayBindToTemp = false; 13233 if (!Compound->body_empty()) { 13234 Stmt *LastStmt = Compound->body_back(); 13235 LabelStmt *LastLabelStmt = nullptr; 13236 // If LastStmt is a label, skip down through into the body. 13237 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 13238 LastLabelStmt = Label; 13239 LastStmt = Label->getSubStmt(); 13240 } 13241 13242 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 13243 // Do function/array conversion on the last expression, but not 13244 // lvalue-to-rvalue. However, initialize an unqualified type. 13245 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 13246 if (LastExpr.isInvalid()) 13247 return ExprError(); 13248 Ty = LastExpr.get()->getType().getUnqualifiedType(); 13249 13250 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 13251 // In ARC, if the final expression ends in a consume, splice 13252 // the consume out and bind it later. In the alternate case 13253 // (when dealing with a retainable type), the result 13254 // initialization will create a produce. In both cases the 13255 // result will be +1, and we'll need to balance that out with 13256 // a bind. 13257 if (Expr *rebuiltLastStmt 13258 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 13259 LastExpr = rebuiltLastStmt; 13260 } else { 13261 LastExpr = PerformCopyInitialization( 13262 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 13263 SourceLocation(), LastExpr); 13264 } 13265 13266 if (LastExpr.isInvalid()) 13267 return ExprError(); 13268 if (LastExpr.get() != nullptr) { 13269 if (!LastLabelStmt) 13270 Compound->setLastStmt(LastExpr.get()); 13271 else 13272 LastLabelStmt->setSubStmt(LastExpr.get()); 13273 StmtExprMayBindToTemp = true; 13274 } 13275 } 13276 } 13277 } 13278 13279 // FIXME: Check that expression type is complete/non-abstract; statement 13280 // expressions are not lvalues. 13281 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13282 if (StmtExprMayBindToTemp) 13283 return MaybeBindToTemporary(ResStmtExpr); 13284 return ResStmtExpr; 13285 } 13286 13287 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13288 TypeSourceInfo *TInfo, 13289 ArrayRef<OffsetOfComponent> Components, 13290 SourceLocation RParenLoc) { 13291 QualType ArgTy = TInfo->getType(); 13292 bool Dependent = ArgTy->isDependentType(); 13293 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13294 13295 // We must have at least one component that refers to the type, and the first 13296 // one is known to be a field designator. Verify that the ArgTy represents 13297 // a struct/union/class. 13298 if (!Dependent && !ArgTy->isRecordType()) 13299 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13300 << ArgTy << TypeRange); 13301 13302 // Type must be complete per C99 7.17p3 because a declaring a variable 13303 // with an incomplete type would be ill-formed. 13304 if (!Dependent 13305 && RequireCompleteType(BuiltinLoc, ArgTy, 13306 diag::err_offsetof_incomplete_type, TypeRange)) 13307 return ExprError(); 13308 13309 bool DidWarnAboutNonPOD = false; 13310 QualType CurrentType = ArgTy; 13311 SmallVector<OffsetOfNode, 4> Comps; 13312 SmallVector<Expr*, 4> Exprs; 13313 for (const OffsetOfComponent &OC : Components) { 13314 if (OC.isBrackets) { 13315 // Offset of an array sub-field. TODO: Should we allow vector elements? 13316 if (!CurrentType->isDependentType()) { 13317 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13318 if(!AT) 13319 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13320 << CurrentType); 13321 CurrentType = AT->getElementType(); 13322 } else 13323 CurrentType = Context.DependentTy; 13324 13325 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13326 if (IdxRval.isInvalid()) 13327 return ExprError(); 13328 Expr *Idx = IdxRval.get(); 13329 13330 // The expression must be an integral expression. 13331 // FIXME: An integral constant expression? 13332 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13333 !Idx->getType()->isIntegerType()) 13334 return ExprError( 13335 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13336 << Idx->getSourceRange()); 13337 13338 // Record this array index. 13339 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13340 Exprs.push_back(Idx); 13341 continue; 13342 } 13343 13344 // Offset of a field. 13345 if (CurrentType->isDependentType()) { 13346 // We have the offset of a field, but we can't look into the dependent 13347 // type. Just record the identifier of the field. 13348 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13349 CurrentType = Context.DependentTy; 13350 continue; 13351 } 13352 13353 // We need to have a complete type to look into. 13354 if (RequireCompleteType(OC.LocStart, CurrentType, 13355 diag::err_offsetof_incomplete_type)) 13356 return ExprError(); 13357 13358 // Look for the designated field. 13359 const RecordType *RC = CurrentType->getAs<RecordType>(); 13360 if (!RC) 13361 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13362 << CurrentType); 13363 RecordDecl *RD = RC->getDecl(); 13364 13365 // C++ [lib.support.types]p5: 13366 // The macro offsetof accepts a restricted set of type arguments in this 13367 // International Standard. type shall be a POD structure or a POD union 13368 // (clause 9). 13369 // C++11 [support.types]p4: 13370 // If type is not a standard-layout class (Clause 9), the results are 13371 // undefined. 13372 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13373 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13374 unsigned DiagID = 13375 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13376 : diag::ext_offsetof_non_pod_type; 13377 13378 if (!IsSafe && !DidWarnAboutNonPOD && 13379 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13380 PDiag(DiagID) 13381 << SourceRange(Components[0].LocStart, OC.LocEnd) 13382 << CurrentType)) 13383 DidWarnAboutNonPOD = true; 13384 } 13385 13386 // Look for the field. 13387 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13388 LookupQualifiedName(R, RD); 13389 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13390 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13391 if (!MemberDecl) { 13392 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13393 MemberDecl = IndirectMemberDecl->getAnonField(); 13394 } 13395 13396 if (!MemberDecl) 13397 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13398 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13399 OC.LocEnd)); 13400 13401 // C99 7.17p3: 13402 // (If the specified member is a bit-field, the behavior is undefined.) 13403 // 13404 // We diagnose this as an error. 13405 if (MemberDecl->isBitField()) { 13406 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13407 << MemberDecl->getDeclName() 13408 << SourceRange(BuiltinLoc, RParenLoc); 13409 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13410 return ExprError(); 13411 } 13412 13413 RecordDecl *Parent = MemberDecl->getParent(); 13414 if (IndirectMemberDecl) 13415 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13416 13417 // If the member was found in a base class, introduce OffsetOfNodes for 13418 // the base class indirections. 13419 CXXBasePaths Paths; 13420 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13421 Paths)) { 13422 if (Paths.getDetectedVirtual()) { 13423 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13424 << MemberDecl->getDeclName() 13425 << SourceRange(BuiltinLoc, RParenLoc); 13426 return ExprError(); 13427 } 13428 13429 CXXBasePath &Path = Paths.front(); 13430 for (const CXXBasePathElement &B : Path) 13431 Comps.push_back(OffsetOfNode(B.Base)); 13432 } 13433 13434 if (IndirectMemberDecl) { 13435 for (auto *FI : IndirectMemberDecl->chain()) { 13436 assert(isa<FieldDecl>(FI)); 13437 Comps.push_back(OffsetOfNode(OC.LocStart, 13438 cast<FieldDecl>(FI), OC.LocEnd)); 13439 } 13440 } else 13441 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13442 13443 CurrentType = MemberDecl->getType().getNonReferenceType(); 13444 } 13445 13446 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13447 Comps, Exprs, RParenLoc); 13448 } 13449 13450 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13451 SourceLocation BuiltinLoc, 13452 SourceLocation TypeLoc, 13453 ParsedType ParsedArgTy, 13454 ArrayRef<OffsetOfComponent> Components, 13455 SourceLocation RParenLoc) { 13456 13457 TypeSourceInfo *ArgTInfo; 13458 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13459 if (ArgTy.isNull()) 13460 return ExprError(); 13461 13462 if (!ArgTInfo) 13463 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13464 13465 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13466 } 13467 13468 13469 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13470 Expr *CondExpr, 13471 Expr *LHSExpr, Expr *RHSExpr, 13472 SourceLocation RPLoc) { 13473 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13474 13475 ExprValueKind VK = VK_RValue; 13476 ExprObjectKind OK = OK_Ordinary; 13477 QualType resType; 13478 bool ValueDependent = false; 13479 bool CondIsTrue = false; 13480 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13481 resType = Context.DependentTy; 13482 ValueDependent = true; 13483 } else { 13484 // The conditional expression is required to be a constant expression. 13485 llvm::APSInt condEval(32); 13486 ExprResult CondICE 13487 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13488 diag::err_typecheck_choose_expr_requires_constant, false); 13489 if (CondICE.isInvalid()) 13490 return ExprError(); 13491 CondExpr = CondICE.get(); 13492 CondIsTrue = condEval.getZExtValue(); 13493 13494 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13495 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13496 13497 resType = ActiveExpr->getType(); 13498 ValueDependent = ActiveExpr->isValueDependent(); 13499 VK = ActiveExpr->getValueKind(); 13500 OK = ActiveExpr->getObjectKind(); 13501 } 13502 13503 return new (Context) 13504 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13505 CondIsTrue, resType->isDependentType(), ValueDependent); 13506 } 13507 13508 //===----------------------------------------------------------------------===// 13509 // Clang Extensions. 13510 //===----------------------------------------------------------------------===// 13511 13512 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13513 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13514 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13515 13516 if (LangOpts.CPlusPlus) { 13517 Decl *ManglingContextDecl; 13518 if (MangleNumberingContext *MCtx = 13519 getCurrentMangleNumberContext(Block->getDeclContext(), 13520 ManglingContextDecl)) { 13521 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13522 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13523 } 13524 } 13525 13526 PushBlockScope(CurScope, Block); 13527 CurContext->addDecl(Block); 13528 if (CurScope) 13529 PushDeclContext(CurScope, Block); 13530 else 13531 CurContext = Block; 13532 13533 getCurBlock()->HasImplicitReturnType = true; 13534 13535 // Enter a new evaluation context to insulate the block from any 13536 // cleanups from the enclosing full-expression. 13537 PushExpressionEvaluationContext( 13538 ExpressionEvaluationContext::PotentiallyEvaluated); 13539 } 13540 13541 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13542 Scope *CurScope) { 13543 assert(ParamInfo.getIdentifier() == nullptr && 13544 "block-id should have no identifier!"); 13545 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13546 BlockScopeInfo *CurBlock = getCurBlock(); 13547 13548 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13549 QualType T = Sig->getType(); 13550 13551 // FIXME: We should allow unexpanded parameter packs here, but that would, 13552 // in turn, make the block expression contain unexpanded parameter packs. 13553 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13554 // Drop the parameters. 13555 FunctionProtoType::ExtProtoInfo EPI; 13556 EPI.HasTrailingReturn = false; 13557 EPI.TypeQuals |= DeclSpec::TQ_const; 13558 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13559 Sig = Context.getTrivialTypeSourceInfo(T); 13560 } 13561 13562 // GetTypeForDeclarator always produces a function type for a block 13563 // literal signature. Furthermore, it is always a FunctionProtoType 13564 // unless the function was written with a typedef. 13565 assert(T->isFunctionType() && 13566 "GetTypeForDeclarator made a non-function block signature"); 13567 13568 // Look for an explicit signature in that function type. 13569 FunctionProtoTypeLoc ExplicitSignature; 13570 13571 if ((ExplicitSignature = 13572 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13573 13574 // Check whether that explicit signature was synthesized by 13575 // GetTypeForDeclarator. If so, don't save that as part of the 13576 // written signature. 13577 if (ExplicitSignature.getLocalRangeBegin() == 13578 ExplicitSignature.getLocalRangeEnd()) { 13579 // This would be much cheaper if we stored TypeLocs instead of 13580 // TypeSourceInfos. 13581 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13582 unsigned Size = Result.getFullDataSize(); 13583 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13584 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13585 13586 ExplicitSignature = FunctionProtoTypeLoc(); 13587 } 13588 } 13589 13590 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13591 CurBlock->FunctionType = T; 13592 13593 const FunctionType *Fn = T->getAs<FunctionType>(); 13594 QualType RetTy = Fn->getReturnType(); 13595 bool isVariadic = 13596 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13597 13598 CurBlock->TheDecl->setIsVariadic(isVariadic); 13599 13600 // Context.DependentTy is used as a placeholder for a missing block 13601 // return type. TODO: what should we do with declarators like: 13602 // ^ * { ... } 13603 // If the answer is "apply template argument deduction".... 13604 if (RetTy != Context.DependentTy) { 13605 CurBlock->ReturnType = RetTy; 13606 CurBlock->TheDecl->setBlockMissingReturnType(false); 13607 CurBlock->HasImplicitReturnType = false; 13608 } 13609 13610 // Push block parameters from the declarator if we had them. 13611 SmallVector<ParmVarDecl*, 8> Params; 13612 if (ExplicitSignature) { 13613 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13614 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13615 if (Param->getIdentifier() == nullptr && 13616 !Param->isImplicit() && 13617 !Param->isInvalidDecl() && 13618 !getLangOpts().CPlusPlus) 13619 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13620 Params.push_back(Param); 13621 } 13622 13623 // Fake up parameter variables if we have a typedef, like 13624 // ^ fntype { ... } 13625 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13626 for (const auto &I : Fn->param_types()) { 13627 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13628 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13629 Params.push_back(Param); 13630 } 13631 } 13632 13633 // Set the parameters on the block decl. 13634 if (!Params.empty()) { 13635 CurBlock->TheDecl->setParams(Params); 13636 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13637 /*CheckParameterNames=*/false); 13638 } 13639 13640 // Finally we can process decl attributes. 13641 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13642 13643 // Put the parameter variables in scope. 13644 for (auto AI : CurBlock->TheDecl->parameters()) { 13645 AI->setOwningFunction(CurBlock->TheDecl); 13646 13647 // If this has an identifier, add it to the scope stack. 13648 if (AI->getIdentifier()) { 13649 CheckShadow(CurBlock->TheScope, AI); 13650 13651 PushOnScopeChains(AI, CurBlock->TheScope); 13652 } 13653 } 13654 } 13655 13656 /// ActOnBlockError - If there is an error parsing a block, this callback 13657 /// is invoked to pop the information about the block from the action impl. 13658 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13659 // Leave the expression-evaluation context. 13660 DiscardCleanupsInEvaluationContext(); 13661 PopExpressionEvaluationContext(); 13662 13663 // Pop off CurBlock, handle nested blocks. 13664 PopDeclContext(); 13665 PopFunctionScopeInfo(); 13666 } 13667 13668 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13669 /// literal was successfully completed. ^(int x){...} 13670 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13671 Stmt *Body, Scope *CurScope) { 13672 // If blocks are disabled, emit an error. 13673 if (!LangOpts.Blocks) 13674 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13675 13676 // Leave the expression-evaluation context. 13677 if (hasAnyUnrecoverableErrorsInThisFunction()) 13678 DiscardCleanupsInEvaluationContext(); 13679 assert(!Cleanup.exprNeedsCleanups() && 13680 "cleanups within block not correctly bound!"); 13681 PopExpressionEvaluationContext(); 13682 13683 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13684 BlockDecl *BD = BSI->TheDecl; 13685 13686 if (BSI->HasImplicitReturnType) 13687 deduceClosureReturnType(*BSI); 13688 13689 PopDeclContext(); 13690 13691 QualType RetTy = Context.VoidTy; 13692 if (!BSI->ReturnType.isNull()) 13693 RetTy = BSI->ReturnType; 13694 13695 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13696 QualType BlockTy; 13697 13698 // Set the captured variables on the block. 13699 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13700 SmallVector<BlockDecl::Capture, 4> Captures; 13701 for (Capture &Cap : BSI->Captures) { 13702 if (Cap.isThisCapture()) 13703 continue; 13704 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13705 Cap.isNested(), Cap.getInitExpr()); 13706 Captures.push_back(NewCap); 13707 } 13708 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13709 13710 // If the user wrote a function type in some form, try to use that. 13711 if (!BSI->FunctionType.isNull()) { 13712 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13713 13714 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13715 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13716 13717 // Turn protoless block types into nullary block types. 13718 if (isa<FunctionNoProtoType>(FTy)) { 13719 FunctionProtoType::ExtProtoInfo EPI; 13720 EPI.ExtInfo = Ext; 13721 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13722 13723 // Otherwise, if we don't need to change anything about the function type, 13724 // preserve its sugar structure. 13725 } else if (FTy->getReturnType() == RetTy && 13726 (!NoReturn || FTy->getNoReturnAttr())) { 13727 BlockTy = BSI->FunctionType; 13728 13729 // Otherwise, make the minimal modifications to the function type. 13730 } else { 13731 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13732 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13733 EPI.TypeQuals = 0; // FIXME: silently? 13734 EPI.ExtInfo = Ext; 13735 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13736 } 13737 13738 // If we don't have a function type, just build one from nothing. 13739 } else { 13740 FunctionProtoType::ExtProtoInfo EPI; 13741 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13742 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13743 } 13744 13745 DiagnoseUnusedParameters(BD->parameters()); 13746 BlockTy = Context.getBlockPointerType(BlockTy); 13747 13748 // If needed, diagnose invalid gotos and switches in the block. 13749 if (getCurFunction()->NeedsScopeChecking() && 13750 !PP.isCodeCompletionEnabled()) 13751 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13752 13753 BD->setBody(cast<CompoundStmt>(Body)); 13754 13755 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13756 DiagnoseUnguardedAvailabilityViolations(BD); 13757 13758 // Try to apply the named return value optimization. We have to check again 13759 // if we can do this, though, because blocks keep return statements around 13760 // to deduce an implicit return type. 13761 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13762 !BD->isDependentContext()) 13763 computeNRVO(Body, BSI); 13764 13765 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13766 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13767 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13768 13769 // If the block isn't obviously global, i.e. it captures anything at 13770 // all, then we need to do a few things in the surrounding context: 13771 if (Result->getBlockDecl()->hasCaptures()) { 13772 // First, this expression has a new cleanup object. 13773 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13774 Cleanup.setExprNeedsCleanups(true); 13775 13776 // It also gets a branch-protected scope if any of the captured 13777 // variables needs destruction. 13778 for (const auto &CI : Result->getBlockDecl()->captures()) { 13779 const VarDecl *var = CI.getVariable(); 13780 if (var->getType().isDestructedType() != QualType::DK_none) { 13781 setFunctionHasBranchProtectedScope(); 13782 break; 13783 } 13784 } 13785 } 13786 13787 if (getCurFunction()) 13788 getCurFunction()->addBlock(BD); 13789 13790 return Result; 13791 } 13792 13793 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13794 SourceLocation RPLoc) { 13795 TypeSourceInfo *TInfo; 13796 GetTypeFromParser(Ty, &TInfo); 13797 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13798 } 13799 13800 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13801 Expr *E, TypeSourceInfo *TInfo, 13802 SourceLocation RPLoc) { 13803 Expr *OrigExpr = E; 13804 bool IsMS = false; 13805 13806 // CUDA device code does not support varargs. 13807 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13808 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13809 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13810 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13811 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13812 } 13813 } 13814 13815 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13816 // as Microsoft ABI on an actual Microsoft platform, where 13817 // __builtin_ms_va_list and __builtin_va_list are the same.) 13818 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13819 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13820 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13821 if (Context.hasSameType(MSVaListType, E->getType())) { 13822 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13823 return ExprError(); 13824 IsMS = true; 13825 } 13826 } 13827 13828 // Get the va_list type 13829 QualType VaListType = Context.getBuiltinVaListType(); 13830 if (!IsMS) { 13831 if (VaListType->isArrayType()) { 13832 // Deal with implicit array decay; for example, on x86-64, 13833 // va_list is an array, but it's supposed to decay to 13834 // a pointer for va_arg. 13835 VaListType = Context.getArrayDecayedType(VaListType); 13836 // Make sure the input expression also decays appropriately. 13837 ExprResult Result = UsualUnaryConversions(E); 13838 if (Result.isInvalid()) 13839 return ExprError(); 13840 E = Result.get(); 13841 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13842 // If va_list is a record type and we are compiling in C++ mode, 13843 // check the argument using reference binding. 13844 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13845 Context, Context.getLValueReferenceType(VaListType), false); 13846 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13847 if (Init.isInvalid()) 13848 return ExprError(); 13849 E = Init.getAs<Expr>(); 13850 } else { 13851 // Otherwise, the va_list argument must be an l-value because 13852 // it is modified by va_arg. 13853 if (!E->isTypeDependent() && 13854 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13855 return ExprError(); 13856 } 13857 } 13858 13859 if (!IsMS && !E->isTypeDependent() && 13860 !Context.hasSameType(VaListType, E->getType())) 13861 return ExprError( 13862 Diag(E->getBeginLoc(), 13863 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13864 << OrigExpr->getType() << E->getSourceRange()); 13865 13866 if (!TInfo->getType()->isDependentType()) { 13867 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13868 diag::err_second_parameter_to_va_arg_incomplete, 13869 TInfo->getTypeLoc())) 13870 return ExprError(); 13871 13872 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13873 TInfo->getType(), 13874 diag::err_second_parameter_to_va_arg_abstract, 13875 TInfo->getTypeLoc())) 13876 return ExprError(); 13877 13878 if (!TInfo->getType().isPODType(Context)) { 13879 Diag(TInfo->getTypeLoc().getBeginLoc(), 13880 TInfo->getType()->isObjCLifetimeType() 13881 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13882 : diag::warn_second_parameter_to_va_arg_not_pod) 13883 << TInfo->getType() 13884 << TInfo->getTypeLoc().getSourceRange(); 13885 } 13886 13887 // Check for va_arg where arguments of the given type will be promoted 13888 // (i.e. this va_arg is guaranteed to have undefined behavior). 13889 QualType PromoteType; 13890 if (TInfo->getType()->isPromotableIntegerType()) { 13891 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13892 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13893 PromoteType = QualType(); 13894 } 13895 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13896 PromoteType = Context.DoubleTy; 13897 if (!PromoteType.isNull()) 13898 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13899 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13900 << TInfo->getType() 13901 << PromoteType 13902 << TInfo->getTypeLoc().getSourceRange()); 13903 } 13904 13905 QualType T = TInfo->getType().getNonLValueExprType(Context); 13906 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13907 } 13908 13909 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13910 // The type of __null will be int or long, depending on the size of 13911 // pointers on the target. 13912 QualType Ty; 13913 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13914 if (pw == Context.getTargetInfo().getIntWidth()) 13915 Ty = Context.IntTy; 13916 else if (pw == Context.getTargetInfo().getLongWidth()) 13917 Ty = Context.LongTy; 13918 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13919 Ty = Context.LongLongTy; 13920 else { 13921 llvm_unreachable("I don't know size of pointer!"); 13922 } 13923 13924 return new (Context) GNUNullExpr(Ty, TokenLoc); 13925 } 13926 13927 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13928 bool Diagnose) { 13929 if (!getLangOpts().ObjC) 13930 return false; 13931 13932 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13933 if (!PT) 13934 return false; 13935 13936 if (!PT->isObjCIdType()) { 13937 // Check if the destination is the 'NSString' interface. 13938 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13939 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13940 return false; 13941 } 13942 13943 // Ignore any parens, implicit casts (should only be 13944 // array-to-pointer decays), and not-so-opaque values. The last is 13945 // important for making this trigger for property assignments. 13946 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13947 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13948 if (OV->getSourceExpr()) 13949 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13950 13951 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13952 if (!SL || !SL->isAscii()) 13953 return false; 13954 if (Diagnose) { 13955 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13956 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13957 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13958 } 13959 return true; 13960 } 13961 13962 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13963 const Expr *SrcExpr) { 13964 if (!DstType->isFunctionPointerType() || 13965 !SrcExpr->getType()->isFunctionType()) 13966 return false; 13967 13968 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13969 if (!DRE) 13970 return false; 13971 13972 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13973 if (!FD) 13974 return false; 13975 13976 return !S.checkAddressOfFunctionIsAvailable(FD, 13977 /*Complain=*/true, 13978 SrcExpr->getBeginLoc()); 13979 } 13980 13981 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13982 SourceLocation Loc, 13983 QualType DstType, QualType SrcType, 13984 Expr *SrcExpr, AssignmentAction Action, 13985 bool *Complained) { 13986 if (Complained) 13987 *Complained = false; 13988 13989 // Decode the result (notice that AST's are still created for extensions). 13990 bool CheckInferredResultType = false; 13991 bool isInvalid = false; 13992 unsigned DiagKind = 0; 13993 FixItHint Hint; 13994 ConversionFixItGenerator ConvHints; 13995 bool MayHaveConvFixit = false; 13996 bool MayHaveFunctionDiff = false; 13997 const ObjCInterfaceDecl *IFace = nullptr; 13998 const ObjCProtocolDecl *PDecl = nullptr; 13999 14000 switch (ConvTy) { 14001 case Compatible: 14002 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14003 return false; 14004 14005 case PointerToInt: 14006 DiagKind = diag::ext_typecheck_convert_pointer_int; 14007 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14008 MayHaveConvFixit = true; 14009 break; 14010 case IntToPointer: 14011 DiagKind = diag::ext_typecheck_convert_int_pointer; 14012 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14013 MayHaveConvFixit = true; 14014 break; 14015 case IncompatiblePointer: 14016 if (Action == AA_Passing_CFAudited) 14017 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14018 else if (SrcType->isFunctionPointerType() && 14019 DstType->isFunctionPointerType()) 14020 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14021 else 14022 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14023 14024 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14025 SrcType->isObjCObjectPointerType(); 14026 if (Hint.isNull() && !CheckInferredResultType) { 14027 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14028 } 14029 else if (CheckInferredResultType) { 14030 SrcType = SrcType.getUnqualifiedType(); 14031 DstType = DstType.getUnqualifiedType(); 14032 } 14033 MayHaveConvFixit = true; 14034 break; 14035 case IncompatiblePointerSign: 14036 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14037 break; 14038 case FunctionVoidPointer: 14039 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14040 break; 14041 case IncompatiblePointerDiscardsQualifiers: { 14042 // Perform array-to-pointer decay if necessary. 14043 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14044 14045 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14046 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14047 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14048 DiagKind = diag::err_typecheck_incompatible_address_space; 14049 break; 14050 14051 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14052 DiagKind = diag::err_typecheck_incompatible_ownership; 14053 break; 14054 } 14055 14056 llvm_unreachable("unknown error case for discarding qualifiers!"); 14057 // fallthrough 14058 } 14059 case CompatiblePointerDiscardsQualifiers: 14060 // If the qualifiers lost were because we were applying the 14061 // (deprecated) C++ conversion from a string literal to a char* 14062 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14063 // Ideally, this check would be performed in 14064 // checkPointerTypesForAssignment. However, that would require a 14065 // bit of refactoring (so that the second argument is an 14066 // expression, rather than a type), which should be done as part 14067 // of a larger effort to fix checkPointerTypesForAssignment for 14068 // C++ semantics. 14069 if (getLangOpts().CPlusPlus && 14070 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14071 return false; 14072 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14073 break; 14074 case IncompatibleNestedPointerQualifiers: 14075 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14076 break; 14077 case IntToBlockPointer: 14078 DiagKind = diag::err_int_to_block_pointer; 14079 break; 14080 case IncompatibleBlockPointer: 14081 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14082 break; 14083 case IncompatibleObjCQualifiedId: { 14084 if (SrcType->isObjCQualifiedIdType()) { 14085 const ObjCObjectPointerType *srcOPT = 14086 SrcType->getAs<ObjCObjectPointerType>(); 14087 for (auto *srcProto : srcOPT->quals()) { 14088 PDecl = srcProto; 14089 break; 14090 } 14091 if (const ObjCInterfaceType *IFaceT = 14092 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14093 IFace = IFaceT->getDecl(); 14094 } 14095 else if (DstType->isObjCQualifiedIdType()) { 14096 const ObjCObjectPointerType *dstOPT = 14097 DstType->getAs<ObjCObjectPointerType>(); 14098 for (auto *dstProto : dstOPT->quals()) { 14099 PDecl = dstProto; 14100 break; 14101 } 14102 if (const ObjCInterfaceType *IFaceT = 14103 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14104 IFace = IFaceT->getDecl(); 14105 } 14106 DiagKind = diag::warn_incompatible_qualified_id; 14107 break; 14108 } 14109 case IncompatibleVectors: 14110 DiagKind = diag::warn_incompatible_vectors; 14111 break; 14112 case IncompatibleObjCWeakRef: 14113 DiagKind = diag::err_arc_weak_unavailable_assign; 14114 break; 14115 case Incompatible: 14116 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14117 if (Complained) 14118 *Complained = true; 14119 return true; 14120 } 14121 14122 DiagKind = diag::err_typecheck_convert_incompatible; 14123 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14124 MayHaveConvFixit = true; 14125 isInvalid = true; 14126 MayHaveFunctionDiff = true; 14127 break; 14128 } 14129 14130 QualType FirstType, SecondType; 14131 switch (Action) { 14132 case AA_Assigning: 14133 case AA_Initializing: 14134 // The destination type comes first. 14135 FirstType = DstType; 14136 SecondType = SrcType; 14137 break; 14138 14139 case AA_Returning: 14140 case AA_Passing: 14141 case AA_Passing_CFAudited: 14142 case AA_Converting: 14143 case AA_Sending: 14144 case AA_Casting: 14145 // The source type comes first. 14146 FirstType = SrcType; 14147 SecondType = DstType; 14148 break; 14149 } 14150 14151 PartialDiagnostic FDiag = PDiag(DiagKind); 14152 if (Action == AA_Passing_CFAudited) 14153 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14154 else 14155 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14156 14157 // If we can fix the conversion, suggest the FixIts. 14158 assert(ConvHints.isNull() || Hint.isNull()); 14159 if (!ConvHints.isNull()) { 14160 for (FixItHint &H : ConvHints.Hints) 14161 FDiag << H; 14162 } else { 14163 FDiag << Hint; 14164 } 14165 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14166 14167 if (MayHaveFunctionDiff) 14168 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14169 14170 Diag(Loc, FDiag); 14171 if (DiagKind == diag::warn_incompatible_qualified_id && 14172 PDecl && IFace && !IFace->hasDefinition()) 14173 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14174 << IFace << PDecl; 14175 14176 if (SecondType == Context.OverloadTy) 14177 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14178 FirstType, /*TakingAddress=*/true); 14179 14180 if (CheckInferredResultType) 14181 EmitRelatedResultTypeNote(SrcExpr); 14182 14183 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14184 EmitRelatedResultTypeNoteForReturn(DstType); 14185 14186 if (Complained) 14187 *Complained = true; 14188 return isInvalid; 14189 } 14190 14191 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14192 llvm::APSInt *Result) { 14193 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14194 public: 14195 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14196 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14197 } 14198 } Diagnoser; 14199 14200 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14201 } 14202 14203 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14204 llvm::APSInt *Result, 14205 unsigned DiagID, 14206 bool AllowFold) { 14207 class IDDiagnoser : public VerifyICEDiagnoser { 14208 unsigned DiagID; 14209 14210 public: 14211 IDDiagnoser(unsigned DiagID) 14212 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14213 14214 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14215 S.Diag(Loc, DiagID) << SR; 14216 } 14217 } Diagnoser(DiagID); 14218 14219 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14220 } 14221 14222 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14223 SourceRange SR) { 14224 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14225 } 14226 14227 ExprResult 14228 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14229 VerifyICEDiagnoser &Diagnoser, 14230 bool AllowFold) { 14231 SourceLocation DiagLoc = E->getBeginLoc(); 14232 14233 if (getLangOpts().CPlusPlus11) { 14234 // C++11 [expr.const]p5: 14235 // If an expression of literal class type is used in a context where an 14236 // integral constant expression is required, then that class type shall 14237 // have a single non-explicit conversion function to an integral or 14238 // unscoped enumeration type 14239 ExprResult Converted; 14240 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14241 public: 14242 CXX11ConvertDiagnoser(bool Silent) 14243 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14244 Silent, true) {} 14245 14246 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14247 QualType T) override { 14248 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14249 } 14250 14251 SemaDiagnosticBuilder diagnoseIncomplete( 14252 Sema &S, SourceLocation Loc, QualType T) override { 14253 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14254 } 14255 14256 SemaDiagnosticBuilder diagnoseExplicitConv( 14257 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14258 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14259 } 14260 14261 SemaDiagnosticBuilder noteExplicitConv( 14262 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14263 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14264 << ConvTy->isEnumeralType() << ConvTy; 14265 } 14266 14267 SemaDiagnosticBuilder diagnoseAmbiguous( 14268 Sema &S, SourceLocation Loc, QualType T) override { 14269 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14270 } 14271 14272 SemaDiagnosticBuilder noteAmbiguous( 14273 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14274 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14275 << ConvTy->isEnumeralType() << ConvTy; 14276 } 14277 14278 SemaDiagnosticBuilder diagnoseConversion( 14279 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14280 llvm_unreachable("conversion functions are permitted"); 14281 } 14282 } ConvertDiagnoser(Diagnoser.Suppress); 14283 14284 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14285 ConvertDiagnoser); 14286 if (Converted.isInvalid()) 14287 return Converted; 14288 E = Converted.get(); 14289 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14290 return ExprError(); 14291 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14292 // An ICE must be of integral or unscoped enumeration type. 14293 if (!Diagnoser.Suppress) 14294 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14295 return ExprError(); 14296 } 14297 14298 if (!isa<ConstantExpr>(E)) 14299 E = ConstantExpr::Create(Context, E); 14300 14301 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14302 // in the non-ICE case. 14303 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14304 if (Result) 14305 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14306 return E; 14307 } 14308 14309 Expr::EvalResult EvalResult; 14310 SmallVector<PartialDiagnosticAt, 8> Notes; 14311 EvalResult.Diag = &Notes; 14312 14313 // Try to evaluate the expression, and produce diagnostics explaining why it's 14314 // not a constant expression as a side-effect. 14315 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14316 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14317 14318 // In C++11, we can rely on diagnostics being produced for any expression 14319 // which is not a constant expression. If no diagnostics were produced, then 14320 // this is a constant expression. 14321 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14322 if (Result) 14323 *Result = EvalResult.Val.getInt(); 14324 return E; 14325 } 14326 14327 // If our only note is the usual "invalid subexpression" note, just point 14328 // the caret at its location rather than producing an essentially 14329 // redundant note. 14330 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14331 diag::note_invalid_subexpr_in_const_expr) { 14332 DiagLoc = Notes[0].first; 14333 Notes.clear(); 14334 } 14335 14336 if (!Folded || !AllowFold) { 14337 if (!Diagnoser.Suppress) { 14338 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14339 for (const PartialDiagnosticAt &Note : Notes) 14340 Diag(Note.first, Note.second); 14341 } 14342 14343 return ExprError(); 14344 } 14345 14346 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14347 for (const PartialDiagnosticAt &Note : Notes) 14348 Diag(Note.first, Note.second); 14349 14350 if (Result) 14351 *Result = EvalResult.Val.getInt(); 14352 return E; 14353 } 14354 14355 namespace { 14356 // Handle the case where we conclude a expression which we speculatively 14357 // considered to be unevaluated is actually evaluated. 14358 class TransformToPE : public TreeTransform<TransformToPE> { 14359 typedef TreeTransform<TransformToPE> BaseTransform; 14360 14361 public: 14362 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14363 14364 // Make sure we redo semantic analysis 14365 bool AlwaysRebuild() { return true; } 14366 14367 // Make sure we handle LabelStmts correctly. 14368 // FIXME: This does the right thing, but maybe we need a more general 14369 // fix to TreeTransform? 14370 StmtResult TransformLabelStmt(LabelStmt *S) { 14371 S->getDecl()->setStmt(nullptr); 14372 return BaseTransform::TransformLabelStmt(S); 14373 } 14374 14375 // We need to special-case DeclRefExprs referring to FieldDecls which 14376 // are not part of a member pointer formation; normal TreeTransforming 14377 // doesn't catch this case because of the way we represent them in the AST. 14378 // FIXME: This is a bit ugly; is it really the best way to handle this 14379 // case? 14380 // 14381 // Error on DeclRefExprs referring to FieldDecls. 14382 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14383 if (isa<FieldDecl>(E->getDecl()) && 14384 !SemaRef.isUnevaluatedContext()) 14385 return SemaRef.Diag(E->getLocation(), 14386 diag::err_invalid_non_static_member_use) 14387 << E->getDecl() << E->getSourceRange(); 14388 14389 return BaseTransform::TransformDeclRefExpr(E); 14390 } 14391 14392 // Exception: filter out member pointer formation 14393 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14394 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14395 return E; 14396 14397 return BaseTransform::TransformUnaryOperator(E); 14398 } 14399 14400 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14401 // Lambdas never need to be transformed. 14402 return E; 14403 } 14404 }; 14405 } 14406 14407 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14408 assert(isUnevaluatedContext() && 14409 "Should only transform unevaluated expressions"); 14410 ExprEvalContexts.back().Context = 14411 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14412 if (isUnevaluatedContext()) 14413 return E; 14414 return TransformToPE(*this).TransformExpr(E); 14415 } 14416 14417 void 14418 Sema::PushExpressionEvaluationContext( 14419 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14420 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14421 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14422 LambdaContextDecl, ExprContext); 14423 Cleanup.reset(); 14424 if (!MaybeODRUseExprs.empty()) 14425 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14426 } 14427 14428 void 14429 Sema::PushExpressionEvaluationContext( 14430 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14431 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14432 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14433 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14434 } 14435 14436 namespace { 14437 14438 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 14439 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 14440 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 14441 if (E->getOpcode() == UO_Deref) 14442 return CheckPossibleDeref(S, E->getSubExpr()); 14443 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 14444 return CheckPossibleDeref(S, E->getBase()); 14445 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 14446 return CheckPossibleDeref(S, E->getBase()); 14447 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 14448 QualType Inner; 14449 QualType Ty = E->getType(); 14450 if (const auto *Ptr = Ty->getAs<PointerType>()) 14451 Inner = Ptr->getPointeeType(); 14452 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 14453 Inner = Arr->getElementType(); 14454 else 14455 return nullptr; 14456 14457 if (Inner->hasAttr(attr::NoDeref)) 14458 return E; 14459 } 14460 return nullptr; 14461 } 14462 14463 } // namespace 14464 14465 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 14466 for (const Expr *E : Rec.PossibleDerefs) { 14467 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 14468 if (DeclRef) { 14469 const ValueDecl *Decl = DeclRef->getDecl(); 14470 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 14471 << Decl->getName() << E->getSourceRange(); 14472 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 14473 } else { 14474 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 14475 << E->getSourceRange(); 14476 } 14477 } 14478 Rec.PossibleDerefs.clear(); 14479 } 14480 14481 void Sema::PopExpressionEvaluationContext() { 14482 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14483 unsigned NumTypos = Rec.NumTypos; 14484 14485 if (!Rec.Lambdas.empty()) { 14486 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14487 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14488 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14489 unsigned D; 14490 if (Rec.isUnevaluated()) { 14491 // C++11 [expr.prim.lambda]p2: 14492 // A lambda-expression shall not appear in an unevaluated operand 14493 // (Clause 5). 14494 D = diag::err_lambda_unevaluated_operand; 14495 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14496 // C++1y [expr.const]p2: 14497 // A conditional-expression e is a core constant expression unless the 14498 // evaluation of e, following the rules of the abstract machine, would 14499 // evaluate [...] a lambda-expression. 14500 D = diag::err_lambda_in_constant_expression; 14501 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14502 // C++17 [expr.prim.lamda]p2: 14503 // A lambda-expression shall not appear [...] in a template-argument. 14504 D = diag::err_lambda_in_invalid_context; 14505 } else 14506 llvm_unreachable("Couldn't infer lambda error message."); 14507 14508 for (const auto *L : Rec.Lambdas) 14509 Diag(L->getBeginLoc(), D); 14510 } else { 14511 // Mark the capture expressions odr-used. This was deferred 14512 // during lambda expression creation. 14513 for (auto *Lambda : Rec.Lambdas) { 14514 for (auto *C : Lambda->capture_inits()) 14515 MarkDeclarationsReferencedInExpr(C); 14516 } 14517 } 14518 } 14519 14520 WarnOnPendingNoDerefs(Rec); 14521 14522 // When are coming out of an unevaluated context, clear out any 14523 // temporaries that we may have created as part of the evaluation of 14524 // the expression in that context: they aren't relevant because they 14525 // will never be constructed. 14526 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14527 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14528 ExprCleanupObjects.end()); 14529 Cleanup = Rec.ParentCleanup; 14530 CleanupVarDeclMarking(); 14531 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14532 // Otherwise, merge the contexts together. 14533 } else { 14534 Cleanup.mergeFrom(Rec.ParentCleanup); 14535 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14536 Rec.SavedMaybeODRUseExprs.end()); 14537 } 14538 14539 // Pop the current expression evaluation context off the stack. 14540 ExprEvalContexts.pop_back(); 14541 14542 // The global expression evaluation context record is never popped. 14543 ExprEvalContexts.back().NumTypos += NumTypos; 14544 } 14545 14546 void Sema::DiscardCleanupsInEvaluationContext() { 14547 ExprCleanupObjects.erase( 14548 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14549 ExprCleanupObjects.end()); 14550 Cleanup.reset(); 14551 MaybeODRUseExprs.clear(); 14552 } 14553 14554 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14555 if (!E->getType()->isVariablyModifiedType()) 14556 return E; 14557 return TransformToPotentiallyEvaluated(E); 14558 } 14559 14560 /// Are we within a context in which some evaluation could be performed (be it 14561 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14562 /// captured by C++'s idea of an "unevaluated context". 14563 static bool isEvaluatableContext(Sema &SemaRef) { 14564 switch (SemaRef.ExprEvalContexts.back().Context) { 14565 case Sema::ExpressionEvaluationContext::Unevaluated: 14566 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14567 // Expressions in this context are never evaluated. 14568 return false; 14569 14570 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14571 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14572 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14573 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14574 // Expressions in this context could be evaluated. 14575 return true; 14576 14577 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14578 // Referenced declarations will only be used if the construct in the 14579 // containing expression is used, at which point we'll be given another 14580 // turn to mark them. 14581 return false; 14582 } 14583 llvm_unreachable("Invalid context"); 14584 } 14585 14586 /// Are we within a context in which references to resolved functions or to 14587 /// variables result in odr-use? 14588 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14589 // An expression in a template is not really an expression until it's been 14590 // instantiated, so it doesn't trigger odr-use. 14591 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14592 return false; 14593 14594 switch (SemaRef.ExprEvalContexts.back().Context) { 14595 case Sema::ExpressionEvaluationContext::Unevaluated: 14596 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14597 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14598 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14599 return false; 14600 14601 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14602 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14603 return true; 14604 14605 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14606 return false; 14607 } 14608 llvm_unreachable("Invalid context"); 14609 } 14610 14611 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14612 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14613 return Func->isConstexpr() && 14614 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14615 } 14616 14617 /// Mark a function referenced, and check whether it is odr-used 14618 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14619 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14620 bool MightBeOdrUse) { 14621 assert(Func && "No function?"); 14622 14623 Func->setReferenced(); 14624 14625 // C++11 [basic.def.odr]p3: 14626 // A function whose name appears as a potentially-evaluated expression is 14627 // odr-used if it is the unique lookup result or the selected member of a 14628 // set of overloaded functions [...]. 14629 // 14630 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14631 // can just check that here. 14632 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14633 14634 // Determine whether we require a function definition to exist, per 14635 // C++11 [temp.inst]p3: 14636 // Unless a function template specialization has been explicitly 14637 // instantiated or explicitly specialized, the function template 14638 // specialization is implicitly instantiated when the specialization is 14639 // referenced in a context that requires a function definition to exist. 14640 // 14641 // That is either when this is an odr-use, or when a usage of a constexpr 14642 // function occurs within an evaluatable context. 14643 bool NeedDefinition = 14644 OdrUse || (isEvaluatableContext(*this) && 14645 isImplicitlyDefinableConstexprFunction(Func)); 14646 14647 // C++14 [temp.expl.spec]p6: 14648 // If a template [...] is explicitly specialized then that specialization 14649 // shall be declared before the first use of that specialization that would 14650 // cause an implicit instantiation to take place, in every translation unit 14651 // in which such a use occurs 14652 if (NeedDefinition && 14653 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14654 Func->getMemberSpecializationInfo())) 14655 checkSpecializationVisibility(Loc, Func); 14656 14657 // C++14 [except.spec]p17: 14658 // An exception-specification is considered to be needed when: 14659 // - the function is odr-used or, if it appears in an unevaluated operand, 14660 // would be odr-used if the expression were potentially-evaluated; 14661 // 14662 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14663 // function is a pure virtual function we're calling, and in that case the 14664 // function was selected by overload resolution and we need to resolve its 14665 // exception specification for a different reason. 14666 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14667 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14668 ResolveExceptionSpec(Loc, FPT); 14669 14670 // If we don't need to mark the function as used, and we don't need to 14671 // try to provide a definition, there's nothing more to do. 14672 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14673 (!NeedDefinition || Func->getBody())) 14674 return; 14675 14676 // Note that this declaration has been used. 14677 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14678 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14679 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14680 if (Constructor->isDefaultConstructor()) { 14681 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14682 return; 14683 DefineImplicitDefaultConstructor(Loc, Constructor); 14684 } else if (Constructor->isCopyConstructor()) { 14685 DefineImplicitCopyConstructor(Loc, Constructor); 14686 } else if (Constructor->isMoveConstructor()) { 14687 DefineImplicitMoveConstructor(Loc, Constructor); 14688 } 14689 } else if (Constructor->getInheritedConstructor()) { 14690 DefineInheritingConstructor(Loc, Constructor); 14691 } 14692 } else if (CXXDestructorDecl *Destructor = 14693 dyn_cast<CXXDestructorDecl>(Func)) { 14694 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14695 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14696 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14697 return; 14698 DefineImplicitDestructor(Loc, Destructor); 14699 } 14700 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14701 MarkVTableUsed(Loc, Destructor->getParent()); 14702 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14703 if (MethodDecl->isOverloadedOperator() && 14704 MethodDecl->getOverloadedOperator() == OO_Equal) { 14705 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14706 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14707 if (MethodDecl->isCopyAssignmentOperator()) 14708 DefineImplicitCopyAssignment(Loc, MethodDecl); 14709 else if (MethodDecl->isMoveAssignmentOperator()) 14710 DefineImplicitMoveAssignment(Loc, MethodDecl); 14711 } 14712 } else if (isa<CXXConversionDecl>(MethodDecl) && 14713 MethodDecl->getParent()->isLambda()) { 14714 CXXConversionDecl *Conversion = 14715 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14716 if (Conversion->isLambdaToBlockPointerConversion()) 14717 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14718 else 14719 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14720 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14721 MarkVTableUsed(Loc, MethodDecl->getParent()); 14722 } 14723 14724 // Recursive functions should be marked when used from another function. 14725 // FIXME: Is this really right? 14726 if (CurContext == Func) return; 14727 14728 // Implicit instantiation of function templates and member functions of 14729 // class templates. 14730 if (Func->isImplicitlyInstantiable()) { 14731 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14732 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14733 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14734 if (FirstInstantiation) { 14735 PointOfInstantiation = Loc; 14736 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14737 } else if (TSK != TSK_ImplicitInstantiation) { 14738 // Use the point of use as the point of instantiation, instead of the 14739 // point of explicit instantiation (which we track as the actual point of 14740 // instantiation). This gives better backtraces in diagnostics. 14741 PointOfInstantiation = Loc; 14742 } 14743 14744 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14745 Func->isConstexpr()) { 14746 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14747 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14748 CodeSynthesisContexts.size()) 14749 PendingLocalImplicitInstantiations.push_back( 14750 std::make_pair(Func, PointOfInstantiation)); 14751 else if (Func->isConstexpr()) 14752 // Do not defer instantiations of constexpr functions, to avoid the 14753 // expression evaluator needing to call back into Sema if it sees a 14754 // call to such a function. 14755 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14756 else { 14757 Func->setInstantiationIsPending(true); 14758 PendingInstantiations.push_back(std::make_pair(Func, 14759 PointOfInstantiation)); 14760 // Notify the consumer that a function was implicitly instantiated. 14761 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14762 } 14763 } 14764 } else { 14765 // Walk redefinitions, as some of them may be instantiable. 14766 for (auto i : Func->redecls()) { 14767 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14768 MarkFunctionReferenced(Loc, i, OdrUse); 14769 } 14770 } 14771 14772 if (!OdrUse) return; 14773 14774 // Keep track of used but undefined functions. 14775 if (!Func->isDefined()) { 14776 if (mightHaveNonExternalLinkage(Func)) 14777 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14778 else if (Func->getMostRecentDecl()->isInlined() && 14779 !LangOpts.GNUInline && 14780 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14781 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14782 else if (isExternalWithNoLinkageType(Func)) 14783 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14784 } 14785 14786 Func->markUsed(Context); 14787 } 14788 14789 static void 14790 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14791 ValueDecl *var, DeclContext *DC) { 14792 DeclContext *VarDC = var->getDeclContext(); 14793 14794 // If the parameter still belongs to the translation unit, then 14795 // we're actually just using one parameter in the declaration of 14796 // the next. 14797 if (isa<ParmVarDecl>(var) && 14798 isa<TranslationUnitDecl>(VarDC)) 14799 return; 14800 14801 // For C code, don't diagnose about capture if we're not actually in code 14802 // right now; it's impossible to write a non-constant expression outside of 14803 // function context, so we'll get other (more useful) diagnostics later. 14804 // 14805 // For C++, things get a bit more nasty... it would be nice to suppress this 14806 // diagnostic for certain cases like using a local variable in an array bound 14807 // for a member of a local class, but the correct predicate is not obvious. 14808 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14809 return; 14810 14811 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14812 unsigned ContextKind = 3; // unknown 14813 if (isa<CXXMethodDecl>(VarDC) && 14814 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14815 ContextKind = 2; 14816 } else if (isa<FunctionDecl>(VarDC)) { 14817 ContextKind = 0; 14818 } else if (isa<BlockDecl>(VarDC)) { 14819 ContextKind = 1; 14820 } 14821 14822 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14823 << var << ValueKind << ContextKind << VarDC; 14824 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14825 << var; 14826 14827 // FIXME: Add additional diagnostic info about class etc. which prevents 14828 // capture. 14829 } 14830 14831 14832 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14833 bool &SubCapturesAreNested, 14834 QualType &CaptureType, 14835 QualType &DeclRefType) { 14836 // Check whether we've already captured it. 14837 if (CSI->CaptureMap.count(Var)) { 14838 // If we found a capture, any subcaptures are nested. 14839 SubCapturesAreNested = true; 14840 14841 // Retrieve the capture type for this variable. 14842 CaptureType = CSI->getCapture(Var).getCaptureType(); 14843 14844 // Compute the type of an expression that refers to this variable. 14845 DeclRefType = CaptureType.getNonReferenceType(); 14846 14847 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14848 // are mutable in the sense that user can change their value - they are 14849 // private instances of the captured declarations. 14850 const Capture &Cap = CSI->getCapture(Var); 14851 if (Cap.isCopyCapture() && 14852 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14853 !(isa<CapturedRegionScopeInfo>(CSI) && 14854 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14855 DeclRefType.addConst(); 14856 return true; 14857 } 14858 return false; 14859 } 14860 14861 // Only block literals, captured statements, and lambda expressions can 14862 // capture; other scopes don't work. 14863 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14864 SourceLocation Loc, 14865 const bool Diagnose, Sema &S) { 14866 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14867 return getLambdaAwareParentOfDeclContext(DC); 14868 else if (Var->hasLocalStorage()) { 14869 if (Diagnose) 14870 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14871 } 14872 return nullptr; 14873 } 14874 14875 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14876 // certain types of variables (unnamed, variably modified types etc.) 14877 // so check for eligibility. 14878 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14879 SourceLocation Loc, 14880 const bool Diagnose, Sema &S) { 14881 14882 bool IsBlock = isa<BlockScopeInfo>(CSI); 14883 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14884 14885 // Lambdas are not allowed to capture unnamed variables 14886 // (e.g. anonymous unions). 14887 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14888 // assuming that's the intent. 14889 if (IsLambda && !Var->getDeclName()) { 14890 if (Diagnose) { 14891 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14892 S.Diag(Var->getLocation(), diag::note_declared_at); 14893 } 14894 return false; 14895 } 14896 14897 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14898 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14899 if (Diagnose) { 14900 S.Diag(Loc, diag::err_ref_vm_type); 14901 S.Diag(Var->getLocation(), diag::note_previous_decl) 14902 << Var->getDeclName(); 14903 } 14904 return false; 14905 } 14906 // Prohibit structs with flexible array members too. 14907 // We cannot capture what is in the tail end of the struct. 14908 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14909 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14910 if (Diagnose) { 14911 if (IsBlock) 14912 S.Diag(Loc, diag::err_ref_flexarray_type); 14913 else 14914 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14915 << Var->getDeclName(); 14916 S.Diag(Var->getLocation(), diag::note_previous_decl) 14917 << Var->getDeclName(); 14918 } 14919 return false; 14920 } 14921 } 14922 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14923 // Lambdas and captured statements are not allowed to capture __block 14924 // variables; they don't support the expected semantics. 14925 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14926 if (Diagnose) { 14927 S.Diag(Loc, diag::err_capture_block_variable) 14928 << Var->getDeclName() << !IsLambda; 14929 S.Diag(Var->getLocation(), diag::note_previous_decl) 14930 << Var->getDeclName(); 14931 } 14932 return false; 14933 } 14934 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14935 if (S.getLangOpts().OpenCL && IsBlock && 14936 Var->getType()->isBlockPointerType()) { 14937 if (Diagnose) 14938 S.Diag(Loc, diag::err_opencl_block_ref_block); 14939 return false; 14940 } 14941 14942 return true; 14943 } 14944 14945 // Returns true if the capture by block was successful. 14946 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14947 SourceLocation Loc, 14948 const bool BuildAndDiagnose, 14949 QualType &CaptureType, 14950 QualType &DeclRefType, 14951 const bool Nested, 14952 Sema &S) { 14953 Expr *CopyExpr = nullptr; 14954 bool ByRef = false; 14955 14956 // Blocks are not allowed to capture arrays, excepting OpenCL. 14957 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 14958 // (decayed to pointers). 14959 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 14960 if (BuildAndDiagnose) { 14961 S.Diag(Loc, diag::err_ref_array_type); 14962 S.Diag(Var->getLocation(), diag::note_previous_decl) 14963 << Var->getDeclName(); 14964 } 14965 return false; 14966 } 14967 14968 // Forbid the block-capture of autoreleasing variables. 14969 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14970 if (BuildAndDiagnose) { 14971 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14972 << /*block*/ 0; 14973 S.Diag(Var->getLocation(), diag::note_previous_decl) 14974 << Var->getDeclName(); 14975 } 14976 return false; 14977 } 14978 14979 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14980 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14981 // This function finds out whether there is an AttributedType of kind 14982 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14983 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14984 // rather than being added implicitly by the compiler. 14985 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14986 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14987 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14988 return true; 14989 14990 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14991 Ty = AttrTy->getModifiedType(); 14992 } 14993 14994 return false; 14995 }; 14996 14997 QualType PointeeTy = PT->getPointeeType(); 14998 14999 if (PointeeTy->getAs<ObjCObjectPointerType>() && 15000 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15001 !IsObjCOwnershipAttributedType(PointeeTy)) { 15002 if (BuildAndDiagnose) { 15003 SourceLocation VarLoc = Var->getLocation(); 15004 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15005 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15006 } 15007 } 15008 } 15009 15010 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15011 if (HasBlocksAttr || CaptureType->isReferenceType() || 15012 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15013 // Block capture by reference does not change the capture or 15014 // declaration reference types. 15015 ByRef = true; 15016 } else { 15017 // Block capture by copy introduces 'const'. 15018 CaptureType = CaptureType.getNonReferenceType().withConst(); 15019 DeclRefType = CaptureType; 15020 15021 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 15022 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 15023 // The capture logic needs the destructor, so make sure we mark it. 15024 // Usually this is unnecessary because most local variables have 15025 // their destructors marked at declaration time, but parameters are 15026 // an exception because it's technically only the call site that 15027 // actually requires the destructor. 15028 if (isa<ParmVarDecl>(Var)) 15029 S.FinalizeVarWithDestructor(Var, Record); 15030 15031 // Enter a new evaluation context to insulate the copy 15032 // full-expression. 15033 EnterExpressionEvaluationContext scope( 15034 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 15035 15036 // According to the blocks spec, the capture of a variable from 15037 // the stack requires a const copy constructor. This is not true 15038 // of the copy/move done to move a __block variable to the heap. 15039 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 15040 DeclRefType.withConst(), 15041 VK_LValue, Loc); 15042 15043 ExprResult Result 15044 = S.PerformCopyInitialization( 15045 InitializedEntity::InitializeBlock(Var->getLocation(), 15046 CaptureType, false), 15047 Loc, DeclRef); 15048 15049 // Build a full-expression copy expression if initialization 15050 // succeeded and used a non-trivial constructor. Recover from 15051 // errors by pretending that the copy isn't necessary. 15052 if (!Result.isInvalid() && 15053 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15054 ->isTrivial()) { 15055 Result = S.MaybeCreateExprWithCleanups(Result); 15056 CopyExpr = Result.get(); 15057 } 15058 } 15059 } 15060 } 15061 15062 // Actually capture the variable. 15063 if (BuildAndDiagnose) 15064 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 15065 SourceLocation(), CaptureType, CopyExpr); 15066 15067 return true; 15068 15069 } 15070 15071 15072 /// Capture the given variable in the captured region. 15073 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15074 VarDecl *Var, 15075 SourceLocation Loc, 15076 const bool BuildAndDiagnose, 15077 QualType &CaptureType, 15078 QualType &DeclRefType, 15079 const bool RefersToCapturedVariable, 15080 Sema &S) { 15081 // By default, capture variables by reference. 15082 bool ByRef = true; 15083 // Using an LValue reference type is consistent with Lambdas (see below). 15084 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15085 if (S.isOpenMPCapturedDecl(Var)) { 15086 bool HasConst = DeclRefType.isConstQualified(); 15087 DeclRefType = DeclRefType.getUnqualifiedType(); 15088 // Don't lose diagnostics about assignments to const. 15089 if (HasConst) 15090 DeclRefType.addConst(); 15091 } 15092 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 15093 } 15094 15095 if (ByRef) 15096 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15097 else 15098 CaptureType = DeclRefType; 15099 15100 Expr *CopyExpr = nullptr; 15101 if (BuildAndDiagnose) { 15102 // The current implementation assumes that all variables are captured 15103 // by references. Since there is no capture by copy, no expression 15104 // evaluation will be needed. 15105 RecordDecl *RD = RSI->TheRecordDecl; 15106 15107 FieldDecl *Field 15108 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 15109 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 15110 nullptr, false, ICIS_NoInit); 15111 Field->setImplicit(true); 15112 Field->setAccess(AS_private); 15113 RD->addDecl(Field); 15114 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 15115 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 15116 15117 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 15118 DeclRefType, VK_LValue, Loc); 15119 Var->setReferenced(true); 15120 Var->markUsed(S.Context); 15121 } 15122 15123 // Actually capture the variable. 15124 if (BuildAndDiagnose) 15125 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 15126 SourceLocation(), CaptureType, CopyExpr); 15127 15128 15129 return true; 15130 } 15131 15132 /// Create a field within the lambda class for the variable 15133 /// being captured. 15134 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 15135 QualType FieldType, QualType DeclRefType, 15136 SourceLocation Loc, 15137 bool RefersToCapturedVariable) { 15138 CXXRecordDecl *Lambda = LSI->Lambda; 15139 15140 // Build the non-static data member. 15141 FieldDecl *Field 15142 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 15143 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 15144 nullptr, false, ICIS_NoInit); 15145 // If the variable being captured has an invalid type, mark the lambda class 15146 // as invalid as well. 15147 if (!FieldType->isDependentType()) { 15148 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 15149 Lambda->setInvalidDecl(); 15150 Field->setInvalidDecl(); 15151 } else { 15152 NamedDecl *Def; 15153 FieldType->isIncompleteType(&Def); 15154 if (Def && Def->isInvalidDecl()) { 15155 Lambda->setInvalidDecl(); 15156 Field->setInvalidDecl(); 15157 } 15158 } 15159 } 15160 Field->setImplicit(true); 15161 Field->setAccess(AS_private); 15162 Lambda->addDecl(Field); 15163 } 15164 15165 /// Capture the given variable in the lambda. 15166 static bool captureInLambda(LambdaScopeInfo *LSI, 15167 VarDecl *Var, 15168 SourceLocation Loc, 15169 const bool BuildAndDiagnose, 15170 QualType &CaptureType, 15171 QualType &DeclRefType, 15172 const bool RefersToCapturedVariable, 15173 const Sema::TryCaptureKind Kind, 15174 SourceLocation EllipsisLoc, 15175 const bool IsTopScope, 15176 Sema &S) { 15177 15178 // Determine whether we are capturing by reference or by value. 15179 bool ByRef = false; 15180 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15181 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15182 } else { 15183 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15184 } 15185 15186 // Compute the type of the field that will capture this variable. 15187 if (ByRef) { 15188 // C++11 [expr.prim.lambda]p15: 15189 // An entity is captured by reference if it is implicitly or 15190 // explicitly captured but not captured by copy. It is 15191 // unspecified whether additional unnamed non-static data 15192 // members are declared in the closure type for entities 15193 // captured by reference. 15194 // 15195 // FIXME: It is not clear whether we want to build an lvalue reference 15196 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15197 // to do the former, while EDG does the latter. Core issue 1249 will 15198 // clarify, but for now we follow GCC because it's a more permissive and 15199 // easily defensible position. 15200 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15201 } else { 15202 // C++11 [expr.prim.lambda]p14: 15203 // For each entity captured by copy, an unnamed non-static 15204 // data member is declared in the closure type. The 15205 // declaration order of these members is unspecified. The type 15206 // of such a data member is the type of the corresponding 15207 // captured entity if the entity is not a reference to an 15208 // object, or the referenced type otherwise. [Note: If the 15209 // captured entity is a reference to a function, the 15210 // corresponding data member is also a reference to a 15211 // function. - end note ] 15212 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15213 if (!RefType->getPointeeType()->isFunctionType()) 15214 CaptureType = RefType->getPointeeType(); 15215 } 15216 15217 // Forbid the lambda copy-capture of autoreleasing variables. 15218 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15219 if (BuildAndDiagnose) { 15220 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15221 S.Diag(Var->getLocation(), diag::note_previous_decl) 15222 << Var->getDeclName(); 15223 } 15224 return false; 15225 } 15226 15227 // Make sure that by-copy captures are of a complete and non-abstract type. 15228 if (BuildAndDiagnose) { 15229 if (!CaptureType->isDependentType() && 15230 S.RequireCompleteType(Loc, CaptureType, 15231 diag::err_capture_of_incomplete_type, 15232 Var->getDeclName())) 15233 return false; 15234 15235 if (S.RequireNonAbstractType(Loc, CaptureType, 15236 diag::err_capture_of_abstract_type)) 15237 return false; 15238 } 15239 } 15240 15241 // Capture this variable in the lambda. 15242 if (BuildAndDiagnose) 15243 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15244 RefersToCapturedVariable); 15245 15246 // Compute the type of a reference to this captured variable. 15247 if (ByRef) 15248 DeclRefType = CaptureType.getNonReferenceType(); 15249 else { 15250 // C++ [expr.prim.lambda]p5: 15251 // The closure type for a lambda-expression has a public inline 15252 // function call operator [...]. This function call operator is 15253 // declared const (9.3.1) if and only if the lambda-expression's 15254 // parameter-declaration-clause is not followed by mutable. 15255 DeclRefType = CaptureType.getNonReferenceType(); 15256 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15257 DeclRefType.addConst(); 15258 } 15259 15260 // Add the capture. 15261 if (BuildAndDiagnose) 15262 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15263 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15264 15265 return true; 15266 } 15267 15268 bool Sema::tryCaptureVariable( 15269 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15270 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15271 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15272 // An init-capture is notionally from the context surrounding its 15273 // declaration, but its parent DC is the lambda class. 15274 DeclContext *VarDC = Var->getDeclContext(); 15275 if (Var->isInitCapture()) 15276 VarDC = VarDC->getParent(); 15277 15278 DeclContext *DC = CurContext; 15279 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15280 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15281 // We need to sync up the Declaration Context with the 15282 // FunctionScopeIndexToStopAt 15283 if (FunctionScopeIndexToStopAt) { 15284 unsigned FSIndex = FunctionScopes.size() - 1; 15285 while (FSIndex != MaxFunctionScopesIndex) { 15286 DC = getLambdaAwareParentOfDeclContext(DC); 15287 --FSIndex; 15288 } 15289 } 15290 15291 15292 // If the variable is declared in the current context, there is no need to 15293 // capture it. 15294 if (VarDC == DC) return true; 15295 15296 // Capture global variables if it is required to use private copy of this 15297 // variable. 15298 bool IsGlobal = !Var->hasLocalStorage(); 15299 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15300 return true; 15301 Var = Var->getCanonicalDecl(); 15302 15303 // Walk up the stack to determine whether we can capture the variable, 15304 // performing the "simple" checks that don't depend on type. We stop when 15305 // we've either hit the declared scope of the variable or find an existing 15306 // capture of that variable. We start from the innermost capturing-entity 15307 // (the DC) and ensure that all intervening capturing-entities 15308 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15309 // declcontext can either capture the variable or have already captured 15310 // the variable. 15311 CaptureType = Var->getType(); 15312 DeclRefType = CaptureType.getNonReferenceType(); 15313 bool Nested = false; 15314 bool Explicit = (Kind != TryCapture_Implicit); 15315 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15316 do { 15317 // Only block literals, captured statements, and lambda expressions can 15318 // capture; other scopes don't work. 15319 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15320 ExprLoc, 15321 BuildAndDiagnose, 15322 *this); 15323 // We need to check for the parent *first* because, if we *have* 15324 // private-captured a global variable, we need to recursively capture it in 15325 // intermediate blocks, lambdas, etc. 15326 if (!ParentDC) { 15327 if (IsGlobal) { 15328 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15329 break; 15330 } 15331 return true; 15332 } 15333 15334 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15335 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15336 15337 15338 // Check whether we've already captured it. 15339 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15340 DeclRefType)) { 15341 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15342 break; 15343 } 15344 // If we are instantiating a generic lambda call operator body, 15345 // we do not want to capture new variables. What was captured 15346 // during either a lambdas transformation or initial parsing 15347 // should be used. 15348 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15349 if (BuildAndDiagnose) { 15350 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15351 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15352 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15353 Diag(Var->getLocation(), diag::note_previous_decl) 15354 << Var->getDeclName(); 15355 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15356 } else 15357 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15358 } 15359 return true; 15360 } 15361 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15362 // certain types of variables (unnamed, variably modified types etc.) 15363 // so check for eligibility. 15364 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15365 return true; 15366 15367 // Try to capture variable-length arrays types. 15368 if (Var->getType()->isVariablyModifiedType()) { 15369 // We're going to walk down into the type and look for VLA 15370 // expressions. 15371 QualType QTy = Var->getType(); 15372 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15373 QTy = PVD->getOriginalType(); 15374 captureVariablyModifiedType(Context, QTy, CSI); 15375 } 15376 15377 if (getLangOpts().OpenMP) { 15378 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15379 // OpenMP private variables should not be captured in outer scope, so 15380 // just break here. Similarly, global variables that are captured in a 15381 // target region should not be captured outside the scope of the region. 15382 if (RSI->CapRegionKind == CR_OpenMP) { 15383 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15384 auto IsTargetCap = !IsOpenMPPrivateDecl && 15385 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15386 // When we detect target captures we are looking from inside the 15387 // target region, therefore we need to propagate the capture from the 15388 // enclosing region. Therefore, the capture is not initially nested. 15389 if (IsTargetCap) 15390 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15391 15392 if (IsTargetCap || IsOpenMPPrivateDecl) { 15393 Nested = !IsTargetCap; 15394 DeclRefType = DeclRefType.getUnqualifiedType(); 15395 CaptureType = Context.getLValueReferenceType(DeclRefType); 15396 break; 15397 } 15398 } 15399 } 15400 } 15401 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15402 // No capture-default, and this is not an explicit capture 15403 // so cannot capture this variable. 15404 if (BuildAndDiagnose) { 15405 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15406 Diag(Var->getLocation(), diag::note_previous_decl) 15407 << Var->getDeclName(); 15408 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15409 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15410 diag::note_lambda_decl); 15411 // FIXME: If we error out because an outer lambda can not implicitly 15412 // capture a variable that an inner lambda explicitly captures, we 15413 // should have the inner lambda do the explicit capture - because 15414 // it makes for cleaner diagnostics later. This would purely be done 15415 // so that the diagnostic does not misleadingly claim that a variable 15416 // can not be captured by a lambda implicitly even though it is captured 15417 // explicitly. Suggestion: 15418 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15419 // at the function head 15420 // - cache the StartingDeclContext - this must be a lambda 15421 // - captureInLambda in the innermost lambda the variable. 15422 } 15423 return true; 15424 } 15425 15426 FunctionScopesIndex--; 15427 DC = ParentDC; 15428 Explicit = false; 15429 } while (!VarDC->Equals(DC)); 15430 15431 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15432 // computing the type of the capture at each step, checking type-specific 15433 // requirements, and adding captures if requested. 15434 // If the variable had already been captured previously, we start capturing 15435 // at the lambda nested within that one. 15436 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15437 ++I) { 15438 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15439 15440 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15441 if (!captureInBlock(BSI, Var, ExprLoc, 15442 BuildAndDiagnose, CaptureType, 15443 DeclRefType, Nested, *this)) 15444 return true; 15445 Nested = true; 15446 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15447 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15448 BuildAndDiagnose, CaptureType, 15449 DeclRefType, Nested, *this)) 15450 return true; 15451 Nested = true; 15452 } else { 15453 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15454 if (!captureInLambda(LSI, Var, ExprLoc, 15455 BuildAndDiagnose, CaptureType, 15456 DeclRefType, Nested, Kind, EllipsisLoc, 15457 /*IsTopScope*/I == N - 1, *this)) 15458 return true; 15459 Nested = true; 15460 } 15461 } 15462 return false; 15463 } 15464 15465 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15466 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15467 QualType CaptureType; 15468 QualType DeclRefType; 15469 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15470 /*BuildAndDiagnose=*/true, CaptureType, 15471 DeclRefType, nullptr); 15472 } 15473 15474 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15475 QualType CaptureType; 15476 QualType DeclRefType; 15477 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15478 /*BuildAndDiagnose=*/false, CaptureType, 15479 DeclRefType, nullptr); 15480 } 15481 15482 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15483 QualType CaptureType; 15484 QualType DeclRefType; 15485 15486 // Determine whether we can capture this variable. 15487 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15488 /*BuildAndDiagnose=*/false, CaptureType, 15489 DeclRefType, nullptr)) 15490 return QualType(); 15491 15492 return DeclRefType; 15493 } 15494 15495 15496 15497 // If either the type of the variable or the initializer is dependent, 15498 // return false. Otherwise, determine whether the variable is a constant 15499 // expression. Use this if you need to know if a variable that might or 15500 // might not be dependent is truly a constant expression. 15501 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15502 ASTContext &Context) { 15503 15504 if (Var->getType()->isDependentType()) 15505 return false; 15506 const VarDecl *DefVD = nullptr; 15507 Var->getAnyInitializer(DefVD); 15508 if (!DefVD) 15509 return false; 15510 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15511 Expr *Init = cast<Expr>(Eval->Value); 15512 if (Init->isValueDependent()) 15513 return false; 15514 return IsVariableAConstantExpression(Var, Context); 15515 } 15516 15517 15518 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15519 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15520 // an object that satisfies the requirements for appearing in a 15521 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15522 // is immediately applied." This function handles the lvalue-to-rvalue 15523 // conversion part. 15524 MaybeODRUseExprs.erase(E->IgnoreParens()); 15525 15526 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15527 // to a variable that is a constant expression, and if so, identify it as 15528 // a reference to a variable that does not involve an odr-use of that 15529 // variable. 15530 if (LambdaScopeInfo *LSI = getCurLambda()) { 15531 Expr *SansParensExpr = E->IgnoreParens(); 15532 VarDecl *Var = nullptr; 15533 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15534 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15535 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15536 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15537 15538 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15539 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15540 } 15541 } 15542 15543 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15544 Res = CorrectDelayedTyposInExpr(Res); 15545 15546 if (!Res.isUsable()) 15547 return Res; 15548 15549 // If a constant-expression is a reference to a variable where we delay 15550 // deciding whether it is an odr-use, just assume we will apply the 15551 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15552 // (a non-type template argument), we have special handling anyway. 15553 UpdateMarkingForLValueToRValue(Res.get()); 15554 return Res; 15555 } 15556 15557 void Sema::CleanupVarDeclMarking() { 15558 for (Expr *E : MaybeODRUseExprs) { 15559 VarDecl *Var; 15560 SourceLocation Loc; 15561 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15562 Var = cast<VarDecl>(DRE->getDecl()); 15563 Loc = DRE->getLocation(); 15564 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15565 Var = cast<VarDecl>(ME->getMemberDecl()); 15566 Loc = ME->getMemberLoc(); 15567 } else { 15568 llvm_unreachable("Unexpected expression"); 15569 } 15570 15571 MarkVarDeclODRUsed(Var, Loc, *this, 15572 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15573 } 15574 15575 MaybeODRUseExprs.clear(); 15576 } 15577 15578 15579 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15580 VarDecl *Var, Expr *E) { 15581 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15582 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15583 Var->setReferenced(); 15584 15585 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15586 15587 bool OdrUseContext = isOdrUseContext(SemaRef); 15588 bool UsableInConstantExpr = 15589 Var->isUsableInConstantExpressions(SemaRef.Context); 15590 bool NeedDefinition = 15591 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15592 15593 VarTemplateSpecializationDecl *VarSpec = 15594 dyn_cast<VarTemplateSpecializationDecl>(Var); 15595 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15596 "Can't instantiate a partial template specialization."); 15597 15598 // If this might be a member specialization of a static data member, check 15599 // the specialization is visible. We already did the checks for variable 15600 // template specializations when we created them. 15601 if (NeedDefinition && TSK != TSK_Undeclared && 15602 !isa<VarTemplateSpecializationDecl>(Var)) 15603 SemaRef.checkSpecializationVisibility(Loc, Var); 15604 15605 // Perform implicit instantiation of static data members, static data member 15606 // templates of class templates, and variable template specializations. Delay 15607 // instantiations of variable templates, except for those that could be used 15608 // in a constant expression. 15609 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15610 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15611 // instantiation declaration if a variable is usable in a constant 15612 // expression (among other cases). 15613 bool TryInstantiating = 15614 TSK == TSK_ImplicitInstantiation || 15615 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15616 15617 if (TryInstantiating) { 15618 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15619 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15620 if (FirstInstantiation) { 15621 PointOfInstantiation = Loc; 15622 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15623 } 15624 15625 bool InstantiationDependent = false; 15626 bool IsNonDependent = 15627 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15628 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15629 : true; 15630 15631 // Do not instantiate specializations that are still type-dependent. 15632 if (IsNonDependent) { 15633 if (UsableInConstantExpr) { 15634 // Do not defer instantiations of variables that could be used in a 15635 // constant expression. 15636 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15637 } else if (FirstInstantiation || 15638 isa<VarTemplateSpecializationDecl>(Var)) { 15639 // FIXME: For a specialization of a variable template, we don't 15640 // distinguish between "declaration and type implicitly instantiated" 15641 // and "implicit instantiation of definition requested", so we have 15642 // no direct way to avoid enqueueing the pending instantiation 15643 // multiple times. 15644 SemaRef.PendingInstantiations 15645 .push_back(std::make_pair(Var, PointOfInstantiation)); 15646 } 15647 } 15648 } 15649 } 15650 15651 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15652 // the requirements for appearing in a constant expression (5.19) and, if 15653 // it is an object, the lvalue-to-rvalue conversion (4.1) 15654 // is immediately applied." We check the first part here, and 15655 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15656 // Note that we use the C++11 definition everywhere because nothing in 15657 // C++03 depends on whether we get the C++03 version correct. The second 15658 // part does not apply to references, since they are not objects. 15659 if (OdrUseContext && E && 15660 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15661 // A reference initialized by a constant expression can never be 15662 // odr-used, so simply ignore it. 15663 if (!Var->getType()->isReferenceType() || 15664 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15665 SemaRef.MaybeODRUseExprs.insert(E); 15666 } else if (OdrUseContext) { 15667 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15668 /*MaxFunctionScopeIndex ptr*/ nullptr); 15669 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15670 // If this is a dependent context, we don't need to mark variables as 15671 // odr-used, but we may still need to track them for lambda capture. 15672 // FIXME: Do we also need to do this inside dependent typeid expressions 15673 // (which are modeled as unevaluated at this point)? 15674 const bool RefersToEnclosingScope = 15675 (SemaRef.CurContext != Var->getDeclContext() && 15676 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15677 if (RefersToEnclosingScope) { 15678 LambdaScopeInfo *const LSI = 15679 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15680 if (LSI && (!LSI->CallOperator || 15681 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15682 // If a variable could potentially be odr-used, defer marking it so 15683 // until we finish analyzing the full expression for any 15684 // lvalue-to-rvalue 15685 // or discarded value conversions that would obviate odr-use. 15686 // Add it to the list of potential captures that will be analyzed 15687 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15688 // unless the variable is a reference that was initialized by a constant 15689 // expression (this will never need to be captured or odr-used). 15690 assert(E && "Capture variable should be used in an expression."); 15691 if (!Var->getType()->isReferenceType() || 15692 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15693 LSI->addPotentialCapture(E->IgnoreParens()); 15694 } 15695 } 15696 } 15697 } 15698 15699 /// Mark a variable referenced, and check whether it is odr-used 15700 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15701 /// used directly for normal expressions referring to VarDecl. 15702 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15703 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15704 } 15705 15706 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15707 Decl *D, Expr *E, bool MightBeOdrUse) { 15708 if (SemaRef.isInOpenMPDeclareTargetContext()) 15709 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15710 15711 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15712 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15713 return; 15714 } 15715 15716 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15717 15718 // If this is a call to a method via a cast, also mark the method in the 15719 // derived class used in case codegen can devirtualize the call. 15720 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15721 if (!ME) 15722 return; 15723 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15724 if (!MD) 15725 return; 15726 // Only attempt to devirtualize if this is truly a virtual call. 15727 bool IsVirtualCall = MD->isVirtual() && 15728 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15729 if (!IsVirtualCall) 15730 return; 15731 15732 // If it's possible to devirtualize the call, mark the called function 15733 // referenced. 15734 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15735 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15736 if (DM) 15737 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15738 } 15739 15740 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15741 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15742 // TODO: update this with DR# once a defect report is filed. 15743 // C++11 defect. The address of a pure member should not be an ODR use, even 15744 // if it's a qualified reference. 15745 bool OdrUse = true; 15746 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15747 if (Method->isVirtual() && 15748 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15749 OdrUse = false; 15750 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15751 } 15752 15753 /// Perform reference-marking and odr-use handling for a MemberExpr. 15754 void Sema::MarkMemberReferenced(MemberExpr *E) { 15755 // C++11 [basic.def.odr]p2: 15756 // A non-overloaded function whose name appears as a potentially-evaluated 15757 // expression or a member of a set of candidate functions, if selected by 15758 // overload resolution when referred to from a potentially-evaluated 15759 // expression, is odr-used, unless it is a pure virtual function and its 15760 // name is not explicitly qualified. 15761 bool MightBeOdrUse = true; 15762 if (E->performsVirtualDispatch(getLangOpts())) { 15763 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15764 if (Method->isPure()) 15765 MightBeOdrUse = false; 15766 } 15767 SourceLocation Loc = 15768 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15769 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15770 } 15771 15772 /// Perform marking for a reference to an arbitrary declaration. It 15773 /// marks the declaration referenced, and performs odr-use checking for 15774 /// functions and variables. This method should not be used when building a 15775 /// normal expression which refers to a variable. 15776 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15777 bool MightBeOdrUse) { 15778 if (MightBeOdrUse) { 15779 if (auto *VD = dyn_cast<VarDecl>(D)) { 15780 MarkVariableReferenced(Loc, VD); 15781 return; 15782 } 15783 } 15784 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15785 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15786 return; 15787 } 15788 D->setReferenced(); 15789 } 15790 15791 namespace { 15792 // Mark all of the declarations used by a type as referenced. 15793 // FIXME: Not fully implemented yet! We need to have a better understanding 15794 // of when we're entering a context we should not recurse into. 15795 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15796 // TreeTransforms rebuilding the type in a new context. Rather than 15797 // duplicating the TreeTransform logic, we should consider reusing it here. 15798 // Currently that causes problems when rebuilding LambdaExprs. 15799 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15800 Sema &S; 15801 SourceLocation Loc; 15802 15803 public: 15804 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15805 15806 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15807 15808 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15809 }; 15810 } 15811 15812 bool MarkReferencedDecls::TraverseTemplateArgument( 15813 const TemplateArgument &Arg) { 15814 { 15815 // A non-type template argument is a constant-evaluated context. 15816 EnterExpressionEvaluationContext Evaluated( 15817 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15818 if (Arg.getKind() == TemplateArgument::Declaration) { 15819 if (Decl *D = Arg.getAsDecl()) 15820 S.MarkAnyDeclReferenced(Loc, D, true); 15821 } else if (Arg.getKind() == TemplateArgument::Expression) { 15822 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15823 } 15824 } 15825 15826 return Inherited::TraverseTemplateArgument(Arg); 15827 } 15828 15829 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15830 MarkReferencedDecls Marker(*this, Loc); 15831 Marker.TraverseType(T); 15832 } 15833 15834 namespace { 15835 /// Helper class that marks all of the declarations referenced by 15836 /// potentially-evaluated subexpressions as "referenced". 15837 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15838 Sema &S; 15839 bool SkipLocalVariables; 15840 15841 public: 15842 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15843 15844 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15845 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15846 15847 void VisitDeclRefExpr(DeclRefExpr *E) { 15848 // If we were asked not to visit local variables, don't. 15849 if (SkipLocalVariables) { 15850 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15851 if (VD->hasLocalStorage()) 15852 return; 15853 } 15854 15855 S.MarkDeclRefReferenced(E); 15856 } 15857 15858 void VisitMemberExpr(MemberExpr *E) { 15859 S.MarkMemberReferenced(E); 15860 Inherited::VisitMemberExpr(E); 15861 } 15862 15863 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15864 S.MarkFunctionReferenced( 15865 E->getBeginLoc(), 15866 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15867 Visit(E->getSubExpr()); 15868 } 15869 15870 void VisitCXXNewExpr(CXXNewExpr *E) { 15871 if (E->getOperatorNew()) 15872 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15873 if (E->getOperatorDelete()) 15874 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15875 Inherited::VisitCXXNewExpr(E); 15876 } 15877 15878 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15879 if (E->getOperatorDelete()) 15880 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15881 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15882 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15883 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15884 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15885 } 15886 15887 Inherited::VisitCXXDeleteExpr(E); 15888 } 15889 15890 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15891 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15892 Inherited::VisitCXXConstructExpr(E); 15893 } 15894 15895 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15896 Visit(E->getExpr()); 15897 } 15898 15899 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15900 Inherited::VisitImplicitCastExpr(E); 15901 15902 if (E->getCastKind() == CK_LValueToRValue) 15903 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15904 } 15905 }; 15906 } 15907 15908 /// Mark any declarations that appear within this expression or any 15909 /// potentially-evaluated subexpressions as "referenced". 15910 /// 15911 /// \param SkipLocalVariables If true, don't mark local variables as 15912 /// 'referenced'. 15913 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15914 bool SkipLocalVariables) { 15915 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15916 } 15917 15918 /// Emit a diagnostic that describes an effect on the run-time behavior 15919 /// of the program being compiled. 15920 /// 15921 /// This routine emits the given diagnostic when the code currently being 15922 /// type-checked is "potentially evaluated", meaning that there is a 15923 /// possibility that the code will actually be executable. Code in sizeof() 15924 /// expressions, code used only during overload resolution, etc., are not 15925 /// potentially evaluated. This routine will suppress such diagnostics or, 15926 /// in the absolutely nutty case of potentially potentially evaluated 15927 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15928 /// later. 15929 /// 15930 /// This routine should be used for all diagnostics that describe the run-time 15931 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15932 /// Failure to do so will likely result in spurious diagnostics or failures 15933 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15934 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15935 const PartialDiagnostic &PD) { 15936 switch (ExprEvalContexts.back().Context) { 15937 case ExpressionEvaluationContext::Unevaluated: 15938 case ExpressionEvaluationContext::UnevaluatedList: 15939 case ExpressionEvaluationContext::UnevaluatedAbstract: 15940 case ExpressionEvaluationContext::DiscardedStatement: 15941 // The argument will never be evaluated, so don't complain. 15942 break; 15943 15944 case ExpressionEvaluationContext::ConstantEvaluated: 15945 // Relevant diagnostics should be produced by constant evaluation. 15946 break; 15947 15948 case ExpressionEvaluationContext::PotentiallyEvaluated: 15949 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15950 if (Statement && getCurFunctionOrMethodDecl()) { 15951 FunctionScopes.back()->PossiblyUnreachableDiags. 15952 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15953 return true; 15954 } 15955 15956 // The initializer of a constexpr variable or of the first declaration of a 15957 // static data member is not syntactically a constant evaluated constant, 15958 // but nonetheless is always required to be a constant expression, so we 15959 // can skip diagnosing. 15960 // FIXME: Using the mangling context here is a hack. 15961 if (auto *VD = dyn_cast_or_null<VarDecl>( 15962 ExprEvalContexts.back().ManglingContextDecl)) { 15963 if (VD->isConstexpr() || 15964 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15965 break; 15966 // FIXME: For any other kind of variable, we should build a CFG for its 15967 // initializer and check whether the context in question is reachable. 15968 } 15969 15970 Diag(Loc, PD); 15971 return true; 15972 } 15973 15974 return false; 15975 } 15976 15977 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15978 CallExpr *CE, FunctionDecl *FD) { 15979 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15980 return false; 15981 15982 // If we're inside a decltype's expression, don't check for a valid return 15983 // type or construct temporaries until we know whether this is the last call. 15984 if (ExprEvalContexts.back().ExprContext == 15985 ExpressionEvaluationContextRecord::EK_Decltype) { 15986 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15987 return false; 15988 } 15989 15990 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15991 FunctionDecl *FD; 15992 CallExpr *CE; 15993 15994 public: 15995 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15996 : FD(FD), CE(CE) { } 15997 15998 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15999 if (!FD) { 16000 S.Diag(Loc, diag::err_call_incomplete_return) 16001 << T << CE->getSourceRange(); 16002 return; 16003 } 16004 16005 S.Diag(Loc, diag::err_call_function_incomplete_return) 16006 << CE->getSourceRange() << FD->getDeclName() << T; 16007 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 16008 << FD->getDeclName(); 16009 } 16010 } Diagnoser(FD, CE); 16011 16012 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 16013 return true; 16014 16015 return false; 16016 } 16017 16018 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 16019 // will prevent this condition from triggering, which is what we want. 16020 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 16021 SourceLocation Loc; 16022 16023 unsigned diagnostic = diag::warn_condition_is_assignment; 16024 bool IsOrAssign = false; 16025 16026 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 16027 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 16028 return; 16029 16030 IsOrAssign = Op->getOpcode() == BO_OrAssign; 16031 16032 // Greylist some idioms by putting them into a warning subcategory. 16033 if (ObjCMessageExpr *ME 16034 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 16035 Selector Sel = ME->getSelector(); 16036 16037 // self = [<foo> init...] 16038 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 16039 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16040 16041 // <foo> = [<bar> nextObject] 16042 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 16043 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16044 } 16045 16046 Loc = Op->getOperatorLoc(); 16047 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 16048 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 16049 return; 16050 16051 IsOrAssign = Op->getOperator() == OO_PipeEqual; 16052 Loc = Op->getOperatorLoc(); 16053 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 16054 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 16055 else { 16056 // Not an assignment. 16057 return; 16058 } 16059 16060 Diag(Loc, diagnostic) << E->getSourceRange(); 16061 16062 SourceLocation Open = E->getBeginLoc(); 16063 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 16064 Diag(Loc, diag::note_condition_assign_silence) 16065 << FixItHint::CreateInsertion(Open, "(") 16066 << FixItHint::CreateInsertion(Close, ")"); 16067 16068 if (IsOrAssign) 16069 Diag(Loc, diag::note_condition_or_assign_to_comparison) 16070 << FixItHint::CreateReplacement(Loc, "!="); 16071 else 16072 Diag(Loc, diag::note_condition_assign_to_comparison) 16073 << FixItHint::CreateReplacement(Loc, "=="); 16074 } 16075 16076 /// Redundant parentheses over an equality comparison can indicate 16077 /// that the user intended an assignment used as condition. 16078 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 16079 // Don't warn if the parens came from a macro. 16080 SourceLocation parenLoc = ParenE->getBeginLoc(); 16081 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 16082 return; 16083 // Don't warn for dependent expressions. 16084 if (ParenE->isTypeDependent()) 16085 return; 16086 16087 Expr *E = ParenE->IgnoreParens(); 16088 16089 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 16090 if (opE->getOpcode() == BO_EQ && 16091 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 16092 == Expr::MLV_Valid) { 16093 SourceLocation Loc = opE->getOperatorLoc(); 16094 16095 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 16096 SourceRange ParenERange = ParenE->getSourceRange(); 16097 Diag(Loc, diag::note_equality_comparison_silence) 16098 << FixItHint::CreateRemoval(ParenERange.getBegin()) 16099 << FixItHint::CreateRemoval(ParenERange.getEnd()); 16100 Diag(Loc, diag::note_equality_comparison_to_assign) 16101 << FixItHint::CreateReplacement(Loc, "="); 16102 } 16103 } 16104 16105 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 16106 bool IsConstexpr) { 16107 DiagnoseAssignmentAsCondition(E); 16108 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 16109 DiagnoseEqualityWithExtraParens(parenE); 16110 16111 ExprResult result = CheckPlaceholderExpr(E); 16112 if (result.isInvalid()) return ExprError(); 16113 E = result.get(); 16114 16115 if (!E->isTypeDependent()) { 16116 if (getLangOpts().CPlusPlus) 16117 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 16118 16119 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 16120 if (ERes.isInvalid()) 16121 return ExprError(); 16122 E = ERes.get(); 16123 16124 QualType T = E->getType(); 16125 if (!T->isScalarType()) { // C99 6.8.4.1p1 16126 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 16127 << T << E->getSourceRange(); 16128 return ExprError(); 16129 } 16130 CheckBoolLikeConversion(E, Loc); 16131 } 16132 16133 return E; 16134 } 16135 16136 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 16137 Expr *SubExpr, ConditionKind CK) { 16138 // Empty conditions are valid in for-statements. 16139 if (!SubExpr) 16140 return ConditionResult(); 16141 16142 ExprResult Cond; 16143 switch (CK) { 16144 case ConditionKind::Boolean: 16145 Cond = CheckBooleanCondition(Loc, SubExpr); 16146 break; 16147 16148 case ConditionKind::ConstexprIf: 16149 Cond = CheckBooleanCondition(Loc, SubExpr, true); 16150 break; 16151 16152 case ConditionKind::Switch: 16153 Cond = CheckSwitchCondition(Loc, SubExpr); 16154 break; 16155 } 16156 if (Cond.isInvalid()) 16157 return ConditionError(); 16158 16159 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 16160 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 16161 if (!FullExpr.get()) 16162 return ConditionError(); 16163 16164 return ConditionResult(*this, nullptr, FullExpr, 16165 CK == ConditionKind::ConstexprIf); 16166 } 16167 16168 namespace { 16169 /// A visitor for rebuilding a call to an __unknown_any expression 16170 /// to have an appropriate type. 16171 struct RebuildUnknownAnyFunction 16172 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 16173 16174 Sema &S; 16175 16176 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 16177 16178 ExprResult VisitStmt(Stmt *S) { 16179 llvm_unreachable("unexpected statement!"); 16180 } 16181 16182 ExprResult VisitExpr(Expr *E) { 16183 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 16184 << E->getSourceRange(); 16185 return ExprError(); 16186 } 16187 16188 /// Rebuild an expression which simply semantically wraps another 16189 /// expression which it shares the type and value kind of. 16190 template <class T> ExprResult rebuildSugarExpr(T *E) { 16191 ExprResult SubResult = Visit(E->getSubExpr()); 16192 if (SubResult.isInvalid()) return ExprError(); 16193 16194 Expr *SubExpr = SubResult.get(); 16195 E->setSubExpr(SubExpr); 16196 E->setType(SubExpr->getType()); 16197 E->setValueKind(SubExpr->getValueKind()); 16198 assert(E->getObjectKind() == OK_Ordinary); 16199 return E; 16200 } 16201 16202 ExprResult VisitParenExpr(ParenExpr *E) { 16203 return rebuildSugarExpr(E); 16204 } 16205 16206 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16207 return rebuildSugarExpr(E); 16208 } 16209 16210 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16211 ExprResult SubResult = Visit(E->getSubExpr()); 16212 if (SubResult.isInvalid()) return ExprError(); 16213 16214 Expr *SubExpr = SubResult.get(); 16215 E->setSubExpr(SubExpr); 16216 E->setType(S.Context.getPointerType(SubExpr->getType())); 16217 assert(E->getValueKind() == VK_RValue); 16218 assert(E->getObjectKind() == OK_Ordinary); 16219 return E; 16220 } 16221 16222 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16223 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16224 16225 E->setType(VD->getType()); 16226 16227 assert(E->getValueKind() == VK_RValue); 16228 if (S.getLangOpts().CPlusPlus && 16229 !(isa<CXXMethodDecl>(VD) && 16230 cast<CXXMethodDecl>(VD)->isInstance())) 16231 E->setValueKind(VK_LValue); 16232 16233 return E; 16234 } 16235 16236 ExprResult VisitMemberExpr(MemberExpr *E) { 16237 return resolveDecl(E, E->getMemberDecl()); 16238 } 16239 16240 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16241 return resolveDecl(E, E->getDecl()); 16242 } 16243 }; 16244 } 16245 16246 /// Given a function expression of unknown-any type, try to rebuild it 16247 /// to have a function type. 16248 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16249 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16250 if (Result.isInvalid()) return ExprError(); 16251 return S.DefaultFunctionArrayConversion(Result.get()); 16252 } 16253 16254 namespace { 16255 /// A visitor for rebuilding an expression of type __unknown_anytype 16256 /// into one which resolves the type directly on the referring 16257 /// expression. Strict preservation of the original source 16258 /// structure is not a goal. 16259 struct RebuildUnknownAnyExpr 16260 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16261 16262 Sema &S; 16263 16264 /// The current destination type. 16265 QualType DestType; 16266 16267 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16268 : S(S), DestType(CastType) {} 16269 16270 ExprResult VisitStmt(Stmt *S) { 16271 llvm_unreachable("unexpected statement!"); 16272 } 16273 16274 ExprResult VisitExpr(Expr *E) { 16275 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16276 << E->getSourceRange(); 16277 return ExprError(); 16278 } 16279 16280 ExprResult VisitCallExpr(CallExpr *E); 16281 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16282 16283 /// Rebuild an expression which simply semantically wraps another 16284 /// expression which it shares the type and value kind of. 16285 template <class T> ExprResult rebuildSugarExpr(T *E) { 16286 ExprResult SubResult = Visit(E->getSubExpr()); 16287 if (SubResult.isInvalid()) return ExprError(); 16288 Expr *SubExpr = SubResult.get(); 16289 E->setSubExpr(SubExpr); 16290 E->setType(SubExpr->getType()); 16291 E->setValueKind(SubExpr->getValueKind()); 16292 assert(E->getObjectKind() == OK_Ordinary); 16293 return E; 16294 } 16295 16296 ExprResult VisitParenExpr(ParenExpr *E) { 16297 return rebuildSugarExpr(E); 16298 } 16299 16300 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16301 return rebuildSugarExpr(E); 16302 } 16303 16304 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16305 const PointerType *Ptr = DestType->getAs<PointerType>(); 16306 if (!Ptr) { 16307 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16308 << E->getSourceRange(); 16309 return ExprError(); 16310 } 16311 16312 if (isa<CallExpr>(E->getSubExpr())) { 16313 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16314 << E->getSourceRange(); 16315 return ExprError(); 16316 } 16317 16318 assert(E->getValueKind() == VK_RValue); 16319 assert(E->getObjectKind() == OK_Ordinary); 16320 E->setType(DestType); 16321 16322 // Build the sub-expression as if it were an object of the pointee type. 16323 DestType = Ptr->getPointeeType(); 16324 ExprResult SubResult = Visit(E->getSubExpr()); 16325 if (SubResult.isInvalid()) return ExprError(); 16326 E->setSubExpr(SubResult.get()); 16327 return E; 16328 } 16329 16330 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16331 16332 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16333 16334 ExprResult VisitMemberExpr(MemberExpr *E) { 16335 return resolveDecl(E, E->getMemberDecl()); 16336 } 16337 16338 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16339 return resolveDecl(E, E->getDecl()); 16340 } 16341 }; 16342 } 16343 16344 /// Rebuilds a call expression which yielded __unknown_anytype. 16345 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16346 Expr *CalleeExpr = E->getCallee(); 16347 16348 enum FnKind { 16349 FK_MemberFunction, 16350 FK_FunctionPointer, 16351 FK_BlockPointer 16352 }; 16353 16354 FnKind Kind; 16355 QualType CalleeType = CalleeExpr->getType(); 16356 if (CalleeType == S.Context.BoundMemberTy) { 16357 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16358 Kind = FK_MemberFunction; 16359 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16360 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16361 CalleeType = Ptr->getPointeeType(); 16362 Kind = FK_FunctionPointer; 16363 } else { 16364 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16365 Kind = FK_BlockPointer; 16366 } 16367 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16368 16369 // Verify that this is a legal result type of a function. 16370 if (DestType->isArrayType() || DestType->isFunctionType()) { 16371 unsigned diagID = diag::err_func_returning_array_function; 16372 if (Kind == FK_BlockPointer) 16373 diagID = diag::err_block_returning_array_function; 16374 16375 S.Diag(E->getExprLoc(), diagID) 16376 << DestType->isFunctionType() << DestType; 16377 return ExprError(); 16378 } 16379 16380 // Otherwise, go ahead and set DestType as the call's result. 16381 E->setType(DestType.getNonLValueExprType(S.Context)); 16382 E->setValueKind(Expr::getValueKindForType(DestType)); 16383 assert(E->getObjectKind() == OK_Ordinary); 16384 16385 // Rebuild the function type, replacing the result type with DestType. 16386 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16387 if (Proto) { 16388 // __unknown_anytype(...) is a special case used by the debugger when 16389 // it has no idea what a function's signature is. 16390 // 16391 // We want to build this call essentially under the K&R 16392 // unprototyped rules, but making a FunctionNoProtoType in C++ 16393 // would foul up all sorts of assumptions. However, we cannot 16394 // simply pass all arguments as variadic arguments, nor can we 16395 // portably just call the function under a non-variadic type; see 16396 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16397 // However, it turns out that in practice it is generally safe to 16398 // call a function declared as "A foo(B,C,D);" under the prototype 16399 // "A foo(B,C,D,...);". The only known exception is with the 16400 // Windows ABI, where any variadic function is implicitly cdecl 16401 // regardless of its normal CC. Therefore we change the parameter 16402 // types to match the types of the arguments. 16403 // 16404 // This is a hack, but it is far superior to moving the 16405 // corresponding target-specific code from IR-gen to Sema/AST. 16406 16407 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16408 SmallVector<QualType, 8> ArgTypes; 16409 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16410 ArgTypes.reserve(E->getNumArgs()); 16411 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16412 Expr *Arg = E->getArg(i); 16413 QualType ArgType = Arg->getType(); 16414 if (E->isLValue()) { 16415 ArgType = S.Context.getLValueReferenceType(ArgType); 16416 } else if (E->isXValue()) { 16417 ArgType = S.Context.getRValueReferenceType(ArgType); 16418 } 16419 ArgTypes.push_back(ArgType); 16420 } 16421 ParamTypes = ArgTypes; 16422 } 16423 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16424 Proto->getExtProtoInfo()); 16425 } else { 16426 DestType = S.Context.getFunctionNoProtoType(DestType, 16427 FnType->getExtInfo()); 16428 } 16429 16430 // Rebuild the appropriate pointer-to-function type. 16431 switch (Kind) { 16432 case FK_MemberFunction: 16433 // Nothing to do. 16434 break; 16435 16436 case FK_FunctionPointer: 16437 DestType = S.Context.getPointerType(DestType); 16438 break; 16439 16440 case FK_BlockPointer: 16441 DestType = S.Context.getBlockPointerType(DestType); 16442 break; 16443 } 16444 16445 // Finally, we can recurse. 16446 ExprResult CalleeResult = Visit(CalleeExpr); 16447 if (!CalleeResult.isUsable()) return ExprError(); 16448 E->setCallee(CalleeResult.get()); 16449 16450 // Bind a temporary if necessary. 16451 return S.MaybeBindToTemporary(E); 16452 } 16453 16454 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16455 // Verify that this is a legal result type of a call. 16456 if (DestType->isArrayType() || DestType->isFunctionType()) { 16457 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16458 << DestType->isFunctionType() << DestType; 16459 return ExprError(); 16460 } 16461 16462 // Rewrite the method result type if available. 16463 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16464 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16465 Method->setReturnType(DestType); 16466 } 16467 16468 // Change the type of the message. 16469 E->setType(DestType.getNonReferenceType()); 16470 E->setValueKind(Expr::getValueKindForType(DestType)); 16471 16472 return S.MaybeBindToTemporary(E); 16473 } 16474 16475 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16476 // The only case we should ever see here is a function-to-pointer decay. 16477 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16478 assert(E->getValueKind() == VK_RValue); 16479 assert(E->getObjectKind() == OK_Ordinary); 16480 16481 E->setType(DestType); 16482 16483 // Rebuild the sub-expression as the pointee (function) type. 16484 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16485 16486 ExprResult Result = Visit(E->getSubExpr()); 16487 if (!Result.isUsable()) return ExprError(); 16488 16489 E->setSubExpr(Result.get()); 16490 return E; 16491 } else if (E->getCastKind() == CK_LValueToRValue) { 16492 assert(E->getValueKind() == VK_RValue); 16493 assert(E->getObjectKind() == OK_Ordinary); 16494 16495 assert(isa<BlockPointerType>(E->getType())); 16496 16497 E->setType(DestType); 16498 16499 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16500 DestType = S.Context.getLValueReferenceType(DestType); 16501 16502 ExprResult Result = Visit(E->getSubExpr()); 16503 if (!Result.isUsable()) return ExprError(); 16504 16505 E->setSubExpr(Result.get()); 16506 return E; 16507 } else { 16508 llvm_unreachable("Unhandled cast type!"); 16509 } 16510 } 16511 16512 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16513 ExprValueKind ValueKind = VK_LValue; 16514 QualType Type = DestType; 16515 16516 // We know how to make this work for certain kinds of decls: 16517 16518 // - functions 16519 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16520 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16521 DestType = Ptr->getPointeeType(); 16522 ExprResult Result = resolveDecl(E, VD); 16523 if (Result.isInvalid()) return ExprError(); 16524 return S.ImpCastExprToType(Result.get(), Type, 16525 CK_FunctionToPointerDecay, VK_RValue); 16526 } 16527 16528 if (!Type->isFunctionType()) { 16529 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16530 << VD << E->getSourceRange(); 16531 return ExprError(); 16532 } 16533 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16534 // We must match the FunctionDecl's type to the hack introduced in 16535 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16536 // type. See the lengthy commentary in that routine. 16537 QualType FDT = FD->getType(); 16538 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16539 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16540 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16541 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16542 SourceLocation Loc = FD->getLocation(); 16543 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16544 FD->getDeclContext(), 16545 Loc, Loc, FD->getNameInfo().getName(), 16546 DestType, FD->getTypeSourceInfo(), 16547 SC_None, false/*isInlineSpecified*/, 16548 FD->hasPrototype(), 16549 false/*isConstexprSpecified*/); 16550 16551 if (FD->getQualifier()) 16552 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16553 16554 SmallVector<ParmVarDecl*, 16> Params; 16555 for (const auto &AI : FT->param_types()) { 16556 ParmVarDecl *Param = 16557 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16558 Param->setScopeInfo(0, Params.size()); 16559 Params.push_back(Param); 16560 } 16561 NewFD->setParams(Params); 16562 DRE->setDecl(NewFD); 16563 VD = DRE->getDecl(); 16564 } 16565 } 16566 16567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16568 if (MD->isInstance()) { 16569 ValueKind = VK_RValue; 16570 Type = S.Context.BoundMemberTy; 16571 } 16572 16573 // Function references aren't l-values in C. 16574 if (!S.getLangOpts().CPlusPlus) 16575 ValueKind = VK_RValue; 16576 16577 // - variables 16578 } else if (isa<VarDecl>(VD)) { 16579 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16580 Type = RefTy->getPointeeType(); 16581 } else if (Type->isFunctionType()) { 16582 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16583 << VD << E->getSourceRange(); 16584 return ExprError(); 16585 } 16586 16587 // - nothing else 16588 } else { 16589 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16590 << VD << E->getSourceRange(); 16591 return ExprError(); 16592 } 16593 16594 // Modifying the declaration like this is friendly to IR-gen but 16595 // also really dangerous. 16596 VD->setType(DestType); 16597 E->setType(Type); 16598 E->setValueKind(ValueKind); 16599 return E; 16600 } 16601 16602 /// Check a cast of an unknown-any type. We intentionally only 16603 /// trigger this for C-style casts. 16604 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16605 Expr *CastExpr, CastKind &CastKind, 16606 ExprValueKind &VK, CXXCastPath &Path) { 16607 // The type we're casting to must be either void or complete. 16608 if (!CastType->isVoidType() && 16609 RequireCompleteType(TypeRange.getBegin(), CastType, 16610 diag::err_typecheck_cast_to_incomplete)) 16611 return ExprError(); 16612 16613 // Rewrite the casted expression from scratch. 16614 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16615 if (!result.isUsable()) return ExprError(); 16616 16617 CastExpr = result.get(); 16618 VK = CastExpr->getValueKind(); 16619 CastKind = CK_NoOp; 16620 16621 return CastExpr; 16622 } 16623 16624 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16625 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16626 } 16627 16628 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16629 Expr *arg, QualType ¶mType) { 16630 // If the syntactic form of the argument is not an explicit cast of 16631 // any sort, just do default argument promotion. 16632 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16633 if (!castArg) { 16634 ExprResult result = DefaultArgumentPromotion(arg); 16635 if (result.isInvalid()) return ExprError(); 16636 paramType = result.get()->getType(); 16637 return result; 16638 } 16639 16640 // Otherwise, use the type that was written in the explicit cast. 16641 assert(!arg->hasPlaceholderType()); 16642 paramType = castArg->getTypeAsWritten(); 16643 16644 // Copy-initialize a parameter of that type. 16645 InitializedEntity entity = 16646 InitializedEntity::InitializeParameter(Context, paramType, 16647 /*consumed*/ false); 16648 return PerformCopyInitialization(entity, callLoc, arg); 16649 } 16650 16651 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16652 Expr *orig = E; 16653 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16654 while (true) { 16655 E = E->IgnoreParenImpCasts(); 16656 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16657 E = call->getCallee(); 16658 diagID = diag::err_uncasted_call_of_unknown_any; 16659 } else { 16660 break; 16661 } 16662 } 16663 16664 SourceLocation loc; 16665 NamedDecl *d; 16666 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16667 loc = ref->getLocation(); 16668 d = ref->getDecl(); 16669 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16670 loc = mem->getMemberLoc(); 16671 d = mem->getMemberDecl(); 16672 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16673 diagID = diag::err_uncasted_call_of_unknown_any; 16674 loc = msg->getSelectorStartLoc(); 16675 d = msg->getMethodDecl(); 16676 if (!d) { 16677 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16678 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16679 << orig->getSourceRange(); 16680 return ExprError(); 16681 } 16682 } else { 16683 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16684 << E->getSourceRange(); 16685 return ExprError(); 16686 } 16687 16688 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16689 16690 // Never recoverable. 16691 return ExprError(); 16692 } 16693 16694 /// Check for operands with placeholder types and complain if found. 16695 /// Returns ExprError() if there was an error and no recovery was possible. 16696 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16697 if (!getLangOpts().CPlusPlus) { 16698 // C cannot handle TypoExpr nodes on either side of a binop because it 16699 // doesn't handle dependent types properly, so make sure any TypoExprs have 16700 // been dealt with before checking the operands. 16701 ExprResult Result = CorrectDelayedTyposInExpr(E); 16702 if (!Result.isUsable()) return ExprError(); 16703 E = Result.get(); 16704 } 16705 16706 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16707 if (!placeholderType) return E; 16708 16709 switch (placeholderType->getKind()) { 16710 16711 // Overloaded expressions. 16712 case BuiltinType::Overload: { 16713 // Try to resolve a single function template specialization. 16714 // This is obligatory. 16715 ExprResult Result = E; 16716 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16717 return Result; 16718 16719 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16720 // leaves Result unchanged on failure. 16721 Result = E; 16722 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16723 return Result; 16724 16725 // If that failed, try to recover with a call. 16726 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16727 /*complain*/ true); 16728 return Result; 16729 } 16730 16731 // Bound member functions. 16732 case BuiltinType::BoundMember: { 16733 ExprResult result = E; 16734 const Expr *BME = E->IgnoreParens(); 16735 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16736 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16737 if (isa<CXXPseudoDestructorExpr>(BME)) { 16738 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16739 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16740 if (ME->getMemberNameInfo().getName().getNameKind() == 16741 DeclarationName::CXXDestructorName) 16742 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16743 } 16744 tryToRecoverWithCall(result, PD, 16745 /*complain*/ true); 16746 return result; 16747 } 16748 16749 // ARC unbridged casts. 16750 case BuiltinType::ARCUnbridgedCast: { 16751 Expr *realCast = stripARCUnbridgedCast(E); 16752 diagnoseARCUnbridgedCast(realCast); 16753 return realCast; 16754 } 16755 16756 // Expressions of unknown type. 16757 case BuiltinType::UnknownAny: 16758 return diagnoseUnknownAnyExpr(*this, E); 16759 16760 // Pseudo-objects. 16761 case BuiltinType::PseudoObject: 16762 return checkPseudoObjectRValue(E); 16763 16764 case BuiltinType::BuiltinFn: { 16765 // Accept __noop without parens by implicitly converting it to a call expr. 16766 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16767 if (DRE) { 16768 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16769 if (FD->getBuiltinID() == Builtin::BI__noop) { 16770 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16771 CK_BuiltinFnToFnPtr).get(); 16772 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16773 VK_RValue, SourceLocation()); 16774 } 16775 } 16776 16777 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16778 return ExprError(); 16779 } 16780 16781 // Expressions of unknown type. 16782 case BuiltinType::OMPArraySection: 16783 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16784 return ExprError(); 16785 16786 // Everything else should be impossible. 16787 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16788 case BuiltinType::Id: 16789 #include "clang/Basic/OpenCLImageTypes.def" 16790 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16791 case BuiltinType::Id: 16792 #include "clang/Basic/OpenCLExtensionTypes.def" 16793 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16794 #define PLACEHOLDER_TYPE(Id, SingletonId) 16795 #include "clang/AST/BuiltinTypes.def" 16796 break; 16797 } 16798 16799 llvm_unreachable("invalid placeholder type!"); 16800 } 16801 16802 bool Sema::CheckCaseExpression(Expr *E) { 16803 if (E->isTypeDependent()) 16804 return true; 16805 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16806 return E->getType()->isIntegralOrEnumerationType(); 16807 return false; 16808 } 16809 16810 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16811 ExprResult 16812 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16813 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16814 "Unknown Objective-C Boolean value!"); 16815 QualType BoolT = Context.ObjCBuiltinBoolTy; 16816 if (!Context.getBOOLDecl()) { 16817 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16818 Sema::LookupOrdinaryName); 16819 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16820 NamedDecl *ND = Result.getFoundDecl(); 16821 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16822 Context.setBOOLDecl(TD); 16823 } 16824 } 16825 if (Context.getBOOLDecl()) 16826 BoolT = Context.getBOOLType(); 16827 return new (Context) 16828 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16829 } 16830 16831 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16832 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16833 SourceLocation RParen) { 16834 16835 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16836 16837 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16838 [&](const AvailabilitySpec &Spec) { 16839 return Spec.getPlatform() == Platform; 16840 }); 16841 16842 VersionTuple Version; 16843 if (Spec != AvailSpecs.end()) 16844 Version = Spec->getVersion(); 16845 16846 // The use of `@available` in the enclosing function should be analyzed to 16847 // warn when it's used inappropriately (i.e. not if(@available)). 16848 if (getCurFunctionOrMethodDecl()) 16849 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16850 else if (getCurBlock() || getCurLambda()) 16851 getCurFunction()->HasPotentialAvailabilityViolations = true; 16852 16853 return new (Context) 16854 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16855 } 16856