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 SourceLocation Loc = Locs.front(); 211 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 212 // If there were any diagnostics suppressed by template argument deduction, 213 // emit them now. 214 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 215 if (Pos != SuppressedDiagnostics.end()) { 216 for (const PartialDiagnosticAt &Suppressed : Pos->second) 217 Diag(Suppressed.first, Suppressed.second); 218 219 // Clear out the list of suppressed diagnostics, so that we don't emit 220 // them again for this specialization. However, we don't obsolete this 221 // entry from the table, because we want to avoid ever emitting these 222 // diagnostics again. 223 Pos->second.clear(); 224 } 225 226 // C++ [basic.start.main]p3: 227 // The function 'main' shall not be used within a program. 228 if (cast<FunctionDecl>(D)->isMain()) 229 Diag(Loc, diag::ext_main_used); 230 } 231 232 // See if this is an auto-typed variable whose initializer we are parsing. 233 if (ParsingInitForAutoVars.count(D)) { 234 if (isa<BindingDecl>(D)) { 235 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 236 << D->getDeclName(); 237 } else { 238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 239 << D->getDeclName() << cast<VarDecl>(D)->getType(); 240 } 241 return true; 242 } 243 244 // See if this is a deleted function. 245 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 246 if (FD->isDeleted()) { 247 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 248 if (Ctor && Ctor->isInheritingConstructor()) 249 Diag(Loc, diag::err_deleted_inherited_ctor_use) 250 << Ctor->getParent() 251 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 252 else 253 Diag(Loc, diag::err_deleted_function_use); 254 NoteDeletedFunction(FD); 255 return true; 256 } 257 258 // If the function has a deduced return type, and we can't deduce it, 259 // then we can't use it either. 260 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 261 DeduceReturnType(FD, Loc)) 262 return true; 263 264 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 265 return true; 266 } 267 268 auto getReferencedObjCProp = [](const NamedDecl *D) -> 269 const ObjCPropertyDecl * { 270 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 271 return MD->findPropertyDecl(); 272 return nullptr; 273 }; 274 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 275 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 276 return true; 277 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 278 return true; 279 } 280 281 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 282 // Only the variables omp_in and omp_out are allowed in the combiner. 283 // Only the variables omp_priv and omp_orig are allowed in the 284 // initializer-clause. 285 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 286 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 287 isa<VarDecl>(D)) { 288 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 289 << getCurFunction()->HasOMPDeclareReductionCombiner; 290 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 291 return true; 292 } 293 294 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 295 AvoidPartialAvailabilityChecks); 296 297 DiagnoseUnusedOfDecl(*this, D, Loc); 298 299 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 300 301 return false; 302 } 303 304 /// Retrieve the message suffix that should be added to a 305 /// diagnostic complaining about the given function being deleted or 306 /// unavailable. 307 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 308 std::string Message; 309 if (FD->getAvailability(&Message)) 310 return ": " + Message; 311 312 return std::string(); 313 } 314 315 /// DiagnoseSentinelCalls - This routine checks whether a call or 316 /// message-send is to a declaration with the sentinel attribute, and 317 /// if so, it checks that the requirements of the sentinel are 318 /// satisfied. 319 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 320 ArrayRef<Expr *> Args) { 321 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 322 if (!attr) 323 return; 324 325 // The number of formal parameters of the declaration. 326 unsigned numFormalParams; 327 328 // The kind of declaration. This is also an index into a %select in 329 // the diagnostic. 330 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 331 332 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 333 numFormalParams = MD->param_size(); 334 calleeType = CT_Method; 335 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 336 numFormalParams = FD->param_size(); 337 calleeType = CT_Function; 338 } else if (isa<VarDecl>(D)) { 339 QualType type = cast<ValueDecl>(D)->getType(); 340 const FunctionType *fn = nullptr; 341 if (const PointerType *ptr = type->getAs<PointerType>()) { 342 fn = ptr->getPointeeType()->getAs<FunctionType>(); 343 if (!fn) return; 344 calleeType = CT_Function; 345 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 346 fn = ptr->getPointeeType()->castAs<FunctionType>(); 347 calleeType = CT_Block; 348 } else { 349 return; 350 } 351 352 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 353 numFormalParams = proto->getNumParams(); 354 } else { 355 numFormalParams = 0; 356 } 357 } else { 358 return; 359 } 360 361 // "nullPos" is the number of formal parameters at the end which 362 // effectively count as part of the variadic arguments. This is 363 // useful if you would prefer to not have *any* formal parameters, 364 // but the language forces you to have at least one. 365 unsigned nullPos = attr->getNullPos(); 366 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 367 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 368 369 // The number of arguments which should follow the sentinel. 370 unsigned numArgsAfterSentinel = attr->getSentinel(); 371 372 // If there aren't enough arguments for all the formal parameters, 373 // the sentinel, and the args after the sentinel, complain. 374 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 375 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 376 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 377 return; 378 } 379 380 // Otherwise, find the sentinel expression. 381 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 382 if (!sentinelExpr) return; 383 if (sentinelExpr->isValueDependent()) return; 384 if (Context.isSentinelNullExpr(sentinelExpr)) return; 385 386 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 387 // or 'NULL' if those are actually defined in the context. Only use 388 // 'nil' for ObjC methods, where it's much more likely that the 389 // variadic arguments form a list of object pointers. 390 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 391 std::string NullValue; 392 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 393 NullValue = "nil"; 394 else if (getLangOpts().CPlusPlus11) 395 NullValue = "nullptr"; 396 else if (PP.isMacroDefined("NULL")) 397 NullValue = "NULL"; 398 else 399 NullValue = "(void*) 0"; 400 401 if (MissingNilLoc.isInvalid()) 402 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 403 else 404 Diag(MissingNilLoc, diag::warn_missing_sentinel) 405 << int(calleeType) 406 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 407 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 408 } 409 410 SourceRange Sema::getExprRange(Expr *E) const { 411 return E ? E->getSourceRange() : SourceRange(); 412 } 413 414 //===----------------------------------------------------------------------===// 415 // Standard Promotions and Conversions 416 //===----------------------------------------------------------------------===// 417 418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 420 // Handle any placeholder expressions which made it here. 421 if (E->getType()->isPlaceholderType()) { 422 ExprResult result = CheckPlaceholderExpr(E); 423 if (result.isInvalid()) return ExprError(); 424 E = result.get(); 425 } 426 427 QualType Ty = E->getType(); 428 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 429 430 if (Ty->isFunctionType()) { 431 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 432 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 433 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 434 return ExprError(); 435 436 E = ImpCastExprToType(E, Context.getPointerType(Ty), 437 CK_FunctionToPointerDecay).get(); 438 } else if (Ty->isArrayType()) { 439 // In C90 mode, arrays only promote to pointers if the array expression is 440 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 441 // type 'array of type' is converted to an expression that has type 'pointer 442 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 443 // that has type 'array of type' ...". The relevant change is "an lvalue" 444 // (C90) to "an expression" (C99). 445 // 446 // C++ 4.2p1: 447 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 448 // T" can be converted to an rvalue of type "pointer to T". 449 // 450 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 451 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 452 CK_ArrayToPointerDecay).get(); 453 } 454 return E; 455 } 456 457 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 458 // Check to see if we are dereferencing a null pointer. If so, 459 // and if not volatile-qualified, this is undefined behavior that the 460 // optimizer will delete, so warn about it. People sometimes try to use this 461 // to get a deterministic trap and are surprised by clang's behavior. This 462 // only handles the pattern "*null", which is a very syntactic check. 463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 464 if (UO->getOpcode() == UO_Deref && 465 UO->getSubExpr()->IgnoreParenCasts()-> 466 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 467 !UO->getType().isVolatileQualified()) { 468 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 469 S.PDiag(diag::warn_indirection_through_null) 470 << UO->getSubExpr()->getSourceRange()); 471 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 472 S.PDiag(diag::note_indirection_through_null)); 473 } 474 } 475 476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 477 SourceLocation AssignLoc, 478 const Expr* RHS) { 479 const ObjCIvarDecl *IV = OIRE->getDecl(); 480 if (!IV) 481 return; 482 483 DeclarationName MemberName = IV->getDeclName(); 484 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 485 if (!Member || !Member->isStr("isa")) 486 return; 487 488 const Expr *Base = OIRE->getBase(); 489 QualType BaseType = Base->getType(); 490 if (OIRE->isArrow()) 491 BaseType = BaseType->getPointeeType(); 492 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 493 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 494 ObjCInterfaceDecl *ClassDeclared = nullptr; 495 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 496 if (!ClassDeclared->getSuperClass() 497 && (*ClassDeclared->ivar_begin()) == IV) { 498 if (RHS) { 499 NamedDecl *ObjectSetClass = 500 S.LookupSingleName(S.TUScope, 501 &S.Context.Idents.get("object_setClass"), 502 SourceLocation(), S.LookupOrdinaryName); 503 if (ObjectSetClass) { 504 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 505 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 506 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 507 "object_setClass(") 508 << FixItHint::CreateReplacement( 509 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 510 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 511 } 512 else 513 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 514 } else { 515 NamedDecl *ObjectGetClass = 516 S.LookupSingleName(S.TUScope, 517 &S.Context.Idents.get("object_getClass"), 518 SourceLocation(), S.LookupOrdinaryName); 519 if (ObjectGetClass) 520 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 521 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 522 "object_getClass(") 523 << FixItHint::CreateReplacement( 524 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 525 else 526 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 527 } 528 S.Diag(IV->getLocation(), diag::note_ivar_decl); 529 } 530 } 531 } 532 533 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 534 // Handle any placeholder expressions which made it here. 535 if (E->getType()->isPlaceholderType()) { 536 ExprResult result = CheckPlaceholderExpr(E); 537 if (result.isInvalid()) return ExprError(); 538 E = result.get(); 539 } 540 541 // C++ [conv.lval]p1: 542 // A glvalue of a non-function, non-array type T can be 543 // converted to a prvalue. 544 if (!E->isGLValue()) return E; 545 546 QualType T = E->getType(); 547 assert(!T.isNull() && "r-value conversion on typeless expression?"); 548 549 // We don't want to throw lvalue-to-rvalue casts on top of 550 // expressions of certain types in C++. 551 if (getLangOpts().CPlusPlus && 552 (E->getType() == Context.OverloadTy || 553 T->isDependentType() || 554 T->isRecordType())) 555 return E; 556 557 // The C standard is actually really unclear on this point, and 558 // DR106 tells us what the result should be but not why. It's 559 // generally best to say that void types just doesn't undergo 560 // lvalue-to-rvalue at all. Note that expressions of unqualified 561 // 'void' type are never l-values, but qualified void can be. 562 if (T->isVoidType()) 563 return E; 564 565 // OpenCL usually rejects direct accesses to values of 'half' type. 566 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 567 T->isHalfType()) { 568 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 569 << 0 << T; 570 return ExprError(); 571 } 572 573 CheckForNullPointerDereference(*this, E); 574 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 575 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 576 &Context.Idents.get("object_getClass"), 577 SourceLocation(), LookupOrdinaryName); 578 if (ObjectGetClass) 579 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 580 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 583 else 584 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 585 } 586 else if (const ObjCIvarRefExpr *OIRE = 587 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 588 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 589 590 // C++ [conv.lval]p1: 591 // [...] If T is a non-class type, the type of the prvalue is the 592 // cv-unqualified version of T. Otherwise, the type of the 593 // rvalue is T. 594 // 595 // C99 6.3.2.1p2: 596 // If the lvalue has qualified type, the value has the unqualified 597 // version of the type of the lvalue; otherwise, the value has the 598 // type of the lvalue. 599 if (T.hasQualifiers()) 600 T = T.getUnqualifiedType(); 601 602 // Under the MS ABI, lock down the inheritance model now. 603 if (T->isMemberPointerType() && 604 Context.getTargetInfo().getCXXABI().isMicrosoft()) 605 (void)isCompleteType(E->getExprLoc(), T); 606 607 UpdateMarkingForLValueToRValue(E); 608 609 // Loading a __weak object implicitly retains the value, so we need a cleanup to 610 // balance that. 611 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 612 Cleanup.setExprNeedsCleanups(true); 613 614 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 615 nullptr, VK_RValue); 616 617 // C11 6.3.2.1p2: 618 // ... if the lvalue has atomic type, the value has the non-atomic version 619 // of the type of the lvalue ... 620 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 621 T = Atomic->getValueType().getUnqualifiedType(); 622 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 623 nullptr, VK_RValue); 624 } 625 626 return Res; 627 } 628 629 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 630 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 631 if (Res.isInvalid()) 632 return ExprError(); 633 Res = DefaultLvalueConversion(Res.get()); 634 if (Res.isInvalid()) 635 return ExprError(); 636 return Res; 637 } 638 639 /// CallExprUnaryConversions - a special case of an unary conversion 640 /// performed on a function designator of a call expression. 641 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 642 QualType Ty = E->getType(); 643 ExprResult Res = E; 644 // Only do implicit cast for a function type, but not for a pointer 645 // to function type. 646 if (Ty->isFunctionType()) { 647 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 648 CK_FunctionToPointerDecay).get(); 649 if (Res.isInvalid()) 650 return ExprError(); 651 } 652 Res = DefaultLvalueConversion(Res.get()); 653 if (Res.isInvalid()) 654 return ExprError(); 655 return Res.get(); 656 } 657 658 /// UsualUnaryConversions - Performs various conversions that are common to most 659 /// operators (C99 6.3). The conversions of array and function types are 660 /// sometimes suppressed. For example, the array->pointer conversion doesn't 661 /// apply if the array is an argument to the sizeof or address (&) operators. 662 /// In these instances, this routine should *not* be called. 663 ExprResult Sema::UsualUnaryConversions(Expr *E) { 664 // First, convert to an r-value. 665 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 666 if (Res.isInvalid()) 667 return ExprError(); 668 E = Res.get(); 669 670 QualType Ty = E->getType(); 671 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 672 673 // Half FP have to be promoted to float unless it is natively supported 674 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 675 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 676 677 // Try to perform integral promotions if the object has a theoretically 678 // promotable type. 679 if (Ty->isIntegralOrUnscopedEnumerationType()) { 680 // C99 6.3.1.1p2: 681 // 682 // The following may be used in an expression wherever an int or 683 // unsigned int may be used: 684 // - an object or expression with an integer type whose integer 685 // conversion rank is less than or equal to the rank of int 686 // and unsigned int. 687 // - A bit-field of type _Bool, int, signed int, or unsigned int. 688 // 689 // If an int can represent all values of the original type, the 690 // value is converted to an int; otherwise, it is converted to an 691 // unsigned int. These are called the integer promotions. All 692 // other types are unchanged by the integer promotions. 693 694 QualType PTy = Context.isPromotableBitField(E); 695 if (!PTy.isNull()) { 696 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 697 return E; 698 } 699 if (Ty->isPromotableIntegerType()) { 700 QualType PT = Context.getPromotedIntegerType(Ty); 701 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 702 return E; 703 } 704 } 705 return E; 706 } 707 708 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 709 /// do not have a prototype. Arguments that have type float or __fp16 710 /// are promoted to double. All other argument types are converted by 711 /// UsualUnaryConversions(). 712 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 713 QualType Ty = E->getType(); 714 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 715 716 ExprResult Res = UsualUnaryConversions(E); 717 if (Res.isInvalid()) 718 return ExprError(); 719 E = Res.get(); 720 721 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 722 // promote to double. 723 // Note that default argument promotion applies only to float (and 724 // half/fp16); it does not apply to _Float16. 725 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 726 if (BTy && (BTy->getKind() == BuiltinType::Half || 727 BTy->getKind() == BuiltinType::Float)) { 728 if (getLangOpts().OpenCL && 729 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 730 if (BTy->getKind() == BuiltinType::Half) { 731 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 732 } 733 } else { 734 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 735 } 736 } 737 738 // C++ performs lvalue-to-rvalue conversion as a default argument 739 // promotion, even on class types, but note: 740 // C++11 [conv.lval]p2: 741 // When an lvalue-to-rvalue conversion occurs in an unevaluated 742 // operand or a subexpression thereof the value contained in the 743 // referenced object is not accessed. Otherwise, if the glvalue 744 // has a class type, the conversion copy-initializes a temporary 745 // of type T from the glvalue and the result of the conversion 746 // is a prvalue for the temporary. 747 // FIXME: add some way to gate this entire thing for correctness in 748 // potentially potentially evaluated contexts. 749 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 750 ExprResult Temp = PerformCopyInitialization( 751 InitializedEntity::InitializeTemporary(E->getType()), 752 E->getExprLoc(), E); 753 if (Temp.isInvalid()) 754 return ExprError(); 755 E = Temp.get(); 756 } 757 758 return E; 759 } 760 761 /// Determine the degree of POD-ness for an expression. 762 /// Incomplete types are considered POD, since this check can be performed 763 /// when we're in an unevaluated context. 764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 765 if (Ty->isIncompleteType()) { 766 // C++11 [expr.call]p7: 767 // After these conversions, if the argument does not have arithmetic, 768 // enumeration, pointer, pointer to member, or class type, the program 769 // is ill-formed. 770 // 771 // Since we've already performed array-to-pointer and function-to-pointer 772 // decay, the only such type in C++ is cv void. This also handles 773 // initializer lists as variadic arguments. 774 if (Ty->isVoidType()) 775 return VAK_Invalid; 776 777 if (Ty->isObjCObjectType()) 778 return VAK_Invalid; 779 return VAK_Valid; 780 } 781 782 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 783 return VAK_Invalid; 784 785 if (Ty.isCXX98PODType(Context)) 786 return VAK_Valid; 787 788 // C++11 [expr.call]p7: 789 // Passing a potentially-evaluated argument of class type (Clause 9) 790 // having a non-trivial copy constructor, a non-trivial move constructor, 791 // or a non-trivial destructor, with no corresponding parameter, 792 // is conditionally-supported with implementation-defined semantics. 793 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 794 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 795 if (!Record->hasNonTrivialCopyConstructor() && 796 !Record->hasNonTrivialMoveConstructor() && 797 !Record->hasNonTrivialDestructor()) 798 return VAK_ValidInCXX11; 799 800 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 801 return VAK_Valid; 802 803 if (Ty->isObjCObjectType()) 804 return VAK_Invalid; 805 806 if (getLangOpts().MSVCCompat) 807 return VAK_MSVCUndefined; 808 809 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 810 // permitted to reject them. We should consider doing so. 811 return VAK_Undefined; 812 } 813 814 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 815 // Don't allow one to pass an Objective-C interface to a vararg. 816 const QualType &Ty = E->getType(); 817 VarArgKind VAK = isValidVarArgType(Ty); 818 819 // Complain about passing non-POD types through varargs. 820 switch (VAK) { 821 case VAK_ValidInCXX11: 822 DiagRuntimeBehavior( 823 E->getBeginLoc(), nullptr, 824 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 825 LLVM_FALLTHROUGH; 826 case VAK_Valid: 827 if (Ty->isRecordType()) { 828 // This is unlikely to be what the user intended. If the class has a 829 // 'c_str' member function, the user probably meant to call that. 830 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 831 PDiag(diag::warn_pass_class_arg_to_vararg) 832 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 833 } 834 break; 835 836 case VAK_Undefined: 837 case VAK_MSVCUndefined: 838 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 839 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 840 << getLangOpts().CPlusPlus11 << Ty << CT); 841 break; 842 843 case VAK_Invalid: 844 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 845 Diag(E->getBeginLoc(), 846 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 847 << Ty << CT; 848 else if (Ty->isObjCObjectType()) 849 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 850 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 851 << Ty << CT); 852 else 853 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 854 << isa<InitListExpr>(E) << Ty << CT; 855 break; 856 } 857 } 858 859 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 860 /// will create a trap if the resulting type is not a POD type. 861 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 862 FunctionDecl *FDecl) { 863 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 864 // Strip the unbridged-cast placeholder expression off, if applicable. 865 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 866 (CT == VariadicMethod || 867 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 868 E = stripARCUnbridgedCast(E); 869 870 // Otherwise, do normal placeholder checking. 871 } else { 872 ExprResult ExprRes = CheckPlaceholderExpr(E); 873 if (ExprRes.isInvalid()) 874 return ExprError(); 875 E = ExprRes.get(); 876 } 877 } 878 879 ExprResult ExprRes = DefaultArgumentPromotion(E); 880 if (ExprRes.isInvalid()) 881 return ExprError(); 882 E = ExprRes.get(); 883 884 // Diagnostics regarding non-POD argument types are 885 // emitted along with format string checking in Sema::CheckFunctionCall(). 886 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 887 // Turn this into a trap. 888 CXXScopeSpec SS; 889 SourceLocation TemplateKWLoc; 890 UnqualifiedId Name; 891 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 892 E->getBeginLoc()); 893 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 894 Name, true, false); 895 if (TrapFn.isInvalid()) 896 return ExprError(); 897 898 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 899 None, E->getEndLoc()); 900 if (Call.isInvalid()) 901 return ExprError(); 902 903 ExprResult Comma = 904 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 905 if (Comma.isInvalid()) 906 return ExprError(); 907 return Comma.get(); 908 } 909 910 if (!getLangOpts().CPlusPlus && 911 RequireCompleteType(E->getExprLoc(), E->getType(), 912 diag::err_call_incomplete_argument)) 913 return ExprError(); 914 915 return E; 916 } 917 918 /// Converts an integer to complex float type. Helper function of 919 /// UsualArithmeticConversions() 920 /// 921 /// \return false if the integer expression is an integer type and is 922 /// successfully converted to the complex type. 923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 924 ExprResult &ComplexExpr, 925 QualType IntTy, 926 QualType ComplexTy, 927 bool SkipCast) { 928 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 929 if (SkipCast) return false; 930 if (IntTy->isIntegerType()) { 931 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 932 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 933 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 934 CK_FloatingRealToComplex); 935 } else { 936 assert(IntTy->isComplexIntegerType()); 937 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 938 CK_IntegralComplexToFloatingComplex); 939 } 940 return false; 941 } 942 943 /// Handle arithmetic conversion with complex types. Helper function of 944 /// UsualArithmeticConversions() 945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 946 ExprResult &RHS, QualType LHSType, 947 QualType RHSType, 948 bool IsCompAssign) { 949 // if we have an integer operand, the result is the complex type. 950 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 951 /*skipCast*/false)) 952 return LHSType; 953 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 954 /*skipCast*/IsCompAssign)) 955 return RHSType; 956 957 // This handles complex/complex, complex/float, or float/complex. 958 // When both operands are complex, the shorter operand is converted to the 959 // type of the longer, and that is the type of the result. This corresponds 960 // to what is done when combining two real floating-point operands. 961 // The fun begins when size promotion occur across type domains. 962 // From H&S 6.3.4: When one operand is complex and the other is a real 963 // floating-point type, the less precise type is converted, within it's 964 // real or complex domain, to the precision of the other type. For example, 965 // when combining a "long double" with a "double _Complex", the 966 // "double _Complex" is promoted to "long double _Complex". 967 968 // Compute the rank of the two types, regardless of whether they are complex. 969 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 970 971 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 972 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 973 QualType LHSElementType = 974 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 975 QualType RHSElementType = 976 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 977 978 QualType ResultType = S.Context.getComplexType(LHSElementType); 979 if (Order < 0) { 980 // Promote the precision of the LHS if not an assignment. 981 ResultType = S.Context.getComplexType(RHSElementType); 982 if (!IsCompAssign) { 983 if (LHSComplexType) 984 LHS = 985 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 986 else 987 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 988 } 989 } else if (Order > 0) { 990 // Promote the precision of the RHS. 991 if (RHSComplexType) 992 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 993 else 994 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 995 } 996 return ResultType; 997 } 998 999 /// Handle arithmetic conversion from integer to float. Helper function 1000 /// of UsualArithmeticConversions() 1001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1002 ExprResult &IntExpr, 1003 QualType FloatTy, QualType IntTy, 1004 bool ConvertFloat, bool ConvertInt) { 1005 if (IntTy->isIntegerType()) { 1006 if (ConvertInt) 1007 // Convert intExpr to the lhs floating point type. 1008 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1009 CK_IntegralToFloating); 1010 return FloatTy; 1011 } 1012 1013 // Convert both sides to the appropriate complex float. 1014 assert(IntTy->isComplexIntegerType()); 1015 QualType result = S.Context.getComplexType(FloatTy); 1016 1017 // _Complex int -> _Complex float 1018 if (ConvertInt) 1019 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1020 CK_IntegralComplexToFloatingComplex); 1021 1022 // float -> _Complex float 1023 if (ConvertFloat) 1024 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1025 CK_FloatingRealToComplex); 1026 1027 return result; 1028 } 1029 1030 /// Handle arithmethic conversion with floating point types. Helper 1031 /// function of UsualArithmeticConversions() 1032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1033 ExprResult &RHS, QualType LHSType, 1034 QualType RHSType, bool IsCompAssign) { 1035 bool LHSFloat = LHSType->isRealFloatingType(); 1036 bool RHSFloat = RHSType->isRealFloatingType(); 1037 1038 // If we have two real floating types, convert the smaller operand 1039 // to the bigger result. 1040 if (LHSFloat && RHSFloat) { 1041 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1042 if (order > 0) { 1043 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1044 return LHSType; 1045 } 1046 1047 assert(order < 0 && "illegal float comparison"); 1048 if (!IsCompAssign) 1049 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1050 return RHSType; 1051 } 1052 1053 if (LHSFloat) { 1054 // Half FP has to be promoted to float unless it is natively supported 1055 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1056 LHSType = S.Context.FloatTy; 1057 1058 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1059 /*convertFloat=*/!IsCompAssign, 1060 /*convertInt=*/ true); 1061 } 1062 assert(RHSFloat); 1063 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1064 /*convertInt=*/ true, 1065 /*convertFloat=*/!IsCompAssign); 1066 } 1067 1068 /// Diagnose attempts to convert between __float128 and long double if 1069 /// there is no support for such conversion. Helper function of 1070 /// UsualArithmeticConversions(). 1071 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1072 QualType RHSType) { 1073 /* No issue converting if at least one of the types is not a floating point 1074 type or the two types have the same rank. 1075 */ 1076 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1077 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1078 return false; 1079 1080 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1081 "The remaining types must be floating point types."); 1082 1083 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1084 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1085 1086 QualType LHSElemType = LHSComplex ? 1087 LHSComplex->getElementType() : LHSType; 1088 QualType RHSElemType = RHSComplex ? 1089 RHSComplex->getElementType() : RHSType; 1090 1091 // No issue if the two types have the same representation 1092 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1093 &S.Context.getFloatTypeSemantics(RHSElemType)) 1094 return false; 1095 1096 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1097 RHSElemType == S.Context.LongDoubleTy); 1098 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1099 RHSElemType == S.Context.Float128Ty); 1100 1101 // We've handled the situation where __float128 and long double have the same 1102 // representation. We allow all conversions for all possible long double types 1103 // except PPC's double double. 1104 return Float128AndLongDouble && 1105 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1106 &llvm::APFloat::PPCDoubleDouble()); 1107 } 1108 1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1110 1111 namespace { 1112 /// These helper callbacks are placed in an anonymous namespace to 1113 /// permit their use as function template parameters. 1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1116 } 1117 1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1120 CK_IntegralComplexCast); 1121 } 1122 } 1123 1124 /// Handle integer arithmetic conversions. Helper function of 1125 /// UsualArithmeticConversions() 1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1128 ExprResult &RHS, QualType LHSType, 1129 QualType RHSType, bool IsCompAssign) { 1130 // The rules for this case are in C99 6.3.1.8 1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1134 if (LHSSigned == RHSSigned) { 1135 // Same signedness; use the higher-ranked type 1136 if (order >= 0) { 1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1138 return LHSType; 1139 } else if (!IsCompAssign) 1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1141 return RHSType; 1142 } else if (order != (LHSSigned ? 1 : -1)) { 1143 // The unsigned type has greater than or equal rank to the 1144 // signed type, so use the unsigned type 1145 if (RHSSigned) { 1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1147 return LHSType; 1148 } else if (!IsCompAssign) 1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1150 return RHSType; 1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1152 // The two types are different widths; if we are here, that 1153 // means the signed type is larger than the unsigned type, so 1154 // use the signed type. 1155 if (LHSSigned) { 1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1157 return LHSType; 1158 } else if (!IsCompAssign) 1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1160 return RHSType; 1161 } else { 1162 // The signed type is higher-ranked than the unsigned type, 1163 // but isn't actually any bigger (like unsigned int and long 1164 // on most 32-bit systems). Use the unsigned type corresponding 1165 // to the signed type. 1166 QualType result = 1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1168 RHS = (*doRHSCast)(S, RHS.get(), result); 1169 if (!IsCompAssign) 1170 LHS = (*doLHSCast)(S, LHS.get(), result); 1171 return result; 1172 } 1173 } 1174 1175 /// Handle conversions with GCC complex int extension. Helper function 1176 /// of UsualArithmeticConversions() 1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1178 ExprResult &RHS, QualType LHSType, 1179 QualType RHSType, 1180 bool IsCompAssign) { 1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1183 1184 if (LHSComplexInt && RHSComplexInt) { 1185 QualType LHSEltType = LHSComplexInt->getElementType(); 1186 QualType RHSEltType = RHSComplexInt->getElementType(); 1187 QualType ScalarType = 1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1190 1191 return S.Context.getComplexType(ScalarType); 1192 } 1193 1194 if (LHSComplexInt) { 1195 QualType LHSEltType = LHSComplexInt->getElementType(); 1196 QualType ScalarType = 1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1199 QualType ComplexType = S.Context.getComplexType(ScalarType); 1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1201 CK_IntegralRealToComplex); 1202 1203 return ComplexType; 1204 } 1205 1206 assert(RHSComplexInt); 1207 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1212 QualType ComplexType = S.Context.getComplexType(ScalarType); 1213 1214 if (!IsCompAssign) 1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 return ComplexType; 1218 } 1219 1220 /// UsualArithmeticConversions - Performs various conversions that are common to 1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1222 /// routine returns the first non-arithmetic type found. The client is 1223 /// responsible for emitting appropriate error diagnostics. 1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1225 bool IsCompAssign) { 1226 if (!IsCompAssign) { 1227 LHS = UsualUnaryConversions(LHS.get()); 1228 if (LHS.isInvalid()) 1229 return QualType(); 1230 } 1231 1232 RHS = UsualUnaryConversions(RHS.get()); 1233 if (RHS.isInvalid()) 1234 return QualType(); 1235 1236 // For conversion purposes, we ignore any qualifiers. 1237 // For example, "const float" and "float" are equivalent. 1238 QualType LHSType = 1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1240 QualType RHSType = 1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1242 1243 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1245 LHSType = AtomicLHS->getValueType(); 1246 1247 // If both types are identical, no conversion is needed. 1248 if (LHSType == RHSType) 1249 return LHSType; 1250 1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1252 // The caller can deal with this (e.g. pointer + int). 1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1254 return QualType(); 1255 1256 // Apply unary and bitfield promotions to the LHS's type. 1257 QualType LHSUnpromotedType = LHSType; 1258 if (LHSType->isPromotableIntegerType()) 1259 LHSType = Context.getPromotedIntegerType(LHSType); 1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1261 if (!LHSBitfieldPromoteTy.isNull()) 1262 LHSType = LHSBitfieldPromoteTy; 1263 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1265 1266 // If both types are identical, no conversion is needed. 1267 if (LHSType == RHSType) 1268 return LHSType; 1269 1270 // At this point, we have two different arithmetic types. 1271 1272 // Diagnose attempts to convert between __float128 and long double where 1273 // such conversions currently can't be handled. 1274 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1275 return QualType(); 1276 1277 // Handle complex types first (C99 6.3.1.8p1). 1278 if (LHSType->isComplexType() || RHSType->isComplexType()) 1279 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Now handle "real" floating types (i.e. float, double, long double). 1283 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1284 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Handle GCC complex int extension. 1288 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1289 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1290 IsCompAssign); 1291 1292 // Finally, we have two differing integer types. 1293 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1294 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1295 } 1296 1297 1298 //===----------------------------------------------------------------------===// 1299 // Semantic Analysis for various Expression Types 1300 //===----------------------------------------------------------------------===// 1301 1302 1303 ExprResult 1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1305 SourceLocation DefaultLoc, 1306 SourceLocation RParenLoc, 1307 Expr *ControllingExpr, 1308 ArrayRef<ParsedType> ArgTypes, 1309 ArrayRef<Expr *> ArgExprs) { 1310 unsigned NumAssocs = ArgTypes.size(); 1311 assert(NumAssocs == ArgExprs.size()); 1312 1313 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1314 for (unsigned i = 0; i < NumAssocs; ++i) { 1315 if (ArgTypes[i]) 1316 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1317 else 1318 Types[i] = nullptr; 1319 } 1320 1321 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1322 ControllingExpr, 1323 llvm::makeArrayRef(Types, NumAssocs), 1324 ArgExprs); 1325 delete [] Types; 1326 return ER; 1327 } 1328 1329 ExprResult 1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1331 SourceLocation DefaultLoc, 1332 SourceLocation RParenLoc, 1333 Expr *ControllingExpr, 1334 ArrayRef<TypeSourceInfo *> Types, 1335 ArrayRef<Expr *> Exprs) { 1336 unsigned NumAssocs = Types.size(); 1337 assert(NumAssocs == Exprs.size()); 1338 1339 // Decay and strip qualifiers for the controlling expression type, and handle 1340 // placeholder type replacement. See committee discussion from WG14 DR423. 1341 { 1342 EnterExpressionEvaluationContext Unevaluated( 1343 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1344 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1345 if (R.isInvalid()) 1346 return ExprError(); 1347 ControllingExpr = R.get(); 1348 } 1349 1350 // The controlling expression is an unevaluated operand, so side effects are 1351 // likely unintended. 1352 if (!inTemplateInstantiation() && 1353 ControllingExpr->HasSideEffects(Context, false)) 1354 Diag(ControllingExpr->getExprLoc(), 1355 diag::warn_side_effects_unevaluated_context); 1356 1357 bool TypeErrorFound = false, 1358 IsResultDependent = ControllingExpr->isTypeDependent(), 1359 ContainsUnexpandedParameterPack 1360 = ControllingExpr->containsUnexpandedParameterPack(); 1361 1362 for (unsigned i = 0; i < NumAssocs; ++i) { 1363 if (Exprs[i]->containsUnexpandedParameterPack()) 1364 ContainsUnexpandedParameterPack = true; 1365 1366 if (Types[i]) { 1367 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1368 ContainsUnexpandedParameterPack = true; 1369 1370 if (Types[i]->getType()->isDependentType()) { 1371 IsResultDependent = true; 1372 } else { 1373 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1374 // complete object type other than a variably modified type." 1375 unsigned D = 0; 1376 if (Types[i]->getType()->isIncompleteType()) 1377 D = diag::err_assoc_type_incomplete; 1378 else if (!Types[i]->getType()->isObjectType()) 1379 D = diag::err_assoc_type_nonobject; 1380 else if (Types[i]->getType()->isVariablyModifiedType()) 1381 D = diag::err_assoc_type_variably_modified; 1382 1383 if (D != 0) { 1384 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1385 << Types[i]->getTypeLoc().getSourceRange() 1386 << Types[i]->getType(); 1387 TypeErrorFound = true; 1388 } 1389 1390 // C11 6.5.1.1p2 "No two generic associations in the same generic 1391 // selection shall specify compatible types." 1392 for (unsigned j = i+1; j < NumAssocs; ++j) 1393 if (Types[j] && !Types[j]->getType()->isDependentType() && 1394 Context.typesAreCompatible(Types[i]->getType(), 1395 Types[j]->getType())) { 1396 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1397 diag::err_assoc_compatible_types) 1398 << Types[j]->getTypeLoc().getSourceRange() 1399 << Types[j]->getType() 1400 << Types[i]->getType(); 1401 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1402 diag::note_compat_assoc) 1403 << Types[i]->getTypeLoc().getSourceRange() 1404 << Types[i]->getType(); 1405 TypeErrorFound = true; 1406 } 1407 } 1408 } 1409 } 1410 if (TypeErrorFound) 1411 return ExprError(); 1412 1413 // If we determined that the generic selection is result-dependent, don't 1414 // try to compute the result expression. 1415 if (IsResultDependent) 1416 return new (Context) GenericSelectionExpr( 1417 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1418 ContainsUnexpandedParameterPack); 1419 1420 SmallVector<unsigned, 1> CompatIndices; 1421 unsigned DefaultIndex = -1U; 1422 for (unsigned i = 0; i < NumAssocs; ++i) { 1423 if (!Types[i]) 1424 DefaultIndex = i; 1425 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1426 Types[i]->getType())) 1427 CompatIndices.push_back(i); 1428 } 1429 1430 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1431 // type compatible with at most one of the types named in its generic 1432 // association list." 1433 if (CompatIndices.size() > 1) { 1434 // We strip parens here because the controlling expression is typically 1435 // parenthesized in macro definitions. 1436 ControllingExpr = ControllingExpr->IgnoreParens(); 1437 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1438 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1439 << (unsigned)CompatIndices.size(); 1440 for (unsigned I : CompatIndices) { 1441 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1442 diag::note_compat_assoc) 1443 << Types[I]->getTypeLoc().getSourceRange() 1444 << Types[I]->getType(); 1445 } 1446 return ExprError(); 1447 } 1448 1449 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1450 // its controlling expression shall have type compatible with exactly one of 1451 // the types named in its generic association list." 1452 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1453 // We strip parens here because the controlling expression is typically 1454 // parenthesized in macro definitions. 1455 ControllingExpr = ControllingExpr->IgnoreParens(); 1456 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1457 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1458 return ExprError(); 1459 } 1460 1461 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1462 // type name that is compatible with the type of the controlling expression, 1463 // then the result expression of the generic selection is the expression 1464 // in that generic association. Otherwise, the result expression of the 1465 // generic selection is the expression in the default generic association." 1466 unsigned ResultIndex = 1467 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1468 1469 return new (Context) GenericSelectionExpr( 1470 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1471 ContainsUnexpandedParameterPack, ResultIndex); 1472 } 1473 1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1475 /// location of the token and the offset of the ud-suffix within it. 1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1477 unsigned Offset) { 1478 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1479 S.getLangOpts()); 1480 } 1481 1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1485 IdentifierInfo *UDSuffix, 1486 SourceLocation UDSuffixLoc, 1487 ArrayRef<Expr*> Args, 1488 SourceLocation LitEndLoc) { 1489 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1490 1491 QualType ArgTy[2]; 1492 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1493 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1494 if (ArgTy[ArgIdx]->isArrayType()) 1495 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1496 } 1497 1498 DeclarationName OpName = 1499 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1500 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1501 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1502 1503 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1504 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1505 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1506 /*AllowStringTemplate*/ false, 1507 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1508 return ExprError(); 1509 1510 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1511 } 1512 1513 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1514 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1515 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1516 /// multiple tokens. However, the common case is that StringToks points to one 1517 /// string. 1518 /// 1519 ExprResult 1520 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1521 assert(!StringToks.empty() && "Must have at least one string!"); 1522 1523 StringLiteralParser Literal(StringToks, PP); 1524 if (Literal.hadError) 1525 return ExprError(); 1526 1527 SmallVector<SourceLocation, 4> StringTokLocs; 1528 for (const Token &Tok : StringToks) 1529 StringTokLocs.push_back(Tok.getLocation()); 1530 1531 QualType CharTy = Context.CharTy; 1532 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1533 if (Literal.isWide()) { 1534 CharTy = Context.getWideCharType(); 1535 Kind = StringLiteral::Wide; 1536 } else if (Literal.isUTF8()) { 1537 if (getLangOpts().Char8) 1538 CharTy = Context.Char8Ty; 1539 Kind = StringLiteral::UTF8; 1540 } else if (Literal.isUTF16()) { 1541 CharTy = Context.Char16Ty; 1542 Kind = StringLiteral::UTF16; 1543 } else if (Literal.isUTF32()) { 1544 CharTy = Context.Char32Ty; 1545 Kind = StringLiteral::UTF32; 1546 } else if (Literal.isPascal()) { 1547 CharTy = Context.UnsignedCharTy; 1548 } 1549 1550 QualType CharTyConst = CharTy; 1551 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1552 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1553 CharTyConst.addConst(); 1554 1555 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1556 1557 // Get an array type for the string, according to C99 6.4.5. This includes 1558 // the nul terminator character as well as the string length for pascal 1559 // strings. 1560 QualType StrTy = Context.getConstantArrayType( 1561 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1562 ArrayType::Normal, 0); 1563 1564 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1565 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1566 Kind, Literal.Pascal, StrTy, 1567 &StringTokLocs[0], 1568 StringTokLocs.size()); 1569 if (Literal.getUDSuffix().empty()) 1570 return Lit; 1571 1572 // We're building a user-defined literal. 1573 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1574 SourceLocation UDSuffixLoc = 1575 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1576 Literal.getUDSuffixOffset()); 1577 1578 // Make sure we're allowed user-defined literals here. 1579 if (!UDLScope) 1580 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1581 1582 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1583 // operator "" X (str, len) 1584 QualType SizeType = Context.getSizeType(); 1585 1586 DeclarationName OpName = 1587 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1588 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1589 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1590 1591 QualType ArgTy[] = { 1592 Context.getArrayDecayedType(StrTy), SizeType 1593 }; 1594 1595 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1596 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1597 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1598 /*AllowStringTemplate*/ true, 1599 /*DiagnoseMissing*/ true)) { 1600 1601 case LOLR_Cooked: { 1602 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1603 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1604 StringTokLocs[0]); 1605 Expr *Args[] = { Lit, LenArg }; 1606 1607 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1608 } 1609 1610 case LOLR_StringTemplate: { 1611 TemplateArgumentListInfo ExplicitArgs; 1612 1613 unsigned CharBits = Context.getIntWidth(CharTy); 1614 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1615 llvm::APSInt Value(CharBits, CharIsUnsigned); 1616 1617 TemplateArgument TypeArg(CharTy); 1618 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1619 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1620 1621 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1622 Value = Lit->getCodeUnit(I); 1623 TemplateArgument Arg(Context, Value, CharTy); 1624 TemplateArgumentLocInfo ArgInfo; 1625 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1626 } 1627 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1628 &ExplicitArgs); 1629 } 1630 case LOLR_Raw: 1631 case LOLR_Template: 1632 case LOLR_ErrorNoDiagnostic: 1633 llvm_unreachable("unexpected literal operator lookup result"); 1634 case LOLR_Error: 1635 return ExprError(); 1636 } 1637 llvm_unreachable("unexpected literal operator lookup result"); 1638 } 1639 1640 ExprResult 1641 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1642 SourceLocation Loc, 1643 const CXXScopeSpec *SS) { 1644 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1645 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1646 } 1647 1648 /// BuildDeclRefExpr - Build an expression that references a 1649 /// declaration that does not require a closure capture. 1650 ExprResult 1651 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1652 const DeclarationNameInfo &NameInfo, 1653 const CXXScopeSpec *SS, NamedDecl *FoundD, 1654 const TemplateArgumentListInfo *TemplateArgs) { 1655 bool RefersToCapturedVariable = 1656 isa<VarDecl>(D) && 1657 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1658 1659 DeclRefExpr *E; 1660 if (isa<VarTemplateSpecializationDecl>(D)) { 1661 VarTemplateSpecializationDecl *VarSpec = 1662 cast<VarTemplateSpecializationDecl>(D); 1663 1664 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1665 : NestedNameSpecifierLoc(), 1666 VarSpec->getTemplateKeywordLoc(), D, 1667 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1668 FoundD, TemplateArgs); 1669 } else { 1670 assert(!TemplateArgs && "No template arguments for non-variable" 1671 " template specialization references"); 1672 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1673 : NestedNameSpecifierLoc(), 1674 SourceLocation(), D, RefersToCapturedVariable, 1675 NameInfo, Ty, VK, FoundD); 1676 } 1677 1678 MarkDeclRefReferenced(E); 1679 1680 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1681 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1682 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1683 getCurFunction()->recordUseOfWeak(E); 1684 1685 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1686 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1687 FD = IFD->getAnonField(); 1688 if (FD) { 1689 UnusedPrivateFields.remove(FD); 1690 // Just in case we're building an illegal pointer-to-member. 1691 if (FD->isBitField()) 1692 E->setObjectKind(OK_BitField); 1693 } 1694 1695 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1696 // designates a bit-field. 1697 if (auto *BD = dyn_cast<BindingDecl>(D)) 1698 if (auto *BE = BD->getBinding()) 1699 E->setObjectKind(BE->getObjectKind()); 1700 1701 return E; 1702 } 1703 1704 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1705 /// possibly a list of template arguments. 1706 /// 1707 /// If this produces template arguments, it is permitted to call 1708 /// DecomposeTemplateName. 1709 /// 1710 /// This actually loses a lot of source location information for 1711 /// non-standard name kinds; we should consider preserving that in 1712 /// some way. 1713 void 1714 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1715 TemplateArgumentListInfo &Buffer, 1716 DeclarationNameInfo &NameInfo, 1717 const TemplateArgumentListInfo *&TemplateArgs) { 1718 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1719 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1720 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1721 1722 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1723 Id.TemplateId->NumArgs); 1724 translateTemplateArguments(TemplateArgsPtr, Buffer); 1725 1726 TemplateName TName = Id.TemplateId->Template.get(); 1727 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1728 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1729 TemplateArgs = &Buffer; 1730 } else { 1731 NameInfo = GetNameFromUnqualifiedId(Id); 1732 TemplateArgs = nullptr; 1733 } 1734 } 1735 1736 static void emitEmptyLookupTypoDiagnostic( 1737 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1738 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1739 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1740 DeclContext *Ctx = 1741 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1742 if (!TC) { 1743 // Emit a special diagnostic for failed member lookups. 1744 // FIXME: computing the declaration context might fail here (?) 1745 if (Ctx) 1746 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1747 << SS.getRange(); 1748 else 1749 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1750 return; 1751 } 1752 1753 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1754 bool DroppedSpecifier = 1755 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1756 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1757 ? diag::note_implicit_param_decl 1758 : diag::note_previous_decl; 1759 if (!Ctx) 1760 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1761 SemaRef.PDiag(NoteID)); 1762 else 1763 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1764 << Typo << Ctx << DroppedSpecifier 1765 << SS.getRange(), 1766 SemaRef.PDiag(NoteID)); 1767 } 1768 1769 /// Diagnose an empty lookup. 1770 /// 1771 /// \return false if new lookup candidates were found 1772 bool 1773 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1774 std::unique_ptr<CorrectionCandidateCallback> CCC, 1775 TemplateArgumentListInfo *ExplicitTemplateArgs, 1776 ArrayRef<Expr *> Args, TypoExpr **Out) { 1777 DeclarationName Name = R.getLookupName(); 1778 1779 unsigned diagnostic = diag::err_undeclared_var_use; 1780 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1781 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1782 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1783 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1784 diagnostic = diag::err_undeclared_use; 1785 diagnostic_suggest = diag::err_undeclared_use_suggest; 1786 } 1787 1788 // If the original lookup was an unqualified lookup, fake an 1789 // unqualified lookup. This is useful when (for example) the 1790 // original lookup would not have found something because it was a 1791 // dependent name. 1792 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1793 while (DC) { 1794 if (isa<CXXRecordDecl>(DC)) { 1795 LookupQualifiedName(R, DC); 1796 1797 if (!R.empty()) { 1798 // Don't give errors about ambiguities in this lookup. 1799 R.suppressDiagnostics(); 1800 1801 // During a default argument instantiation the CurContext points 1802 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1803 // function parameter list, hence add an explicit check. 1804 bool isDefaultArgument = 1805 !CodeSynthesisContexts.empty() && 1806 CodeSynthesisContexts.back().Kind == 1807 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1808 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1809 bool isInstance = CurMethod && 1810 CurMethod->isInstance() && 1811 DC == CurMethod->getParent() && !isDefaultArgument; 1812 1813 // Give a code modification hint to insert 'this->'. 1814 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1815 // Actually quite difficult! 1816 if (getLangOpts().MSVCCompat) 1817 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1818 if (isInstance) { 1819 Diag(R.getNameLoc(), diagnostic) << Name 1820 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1821 CheckCXXThisCapture(R.getNameLoc()); 1822 } else { 1823 Diag(R.getNameLoc(), diagnostic) << Name; 1824 } 1825 1826 // Do we really want to note all of these? 1827 for (NamedDecl *D : R) 1828 Diag(D->getLocation(), diag::note_dependent_var_use); 1829 1830 // Return true if we are inside a default argument instantiation 1831 // and the found name refers to an instance member function, otherwise 1832 // the function calling DiagnoseEmptyLookup will try to create an 1833 // implicit member call and this is wrong for default argument. 1834 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1835 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1836 return true; 1837 } 1838 1839 // Tell the callee to try to recover. 1840 return false; 1841 } 1842 1843 R.clear(); 1844 } 1845 1846 // In Microsoft mode, if we are performing lookup from within a friend 1847 // function definition declared at class scope then we must set 1848 // DC to the lexical parent to be able to search into the parent 1849 // class. 1850 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1851 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1852 DC->getLexicalParent()->isRecord()) 1853 DC = DC->getLexicalParent(); 1854 else 1855 DC = DC->getParent(); 1856 } 1857 1858 // We didn't find anything, so try to correct for a typo. 1859 TypoCorrection Corrected; 1860 if (S && Out) { 1861 SourceLocation TypoLoc = R.getNameLoc(); 1862 assert(!ExplicitTemplateArgs && 1863 "Diagnosing an empty lookup with explicit template args!"); 1864 *Out = CorrectTypoDelayed( 1865 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1866 [=](const TypoCorrection &TC) { 1867 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1868 diagnostic, diagnostic_suggest); 1869 }, 1870 nullptr, CTK_ErrorRecovery); 1871 if (*Out) 1872 return true; 1873 } else if (S && (Corrected = 1874 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1875 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1876 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1877 bool DroppedSpecifier = 1878 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1879 R.setLookupName(Corrected.getCorrection()); 1880 1881 bool AcceptableWithRecovery = false; 1882 bool AcceptableWithoutRecovery = false; 1883 NamedDecl *ND = Corrected.getFoundDecl(); 1884 if (ND) { 1885 if (Corrected.isOverloaded()) { 1886 OverloadCandidateSet OCS(R.getNameLoc(), 1887 OverloadCandidateSet::CSK_Normal); 1888 OverloadCandidateSet::iterator Best; 1889 for (NamedDecl *CD : Corrected) { 1890 if (FunctionTemplateDecl *FTD = 1891 dyn_cast<FunctionTemplateDecl>(CD)) 1892 AddTemplateOverloadCandidate( 1893 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1894 Args, OCS); 1895 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1896 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1897 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1898 Args, OCS); 1899 } 1900 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1901 case OR_Success: 1902 ND = Best->FoundDecl; 1903 Corrected.setCorrectionDecl(ND); 1904 break; 1905 default: 1906 // FIXME: Arbitrarily pick the first declaration for the note. 1907 Corrected.setCorrectionDecl(ND); 1908 break; 1909 } 1910 } 1911 R.addDecl(ND); 1912 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1913 CXXRecordDecl *Record = nullptr; 1914 if (Corrected.getCorrectionSpecifier()) { 1915 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1916 Record = Ty->getAsCXXRecordDecl(); 1917 } 1918 if (!Record) 1919 Record = cast<CXXRecordDecl>( 1920 ND->getDeclContext()->getRedeclContext()); 1921 R.setNamingClass(Record); 1922 } 1923 1924 auto *UnderlyingND = ND->getUnderlyingDecl(); 1925 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1926 isa<FunctionTemplateDecl>(UnderlyingND); 1927 // FIXME: If we ended up with a typo for a type name or 1928 // Objective-C class name, we're in trouble because the parser 1929 // is in the wrong place to recover. Suggest the typo 1930 // correction, but don't make it a fix-it since we're not going 1931 // to recover well anyway. 1932 AcceptableWithoutRecovery = 1933 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1934 } else { 1935 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1936 // because we aren't able to recover. 1937 AcceptableWithoutRecovery = true; 1938 } 1939 1940 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1941 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1942 ? diag::note_implicit_param_decl 1943 : diag::note_previous_decl; 1944 if (SS.isEmpty()) 1945 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1946 PDiag(NoteID), AcceptableWithRecovery); 1947 else 1948 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1949 << Name << computeDeclContext(SS, false) 1950 << DroppedSpecifier << SS.getRange(), 1951 PDiag(NoteID), AcceptableWithRecovery); 1952 1953 // Tell the callee whether to try to recover. 1954 return !AcceptableWithRecovery; 1955 } 1956 } 1957 R.clear(); 1958 1959 // Emit a special diagnostic for failed member lookups. 1960 // FIXME: computing the declaration context might fail here (?) 1961 if (!SS.isEmpty()) { 1962 Diag(R.getNameLoc(), diag::err_no_member) 1963 << Name << computeDeclContext(SS, false) 1964 << SS.getRange(); 1965 return true; 1966 } 1967 1968 // Give up, we can't recover. 1969 Diag(R.getNameLoc(), diagnostic) << Name; 1970 return true; 1971 } 1972 1973 /// In Microsoft mode, if we are inside a template class whose parent class has 1974 /// dependent base classes, and we can't resolve an unqualified identifier, then 1975 /// assume the identifier is a member of a dependent base class. We can only 1976 /// recover successfully in static methods, instance methods, and other contexts 1977 /// where 'this' is available. This doesn't precisely match MSVC's 1978 /// instantiation model, but it's close enough. 1979 static Expr * 1980 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1981 DeclarationNameInfo &NameInfo, 1982 SourceLocation TemplateKWLoc, 1983 const TemplateArgumentListInfo *TemplateArgs) { 1984 // Only try to recover from lookup into dependent bases in static methods or 1985 // contexts where 'this' is available. 1986 QualType ThisType = S.getCurrentThisType(); 1987 const CXXRecordDecl *RD = nullptr; 1988 if (!ThisType.isNull()) 1989 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1990 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1991 RD = MD->getParent(); 1992 if (!RD || !RD->hasAnyDependentBases()) 1993 return nullptr; 1994 1995 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1996 // is available, suggest inserting 'this->' as a fixit. 1997 SourceLocation Loc = NameInfo.getLoc(); 1998 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1999 DB << NameInfo.getName() << RD; 2000 2001 if (!ThisType.isNull()) { 2002 DB << FixItHint::CreateInsertion(Loc, "this->"); 2003 return CXXDependentScopeMemberExpr::Create( 2004 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2005 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2006 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2007 } 2008 2009 // Synthesize a fake NNS that points to the derived class. This will 2010 // perform name lookup during template instantiation. 2011 CXXScopeSpec SS; 2012 auto *NNS = 2013 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2014 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2015 return DependentScopeDeclRefExpr::Create( 2016 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2017 TemplateArgs); 2018 } 2019 2020 ExprResult 2021 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2022 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2023 bool HasTrailingLParen, bool IsAddressOfOperand, 2024 std::unique_ptr<CorrectionCandidateCallback> CCC, 2025 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2026 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2027 "cannot be direct & operand and have a trailing lparen"); 2028 if (SS.isInvalid()) 2029 return ExprError(); 2030 2031 TemplateArgumentListInfo TemplateArgsBuffer; 2032 2033 // Decompose the UnqualifiedId into the following data. 2034 DeclarationNameInfo NameInfo; 2035 const TemplateArgumentListInfo *TemplateArgs; 2036 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2037 2038 DeclarationName Name = NameInfo.getName(); 2039 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2040 SourceLocation NameLoc = NameInfo.getLoc(); 2041 2042 if (II && II->isEditorPlaceholder()) { 2043 // FIXME: When typed placeholders are supported we can create a typed 2044 // placeholder expression node. 2045 return ExprError(); 2046 } 2047 2048 // C++ [temp.dep.expr]p3: 2049 // An id-expression is type-dependent if it contains: 2050 // -- an identifier that was declared with a dependent type, 2051 // (note: handled after lookup) 2052 // -- a template-id that is dependent, 2053 // (note: handled in BuildTemplateIdExpr) 2054 // -- a conversion-function-id that specifies a dependent type, 2055 // -- a nested-name-specifier that contains a class-name that 2056 // names a dependent type. 2057 // Determine whether this is a member of an unknown specialization; 2058 // we need to handle these differently. 2059 bool DependentID = false; 2060 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2061 Name.getCXXNameType()->isDependentType()) { 2062 DependentID = true; 2063 } else if (SS.isSet()) { 2064 if (DeclContext *DC = computeDeclContext(SS, false)) { 2065 if (RequireCompleteDeclContext(SS, DC)) 2066 return ExprError(); 2067 } else { 2068 DependentID = true; 2069 } 2070 } 2071 2072 if (DependentID) 2073 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2074 IsAddressOfOperand, TemplateArgs); 2075 2076 // Perform the required lookup. 2077 LookupResult R(*this, NameInfo, 2078 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2079 ? LookupObjCImplicitSelfParam 2080 : LookupOrdinaryName); 2081 if (TemplateKWLoc.isValid() || TemplateArgs) { 2082 // Lookup the template name again to correctly establish the context in 2083 // which it was found. This is really unfortunate as we already did the 2084 // lookup to determine that it was a template name in the first place. If 2085 // this becomes a performance hit, we can work harder to preserve those 2086 // results until we get here but it's likely not worth it. 2087 bool MemberOfUnknownSpecialization; 2088 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2089 MemberOfUnknownSpecialization, TemplateKWLoc)) 2090 return ExprError(); 2091 2092 if (MemberOfUnknownSpecialization || 2093 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2094 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2095 IsAddressOfOperand, TemplateArgs); 2096 } else { 2097 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2098 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2099 2100 // If the result might be in a dependent base class, this is a dependent 2101 // id-expression. 2102 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2103 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2104 IsAddressOfOperand, TemplateArgs); 2105 2106 // If this reference is in an Objective-C method, then we need to do 2107 // some special Objective-C lookup, too. 2108 if (IvarLookupFollowUp) { 2109 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2110 if (E.isInvalid()) 2111 return ExprError(); 2112 2113 if (Expr *Ex = E.getAs<Expr>()) 2114 return Ex; 2115 } 2116 } 2117 2118 if (R.isAmbiguous()) 2119 return ExprError(); 2120 2121 // This could be an implicitly declared function reference (legal in C90, 2122 // extension in C99, forbidden in C++). 2123 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2124 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2125 if (D) R.addDecl(D); 2126 } 2127 2128 // Determine whether this name might be a candidate for 2129 // argument-dependent lookup. 2130 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2131 2132 if (R.empty() && !ADL) { 2133 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2134 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2135 TemplateKWLoc, TemplateArgs)) 2136 return E; 2137 } 2138 2139 // Don't diagnose an empty lookup for inline assembly. 2140 if (IsInlineAsmIdentifier) 2141 return ExprError(); 2142 2143 // If this name wasn't predeclared and if this is not a function 2144 // call, diagnose the problem. 2145 TypoExpr *TE = nullptr; 2146 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2147 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2148 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2149 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2150 "Typo correction callback misconfigured"); 2151 if (CCC) { 2152 // Make sure the callback knows what the typo being diagnosed is. 2153 CCC->setTypoName(II); 2154 if (SS.isValid()) 2155 CCC->setTypoNNS(SS.getScopeRep()); 2156 } 2157 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2158 // a template name, but we happen to have always already looked up the name 2159 // before we get here if it must be a template name. 2160 if (DiagnoseEmptyLookup(S, SS, R, 2161 CCC ? std::move(CCC) : std::move(DefaultValidator), 2162 nullptr, None, &TE)) { 2163 if (TE && KeywordReplacement) { 2164 auto &State = getTypoExprState(TE); 2165 auto BestTC = State.Consumer->getNextCorrection(); 2166 if (BestTC.isKeyword()) { 2167 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2168 if (State.DiagHandler) 2169 State.DiagHandler(BestTC); 2170 KeywordReplacement->startToken(); 2171 KeywordReplacement->setKind(II->getTokenID()); 2172 KeywordReplacement->setIdentifierInfo(II); 2173 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2174 // Clean up the state associated with the TypoExpr, since it has 2175 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2176 clearDelayedTypo(TE); 2177 // Signal that a correction to a keyword was performed by returning a 2178 // valid-but-null ExprResult. 2179 return (Expr*)nullptr; 2180 } 2181 State.Consumer->resetCorrectionStream(); 2182 } 2183 return TE ? TE : ExprError(); 2184 } 2185 2186 assert(!R.empty() && 2187 "DiagnoseEmptyLookup returned false but added no results"); 2188 2189 // If we found an Objective-C instance variable, let 2190 // LookupInObjCMethod build the appropriate expression to 2191 // reference the ivar. 2192 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2193 R.clear(); 2194 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2195 // In a hopelessly buggy code, Objective-C instance variable 2196 // lookup fails and no expression will be built to reference it. 2197 if (!E.isInvalid() && !E.get()) 2198 return ExprError(); 2199 return E; 2200 } 2201 } 2202 2203 // This is guaranteed from this point on. 2204 assert(!R.empty() || ADL); 2205 2206 // Check whether this might be a C++ implicit instance member access. 2207 // C++ [class.mfct.non-static]p3: 2208 // When an id-expression that is not part of a class member access 2209 // syntax and not used to form a pointer to member is used in the 2210 // body of a non-static member function of class X, if name lookup 2211 // resolves the name in the id-expression to a non-static non-type 2212 // member of some class C, the id-expression is transformed into a 2213 // class member access expression using (*this) as the 2214 // postfix-expression to the left of the . operator. 2215 // 2216 // But we don't actually need to do this for '&' operands if R 2217 // resolved to a function or overloaded function set, because the 2218 // expression is ill-formed if it actually works out to be a 2219 // non-static member function: 2220 // 2221 // C++ [expr.ref]p4: 2222 // Otherwise, if E1.E2 refers to a non-static member function. . . 2223 // [t]he expression can be used only as the left-hand operand of a 2224 // member function call. 2225 // 2226 // There are other safeguards against such uses, but it's important 2227 // to get this right here so that we don't end up making a 2228 // spuriously dependent expression if we're inside a dependent 2229 // instance method. 2230 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2231 bool MightBeImplicitMember; 2232 if (!IsAddressOfOperand) 2233 MightBeImplicitMember = true; 2234 else if (!SS.isEmpty()) 2235 MightBeImplicitMember = false; 2236 else if (R.isOverloadedResult()) 2237 MightBeImplicitMember = false; 2238 else if (R.isUnresolvableResult()) 2239 MightBeImplicitMember = true; 2240 else 2241 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2242 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2243 isa<MSPropertyDecl>(R.getFoundDecl()); 2244 2245 if (MightBeImplicitMember) 2246 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2247 R, TemplateArgs, S); 2248 } 2249 2250 if (TemplateArgs || TemplateKWLoc.isValid()) { 2251 2252 // In C++1y, if this is a variable template id, then check it 2253 // in BuildTemplateIdExpr(). 2254 // The single lookup result must be a variable template declaration. 2255 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2256 Id.TemplateId->Kind == TNK_Var_template) { 2257 assert(R.getAsSingle<VarTemplateDecl>() && 2258 "There should only be one declaration found."); 2259 } 2260 2261 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2262 } 2263 2264 return BuildDeclarationNameExpr(SS, R, ADL); 2265 } 2266 2267 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2268 /// declaration name, generally during template instantiation. 2269 /// There's a large number of things which don't need to be done along 2270 /// this path. 2271 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2272 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2273 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2274 DeclContext *DC = computeDeclContext(SS, false); 2275 if (!DC) 2276 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2277 NameInfo, /*TemplateArgs=*/nullptr); 2278 2279 if (RequireCompleteDeclContext(SS, DC)) 2280 return ExprError(); 2281 2282 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2283 LookupQualifiedName(R, DC); 2284 2285 if (R.isAmbiguous()) 2286 return ExprError(); 2287 2288 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2289 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2290 NameInfo, /*TemplateArgs=*/nullptr); 2291 2292 if (R.empty()) { 2293 Diag(NameInfo.getLoc(), diag::err_no_member) 2294 << NameInfo.getName() << DC << SS.getRange(); 2295 return ExprError(); 2296 } 2297 2298 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2299 // Diagnose a missing typename if this resolved unambiguously to a type in 2300 // a dependent context. If we can recover with a type, downgrade this to 2301 // a warning in Microsoft compatibility mode. 2302 unsigned DiagID = diag::err_typename_missing; 2303 if (RecoveryTSI && getLangOpts().MSVCCompat) 2304 DiagID = diag::ext_typename_missing; 2305 SourceLocation Loc = SS.getBeginLoc(); 2306 auto D = Diag(Loc, DiagID); 2307 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2308 << SourceRange(Loc, NameInfo.getEndLoc()); 2309 2310 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2311 // context. 2312 if (!RecoveryTSI) 2313 return ExprError(); 2314 2315 // Only issue the fixit if we're prepared to recover. 2316 D << FixItHint::CreateInsertion(Loc, "typename "); 2317 2318 // Recover by pretending this was an elaborated type. 2319 QualType Ty = Context.getTypeDeclType(TD); 2320 TypeLocBuilder TLB; 2321 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2322 2323 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2324 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2325 QTL.setElaboratedKeywordLoc(SourceLocation()); 2326 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2327 2328 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2329 2330 return ExprEmpty(); 2331 } 2332 2333 // Defend against this resolving to an implicit member access. We usually 2334 // won't get here if this might be a legitimate a class member (we end up in 2335 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2336 // a pointer-to-member or in an unevaluated context in C++11. 2337 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2338 return BuildPossibleImplicitMemberExpr(SS, 2339 /*TemplateKWLoc=*/SourceLocation(), 2340 R, /*TemplateArgs=*/nullptr, S); 2341 2342 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2343 } 2344 2345 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2346 /// detected that we're currently inside an ObjC method. Perform some 2347 /// additional lookup. 2348 /// 2349 /// Ideally, most of this would be done by lookup, but there's 2350 /// actually quite a lot of extra work involved. 2351 /// 2352 /// Returns a null sentinel to indicate trivial success. 2353 ExprResult 2354 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2355 IdentifierInfo *II, bool AllowBuiltinCreation) { 2356 SourceLocation Loc = Lookup.getNameLoc(); 2357 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2358 2359 // Check for error condition which is already reported. 2360 if (!CurMethod) 2361 return ExprError(); 2362 2363 // There are two cases to handle here. 1) scoped lookup could have failed, 2364 // in which case we should look for an ivar. 2) scoped lookup could have 2365 // found a decl, but that decl is outside the current instance method (i.e. 2366 // a global variable). In these two cases, we do a lookup for an ivar with 2367 // this name, if the lookup sucedes, we replace it our current decl. 2368 2369 // If we're in a class method, we don't normally want to look for 2370 // ivars. But if we don't find anything else, and there's an 2371 // ivar, that's an error. 2372 bool IsClassMethod = CurMethod->isClassMethod(); 2373 2374 bool LookForIvars; 2375 if (Lookup.empty()) 2376 LookForIvars = true; 2377 else if (IsClassMethod) 2378 LookForIvars = false; 2379 else 2380 LookForIvars = (Lookup.isSingleResult() && 2381 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2382 ObjCInterfaceDecl *IFace = nullptr; 2383 if (LookForIvars) { 2384 IFace = CurMethod->getClassInterface(); 2385 ObjCInterfaceDecl *ClassDeclared; 2386 ObjCIvarDecl *IV = nullptr; 2387 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2388 // Diagnose using an ivar in a class method. 2389 if (IsClassMethod) 2390 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2391 << IV->getDeclName()); 2392 2393 // If we're referencing an invalid decl, just return this as a silent 2394 // error node. The error diagnostic was already emitted on the decl. 2395 if (IV->isInvalidDecl()) 2396 return ExprError(); 2397 2398 // Check if referencing a field with __attribute__((deprecated)). 2399 if (DiagnoseUseOfDecl(IV, Loc)) 2400 return ExprError(); 2401 2402 // Diagnose the use of an ivar outside of the declaring class. 2403 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2404 !declaresSameEntity(ClassDeclared, IFace) && 2405 !getLangOpts().DebuggerSupport) 2406 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2407 2408 // FIXME: This should use a new expr for a direct reference, don't 2409 // turn this into Self->ivar, just return a BareIVarExpr or something. 2410 IdentifierInfo &II = Context.Idents.get("self"); 2411 UnqualifiedId SelfName; 2412 SelfName.setIdentifier(&II, SourceLocation()); 2413 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2414 CXXScopeSpec SelfScopeSpec; 2415 SourceLocation TemplateKWLoc; 2416 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2417 SelfName, false, false); 2418 if (SelfExpr.isInvalid()) 2419 return ExprError(); 2420 2421 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2422 if (SelfExpr.isInvalid()) 2423 return ExprError(); 2424 2425 MarkAnyDeclReferenced(Loc, IV, true); 2426 2427 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2428 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2429 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2430 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2431 2432 ObjCIvarRefExpr *Result = new (Context) 2433 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2434 IV->getLocation(), SelfExpr.get(), true, true); 2435 2436 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2437 if (!isUnevaluatedContext() && 2438 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2439 getCurFunction()->recordUseOfWeak(Result); 2440 } 2441 if (getLangOpts().ObjCAutoRefCount) { 2442 if (CurContext->isClosure()) 2443 Diag(Loc, diag::warn_implicitly_retains_self) 2444 << FixItHint::CreateInsertion(Loc, "self->"); 2445 } 2446 2447 return Result; 2448 } 2449 } else if (CurMethod->isInstanceMethod()) { 2450 // We should warn if a local variable hides an ivar. 2451 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2452 ObjCInterfaceDecl *ClassDeclared; 2453 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2454 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2455 declaresSameEntity(IFace, ClassDeclared)) 2456 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2457 } 2458 } 2459 } else if (Lookup.isSingleResult() && 2460 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2461 // If accessing a stand-alone ivar in a class method, this is an error. 2462 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2463 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2464 << IV->getDeclName()); 2465 } 2466 2467 if (Lookup.empty() && II && AllowBuiltinCreation) { 2468 // FIXME. Consolidate this with similar code in LookupName. 2469 if (unsigned BuiltinID = II->getBuiltinID()) { 2470 if (!(getLangOpts().CPlusPlus && 2471 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2472 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2473 S, Lookup.isForRedeclaration(), 2474 Lookup.getNameLoc()); 2475 if (D) Lookup.addDecl(D); 2476 } 2477 } 2478 } 2479 // Sentinel value saying that we didn't do anything special. 2480 return ExprResult((Expr *)nullptr); 2481 } 2482 2483 /// Cast a base object to a member's actual type. 2484 /// 2485 /// Logically this happens in three phases: 2486 /// 2487 /// * First we cast from the base type to the naming class. 2488 /// The naming class is the class into which we were looking 2489 /// when we found the member; it's the qualifier type if a 2490 /// qualifier was provided, and otherwise it's the base type. 2491 /// 2492 /// * Next we cast from the naming class to the declaring class. 2493 /// If the member we found was brought into a class's scope by 2494 /// a using declaration, this is that class; otherwise it's 2495 /// the class declaring the member. 2496 /// 2497 /// * Finally we cast from the declaring class to the "true" 2498 /// declaring class of the member. This conversion does not 2499 /// obey access control. 2500 ExprResult 2501 Sema::PerformObjectMemberConversion(Expr *From, 2502 NestedNameSpecifier *Qualifier, 2503 NamedDecl *FoundDecl, 2504 NamedDecl *Member) { 2505 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2506 if (!RD) 2507 return From; 2508 2509 QualType DestRecordType; 2510 QualType DestType; 2511 QualType FromRecordType; 2512 QualType FromType = From->getType(); 2513 bool PointerConversions = false; 2514 if (isa<FieldDecl>(Member)) { 2515 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2516 2517 if (FromType->getAs<PointerType>()) { 2518 DestType = Context.getPointerType(DestRecordType); 2519 FromRecordType = FromType->getPointeeType(); 2520 PointerConversions = true; 2521 } else { 2522 DestType = DestRecordType; 2523 FromRecordType = FromType; 2524 } 2525 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2526 if (Method->isStatic()) 2527 return From; 2528 2529 DestType = Method->getThisType(Context); 2530 DestRecordType = DestType->getPointeeType(); 2531 2532 if (FromType->getAs<PointerType>()) { 2533 FromRecordType = FromType->getPointeeType(); 2534 PointerConversions = true; 2535 } else { 2536 FromRecordType = FromType; 2537 DestType = DestRecordType; 2538 } 2539 } else { 2540 // No conversion necessary. 2541 return From; 2542 } 2543 2544 if (DestType->isDependentType() || FromType->isDependentType()) 2545 return From; 2546 2547 // If the unqualified types are the same, no conversion is necessary. 2548 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2549 return From; 2550 2551 SourceRange FromRange = From->getSourceRange(); 2552 SourceLocation FromLoc = FromRange.getBegin(); 2553 2554 ExprValueKind VK = From->getValueKind(); 2555 2556 // C++ [class.member.lookup]p8: 2557 // [...] Ambiguities can often be resolved by qualifying a name with its 2558 // class name. 2559 // 2560 // If the member was a qualified name and the qualified referred to a 2561 // specific base subobject type, we'll cast to that intermediate type 2562 // first and then to the object in which the member is declared. That allows 2563 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2564 // 2565 // class Base { public: int x; }; 2566 // class Derived1 : public Base { }; 2567 // class Derived2 : public Base { }; 2568 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2569 // 2570 // void VeryDerived::f() { 2571 // x = 17; // error: ambiguous base subobjects 2572 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2573 // } 2574 if (Qualifier && Qualifier->getAsType()) { 2575 QualType QType = QualType(Qualifier->getAsType(), 0); 2576 assert(QType->isRecordType() && "lookup done with non-record type"); 2577 2578 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2579 2580 // In C++98, the qualifier type doesn't actually have to be a base 2581 // type of the object type, in which case we just ignore it. 2582 // Otherwise build the appropriate casts. 2583 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2584 CXXCastPath BasePath; 2585 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2586 FromLoc, FromRange, &BasePath)) 2587 return ExprError(); 2588 2589 if (PointerConversions) 2590 QType = Context.getPointerType(QType); 2591 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2592 VK, &BasePath).get(); 2593 2594 FromType = QType; 2595 FromRecordType = QRecordType; 2596 2597 // If the qualifier type was the same as the destination type, 2598 // we're done. 2599 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2600 return From; 2601 } 2602 } 2603 2604 bool IgnoreAccess = false; 2605 2606 // If we actually found the member through a using declaration, cast 2607 // down to the using declaration's type. 2608 // 2609 // Pointer equality is fine here because only one declaration of a 2610 // class ever has member declarations. 2611 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2612 assert(isa<UsingShadowDecl>(FoundDecl)); 2613 QualType URecordType = Context.getTypeDeclType( 2614 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2615 2616 // We only need to do this if the naming-class to declaring-class 2617 // conversion is non-trivial. 2618 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2619 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2620 CXXCastPath BasePath; 2621 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2622 FromLoc, FromRange, &BasePath)) 2623 return ExprError(); 2624 2625 QualType UType = URecordType; 2626 if (PointerConversions) 2627 UType = Context.getPointerType(UType); 2628 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2629 VK, &BasePath).get(); 2630 FromType = UType; 2631 FromRecordType = URecordType; 2632 } 2633 2634 // We don't do access control for the conversion from the 2635 // declaring class to the true declaring class. 2636 IgnoreAccess = true; 2637 } 2638 2639 CXXCastPath BasePath; 2640 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2641 FromLoc, FromRange, &BasePath, 2642 IgnoreAccess)) 2643 return ExprError(); 2644 2645 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2646 VK, &BasePath); 2647 } 2648 2649 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2650 const LookupResult &R, 2651 bool HasTrailingLParen) { 2652 // Only when used directly as the postfix-expression of a call. 2653 if (!HasTrailingLParen) 2654 return false; 2655 2656 // Never if a scope specifier was provided. 2657 if (SS.isSet()) 2658 return false; 2659 2660 // Only in C++ or ObjC++. 2661 if (!getLangOpts().CPlusPlus) 2662 return false; 2663 2664 // Turn off ADL when we find certain kinds of declarations during 2665 // normal lookup: 2666 for (NamedDecl *D : R) { 2667 // C++0x [basic.lookup.argdep]p3: 2668 // -- a declaration of a class member 2669 // Since using decls preserve this property, we check this on the 2670 // original decl. 2671 if (D->isCXXClassMember()) 2672 return false; 2673 2674 // C++0x [basic.lookup.argdep]p3: 2675 // -- a block-scope function declaration that is not a 2676 // using-declaration 2677 // NOTE: we also trigger this for function templates (in fact, we 2678 // don't check the decl type at all, since all other decl types 2679 // turn off ADL anyway). 2680 if (isa<UsingShadowDecl>(D)) 2681 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2682 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2683 return false; 2684 2685 // C++0x [basic.lookup.argdep]p3: 2686 // -- a declaration that is neither a function or a function 2687 // template 2688 // And also for builtin functions. 2689 if (isa<FunctionDecl>(D)) { 2690 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2691 2692 // But also builtin functions. 2693 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2694 return false; 2695 } else if (!isa<FunctionTemplateDecl>(D)) 2696 return false; 2697 } 2698 2699 return true; 2700 } 2701 2702 2703 /// Diagnoses obvious problems with the use of the given declaration 2704 /// as an expression. This is only actually called for lookups that 2705 /// were not overloaded, and it doesn't promise that the declaration 2706 /// will in fact be used. 2707 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2708 if (D->isInvalidDecl()) 2709 return true; 2710 2711 if (isa<TypedefNameDecl>(D)) { 2712 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2713 return true; 2714 } 2715 2716 if (isa<ObjCInterfaceDecl>(D)) { 2717 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2718 return true; 2719 } 2720 2721 if (isa<NamespaceDecl>(D)) { 2722 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2723 return true; 2724 } 2725 2726 return false; 2727 } 2728 2729 // Certain multiversion types should be treated as overloaded even when there is 2730 // only one result. 2731 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2732 assert(R.isSingleResult() && "Expected only a single result"); 2733 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2734 return FD && 2735 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2736 } 2737 2738 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2739 LookupResult &R, bool NeedsADL, 2740 bool AcceptInvalidDecl) { 2741 // If this is a single, fully-resolved result and we don't need ADL, 2742 // just build an ordinary singleton decl ref. 2743 if (!NeedsADL && R.isSingleResult() && 2744 !R.getAsSingle<FunctionTemplateDecl>() && 2745 !ShouldLookupResultBeMultiVersionOverload(R)) 2746 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2747 R.getRepresentativeDecl(), nullptr, 2748 AcceptInvalidDecl); 2749 2750 // We only need to check the declaration if there's exactly one 2751 // result, because in the overloaded case the results can only be 2752 // functions and function templates. 2753 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2754 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2755 return ExprError(); 2756 2757 // Otherwise, just build an unresolved lookup expression. Suppress 2758 // any lookup-related diagnostics; we'll hash these out later, when 2759 // we've picked a target. 2760 R.suppressDiagnostics(); 2761 2762 UnresolvedLookupExpr *ULE 2763 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2764 SS.getWithLocInContext(Context), 2765 R.getLookupNameInfo(), 2766 NeedsADL, R.isOverloadedResult(), 2767 R.begin(), R.end()); 2768 2769 return ULE; 2770 } 2771 2772 static void 2773 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2774 ValueDecl *var, DeclContext *DC); 2775 2776 /// Complete semantic analysis for a reference to the given declaration. 2777 ExprResult Sema::BuildDeclarationNameExpr( 2778 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2779 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2780 bool AcceptInvalidDecl) { 2781 assert(D && "Cannot refer to a NULL declaration"); 2782 assert(!isa<FunctionTemplateDecl>(D) && 2783 "Cannot refer unambiguously to a function template"); 2784 2785 SourceLocation Loc = NameInfo.getLoc(); 2786 if (CheckDeclInExpr(*this, Loc, D)) 2787 return ExprError(); 2788 2789 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2790 // Specifically diagnose references to class templates that are missing 2791 // a template argument list. 2792 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2793 return ExprError(); 2794 } 2795 2796 // Make sure that we're referring to a value. 2797 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2798 if (!VD) { 2799 Diag(Loc, diag::err_ref_non_value) 2800 << D << SS.getRange(); 2801 Diag(D->getLocation(), diag::note_declared_at); 2802 return ExprError(); 2803 } 2804 2805 // Check whether this declaration can be used. Note that we suppress 2806 // this check when we're going to perform argument-dependent lookup 2807 // on this function name, because this might not be the function 2808 // that overload resolution actually selects. 2809 if (DiagnoseUseOfDecl(VD, Loc)) 2810 return ExprError(); 2811 2812 // Only create DeclRefExpr's for valid Decl's. 2813 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2814 return ExprError(); 2815 2816 // Handle members of anonymous structs and unions. If we got here, 2817 // and the reference is to a class member indirect field, then this 2818 // must be the subject of a pointer-to-member expression. 2819 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2820 if (!indirectField->isCXXClassMember()) 2821 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2822 indirectField); 2823 2824 { 2825 QualType type = VD->getType(); 2826 if (type.isNull()) 2827 return ExprError(); 2828 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2829 // C++ [except.spec]p17: 2830 // An exception-specification is considered to be needed when: 2831 // - in an expression, the function is the unique lookup result or 2832 // the selected member of a set of overloaded functions. 2833 ResolveExceptionSpec(Loc, FPT); 2834 type = VD->getType(); 2835 } 2836 ExprValueKind valueKind = VK_RValue; 2837 2838 switch (D->getKind()) { 2839 // Ignore all the non-ValueDecl kinds. 2840 #define ABSTRACT_DECL(kind) 2841 #define VALUE(type, base) 2842 #define DECL(type, base) \ 2843 case Decl::type: 2844 #include "clang/AST/DeclNodes.inc" 2845 llvm_unreachable("invalid value decl kind"); 2846 2847 // These shouldn't make it here. 2848 case Decl::ObjCAtDefsField: 2849 case Decl::ObjCIvar: 2850 llvm_unreachable("forming non-member reference to ivar?"); 2851 2852 // Enum constants are always r-values and never references. 2853 // Unresolved using declarations are dependent. 2854 case Decl::EnumConstant: 2855 case Decl::UnresolvedUsingValue: 2856 case Decl::OMPDeclareReduction: 2857 valueKind = VK_RValue; 2858 break; 2859 2860 // Fields and indirect fields that got here must be for 2861 // pointer-to-member expressions; we just call them l-values for 2862 // internal consistency, because this subexpression doesn't really 2863 // exist in the high-level semantics. 2864 case Decl::Field: 2865 case Decl::IndirectField: 2866 assert(getLangOpts().CPlusPlus && 2867 "building reference to field in C?"); 2868 2869 // These can't have reference type in well-formed programs, but 2870 // for internal consistency we do this anyway. 2871 type = type.getNonReferenceType(); 2872 valueKind = VK_LValue; 2873 break; 2874 2875 // Non-type template parameters are either l-values or r-values 2876 // depending on the type. 2877 case Decl::NonTypeTemplateParm: { 2878 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2879 type = reftype->getPointeeType(); 2880 valueKind = VK_LValue; // even if the parameter is an r-value reference 2881 break; 2882 } 2883 2884 // For non-references, we need to strip qualifiers just in case 2885 // the template parameter was declared as 'const int' or whatever. 2886 valueKind = VK_RValue; 2887 type = type.getUnqualifiedType(); 2888 break; 2889 } 2890 2891 case Decl::Var: 2892 case Decl::VarTemplateSpecialization: 2893 case Decl::VarTemplatePartialSpecialization: 2894 case Decl::Decomposition: 2895 case Decl::OMPCapturedExpr: 2896 // In C, "extern void blah;" is valid and is an r-value. 2897 if (!getLangOpts().CPlusPlus && 2898 !type.hasQualifiers() && 2899 type->isVoidType()) { 2900 valueKind = VK_RValue; 2901 break; 2902 } 2903 LLVM_FALLTHROUGH; 2904 2905 case Decl::ImplicitParam: 2906 case Decl::ParmVar: { 2907 // These are always l-values. 2908 valueKind = VK_LValue; 2909 type = type.getNonReferenceType(); 2910 2911 // FIXME: Does the addition of const really only apply in 2912 // potentially-evaluated contexts? Since the variable isn't actually 2913 // captured in an unevaluated context, it seems that the answer is no. 2914 if (!isUnevaluatedContext()) { 2915 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2916 if (!CapturedType.isNull()) 2917 type = CapturedType; 2918 } 2919 2920 break; 2921 } 2922 2923 case Decl::Binding: { 2924 // These are always lvalues. 2925 valueKind = VK_LValue; 2926 type = type.getNonReferenceType(); 2927 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2928 // decides how that's supposed to work. 2929 auto *BD = cast<BindingDecl>(VD); 2930 if (BD->getDeclContext()->isFunctionOrMethod() && 2931 BD->getDeclContext() != CurContext) 2932 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2933 break; 2934 } 2935 2936 case Decl::Function: { 2937 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2938 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2939 type = Context.BuiltinFnTy; 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 } 2944 2945 const FunctionType *fty = type->castAs<FunctionType>(); 2946 2947 // If we're referring to a function with an __unknown_anytype 2948 // result type, make the entire expression __unknown_anytype. 2949 if (fty->getReturnType() == Context.UnknownAnyTy) { 2950 type = Context.UnknownAnyTy; 2951 valueKind = VK_RValue; 2952 break; 2953 } 2954 2955 // Functions are l-values in C++. 2956 if (getLangOpts().CPlusPlus) { 2957 valueKind = VK_LValue; 2958 break; 2959 } 2960 2961 // C99 DR 316 says that, if a function type comes from a 2962 // function definition (without a prototype), that type is only 2963 // used for checking compatibility. Therefore, when referencing 2964 // the function, we pretend that we don't have the full function 2965 // type. 2966 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2967 isa<FunctionProtoType>(fty)) 2968 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2969 fty->getExtInfo()); 2970 2971 // Functions are r-values in C. 2972 valueKind = VK_RValue; 2973 break; 2974 } 2975 2976 case Decl::CXXDeductionGuide: 2977 llvm_unreachable("building reference to deduction guide"); 2978 2979 case Decl::MSProperty: 2980 valueKind = VK_LValue; 2981 break; 2982 2983 case Decl::CXXMethod: 2984 // If we're referring to a method with an __unknown_anytype 2985 // result type, make the entire expression __unknown_anytype. 2986 // This should only be possible with a type written directly. 2987 if (const FunctionProtoType *proto 2988 = dyn_cast<FunctionProtoType>(VD->getType())) 2989 if (proto->getReturnType() == Context.UnknownAnyTy) { 2990 type = Context.UnknownAnyTy; 2991 valueKind = VK_RValue; 2992 break; 2993 } 2994 2995 // C++ methods are l-values if static, r-values if non-static. 2996 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2997 valueKind = VK_LValue; 2998 break; 2999 } 3000 LLVM_FALLTHROUGH; 3001 3002 case Decl::CXXConversion: 3003 case Decl::CXXDestructor: 3004 case Decl::CXXConstructor: 3005 valueKind = VK_RValue; 3006 break; 3007 } 3008 3009 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3010 TemplateArgs); 3011 } 3012 } 3013 3014 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3015 SmallString<32> &Target) { 3016 Target.resize(CharByteWidth * (Source.size() + 1)); 3017 char *ResultPtr = &Target[0]; 3018 const llvm::UTF8 *ErrorPtr; 3019 bool success = 3020 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3021 (void)success; 3022 assert(success); 3023 Target.resize(ResultPtr - &Target[0]); 3024 } 3025 3026 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3027 PredefinedExpr::IdentType IT) { 3028 // Pick the current block, lambda, captured statement or function. 3029 Decl *currentDecl = nullptr; 3030 if (const BlockScopeInfo *BSI = getCurBlock()) 3031 currentDecl = BSI->TheDecl; 3032 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3033 currentDecl = LSI->CallOperator; 3034 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3035 currentDecl = CSI->TheCapturedDecl; 3036 else 3037 currentDecl = getCurFunctionOrMethodDecl(); 3038 3039 if (!currentDecl) { 3040 Diag(Loc, diag::ext_predef_outside_function); 3041 currentDecl = Context.getTranslationUnitDecl(); 3042 } 3043 3044 QualType ResTy; 3045 StringLiteral *SL = nullptr; 3046 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3047 ResTy = Context.DependentTy; 3048 else { 3049 // Pre-defined identifiers are of type char[x], where x is the length of 3050 // the string. 3051 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3052 unsigned Length = Str.length(); 3053 3054 llvm::APInt LengthI(32, Length + 1); 3055 if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) { 3056 ResTy = 3057 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3058 SmallString<32> RawChars; 3059 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3060 Str, RawChars); 3061 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3062 /*IndexTypeQuals*/ 0); 3063 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3064 /*Pascal*/ false, ResTy, Loc); 3065 } else { 3066 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3067 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3068 /*IndexTypeQuals*/ 0); 3069 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3070 /*Pascal*/ false, ResTy, Loc); 3071 } 3072 } 3073 3074 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3075 } 3076 3077 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3078 PredefinedExpr::IdentType IT; 3079 3080 switch (Kind) { 3081 default: llvm_unreachable("Unknown simple primary expr!"); 3082 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3083 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3084 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3085 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3086 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS] 3087 case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS] 3088 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3089 } 3090 3091 return BuildPredefinedExpr(Loc, IT); 3092 } 3093 3094 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3095 SmallString<16> CharBuffer; 3096 bool Invalid = false; 3097 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3098 if (Invalid) 3099 return ExprError(); 3100 3101 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3102 PP, Tok.getKind()); 3103 if (Literal.hadError()) 3104 return ExprError(); 3105 3106 QualType Ty; 3107 if (Literal.isWide()) 3108 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3109 else if (Literal.isUTF8() && getLangOpts().Char8) 3110 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3111 else if (Literal.isUTF16()) 3112 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3113 else if (Literal.isUTF32()) 3114 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3115 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3116 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3117 else 3118 Ty = Context.CharTy; // 'x' -> char in C++ 3119 3120 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3121 if (Literal.isWide()) 3122 Kind = CharacterLiteral::Wide; 3123 else if (Literal.isUTF16()) 3124 Kind = CharacterLiteral::UTF16; 3125 else if (Literal.isUTF32()) 3126 Kind = CharacterLiteral::UTF32; 3127 else if (Literal.isUTF8()) 3128 Kind = CharacterLiteral::UTF8; 3129 3130 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3131 Tok.getLocation()); 3132 3133 if (Literal.getUDSuffix().empty()) 3134 return Lit; 3135 3136 // We're building a user-defined literal. 3137 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3138 SourceLocation UDSuffixLoc = 3139 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3140 3141 // Make sure we're allowed user-defined literals here. 3142 if (!UDLScope) 3143 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3144 3145 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3146 // operator "" X (ch) 3147 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3148 Lit, Tok.getLocation()); 3149 } 3150 3151 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3152 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3153 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3154 Context.IntTy, Loc); 3155 } 3156 3157 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3158 QualType Ty, SourceLocation Loc) { 3159 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3160 3161 using llvm::APFloat; 3162 APFloat Val(Format); 3163 3164 APFloat::opStatus result = Literal.GetFloatValue(Val); 3165 3166 // Overflow is always an error, but underflow is only an error if 3167 // we underflowed to zero (APFloat reports denormals as underflow). 3168 if ((result & APFloat::opOverflow) || 3169 ((result & APFloat::opUnderflow) && Val.isZero())) { 3170 unsigned diagnostic; 3171 SmallString<20> buffer; 3172 if (result & APFloat::opOverflow) { 3173 diagnostic = diag::warn_float_overflow; 3174 APFloat::getLargest(Format).toString(buffer); 3175 } else { 3176 diagnostic = diag::warn_float_underflow; 3177 APFloat::getSmallest(Format).toString(buffer); 3178 } 3179 3180 S.Diag(Loc, diagnostic) 3181 << Ty 3182 << StringRef(buffer.data(), buffer.size()); 3183 } 3184 3185 bool isExact = (result == APFloat::opOK); 3186 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3187 } 3188 3189 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3190 assert(E && "Invalid expression"); 3191 3192 if (E->isValueDependent()) 3193 return false; 3194 3195 QualType QT = E->getType(); 3196 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3197 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3198 return true; 3199 } 3200 3201 llvm::APSInt ValueAPS; 3202 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3203 3204 if (R.isInvalid()) 3205 return true; 3206 3207 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3208 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3209 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3210 << ValueAPS.toString(10) << ValueIsPositive; 3211 return true; 3212 } 3213 3214 return false; 3215 } 3216 3217 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3218 // Fast path for a single digit (which is quite common). A single digit 3219 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3220 if (Tok.getLength() == 1) { 3221 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3222 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3223 } 3224 3225 SmallString<128> SpellingBuffer; 3226 // NumericLiteralParser wants to overread by one character. Add padding to 3227 // the buffer in case the token is copied to the buffer. If getSpelling() 3228 // returns a StringRef to the memory buffer, it should have a null char at 3229 // the EOF, so it is also safe. 3230 SpellingBuffer.resize(Tok.getLength() + 1); 3231 3232 // Get the spelling of the token, which eliminates trigraphs, etc. 3233 bool Invalid = false; 3234 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3235 if (Invalid) 3236 return ExprError(); 3237 3238 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3239 if (Literal.hadError) 3240 return ExprError(); 3241 3242 if (Literal.hasUDSuffix()) { 3243 // We're building a user-defined literal. 3244 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3245 SourceLocation UDSuffixLoc = 3246 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3247 3248 // Make sure we're allowed user-defined literals here. 3249 if (!UDLScope) 3250 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3251 3252 QualType CookedTy; 3253 if (Literal.isFloatingLiteral()) { 3254 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3255 // long double, the literal is treated as a call of the form 3256 // operator "" X (f L) 3257 CookedTy = Context.LongDoubleTy; 3258 } else { 3259 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3260 // unsigned long long, the literal is treated as a call of the form 3261 // operator "" X (n ULL) 3262 CookedTy = Context.UnsignedLongLongTy; 3263 } 3264 3265 DeclarationName OpName = 3266 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3267 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3268 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3269 3270 SourceLocation TokLoc = Tok.getLocation(); 3271 3272 // Perform literal operator lookup to determine if we're building a raw 3273 // literal or a cooked one. 3274 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3275 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3276 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3277 /*AllowStringTemplate*/ false, 3278 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3279 case LOLR_ErrorNoDiagnostic: 3280 // Lookup failure for imaginary constants isn't fatal, there's still the 3281 // GNU extension producing _Complex types. 3282 break; 3283 case LOLR_Error: 3284 return ExprError(); 3285 case LOLR_Cooked: { 3286 Expr *Lit; 3287 if (Literal.isFloatingLiteral()) { 3288 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3289 } else { 3290 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3291 if (Literal.GetIntegerValue(ResultVal)) 3292 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3293 << /* Unsigned */ 1; 3294 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3295 Tok.getLocation()); 3296 } 3297 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3298 } 3299 3300 case LOLR_Raw: { 3301 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3302 // literal is treated as a call of the form 3303 // operator "" X ("n") 3304 unsigned Length = Literal.getUDSuffixOffset(); 3305 QualType StrTy = Context.getConstantArrayType( 3306 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3307 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3308 Expr *Lit = StringLiteral::Create( 3309 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3310 /*Pascal*/false, StrTy, &TokLoc, 1); 3311 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3312 } 3313 3314 case LOLR_Template: { 3315 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3316 // template), L is treated as a call fo the form 3317 // operator "" X <'c1', 'c2', ... 'ck'>() 3318 // where n is the source character sequence c1 c2 ... ck. 3319 TemplateArgumentListInfo ExplicitArgs; 3320 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3321 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3322 llvm::APSInt Value(CharBits, CharIsUnsigned); 3323 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3324 Value = TokSpelling[I]; 3325 TemplateArgument Arg(Context, Value, Context.CharTy); 3326 TemplateArgumentLocInfo ArgInfo; 3327 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3328 } 3329 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3330 &ExplicitArgs); 3331 } 3332 case LOLR_StringTemplate: 3333 llvm_unreachable("unexpected literal operator lookup result"); 3334 } 3335 } 3336 3337 Expr *Res; 3338 3339 if (Literal.isFixedPointLiteral()) { 3340 QualType Ty; 3341 3342 if (Literal.isAccum) { 3343 if (Literal.isHalf) { 3344 Ty = Context.ShortAccumTy; 3345 } else if (Literal.isLong) { 3346 Ty = Context.LongAccumTy; 3347 } else { 3348 Ty = Context.AccumTy; 3349 } 3350 } else if (Literal.isFract) { 3351 if (Literal.isHalf) { 3352 Ty = Context.ShortFractTy; 3353 } else if (Literal.isLong) { 3354 Ty = Context.LongFractTy; 3355 } else { 3356 Ty = Context.FractTy; 3357 } 3358 } 3359 3360 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3361 3362 bool isSigned = !Literal.isUnsigned; 3363 unsigned scale = Context.getFixedPointScale(Ty); 3364 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3365 3366 llvm::APInt Val(bit_width, 0, isSigned); 3367 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3368 bool ValIsZero = Val.isNullValue() && !Overflowed; 3369 3370 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3371 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3372 // Clause 6.4.4 - The value of a constant shall be in the range of 3373 // representable values for its type, with exception for constants of a 3374 // fract type with a value of exactly 1; such a constant shall denote 3375 // the maximal value for the type. 3376 --Val; 3377 else if (Val.ugt(MaxVal) || Overflowed) 3378 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3379 3380 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3381 Tok.getLocation(), scale); 3382 } else if (Literal.isFloatingLiteral()) { 3383 QualType Ty; 3384 if (Literal.isHalf){ 3385 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3386 Ty = Context.HalfTy; 3387 else { 3388 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3389 return ExprError(); 3390 } 3391 } else if (Literal.isFloat) 3392 Ty = Context.FloatTy; 3393 else if (Literal.isLong) 3394 Ty = Context.LongDoubleTy; 3395 else if (Literal.isFloat16) 3396 Ty = Context.Float16Ty; 3397 else if (Literal.isFloat128) 3398 Ty = Context.Float128Ty; 3399 else 3400 Ty = Context.DoubleTy; 3401 3402 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3403 3404 if (Ty == Context.DoubleTy) { 3405 if (getLangOpts().SinglePrecisionConstants) { 3406 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3407 if (BTy->getKind() != BuiltinType::Float) { 3408 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3409 } 3410 } else if (getLangOpts().OpenCL && 3411 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3412 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3413 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3414 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3415 } 3416 } 3417 } else if (!Literal.isIntegerLiteral()) { 3418 return ExprError(); 3419 } else { 3420 QualType Ty; 3421 3422 // 'long long' is a C99 or C++11 feature. 3423 if (!getLangOpts().C99 && Literal.isLongLong) { 3424 if (getLangOpts().CPlusPlus) 3425 Diag(Tok.getLocation(), 3426 getLangOpts().CPlusPlus11 ? 3427 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3428 else 3429 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3430 } 3431 3432 // Get the value in the widest-possible width. 3433 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3434 llvm::APInt ResultVal(MaxWidth, 0); 3435 3436 if (Literal.GetIntegerValue(ResultVal)) { 3437 // If this value didn't fit into uintmax_t, error and force to ull. 3438 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3439 << /* Unsigned */ 1; 3440 Ty = Context.UnsignedLongLongTy; 3441 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3442 "long long is not intmax_t?"); 3443 } else { 3444 // If this value fits into a ULL, try to figure out what else it fits into 3445 // according to the rules of C99 6.4.4.1p5. 3446 3447 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3448 // be an unsigned int. 3449 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3450 3451 // Check from smallest to largest, picking the smallest type we can. 3452 unsigned Width = 0; 3453 3454 // Microsoft specific integer suffixes are explicitly sized. 3455 if (Literal.MicrosoftInteger) { 3456 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3457 Width = 8; 3458 Ty = Context.CharTy; 3459 } else { 3460 Width = Literal.MicrosoftInteger; 3461 Ty = Context.getIntTypeForBitwidth(Width, 3462 /*Signed=*/!Literal.isUnsigned); 3463 } 3464 } 3465 3466 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3467 // Are int/unsigned possibilities? 3468 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3469 3470 // Does it fit in a unsigned int? 3471 if (ResultVal.isIntN(IntSize)) { 3472 // Does it fit in a signed int? 3473 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3474 Ty = Context.IntTy; 3475 else if (AllowUnsigned) 3476 Ty = Context.UnsignedIntTy; 3477 Width = IntSize; 3478 } 3479 } 3480 3481 // Are long/unsigned long possibilities? 3482 if (Ty.isNull() && !Literal.isLongLong) { 3483 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3484 3485 // Does it fit in a unsigned long? 3486 if (ResultVal.isIntN(LongSize)) { 3487 // Does it fit in a signed long? 3488 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3489 Ty = Context.LongTy; 3490 else if (AllowUnsigned) 3491 Ty = Context.UnsignedLongTy; 3492 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3493 // is compatible. 3494 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3495 const unsigned LongLongSize = 3496 Context.getTargetInfo().getLongLongWidth(); 3497 Diag(Tok.getLocation(), 3498 getLangOpts().CPlusPlus 3499 ? Literal.isLong 3500 ? diag::warn_old_implicitly_unsigned_long_cxx 3501 : /*C++98 UB*/ diag:: 3502 ext_old_implicitly_unsigned_long_cxx 3503 : diag::warn_old_implicitly_unsigned_long) 3504 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3505 : /*will be ill-formed*/ 1); 3506 Ty = Context.UnsignedLongTy; 3507 } 3508 Width = LongSize; 3509 } 3510 } 3511 3512 // Check long long if needed. 3513 if (Ty.isNull()) { 3514 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3515 3516 // Does it fit in a unsigned long long? 3517 if (ResultVal.isIntN(LongLongSize)) { 3518 // Does it fit in a signed long long? 3519 // To be compatible with MSVC, hex integer literals ending with the 3520 // LL or i64 suffix are always signed in Microsoft mode. 3521 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3522 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3523 Ty = Context.LongLongTy; 3524 else if (AllowUnsigned) 3525 Ty = Context.UnsignedLongLongTy; 3526 Width = LongLongSize; 3527 } 3528 } 3529 3530 // If we still couldn't decide a type, we probably have something that 3531 // does not fit in a signed long long, but has no U suffix. 3532 if (Ty.isNull()) { 3533 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3534 Ty = Context.UnsignedLongLongTy; 3535 Width = Context.getTargetInfo().getLongLongWidth(); 3536 } 3537 3538 if (ResultVal.getBitWidth() != Width) 3539 ResultVal = ResultVal.trunc(Width); 3540 } 3541 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3542 } 3543 3544 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3545 if (Literal.isImaginary) { 3546 Res = new (Context) ImaginaryLiteral(Res, 3547 Context.getComplexType(Res->getType())); 3548 3549 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3550 } 3551 return Res; 3552 } 3553 3554 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3555 assert(E && "ActOnParenExpr() missing expr"); 3556 return new (Context) ParenExpr(L, R, E); 3557 } 3558 3559 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3560 SourceLocation Loc, 3561 SourceRange ArgRange) { 3562 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3563 // scalar or vector data type argument..." 3564 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3565 // type (C99 6.2.5p18) or void. 3566 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3567 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3568 << T << ArgRange; 3569 return true; 3570 } 3571 3572 assert((T->isVoidType() || !T->isIncompleteType()) && 3573 "Scalar types should always be complete"); 3574 return false; 3575 } 3576 3577 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3578 SourceLocation Loc, 3579 SourceRange ArgRange, 3580 UnaryExprOrTypeTrait TraitKind) { 3581 // Invalid types must be hard errors for SFINAE in C++. 3582 if (S.LangOpts.CPlusPlus) 3583 return true; 3584 3585 // C99 6.5.3.4p1: 3586 if (T->isFunctionType() && 3587 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3588 // sizeof(function)/alignof(function) is allowed as an extension. 3589 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3590 << TraitKind << ArgRange; 3591 return false; 3592 } 3593 3594 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3595 // this is an error (OpenCL v1.1 s6.3.k) 3596 if (T->isVoidType()) { 3597 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3598 : diag::ext_sizeof_alignof_void_type; 3599 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3600 return false; 3601 } 3602 3603 return true; 3604 } 3605 3606 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3607 SourceLocation Loc, 3608 SourceRange ArgRange, 3609 UnaryExprOrTypeTrait TraitKind) { 3610 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3611 // runtime doesn't allow it. 3612 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3613 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3614 << T << (TraitKind == UETT_SizeOf) 3615 << ArgRange; 3616 return true; 3617 } 3618 3619 return false; 3620 } 3621 3622 /// Check whether E is a pointer from a decayed array type (the decayed 3623 /// pointer type is equal to T) and emit a warning if it is. 3624 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3625 Expr *E) { 3626 // Don't warn if the operation changed the type. 3627 if (T != E->getType()) 3628 return; 3629 3630 // Now look for array decays. 3631 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3632 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3633 return; 3634 3635 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3636 << ICE->getType() 3637 << ICE->getSubExpr()->getType(); 3638 } 3639 3640 /// Check the constraints on expression operands to unary type expression 3641 /// and type traits. 3642 /// 3643 /// Completes any types necessary and validates the constraints on the operand 3644 /// expression. The logic mostly mirrors the type-based overload, but may modify 3645 /// the expression as it completes the type for that expression through template 3646 /// instantiation, etc. 3647 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3648 UnaryExprOrTypeTrait ExprKind) { 3649 QualType ExprTy = E->getType(); 3650 assert(!ExprTy->isReferenceType()); 3651 3652 if (ExprKind == UETT_VecStep) 3653 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3654 E->getSourceRange()); 3655 3656 // Whitelist some types as extensions 3657 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3658 E->getSourceRange(), ExprKind)) 3659 return false; 3660 3661 // 'alignof' applied to an expression only requires the base element type of 3662 // the expression to be complete. 'sizeof' requires the expression's type to 3663 // be complete (and will attempt to complete it if it's an array of unknown 3664 // bound). 3665 if (ExprKind == UETT_AlignOf) { 3666 if (RequireCompleteType(E->getExprLoc(), 3667 Context.getBaseElementType(E->getType()), 3668 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3669 E->getSourceRange())) 3670 return true; 3671 } else { 3672 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3673 ExprKind, E->getSourceRange())) 3674 return true; 3675 } 3676 3677 // Completing the expression's type may have changed it. 3678 ExprTy = E->getType(); 3679 assert(!ExprTy->isReferenceType()); 3680 3681 if (ExprTy->isFunctionType()) { 3682 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3683 << ExprKind << E->getSourceRange(); 3684 return true; 3685 } 3686 3687 // The operand for sizeof and alignof is in an unevaluated expression context, 3688 // so side effects could result in unintended consequences. 3689 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3690 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3691 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3692 3693 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3694 E->getSourceRange(), ExprKind)) 3695 return true; 3696 3697 if (ExprKind == UETT_SizeOf) { 3698 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3699 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3700 QualType OType = PVD->getOriginalType(); 3701 QualType Type = PVD->getType(); 3702 if (Type->isPointerType() && OType->isArrayType()) { 3703 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3704 << Type << OType; 3705 Diag(PVD->getLocation(), diag::note_declared_at); 3706 } 3707 } 3708 } 3709 3710 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3711 // decays into a pointer and returns an unintended result. This is most 3712 // likely a typo for "sizeof(array) op x". 3713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3714 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3715 BO->getLHS()); 3716 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3717 BO->getRHS()); 3718 } 3719 } 3720 3721 return false; 3722 } 3723 3724 /// Check the constraints on operands to unary expression and type 3725 /// traits. 3726 /// 3727 /// This will complete any types necessary, and validate the various constraints 3728 /// on those operands. 3729 /// 3730 /// The UsualUnaryConversions() function is *not* called by this routine. 3731 /// C99 6.3.2.1p[2-4] all state: 3732 /// Except when it is the operand of the sizeof operator ... 3733 /// 3734 /// C++ [expr.sizeof]p4 3735 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3736 /// standard conversions are not applied to the operand of sizeof. 3737 /// 3738 /// This policy is followed for all of the unary trait expressions. 3739 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3740 SourceLocation OpLoc, 3741 SourceRange ExprRange, 3742 UnaryExprOrTypeTrait ExprKind) { 3743 if (ExprType->isDependentType()) 3744 return false; 3745 3746 // C++ [expr.sizeof]p2: 3747 // When applied to a reference or a reference type, the result 3748 // is the size of the referenced type. 3749 // C++11 [expr.alignof]p3: 3750 // When alignof is applied to a reference type, the result 3751 // shall be the alignment of the referenced type. 3752 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3753 ExprType = Ref->getPointeeType(); 3754 3755 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3756 // When alignof or _Alignof is applied to an array type, the result 3757 // is the alignment of the element type. 3758 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3759 ExprType = Context.getBaseElementType(ExprType); 3760 3761 if (ExprKind == UETT_VecStep) 3762 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3763 3764 // Whitelist some types as extensions 3765 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3766 ExprKind)) 3767 return false; 3768 3769 if (RequireCompleteType(OpLoc, ExprType, 3770 diag::err_sizeof_alignof_incomplete_type, 3771 ExprKind, ExprRange)) 3772 return true; 3773 3774 if (ExprType->isFunctionType()) { 3775 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3776 << ExprKind << ExprRange; 3777 return true; 3778 } 3779 3780 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3781 ExprKind)) 3782 return true; 3783 3784 return false; 3785 } 3786 3787 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3788 E = E->IgnoreParens(); 3789 3790 // Cannot know anything else if the expression is dependent. 3791 if (E->isTypeDependent()) 3792 return false; 3793 3794 if (E->getObjectKind() == OK_BitField) { 3795 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3796 << 1 << E->getSourceRange(); 3797 return true; 3798 } 3799 3800 ValueDecl *D = nullptr; 3801 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3802 D = DRE->getDecl(); 3803 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3804 D = ME->getMemberDecl(); 3805 } 3806 3807 // If it's a field, require the containing struct to have a 3808 // complete definition so that we can compute the layout. 3809 // 3810 // This can happen in C++11 onwards, either by naming the member 3811 // in a way that is not transformed into a member access expression 3812 // (in an unevaluated operand, for instance), or by naming the member 3813 // in a trailing-return-type. 3814 // 3815 // For the record, since __alignof__ on expressions is a GCC 3816 // extension, GCC seems to permit this but always gives the 3817 // nonsensical answer 0. 3818 // 3819 // We don't really need the layout here --- we could instead just 3820 // directly check for all the appropriate alignment-lowing 3821 // attributes --- but that would require duplicating a lot of 3822 // logic that just isn't worth duplicating for such a marginal 3823 // use-case. 3824 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3825 // Fast path this check, since we at least know the record has a 3826 // definition if we can find a member of it. 3827 if (!FD->getParent()->isCompleteDefinition()) { 3828 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3829 << E->getSourceRange(); 3830 return true; 3831 } 3832 3833 // Otherwise, if it's a field, and the field doesn't have 3834 // reference type, then it must have a complete type (or be a 3835 // flexible array member, which we explicitly want to 3836 // white-list anyway), which makes the following checks trivial. 3837 if (!FD->getType()->isReferenceType()) 3838 return false; 3839 } 3840 3841 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3842 } 3843 3844 bool Sema::CheckVecStepExpr(Expr *E) { 3845 E = E->IgnoreParens(); 3846 3847 // Cannot know anything else if the expression is dependent. 3848 if (E->isTypeDependent()) 3849 return false; 3850 3851 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3852 } 3853 3854 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3855 CapturingScopeInfo *CSI) { 3856 assert(T->isVariablyModifiedType()); 3857 assert(CSI != nullptr); 3858 3859 // We're going to walk down into the type and look for VLA expressions. 3860 do { 3861 const Type *Ty = T.getTypePtr(); 3862 switch (Ty->getTypeClass()) { 3863 #define TYPE(Class, Base) 3864 #define ABSTRACT_TYPE(Class, Base) 3865 #define NON_CANONICAL_TYPE(Class, Base) 3866 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3867 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3868 #include "clang/AST/TypeNodes.def" 3869 T = QualType(); 3870 break; 3871 // These types are never variably-modified. 3872 case Type::Builtin: 3873 case Type::Complex: 3874 case Type::Vector: 3875 case Type::ExtVector: 3876 case Type::Record: 3877 case Type::Enum: 3878 case Type::Elaborated: 3879 case Type::TemplateSpecialization: 3880 case Type::ObjCObject: 3881 case Type::ObjCInterface: 3882 case Type::ObjCObjectPointer: 3883 case Type::ObjCTypeParam: 3884 case Type::Pipe: 3885 llvm_unreachable("type class is never variably-modified!"); 3886 case Type::Adjusted: 3887 T = cast<AdjustedType>(Ty)->getOriginalType(); 3888 break; 3889 case Type::Decayed: 3890 T = cast<DecayedType>(Ty)->getPointeeType(); 3891 break; 3892 case Type::Pointer: 3893 T = cast<PointerType>(Ty)->getPointeeType(); 3894 break; 3895 case Type::BlockPointer: 3896 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3897 break; 3898 case Type::LValueReference: 3899 case Type::RValueReference: 3900 T = cast<ReferenceType>(Ty)->getPointeeType(); 3901 break; 3902 case Type::MemberPointer: 3903 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3904 break; 3905 case Type::ConstantArray: 3906 case Type::IncompleteArray: 3907 // Losing element qualification here is fine. 3908 T = cast<ArrayType>(Ty)->getElementType(); 3909 break; 3910 case Type::VariableArray: { 3911 // Losing element qualification here is fine. 3912 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3913 3914 // Unknown size indication requires no size computation. 3915 // Otherwise, evaluate and record it. 3916 if (auto Size = VAT->getSizeExpr()) { 3917 if (!CSI->isVLATypeCaptured(VAT)) { 3918 RecordDecl *CapRecord = nullptr; 3919 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3920 CapRecord = LSI->Lambda; 3921 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3922 CapRecord = CRSI->TheRecordDecl; 3923 } 3924 if (CapRecord) { 3925 auto ExprLoc = Size->getExprLoc(); 3926 auto SizeType = Context.getSizeType(); 3927 // Build the non-static data member. 3928 auto Field = 3929 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3930 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3931 /*BW*/ nullptr, /*Mutable*/ false, 3932 /*InitStyle*/ ICIS_NoInit); 3933 Field->setImplicit(true); 3934 Field->setAccess(AS_private); 3935 Field->setCapturedVLAType(VAT); 3936 CapRecord->addDecl(Field); 3937 3938 CSI->addVLATypeCapture(ExprLoc, SizeType); 3939 } 3940 } 3941 } 3942 T = VAT->getElementType(); 3943 break; 3944 } 3945 case Type::FunctionProto: 3946 case Type::FunctionNoProto: 3947 T = cast<FunctionType>(Ty)->getReturnType(); 3948 break; 3949 case Type::Paren: 3950 case Type::TypeOf: 3951 case Type::UnaryTransform: 3952 case Type::Attributed: 3953 case Type::SubstTemplateTypeParm: 3954 case Type::PackExpansion: 3955 // Keep walking after single level desugaring. 3956 T = T.getSingleStepDesugaredType(Context); 3957 break; 3958 case Type::Typedef: 3959 T = cast<TypedefType>(Ty)->desugar(); 3960 break; 3961 case Type::Decltype: 3962 T = cast<DecltypeType>(Ty)->desugar(); 3963 break; 3964 case Type::Auto: 3965 case Type::DeducedTemplateSpecialization: 3966 T = cast<DeducedType>(Ty)->getDeducedType(); 3967 break; 3968 case Type::TypeOfExpr: 3969 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3970 break; 3971 case Type::Atomic: 3972 T = cast<AtomicType>(Ty)->getValueType(); 3973 break; 3974 } 3975 } while (!T.isNull() && T->isVariablyModifiedType()); 3976 } 3977 3978 /// Build a sizeof or alignof expression given a type operand. 3979 ExprResult 3980 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3981 SourceLocation OpLoc, 3982 UnaryExprOrTypeTrait ExprKind, 3983 SourceRange R) { 3984 if (!TInfo) 3985 return ExprError(); 3986 3987 QualType T = TInfo->getType(); 3988 3989 if (!T->isDependentType() && 3990 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3991 return ExprError(); 3992 3993 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3994 if (auto *TT = T->getAs<TypedefType>()) { 3995 for (auto I = FunctionScopes.rbegin(), 3996 E = std::prev(FunctionScopes.rend()); 3997 I != E; ++I) { 3998 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3999 if (CSI == nullptr) 4000 break; 4001 DeclContext *DC = nullptr; 4002 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4003 DC = LSI->CallOperator; 4004 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4005 DC = CRSI->TheCapturedDecl; 4006 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4007 DC = BSI->TheDecl; 4008 if (DC) { 4009 if (DC->containsDecl(TT->getDecl())) 4010 break; 4011 captureVariablyModifiedType(Context, T, CSI); 4012 } 4013 } 4014 } 4015 } 4016 4017 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4018 return new (Context) UnaryExprOrTypeTraitExpr( 4019 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4020 } 4021 4022 /// Build a sizeof or alignof expression given an expression 4023 /// operand. 4024 ExprResult 4025 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4026 UnaryExprOrTypeTrait ExprKind) { 4027 ExprResult PE = CheckPlaceholderExpr(E); 4028 if (PE.isInvalid()) 4029 return ExprError(); 4030 4031 E = PE.get(); 4032 4033 // Verify that the operand is valid. 4034 bool isInvalid = false; 4035 if (E->isTypeDependent()) { 4036 // Delay type-checking for type-dependent expressions. 4037 } else if (ExprKind == UETT_AlignOf) { 4038 isInvalid = CheckAlignOfExpr(*this, E); 4039 } else if (ExprKind == UETT_VecStep) { 4040 isInvalid = CheckVecStepExpr(E); 4041 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4042 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4043 isInvalid = true; 4044 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4045 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4046 isInvalid = true; 4047 } else { 4048 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4049 } 4050 4051 if (isInvalid) 4052 return ExprError(); 4053 4054 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4055 PE = TransformToPotentiallyEvaluated(E); 4056 if (PE.isInvalid()) return ExprError(); 4057 E = PE.get(); 4058 } 4059 4060 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4061 return new (Context) UnaryExprOrTypeTraitExpr( 4062 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4063 } 4064 4065 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4066 /// expr and the same for @c alignof and @c __alignof 4067 /// Note that the ArgRange is invalid if isType is false. 4068 ExprResult 4069 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4070 UnaryExprOrTypeTrait ExprKind, bool IsType, 4071 void *TyOrEx, SourceRange ArgRange) { 4072 // If error parsing type, ignore. 4073 if (!TyOrEx) return ExprError(); 4074 4075 if (IsType) { 4076 TypeSourceInfo *TInfo; 4077 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4078 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4079 } 4080 4081 Expr *ArgEx = (Expr *)TyOrEx; 4082 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4083 return Result; 4084 } 4085 4086 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4087 bool IsReal) { 4088 if (V.get()->isTypeDependent()) 4089 return S.Context.DependentTy; 4090 4091 // _Real and _Imag are only l-values for normal l-values. 4092 if (V.get()->getObjectKind() != OK_Ordinary) { 4093 V = S.DefaultLvalueConversion(V.get()); 4094 if (V.isInvalid()) 4095 return QualType(); 4096 } 4097 4098 // These operators return the element type of a complex type. 4099 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4100 return CT->getElementType(); 4101 4102 // Otherwise they pass through real integer and floating point types here. 4103 if (V.get()->getType()->isArithmeticType()) 4104 return V.get()->getType(); 4105 4106 // Test for placeholders. 4107 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4108 if (PR.isInvalid()) return QualType(); 4109 if (PR.get() != V.get()) { 4110 V = PR; 4111 return CheckRealImagOperand(S, V, Loc, IsReal); 4112 } 4113 4114 // Reject anything else. 4115 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4116 << (IsReal ? "__real" : "__imag"); 4117 return QualType(); 4118 } 4119 4120 4121 4122 ExprResult 4123 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4124 tok::TokenKind Kind, Expr *Input) { 4125 UnaryOperatorKind Opc; 4126 switch (Kind) { 4127 default: llvm_unreachable("Unknown unary op!"); 4128 case tok::plusplus: Opc = UO_PostInc; break; 4129 case tok::minusminus: Opc = UO_PostDec; break; 4130 } 4131 4132 // Since this might is a postfix expression, get rid of ParenListExprs. 4133 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4134 if (Result.isInvalid()) return ExprError(); 4135 Input = Result.get(); 4136 4137 return BuildUnaryOp(S, OpLoc, Opc, Input); 4138 } 4139 4140 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4141 /// 4142 /// \return true on error 4143 static bool checkArithmeticOnObjCPointer(Sema &S, 4144 SourceLocation opLoc, 4145 Expr *op) { 4146 assert(op->getType()->isObjCObjectPointerType()); 4147 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4148 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4149 return false; 4150 4151 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4152 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4153 << op->getSourceRange(); 4154 return true; 4155 } 4156 4157 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4158 auto *BaseNoParens = Base->IgnoreParens(); 4159 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4160 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4161 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4162 } 4163 4164 ExprResult 4165 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4166 Expr *idx, SourceLocation rbLoc) { 4167 if (base && !base->getType().isNull() && 4168 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4169 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4170 /*Length=*/nullptr, rbLoc); 4171 4172 // Since this might be a postfix expression, get rid of ParenListExprs. 4173 if (isa<ParenListExpr>(base)) { 4174 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4175 if (result.isInvalid()) return ExprError(); 4176 base = result.get(); 4177 } 4178 4179 // Handle any non-overload placeholder types in the base and index 4180 // expressions. We can't handle overloads here because the other 4181 // operand might be an overloadable type, in which case the overload 4182 // resolution for the operator overload should get the first crack 4183 // at the overload. 4184 bool IsMSPropertySubscript = false; 4185 if (base->getType()->isNonOverloadPlaceholderType()) { 4186 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4187 if (!IsMSPropertySubscript) { 4188 ExprResult result = CheckPlaceholderExpr(base); 4189 if (result.isInvalid()) 4190 return ExprError(); 4191 base = result.get(); 4192 } 4193 } 4194 if (idx->getType()->isNonOverloadPlaceholderType()) { 4195 ExprResult result = CheckPlaceholderExpr(idx); 4196 if (result.isInvalid()) return ExprError(); 4197 idx = result.get(); 4198 } 4199 4200 // Build an unanalyzed expression if either operand is type-dependent. 4201 if (getLangOpts().CPlusPlus && 4202 (base->isTypeDependent() || idx->isTypeDependent())) { 4203 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4204 VK_LValue, OK_Ordinary, rbLoc); 4205 } 4206 4207 // MSDN, property (C++) 4208 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4209 // This attribute can also be used in the declaration of an empty array in a 4210 // class or structure definition. For example: 4211 // __declspec(property(get=GetX, put=PutX)) int x[]; 4212 // The above statement indicates that x[] can be used with one or more array 4213 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4214 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4215 if (IsMSPropertySubscript) { 4216 // Build MS property subscript expression if base is MS property reference 4217 // or MS property subscript. 4218 return new (Context) MSPropertySubscriptExpr( 4219 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4220 } 4221 4222 // Use C++ overloaded-operator rules if either operand has record 4223 // type. The spec says to do this if either type is *overloadable*, 4224 // but enum types can't declare subscript operators or conversion 4225 // operators, so there's nothing interesting for overload resolution 4226 // to do if there aren't any record types involved. 4227 // 4228 // ObjC pointers have their own subscripting logic that is not tied 4229 // to overload resolution and so should not take this path. 4230 if (getLangOpts().CPlusPlus && 4231 (base->getType()->isRecordType() || 4232 (!base->getType()->isObjCObjectPointerType() && 4233 idx->getType()->isRecordType()))) { 4234 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4235 } 4236 4237 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4238 } 4239 4240 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4241 Expr *LowerBound, 4242 SourceLocation ColonLoc, Expr *Length, 4243 SourceLocation RBLoc) { 4244 if (Base->getType()->isPlaceholderType() && 4245 !Base->getType()->isSpecificPlaceholderType( 4246 BuiltinType::OMPArraySection)) { 4247 ExprResult Result = CheckPlaceholderExpr(Base); 4248 if (Result.isInvalid()) 4249 return ExprError(); 4250 Base = Result.get(); 4251 } 4252 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4253 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4254 if (Result.isInvalid()) 4255 return ExprError(); 4256 Result = DefaultLvalueConversion(Result.get()); 4257 if (Result.isInvalid()) 4258 return ExprError(); 4259 LowerBound = Result.get(); 4260 } 4261 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4262 ExprResult Result = CheckPlaceholderExpr(Length); 4263 if (Result.isInvalid()) 4264 return ExprError(); 4265 Result = DefaultLvalueConversion(Result.get()); 4266 if (Result.isInvalid()) 4267 return ExprError(); 4268 Length = Result.get(); 4269 } 4270 4271 // Build an unanalyzed expression if either operand is type-dependent. 4272 if (Base->isTypeDependent() || 4273 (LowerBound && 4274 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4275 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4276 return new (Context) 4277 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4278 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4279 } 4280 4281 // Perform default conversions. 4282 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4283 QualType ResultTy; 4284 if (OriginalTy->isAnyPointerType()) { 4285 ResultTy = OriginalTy->getPointeeType(); 4286 } else if (OriginalTy->isArrayType()) { 4287 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4288 } else { 4289 return ExprError( 4290 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4291 << Base->getSourceRange()); 4292 } 4293 // C99 6.5.2.1p1 4294 if (LowerBound) { 4295 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4296 LowerBound); 4297 if (Res.isInvalid()) 4298 return ExprError(Diag(LowerBound->getExprLoc(), 4299 diag::err_omp_typecheck_section_not_integer) 4300 << 0 << LowerBound->getSourceRange()); 4301 LowerBound = Res.get(); 4302 4303 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4304 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4305 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4306 << 0 << LowerBound->getSourceRange(); 4307 } 4308 if (Length) { 4309 auto Res = 4310 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4311 if (Res.isInvalid()) 4312 return ExprError(Diag(Length->getExprLoc(), 4313 diag::err_omp_typecheck_section_not_integer) 4314 << 1 << Length->getSourceRange()); 4315 Length = Res.get(); 4316 4317 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4318 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4319 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4320 << 1 << Length->getSourceRange(); 4321 } 4322 4323 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4324 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4325 // type. Note that functions are not objects, and that (in C99 parlance) 4326 // incomplete types are not object types. 4327 if (ResultTy->isFunctionType()) { 4328 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4329 << ResultTy << Base->getSourceRange(); 4330 return ExprError(); 4331 } 4332 4333 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4334 diag::err_omp_section_incomplete_type, Base)) 4335 return ExprError(); 4336 4337 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4338 llvm::APSInt LowerBoundValue; 4339 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4340 // OpenMP 4.5, [2.4 Array Sections] 4341 // The array section must be a subset of the original array. 4342 if (LowerBoundValue.isNegative()) { 4343 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4344 << LowerBound->getSourceRange(); 4345 return ExprError(); 4346 } 4347 } 4348 } 4349 4350 if (Length) { 4351 llvm::APSInt LengthValue; 4352 if (Length->EvaluateAsInt(LengthValue, Context)) { 4353 // OpenMP 4.5, [2.4 Array Sections] 4354 // The length must evaluate to non-negative integers. 4355 if (LengthValue.isNegative()) { 4356 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4357 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4358 << Length->getSourceRange(); 4359 return ExprError(); 4360 } 4361 } 4362 } else if (ColonLoc.isValid() && 4363 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4364 !OriginalTy->isVariableArrayType()))) { 4365 // OpenMP 4.5, [2.4 Array Sections] 4366 // When the size of the array dimension is not known, the length must be 4367 // specified explicitly. 4368 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4369 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4370 return ExprError(); 4371 } 4372 4373 if (!Base->getType()->isSpecificPlaceholderType( 4374 BuiltinType::OMPArraySection)) { 4375 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4376 if (Result.isInvalid()) 4377 return ExprError(); 4378 Base = Result.get(); 4379 } 4380 return new (Context) 4381 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4382 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4383 } 4384 4385 ExprResult 4386 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4387 Expr *Idx, SourceLocation RLoc) { 4388 Expr *LHSExp = Base; 4389 Expr *RHSExp = Idx; 4390 4391 ExprValueKind VK = VK_LValue; 4392 ExprObjectKind OK = OK_Ordinary; 4393 4394 // Per C++ core issue 1213, the result is an xvalue if either operand is 4395 // a non-lvalue array, and an lvalue otherwise. 4396 if (getLangOpts().CPlusPlus11) { 4397 for (auto *Op : {LHSExp, RHSExp}) { 4398 Op = Op->IgnoreImplicit(); 4399 if (Op->getType()->isArrayType() && !Op->isLValue()) 4400 VK = VK_XValue; 4401 } 4402 } 4403 4404 // Perform default conversions. 4405 if (!LHSExp->getType()->getAs<VectorType>()) { 4406 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4407 if (Result.isInvalid()) 4408 return ExprError(); 4409 LHSExp = Result.get(); 4410 } 4411 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4412 if (Result.isInvalid()) 4413 return ExprError(); 4414 RHSExp = Result.get(); 4415 4416 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4417 4418 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4419 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4420 // in the subscript position. As a result, we need to derive the array base 4421 // and index from the expression types. 4422 Expr *BaseExpr, *IndexExpr; 4423 QualType ResultType; 4424 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4425 BaseExpr = LHSExp; 4426 IndexExpr = RHSExp; 4427 ResultType = Context.DependentTy; 4428 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4429 BaseExpr = LHSExp; 4430 IndexExpr = RHSExp; 4431 ResultType = PTy->getPointeeType(); 4432 } else if (const ObjCObjectPointerType *PTy = 4433 LHSTy->getAs<ObjCObjectPointerType>()) { 4434 BaseExpr = LHSExp; 4435 IndexExpr = RHSExp; 4436 4437 // Use custom logic if this should be the pseudo-object subscript 4438 // expression. 4439 if (!LangOpts.isSubscriptPointerArithmetic()) 4440 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4441 nullptr); 4442 4443 ResultType = PTy->getPointeeType(); 4444 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4445 // Handle the uncommon case of "123[Ptr]". 4446 BaseExpr = RHSExp; 4447 IndexExpr = LHSExp; 4448 ResultType = PTy->getPointeeType(); 4449 } else if (const ObjCObjectPointerType *PTy = 4450 RHSTy->getAs<ObjCObjectPointerType>()) { 4451 // Handle the uncommon case of "123[Ptr]". 4452 BaseExpr = RHSExp; 4453 IndexExpr = LHSExp; 4454 ResultType = PTy->getPointeeType(); 4455 if (!LangOpts.isSubscriptPointerArithmetic()) { 4456 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4457 << ResultType << BaseExpr->getSourceRange(); 4458 return ExprError(); 4459 } 4460 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4461 BaseExpr = LHSExp; // vectors: V[123] 4462 IndexExpr = RHSExp; 4463 // We apply C++ DR1213 to vector subscripting too. 4464 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4465 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4466 if (Materialized.isInvalid()) 4467 return ExprError(); 4468 LHSExp = Materialized.get(); 4469 } 4470 VK = LHSExp->getValueKind(); 4471 if (VK != VK_RValue) 4472 OK = OK_VectorComponent; 4473 4474 ResultType = VTy->getElementType(); 4475 QualType BaseType = BaseExpr->getType(); 4476 Qualifiers BaseQuals = BaseType.getQualifiers(); 4477 Qualifiers MemberQuals = ResultType.getQualifiers(); 4478 Qualifiers Combined = BaseQuals + MemberQuals; 4479 if (Combined != MemberQuals) 4480 ResultType = Context.getQualifiedType(ResultType, Combined); 4481 } else if (LHSTy->isArrayType()) { 4482 // If we see an array that wasn't promoted by 4483 // DefaultFunctionArrayLvalueConversion, it must be an array that 4484 // wasn't promoted because of the C90 rule that doesn't 4485 // allow promoting non-lvalue arrays. Warn, then 4486 // force the promotion here. 4487 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4488 << LHSExp->getSourceRange(); 4489 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4490 CK_ArrayToPointerDecay).get(); 4491 LHSTy = LHSExp->getType(); 4492 4493 BaseExpr = LHSExp; 4494 IndexExpr = RHSExp; 4495 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4496 } else if (RHSTy->isArrayType()) { 4497 // Same as previous, except for 123[f().a] case 4498 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4499 << RHSExp->getSourceRange(); 4500 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4501 CK_ArrayToPointerDecay).get(); 4502 RHSTy = RHSExp->getType(); 4503 4504 BaseExpr = RHSExp; 4505 IndexExpr = LHSExp; 4506 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4507 } else { 4508 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4509 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4510 } 4511 // C99 6.5.2.1p1 4512 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4513 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4514 << IndexExpr->getSourceRange()); 4515 4516 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4517 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4518 && !IndexExpr->isTypeDependent()) 4519 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4520 4521 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4522 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4523 // type. Note that Functions are not objects, and that (in C99 parlance) 4524 // incomplete types are not object types. 4525 if (ResultType->isFunctionType()) { 4526 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4527 << ResultType << BaseExpr->getSourceRange(); 4528 return ExprError(); 4529 } 4530 4531 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4532 // GNU extension: subscripting on pointer to void 4533 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4534 << BaseExpr->getSourceRange(); 4535 4536 // C forbids expressions of unqualified void type from being l-values. 4537 // See IsCForbiddenLValueType. 4538 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4539 } else if (!ResultType->isDependentType() && 4540 RequireCompleteType(LLoc, ResultType, 4541 diag::err_subscript_incomplete_type, BaseExpr)) 4542 return ExprError(); 4543 4544 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4545 !ResultType.isCForbiddenLValueType()); 4546 4547 return new (Context) 4548 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4549 } 4550 4551 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4552 ParmVarDecl *Param) { 4553 if (Param->hasUnparsedDefaultArg()) { 4554 Diag(CallLoc, 4555 diag::err_use_of_default_argument_to_function_declared_later) << 4556 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4557 Diag(UnparsedDefaultArgLocs[Param], 4558 diag::note_default_argument_declared_here); 4559 return true; 4560 } 4561 4562 if (Param->hasUninstantiatedDefaultArg()) { 4563 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4564 4565 EnterExpressionEvaluationContext EvalContext( 4566 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4567 4568 // Instantiate the expression. 4569 // 4570 // FIXME: Pass in a correct Pattern argument, otherwise 4571 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4572 // 4573 // template<typename T> 4574 // struct A { 4575 // static int FooImpl(); 4576 // 4577 // template<typename Tp> 4578 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4579 // // template argument list [[T], [Tp]], should be [[Tp]]. 4580 // friend A<Tp> Foo(int a); 4581 // }; 4582 // 4583 // template<typename T> 4584 // A<T> Foo(int a = A<T>::FooImpl()); 4585 MultiLevelTemplateArgumentList MutiLevelArgList 4586 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4587 4588 InstantiatingTemplate Inst(*this, CallLoc, Param, 4589 MutiLevelArgList.getInnermost()); 4590 if (Inst.isInvalid()) 4591 return true; 4592 if (Inst.isAlreadyInstantiating()) { 4593 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4594 Param->setInvalidDecl(); 4595 return true; 4596 } 4597 4598 ExprResult Result; 4599 { 4600 // C++ [dcl.fct.default]p5: 4601 // The names in the [default argument] expression are bound, and 4602 // the semantic constraints are checked, at the point where the 4603 // default argument expression appears. 4604 ContextRAII SavedContext(*this, FD); 4605 LocalInstantiationScope Local(*this); 4606 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4607 /*DirectInit*/false); 4608 } 4609 if (Result.isInvalid()) 4610 return true; 4611 4612 // Check the expression as an initializer for the parameter. 4613 InitializedEntity Entity 4614 = InitializedEntity::InitializeParameter(Context, Param); 4615 InitializationKind Kind = InitializationKind::CreateCopy( 4616 Param->getLocation(), 4617 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4618 Expr *ResultE = Result.getAs<Expr>(); 4619 4620 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4621 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4622 if (Result.isInvalid()) 4623 return true; 4624 4625 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4626 Param->getOuterLocStart()); 4627 if (Result.isInvalid()) 4628 return true; 4629 4630 // Remember the instantiated default argument. 4631 Param->setDefaultArg(Result.getAs<Expr>()); 4632 if (ASTMutationListener *L = getASTMutationListener()) { 4633 L->DefaultArgumentInstantiated(Param); 4634 } 4635 } 4636 4637 // If the default argument expression is not set yet, we are building it now. 4638 if (!Param->hasInit()) { 4639 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4640 Param->setInvalidDecl(); 4641 return true; 4642 } 4643 4644 // If the default expression creates temporaries, we need to 4645 // push them to the current stack of expression temporaries so they'll 4646 // be properly destroyed. 4647 // FIXME: We should really be rebuilding the default argument with new 4648 // bound temporaries; see the comment in PR5810. 4649 // We don't need to do that with block decls, though, because 4650 // blocks in default argument expression can never capture anything. 4651 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4652 // Set the "needs cleanups" bit regardless of whether there are 4653 // any explicit objects. 4654 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4655 4656 // Append all the objects to the cleanup list. Right now, this 4657 // should always be a no-op, because blocks in default argument 4658 // expressions should never be able to capture anything. 4659 assert(!Init->getNumObjects() && 4660 "default argument expression has capturing blocks?"); 4661 } 4662 4663 // We already type-checked the argument, so we know it works. 4664 // Just mark all of the declarations in this potentially-evaluated expression 4665 // as being "referenced". 4666 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4667 /*SkipLocalVariables=*/true); 4668 return false; 4669 } 4670 4671 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4672 FunctionDecl *FD, ParmVarDecl *Param) { 4673 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4674 return ExprError(); 4675 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4676 } 4677 4678 Sema::VariadicCallType 4679 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4680 Expr *Fn) { 4681 if (Proto && Proto->isVariadic()) { 4682 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4683 return VariadicConstructor; 4684 else if (Fn && Fn->getType()->isBlockPointerType()) 4685 return VariadicBlock; 4686 else if (FDecl) { 4687 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4688 if (Method->isInstance()) 4689 return VariadicMethod; 4690 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4691 return VariadicMethod; 4692 return VariadicFunction; 4693 } 4694 return VariadicDoesNotApply; 4695 } 4696 4697 namespace { 4698 class FunctionCallCCC : public FunctionCallFilterCCC { 4699 public: 4700 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4701 unsigned NumArgs, MemberExpr *ME) 4702 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4703 FunctionName(FuncName) {} 4704 4705 bool ValidateCandidate(const TypoCorrection &candidate) override { 4706 if (!candidate.getCorrectionSpecifier() || 4707 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4708 return false; 4709 } 4710 4711 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4712 } 4713 4714 private: 4715 const IdentifierInfo *const FunctionName; 4716 }; 4717 } 4718 4719 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4720 FunctionDecl *FDecl, 4721 ArrayRef<Expr *> Args) { 4722 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4723 DeclarationName FuncName = FDecl->getDeclName(); 4724 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4725 4726 if (TypoCorrection Corrected = S.CorrectTypo( 4727 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4728 S.getScopeForContext(S.CurContext), nullptr, 4729 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4730 Args.size(), ME), 4731 Sema::CTK_ErrorRecovery)) { 4732 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4733 if (Corrected.isOverloaded()) { 4734 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4735 OverloadCandidateSet::iterator Best; 4736 for (NamedDecl *CD : Corrected) { 4737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4738 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4739 OCS); 4740 } 4741 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4742 case OR_Success: 4743 ND = Best->FoundDecl; 4744 Corrected.setCorrectionDecl(ND); 4745 break; 4746 default: 4747 break; 4748 } 4749 } 4750 ND = ND->getUnderlyingDecl(); 4751 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4752 return Corrected; 4753 } 4754 } 4755 return TypoCorrection(); 4756 } 4757 4758 /// ConvertArgumentsForCall - Converts the arguments specified in 4759 /// Args/NumArgs to the parameter types of the function FDecl with 4760 /// function prototype Proto. Call is the call expression itself, and 4761 /// Fn is the function expression. For a C++ member function, this 4762 /// routine does not attempt to convert the object argument. Returns 4763 /// true if the call is ill-formed. 4764 bool 4765 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4766 FunctionDecl *FDecl, 4767 const FunctionProtoType *Proto, 4768 ArrayRef<Expr *> Args, 4769 SourceLocation RParenLoc, 4770 bool IsExecConfig) { 4771 // Bail out early if calling a builtin with custom typechecking. 4772 if (FDecl) 4773 if (unsigned ID = FDecl->getBuiltinID()) 4774 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4775 return false; 4776 4777 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4778 // assignment, to the types of the corresponding parameter, ... 4779 unsigned NumParams = Proto->getNumParams(); 4780 bool Invalid = false; 4781 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4782 unsigned FnKind = Fn->getType()->isBlockPointerType() 4783 ? 1 /* block */ 4784 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4785 : 0 /* function */); 4786 4787 // If too few arguments are available (and we don't have default 4788 // arguments for the remaining parameters), don't make the call. 4789 if (Args.size() < NumParams) { 4790 if (Args.size() < MinArgs) { 4791 TypoCorrection TC; 4792 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4793 unsigned diag_id = 4794 MinArgs == NumParams && !Proto->isVariadic() 4795 ? diag::err_typecheck_call_too_few_args_suggest 4796 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4797 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4798 << static_cast<unsigned>(Args.size()) 4799 << TC.getCorrectionRange()); 4800 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4801 Diag(RParenLoc, 4802 MinArgs == NumParams && !Proto->isVariadic() 4803 ? diag::err_typecheck_call_too_few_args_one 4804 : diag::err_typecheck_call_too_few_args_at_least_one) 4805 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4806 else 4807 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4808 ? diag::err_typecheck_call_too_few_args 4809 : diag::err_typecheck_call_too_few_args_at_least) 4810 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4811 << Fn->getSourceRange(); 4812 4813 // Emit the location of the prototype. 4814 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4815 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4816 4817 return true; 4818 } 4819 Call->setNumArgs(Context, NumParams); 4820 } 4821 4822 // If too many are passed and not variadic, error on the extras and drop 4823 // them. 4824 if (Args.size() > NumParams) { 4825 if (!Proto->isVariadic()) { 4826 TypoCorrection TC; 4827 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4828 unsigned diag_id = 4829 MinArgs == NumParams && !Proto->isVariadic() 4830 ? diag::err_typecheck_call_too_many_args_suggest 4831 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4832 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4833 << static_cast<unsigned>(Args.size()) 4834 << TC.getCorrectionRange()); 4835 } else if (NumParams == 1 && FDecl && 4836 FDecl->getParamDecl(0)->getDeclName()) 4837 Diag(Args[NumParams]->getBeginLoc(), 4838 MinArgs == NumParams 4839 ? diag::err_typecheck_call_too_many_args_one 4840 : diag::err_typecheck_call_too_many_args_at_most_one) 4841 << FnKind << FDecl->getParamDecl(0) 4842 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4843 << SourceRange(Args[NumParams]->getBeginLoc(), 4844 Args.back()->getEndLoc()); 4845 else 4846 Diag(Args[NumParams]->getBeginLoc(), 4847 MinArgs == NumParams 4848 ? diag::err_typecheck_call_too_many_args 4849 : diag::err_typecheck_call_too_many_args_at_most) 4850 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4851 << Fn->getSourceRange() 4852 << SourceRange(Args[NumParams]->getBeginLoc(), 4853 Args.back()->getEndLoc()); 4854 4855 // Emit the location of the prototype. 4856 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4857 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4858 4859 // This deletes the extra arguments. 4860 Call->setNumArgs(Context, NumParams); 4861 return true; 4862 } 4863 } 4864 SmallVector<Expr *, 8> AllArgs; 4865 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4866 4867 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4868 AllArgs, CallType); 4869 if (Invalid) 4870 return true; 4871 unsigned TotalNumArgs = AllArgs.size(); 4872 for (unsigned i = 0; i < TotalNumArgs; ++i) 4873 Call->setArg(i, AllArgs[i]); 4874 4875 return false; 4876 } 4877 4878 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4879 const FunctionProtoType *Proto, 4880 unsigned FirstParam, ArrayRef<Expr *> Args, 4881 SmallVectorImpl<Expr *> &AllArgs, 4882 VariadicCallType CallType, bool AllowExplicit, 4883 bool IsListInitialization) { 4884 unsigned NumParams = Proto->getNumParams(); 4885 bool Invalid = false; 4886 size_t ArgIx = 0; 4887 // Continue to check argument types (even if we have too few/many args). 4888 for (unsigned i = FirstParam; i < NumParams; i++) { 4889 QualType ProtoArgType = Proto->getParamType(i); 4890 4891 Expr *Arg; 4892 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4893 if (ArgIx < Args.size()) { 4894 Arg = Args[ArgIx++]; 4895 4896 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4897 diag::err_call_incomplete_argument, Arg)) 4898 return true; 4899 4900 // Strip the unbridged-cast placeholder expression off, if applicable. 4901 bool CFAudited = false; 4902 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4903 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4904 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4905 Arg = stripARCUnbridgedCast(Arg); 4906 else if (getLangOpts().ObjCAutoRefCount && 4907 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4908 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4909 CFAudited = true; 4910 4911 if (Proto->getExtParameterInfo(i).isNoEscape()) 4912 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4913 BE->getBlockDecl()->setDoesNotEscape(); 4914 4915 InitializedEntity Entity = 4916 Param ? InitializedEntity::InitializeParameter(Context, Param, 4917 ProtoArgType) 4918 : InitializedEntity::InitializeParameter( 4919 Context, ProtoArgType, Proto->isParamConsumed(i)); 4920 4921 // Remember that parameter belongs to a CF audited API. 4922 if (CFAudited) 4923 Entity.setParameterCFAudited(); 4924 4925 ExprResult ArgE = PerformCopyInitialization( 4926 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4927 if (ArgE.isInvalid()) 4928 return true; 4929 4930 Arg = ArgE.getAs<Expr>(); 4931 } else { 4932 assert(Param && "can't use default arguments without a known callee"); 4933 4934 ExprResult ArgExpr = 4935 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4936 if (ArgExpr.isInvalid()) 4937 return true; 4938 4939 Arg = ArgExpr.getAs<Expr>(); 4940 } 4941 4942 // Check for array bounds violations for each argument to the call. This 4943 // check only triggers warnings when the argument isn't a more complex Expr 4944 // with its own checking, such as a BinaryOperator. 4945 CheckArrayAccess(Arg); 4946 4947 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4948 CheckStaticArrayArgument(CallLoc, Param, Arg); 4949 4950 AllArgs.push_back(Arg); 4951 } 4952 4953 // If this is a variadic call, handle args passed through "...". 4954 if (CallType != VariadicDoesNotApply) { 4955 // Assume that extern "C" functions with variadic arguments that 4956 // return __unknown_anytype aren't *really* variadic. 4957 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4958 FDecl->isExternC()) { 4959 for (Expr *A : Args.slice(ArgIx)) { 4960 QualType paramType; // ignored 4961 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4962 Invalid |= arg.isInvalid(); 4963 AllArgs.push_back(arg.get()); 4964 } 4965 4966 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4967 } else { 4968 for (Expr *A : Args.slice(ArgIx)) { 4969 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4970 Invalid |= Arg.isInvalid(); 4971 AllArgs.push_back(Arg.get()); 4972 } 4973 } 4974 4975 // Check for array bounds violations. 4976 for (Expr *A : Args.slice(ArgIx)) 4977 CheckArrayAccess(A); 4978 } 4979 return Invalid; 4980 } 4981 4982 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4983 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4984 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4985 TL = DTL.getOriginalLoc(); 4986 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4987 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4988 << ATL.getLocalSourceRange(); 4989 } 4990 4991 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4992 /// array parameter, check that it is non-null, and that if it is formed by 4993 /// array-to-pointer decay, the underlying array is sufficiently large. 4994 /// 4995 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4996 /// array type derivation, then for each call to the function, the value of the 4997 /// corresponding actual argument shall provide access to the first element of 4998 /// an array with at least as many elements as specified by the size expression. 4999 void 5000 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5001 ParmVarDecl *Param, 5002 const Expr *ArgExpr) { 5003 // Static array parameters are not supported in C++. 5004 if (!Param || getLangOpts().CPlusPlus) 5005 return; 5006 5007 QualType OrigTy = Param->getOriginalType(); 5008 5009 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5010 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5011 return; 5012 5013 if (ArgExpr->isNullPointerConstant(Context, 5014 Expr::NPC_NeverValueDependent)) { 5015 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5016 DiagnoseCalleeStaticArrayParam(*this, Param); 5017 return; 5018 } 5019 5020 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5021 if (!CAT) 5022 return; 5023 5024 const ConstantArrayType *ArgCAT = 5025 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5026 if (!ArgCAT) 5027 return; 5028 5029 if (ArgCAT->getSize().ult(CAT->getSize())) { 5030 Diag(CallLoc, diag::warn_static_array_too_small) 5031 << ArgExpr->getSourceRange() 5032 << (unsigned) ArgCAT->getSize().getZExtValue() 5033 << (unsigned) CAT->getSize().getZExtValue(); 5034 DiagnoseCalleeStaticArrayParam(*this, Param); 5035 } 5036 } 5037 5038 /// Given a function expression of unknown-any type, try to rebuild it 5039 /// to have a function type. 5040 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5041 5042 /// Is the given type a placeholder that we need to lower out 5043 /// immediately during argument processing? 5044 static bool isPlaceholderToRemoveAsArg(QualType type) { 5045 // Placeholders are never sugared. 5046 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5047 if (!placeholder) return false; 5048 5049 switch (placeholder->getKind()) { 5050 // Ignore all the non-placeholder types. 5051 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5052 case BuiltinType::Id: 5053 #include "clang/Basic/OpenCLImageTypes.def" 5054 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5055 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5056 #include "clang/AST/BuiltinTypes.def" 5057 return false; 5058 5059 // We cannot lower out overload sets; they might validly be resolved 5060 // by the call machinery. 5061 case BuiltinType::Overload: 5062 return false; 5063 5064 // Unbridged casts in ARC can be handled in some call positions and 5065 // should be left in place. 5066 case BuiltinType::ARCUnbridgedCast: 5067 return false; 5068 5069 // Pseudo-objects should be converted as soon as possible. 5070 case BuiltinType::PseudoObject: 5071 return true; 5072 5073 // The debugger mode could theoretically but currently does not try 5074 // to resolve unknown-typed arguments based on known parameter types. 5075 case BuiltinType::UnknownAny: 5076 return true; 5077 5078 // These are always invalid as call arguments and should be reported. 5079 case BuiltinType::BoundMember: 5080 case BuiltinType::BuiltinFn: 5081 case BuiltinType::OMPArraySection: 5082 return true; 5083 5084 } 5085 llvm_unreachable("bad builtin type kind"); 5086 } 5087 5088 /// Check an argument list for placeholders that we won't try to 5089 /// handle later. 5090 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5091 // Apply this processing to all the arguments at once instead of 5092 // dying at the first failure. 5093 bool hasInvalid = false; 5094 for (size_t i = 0, e = args.size(); i != e; i++) { 5095 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5096 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5097 if (result.isInvalid()) hasInvalid = true; 5098 else args[i] = result.get(); 5099 } else if (hasInvalid) { 5100 (void)S.CorrectDelayedTyposInExpr(args[i]); 5101 } 5102 } 5103 return hasInvalid; 5104 } 5105 5106 /// If a builtin function has a pointer argument with no explicit address 5107 /// space, then it should be able to accept a pointer to any address 5108 /// space as input. In order to do this, we need to replace the 5109 /// standard builtin declaration with one that uses the same address space 5110 /// as the call. 5111 /// 5112 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5113 /// it does not contain any pointer arguments without 5114 /// an address space qualifer. Otherwise the rewritten 5115 /// FunctionDecl is returned. 5116 /// TODO: Handle pointer return types. 5117 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5118 const FunctionDecl *FDecl, 5119 MultiExprArg ArgExprs) { 5120 5121 QualType DeclType = FDecl->getType(); 5122 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5123 5124 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5125 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5126 return nullptr; 5127 5128 bool NeedsNewDecl = false; 5129 unsigned i = 0; 5130 SmallVector<QualType, 8> OverloadParams; 5131 5132 for (QualType ParamType : FT->param_types()) { 5133 5134 // Convert array arguments to pointer to simplify type lookup. 5135 ExprResult ArgRes = 5136 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5137 if (ArgRes.isInvalid()) 5138 return nullptr; 5139 Expr *Arg = ArgRes.get(); 5140 QualType ArgType = Arg->getType(); 5141 if (!ParamType->isPointerType() || 5142 ParamType.getQualifiers().hasAddressSpace() || 5143 !ArgType->isPointerType() || 5144 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5145 OverloadParams.push_back(ParamType); 5146 continue; 5147 } 5148 5149 QualType PointeeType = ParamType->getPointeeType(); 5150 if (PointeeType.getQualifiers().hasAddressSpace()) 5151 continue; 5152 5153 NeedsNewDecl = true; 5154 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5155 5156 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5157 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5158 } 5159 5160 if (!NeedsNewDecl) 5161 return nullptr; 5162 5163 FunctionProtoType::ExtProtoInfo EPI; 5164 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5165 OverloadParams, EPI); 5166 DeclContext *Parent = Context.getTranslationUnitDecl(); 5167 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5168 FDecl->getLocation(), 5169 FDecl->getLocation(), 5170 FDecl->getIdentifier(), 5171 OverloadTy, 5172 /*TInfo=*/nullptr, 5173 SC_Extern, false, 5174 /*hasPrototype=*/true); 5175 SmallVector<ParmVarDecl*, 16> Params; 5176 FT = cast<FunctionProtoType>(OverloadTy); 5177 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5178 QualType ParamType = FT->getParamType(i); 5179 ParmVarDecl *Parm = 5180 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5181 SourceLocation(), nullptr, ParamType, 5182 /*TInfo=*/nullptr, SC_None, nullptr); 5183 Parm->setScopeInfo(0, i); 5184 Params.push_back(Parm); 5185 } 5186 OverloadDecl->setParams(Params); 5187 return OverloadDecl; 5188 } 5189 5190 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5191 FunctionDecl *Callee, 5192 MultiExprArg ArgExprs) { 5193 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5194 // similar attributes) really don't like it when functions are called with an 5195 // invalid number of args. 5196 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5197 /*PartialOverloading=*/false) && 5198 !Callee->isVariadic()) 5199 return; 5200 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5201 return; 5202 5203 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5204 S.Diag(Fn->getBeginLoc(), 5205 isa<CXXMethodDecl>(Callee) 5206 ? diag::err_ovl_no_viable_member_function_in_call 5207 : diag::err_ovl_no_viable_function_in_call) 5208 << Callee << Callee->getSourceRange(); 5209 S.Diag(Callee->getLocation(), 5210 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5211 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5212 return; 5213 } 5214 } 5215 5216 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5217 const UnresolvedMemberExpr *const UME, Sema &S) { 5218 5219 const auto GetFunctionLevelDCIfCXXClass = 5220 [](Sema &S) -> const CXXRecordDecl * { 5221 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5222 if (!DC || !DC->getParent()) 5223 return nullptr; 5224 5225 // If the call to some member function was made from within a member 5226 // function body 'M' return return 'M's parent. 5227 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5228 return MD->getParent()->getCanonicalDecl(); 5229 // else the call was made from within a default member initializer of a 5230 // class, so return the class. 5231 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5232 return RD->getCanonicalDecl(); 5233 return nullptr; 5234 }; 5235 // If our DeclContext is neither a member function nor a class (in the 5236 // case of a lambda in a default member initializer), we can't have an 5237 // enclosing 'this'. 5238 5239 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5240 if (!CurParentClass) 5241 return false; 5242 5243 // The naming class for implicit member functions call is the class in which 5244 // name lookup starts. 5245 const CXXRecordDecl *const NamingClass = 5246 UME->getNamingClass()->getCanonicalDecl(); 5247 assert(NamingClass && "Must have naming class even for implicit access"); 5248 5249 // If the unresolved member functions were found in a 'naming class' that is 5250 // related (either the same or derived from) to the class that contains the 5251 // member function that itself contained the implicit member access. 5252 5253 return CurParentClass == NamingClass || 5254 CurParentClass->isDerivedFrom(NamingClass); 5255 } 5256 5257 static void 5258 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5259 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5260 5261 if (!UME) 5262 return; 5263 5264 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5265 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5266 // already been captured, or if this is an implicit member function call (if 5267 // it isn't, an attempt to capture 'this' should already have been made). 5268 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5269 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5270 return; 5271 5272 // Check if the naming class in which the unresolved members were found is 5273 // related (same as or is a base of) to the enclosing class. 5274 5275 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5276 return; 5277 5278 5279 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5280 // If the enclosing function is not dependent, then this lambda is 5281 // capture ready, so if we can capture this, do so. 5282 if (!EnclosingFunctionCtx->isDependentContext()) { 5283 // If the current lambda and all enclosing lambdas can capture 'this' - 5284 // then go ahead and capture 'this' (since our unresolved overload set 5285 // contains at least one non-static member function). 5286 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5287 S.CheckCXXThisCapture(CallLoc); 5288 } else if (S.CurContext->isDependentContext()) { 5289 // ... since this is an implicit member reference, that might potentially 5290 // involve a 'this' capture, mark 'this' for potential capture in 5291 // enclosing lambdas. 5292 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5293 CurLSI->addPotentialThisCapture(CallLoc); 5294 } 5295 } 5296 5297 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5298 /// This provides the location of the left/right parens and a list of comma 5299 /// locations. 5300 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5301 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5302 Expr *ExecConfig, bool IsExecConfig) { 5303 // Since this might be a postfix expression, get rid of ParenListExprs. 5304 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5305 if (Result.isInvalid()) return ExprError(); 5306 Fn = Result.get(); 5307 5308 if (checkArgsForPlaceholders(*this, ArgExprs)) 5309 return ExprError(); 5310 5311 if (getLangOpts().CPlusPlus) { 5312 // If this is a pseudo-destructor expression, build the call immediately. 5313 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5314 if (!ArgExprs.empty()) { 5315 // Pseudo-destructor calls should not have any arguments. 5316 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5317 << FixItHint::CreateRemoval( 5318 SourceRange(ArgExprs.front()->getBeginLoc(), 5319 ArgExprs.back()->getEndLoc())); 5320 } 5321 5322 return new (Context) 5323 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5324 } 5325 if (Fn->getType() == Context.PseudoObjectTy) { 5326 ExprResult result = CheckPlaceholderExpr(Fn); 5327 if (result.isInvalid()) return ExprError(); 5328 Fn = result.get(); 5329 } 5330 5331 // Determine whether this is a dependent call inside a C++ template, 5332 // in which case we won't do any semantic analysis now. 5333 bool Dependent = false; 5334 if (Fn->isTypeDependent()) 5335 Dependent = true; 5336 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5337 Dependent = true; 5338 5339 if (Dependent) { 5340 if (ExecConfig) { 5341 return new (Context) CUDAKernelCallExpr( 5342 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5343 Context.DependentTy, VK_RValue, RParenLoc); 5344 } else { 5345 5346 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5347 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5348 Fn->getBeginLoc()); 5349 5350 return new (Context) CallExpr( 5351 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5352 } 5353 } 5354 5355 // Determine whether this is a call to an object (C++ [over.call.object]). 5356 if (Fn->getType()->isRecordType()) 5357 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5358 RParenLoc); 5359 5360 if (Fn->getType() == Context.UnknownAnyTy) { 5361 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5362 if (result.isInvalid()) return ExprError(); 5363 Fn = result.get(); 5364 } 5365 5366 if (Fn->getType() == Context.BoundMemberTy) { 5367 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5368 RParenLoc); 5369 } 5370 } 5371 5372 // Check for overloaded calls. This can happen even in C due to extensions. 5373 if (Fn->getType() == Context.OverloadTy) { 5374 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5375 5376 // We aren't supposed to apply this logic if there's an '&' involved. 5377 if (!find.HasFormOfMemberPointer) { 5378 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5379 return new (Context) CallExpr( 5380 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5381 OverloadExpr *ovl = find.Expression; 5382 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5383 return BuildOverloadedCallExpr( 5384 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5385 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5386 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5387 RParenLoc); 5388 } 5389 } 5390 5391 // If we're directly calling a function, get the appropriate declaration. 5392 if (Fn->getType() == Context.UnknownAnyTy) { 5393 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5394 if (result.isInvalid()) return ExprError(); 5395 Fn = result.get(); 5396 } 5397 5398 Expr *NakedFn = Fn->IgnoreParens(); 5399 5400 bool CallingNDeclIndirectly = false; 5401 NamedDecl *NDecl = nullptr; 5402 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5403 if (UnOp->getOpcode() == UO_AddrOf) { 5404 CallingNDeclIndirectly = true; 5405 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5406 } 5407 } 5408 5409 if (isa<DeclRefExpr>(NakedFn)) { 5410 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5411 5412 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5413 if (FDecl && FDecl->getBuiltinID()) { 5414 // Rewrite the function decl for this builtin by replacing parameters 5415 // with no explicit address space with the address space of the arguments 5416 // in ArgExprs. 5417 if ((FDecl = 5418 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5419 NDecl = FDecl; 5420 Fn = DeclRefExpr::Create( 5421 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5422 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5423 } 5424 } 5425 } else if (isa<MemberExpr>(NakedFn)) 5426 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5427 5428 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5429 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5430 FD, /*Complain=*/true, Fn->getBeginLoc())) 5431 return ExprError(); 5432 5433 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5434 return ExprError(); 5435 5436 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5437 } 5438 5439 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5440 ExecConfig, IsExecConfig); 5441 } 5442 5443 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5444 /// 5445 /// __builtin_astype( value, dst type ) 5446 /// 5447 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5448 SourceLocation BuiltinLoc, 5449 SourceLocation RParenLoc) { 5450 ExprValueKind VK = VK_RValue; 5451 ExprObjectKind OK = OK_Ordinary; 5452 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5453 QualType SrcTy = E->getType(); 5454 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5455 return ExprError(Diag(BuiltinLoc, 5456 diag::err_invalid_astype_of_different_size) 5457 << DstTy 5458 << SrcTy 5459 << E->getSourceRange()); 5460 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5461 } 5462 5463 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5464 /// provided arguments. 5465 /// 5466 /// __builtin_convertvector( value, dst type ) 5467 /// 5468 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5469 SourceLocation BuiltinLoc, 5470 SourceLocation RParenLoc) { 5471 TypeSourceInfo *TInfo; 5472 GetTypeFromParser(ParsedDestTy, &TInfo); 5473 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5474 } 5475 5476 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5477 /// i.e. an expression not of \p OverloadTy. The expression should 5478 /// unary-convert to an expression of function-pointer or 5479 /// block-pointer type. 5480 /// 5481 /// \param NDecl the declaration being called, if available 5482 ExprResult 5483 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5484 SourceLocation LParenLoc, 5485 ArrayRef<Expr *> Args, 5486 SourceLocation RParenLoc, 5487 Expr *Config, bool IsExecConfig) { 5488 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5489 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5490 5491 // Functions with 'interrupt' attribute cannot be called directly. 5492 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5493 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5494 return ExprError(); 5495 } 5496 5497 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5498 // so there's some risk when calling out to non-interrupt handler functions 5499 // that the callee might not preserve them. This is easy to diagnose here, 5500 // but can be very challenging to debug. 5501 if (auto *Caller = getCurFunctionDecl()) 5502 if (Caller->hasAttr<ARMInterruptAttr>()) { 5503 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5504 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5505 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5506 } 5507 5508 // Promote the function operand. 5509 // We special-case function promotion here because we only allow promoting 5510 // builtin functions to function pointers in the callee of a call. 5511 ExprResult Result; 5512 if (BuiltinID && 5513 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5514 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5515 CK_BuiltinFnToFnPtr).get(); 5516 } else { 5517 Result = CallExprUnaryConversions(Fn); 5518 } 5519 if (Result.isInvalid()) 5520 return ExprError(); 5521 Fn = Result.get(); 5522 5523 // Make the call expr early, before semantic checks. This guarantees cleanup 5524 // of arguments and function on error. 5525 CallExpr *TheCall; 5526 if (Config) 5527 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5528 cast<CallExpr>(Config), Args, 5529 Context.BoolTy, VK_RValue, 5530 RParenLoc); 5531 else 5532 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5533 VK_RValue, RParenLoc); 5534 5535 if (!getLangOpts().CPlusPlus) { 5536 // C cannot always handle TypoExpr nodes in builtin calls and direct 5537 // function calls as their argument checking don't necessarily handle 5538 // dependent types properly, so make sure any TypoExprs have been 5539 // dealt with. 5540 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5541 if (!Result.isUsable()) return ExprError(); 5542 TheCall = dyn_cast<CallExpr>(Result.get()); 5543 if (!TheCall) return Result; 5544 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5545 } 5546 5547 // Bail out early if calling a builtin with custom typechecking. 5548 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5549 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5550 5551 retry: 5552 const FunctionType *FuncT; 5553 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5554 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5555 // have type pointer to function". 5556 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5557 if (!FuncT) 5558 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5559 << Fn->getType() << Fn->getSourceRange()); 5560 } else if (const BlockPointerType *BPT = 5561 Fn->getType()->getAs<BlockPointerType>()) { 5562 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5563 } else { 5564 // Handle calls to expressions of unknown-any type. 5565 if (Fn->getType() == Context.UnknownAnyTy) { 5566 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5567 if (rewrite.isInvalid()) return ExprError(); 5568 Fn = rewrite.get(); 5569 TheCall->setCallee(Fn); 5570 goto retry; 5571 } 5572 5573 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5574 << Fn->getType() << Fn->getSourceRange()); 5575 } 5576 5577 if (getLangOpts().CUDA) { 5578 if (Config) { 5579 // CUDA: Kernel calls must be to global functions 5580 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5581 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5582 << FDecl << Fn->getSourceRange()); 5583 5584 // CUDA: Kernel function must have 'void' return type 5585 if (!FuncT->getReturnType()->isVoidType()) 5586 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5587 << Fn->getType() << Fn->getSourceRange()); 5588 } else { 5589 // CUDA: Calls to global functions must be configured 5590 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5591 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5592 << FDecl << Fn->getSourceRange()); 5593 } 5594 } 5595 5596 // Check for a valid return type 5597 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5598 FDecl)) 5599 return ExprError(); 5600 5601 // We know the result type of the call, set it. 5602 TheCall->setType(FuncT->getCallResultType(Context)); 5603 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5604 5605 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5606 if (Proto) { 5607 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5608 IsExecConfig)) 5609 return ExprError(); 5610 } else { 5611 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5612 5613 if (FDecl) { 5614 // Check if we have too few/too many template arguments, based 5615 // on our knowledge of the function definition. 5616 const FunctionDecl *Def = nullptr; 5617 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5618 Proto = Def->getType()->getAs<FunctionProtoType>(); 5619 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5620 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5621 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5622 } 5623 5624 // If the function we're calling isn't a function prototype, but we have 5625 // a function prototype from a prior declaratiom, use that prototype. 5626 if (!FDecl->hasPrototype()) 5627 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5628 } 5629 5630 // Promote the arguments (C99 6.5.2.2p6). 5631 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5632 Expr *Arg = Args[i]; 5633 5634 if (Proto && i < Proto->getNumParams()) { 5635 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5636 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5637 ExprResult ArgE = 5638 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5639 if (ArgE.isInvalid()) 5640 return true; 5641 5642 Arg = ArgE.getAs<Expr>(); 5643 5644 } else { 5645 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5646 5647 if (ArgE.isInvalid()) 5648 return true; 5649 5650 Arg = ArgE.getAs<Expr>(); 5651 } 5652 5653 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5654 diag::err_call_incomplete_argument, Arg)) 5655 return ExprError(); 5656 5657 TheCall->setArg(i, Arg); 5658 } 5659 } 5660 5661 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5662 if (!Method->isStatic()) 5663 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5664 << Fn->getSourceRange()); 5665 5666 // Check for sentinels 5667 if (NDecl) 5668 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5669 5670 // Do special checking on direct calls to functions. 5671 if (FDecl) { 5672 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5673 return ExprError(); 5674 5675 if (BuiltinID) 5676 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5677 } else if (NDecl) { 5678 if (CheckPointerCall(NDecl, TheCall, Proto)) 5679 return ExprError(); 5680 } else { 5681 if (CheckOtherCall(TheCall, Proto)) 5682 return ExprError(); 5683 } 5684 5685 return MaybeBindToTemporary(TheCall); 5686 } 5687 5688 ExprResult 5689 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5690 SourceLocation RParenLoc, Expr *InitExpr) { 5691 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5692 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5693 5694 TypeSourceInfo *TInfo; 5695 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5696 if (!TInfo) 5697 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5698 5699 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5700 } 5701 5702 ExprResult 5703 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5704 SourceLocation RParenLoc, Expr *LiteralExpr) { 5705 QualType literalType = TInfo->getType(); 5706 5707 if (literalType->isArrayType()) { 5708 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5709 diag::err_illegal_decl_array_incomplete_type, 5710 SourceRange(LParenLoc, 5711 LiteralExpr->getSourceRange().getEnd()))) 5712 return ExprError(); 5713 if (literalType->isVariableArrayType()) 5714 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5715 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5716 } else if (!literalType->isDependentType() && 5717 RequireCompleteType(LParenLoc, literalType, 5718 diag::err_typecheck_decl_incomplete_type, 5719 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5720 return ExprError(); 5721 5722 InitializedEntity Entity 5723 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5724 InitializationKind Kind 5725 = InitializationKind::CreateCStyleCast(LParenLoc, 5726 SourceRange(LParenLoc, RParenLoc), 5727 /*InitList=*/true); 5728 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5729 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5730 &literalType); 5731 if (Result.isInvalid()) 5732 return ExprError(); 5733 LiteralExpr = Result.get(); 5734 5735 bool isFileScope = !CurContext->isFunctionOrMethod(); 5736 if (isFileScope && 5737 !LiteralExpr->isTypeDependent() && 5738 !LiteralExpr->isValueDependent() && 5739 !literalType->isDependentType()) { // 6.5.2.5p3 5740 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5741 return ExprError(); 5742 } 5743 5744 // In C, compound literals are l-values for some reason. 5745 // For GCC compatibility, in C++, file-scope array compound literals with 5746 // constant initializers are also l-values, and compound literals are 5747 // otherwise prvalues. 5748 // 5749 // (GCC also treats C++ list-initialized file-scope array prvalues with 5750 // constant initializers as l-values, but that's non-conforming, so we don't 5751 // follow it there.) 5752 // 5753 // FIXME: It would be better to handle the lvalue cases as materializing and 5754 // lifetime-extending a temporary object, but our materialized temporaries 5755 // representation only supports lifetime extension from a variable, not "out 5756 // of thin air". 5757 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5758 // is bound to the result of applying array-to-pointer decay to the compound 5759 // literal. 5760 // FIXME: GCC supports compound literals of reference type, which should 5761 // obviously have a value kind derived from the kind of reference involved. 5762 ExprValueKind VK = 5763 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5764 ? VK_RValue 5765 : VK_LValue; 5766 5767 return MaybeBindToTemporary( 5768 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5769 VK, LiteralExpr, isFileScope)); 5770 } 5771 5772 ExprResult 5773 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5774 SourceLocation RBraceLoc) { 5775 // Immediately handle non-overload placeholders. Overloads can be 5776 // resolved contextually, but everything else here can't. 5777 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5778 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5779 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5780 5781 // Ignore failures; dropping the entire initializer list because 5782 // of one failure would be terrible for indexing/etc. 5783 if (result.isInvalid()) continue; 5784 5785 InitArgList[I] = result.get(); 5786 } 5787 } 5788 5789 // Semantic analysis for initializers is done by ActOnDeclarator() and 5790 // CheckInitializer() - it requires knowledge of the object being initialized. 5791 5792 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5793 RBraceLoc); 5794 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5795 return E; 5796 } 5797 5798 /// Do an explicit extend of the given block pointer if we're in ARC. 5799 void Sema::maybeExtendBlockObject(ExprResult &E) { 5800 assert(E.get()->getType()->isBlockPointerType()); 5801 assert(E.get()->isRValue()); 5802 5803 // Only do this in an r-value context. 5804 if (!getLangOpts().ObjCAutoRefCount) return; 5805 5806 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5807 CK_ARCExtendBlockObject, E.get(), 5808 /*base path*/ nullptr, VK_RValue); 5809 Cleanup.setExprNeedsCleanups(true); 5810 } 5811 5812 /// Prepare a conversion of the given expression to an ObjC object 5813 /// pointer type. 5814 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5815 QualType type = E.get()->getType(); 5816 if (type->isObjCObjectPointerType()) { 5817 return CK_BitCast; 5818 } else if (type->isBlockPointerType()) { 5819 maybeExtendBlockObject(E); 5820 return CK_BlockPointerToObjCPointerCast; 5821 } else { 5822 assert(type->isPointerType()); 5823 return CK_CPointerToObjCPointerCast; 5824 } 5825 } 5826 5827 /// Prepares for a scalar cast, performing all the necessary stages 5828 /// except the final cast and returning the kind required. 5829 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5830 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5831 // Also, callers should have filtered out the invalid cases with 5832 // pointers. Everything else should be possible. 5833 5834 QualType SrcTy = Src.get()->getType(); 5835 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5836 return CK_NoOp; 5837 5838 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5839 case Type::STK_MemberPointer: 5840 llvm_unreachable("member pointer type in C"); 5841 5842 case Type::STK_CPointer: 5843 case Type::STK_BlockPointer: 5844 case Type::STK_ObjCObjectPointer: 5845 switch (DestTy->getScalarTypeKind()) { 5846 case Type::STK_CPointer: { 5847 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5848 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5849 if (SrcAS != DestAS) 5850 return CK_AddressSpaceConversion; 5851 return CK_BitCast; 5852 } 5853 case Type::STK_BlockPointer: 5854 return (SrcKind == Type::STK_BlockPointer 5855 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5856 case Type::STK_ObjCObjectPointer: 5857 if (SrcKind == Type::STK_ObjCObjectPointer) 5858 return CK_BitCast; 5859 if (SrcKind == Type::STK_CPointer) 5860 return CK_CPointerToObjCPointerCast; 5861 maybeExtendBlockObject(Src); 5862 return CK_BlockPointerToObjCPointerCast; 5863 case Type::STK_Bool: 5864 return CK_PointerToBoolean; 5865 case Type::STK_Integral: 5866 return CK_PointerToIntegral; 5867 case Type::STK_Floating: 5868 case Type::STK_FloatingComplex: 5869 case Type::STK_IntegralComplex: 5870 case Type::STK_MemberPointer: 5871 llvm_unreachable("illegal cast from pointer"); 5872 } 5873 llvm_unreachable("Should have returned before this"); 5874 5875 case Type::STK_Bool: // casting from bool is like casting from an integer 5876 case Type::STK_Integral: 5877 switch (DestTy->getScalarTypeKind()) { 5878 case Type::STK_CPointer: 5879 case Type::STK_ObjCObjectPointer: 5880 case Type::STK_BlockPointer: 5881 if (Src.get()->isNullPointerConstant(Context, 5882 Expr::NPC_ValueDependentIsNull)) 5883 return CK_NullToPointer; 5884 return CK_IntegralToPointer; 5885 case Type::STK_Bool: 5886 return CK_IntegralToBoolean; 5887 case Type::STK_Integral: 5888 return CK_IntegralCast; 5889 case Type::STK_Floating: 5890 return CK_IntegralToFloating; 5891 case Type::STK_IntegralComplex: 5892 Src = ImpCastExprToType(Src.get(), 5893 DestTy->castAs<ComplexType>()->getElementType(), 5894 CK_IntegralCast); 5895 return CK_IntegralRealToComplex; 5896 case Type::STK_FloatingComplex: 5897 Src = ImpCastExprToType(Src.get(), 5898 DestTy->castAs<ComplexType>()->getElementType(), 5899 CK_IntegralToFloating); 5900 return CK_FloatingRealToComplex; 5901 case Type::STK_MemberPointer: 5902 llvm_unreachable("member pointer type in C"); 5903 } 5904 llvm_unreachable("Should have returned before this"); 5905 5906 case Type::STK_Floating: 5907 switch (DestTy->getScalarTypeKind()) { 5908 case Type::STK_Floating: 5909 return CK_FloatingCast; 5910 case Type::STK_Bool: 5911 return CK_FloatingToBoolean; 5912 case Type::STK_Integral: 5913 return CK_FloatingToIntegral; 5914 case Type::STK_FloatingComplex: 5915 Src = ImpCastExprToType(Src.get(), 5916 DestTy->castAs<ComplexType>()->getElementType(), 5917 CK_FloatingCast); 5918 return CK_FloatingRealToComplex; 5919 case Type::STK_IntegralComplex: 5920 Src = ImpCastExprToType(Src.get(), 5921 DestTy->castAs<ComplexType>()->getElementType(), 5922 CK_FloatingToIntegral); 5923 return CK_IntegralRealToComplex; 5924 case Type::STK_CPointer: 5925 case Type::STK_ObjCObjectPointer: 5926 case Type::STK_BlockPointer: 5927 llvm_unreachable("valid float->pointer cast?"); 5928 case Type::STK_MemberPointer: 5929 llvm_unreachable("member pointer type in C"); 5930 } 5931 llvm_unreachable("Should have returned before this"); 5932 5933 case Type::STK_FloatingComplex: 5934 switch (DestTy->getScalarTypeKind()) { 5935 case Type::STK_FloatingComplex: 5936 return CK_FloatingComplexCast; 5937 case Type::STK_IntegralComplex: 5938 return CK_FloatingComplexToIntegralComplex; 5939 case Type::STK_Floating: { 5940 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5941 if (Context.hasSameType(ET, DestTy)) 5942 return CK_FloatingComplexToReal; 5943 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5944 return CK_FloatingCast; 5945 } 5946 case Type::STK_Bool: 5947 return CK_FloatingComplexToBoolean; 5948 case Type::STK_Integral: 5949 Src = ImpCastExprToType(Src.get(), 5950 SrcTy->castAs<ComplexType>()->getElementType(), 5951 CK_FloatingComplexToReal); 5952 return CK_FloatingToIntegral; 5953 case Type::STK_CPointer: 5954 case Type::STK_ObjCObjectPointer: 5955 case Type::STK_BlockPointer: 5956 llvm_unreachable("valid complex float->pointer cast?"); 5957 case Type::STK_MemberPointer: 5958 llvm_unreachable("member pointer type in C"); 5959 } 5960 llvm_unreachable("Should have returned before this"); 5961 5962 case Type::STK_IntegralComplex: 5963 switch (DestTy->getScalarTypeKind()) { 5964 case Type::STK_FloatingComplex: 5965 return CK_IntegralComplexToFloatingComplex; 5966 case Type::STK_IntegralComplex: 5967 return CK_IntegralComplexCast; 5968 case Type::STK_Integral: { 5969 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5970 if (Context.hasSameType(ET, DestTy)) 5971 return CK_IntegralComplexToReal; 5972 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5973 return CK_IntegralCast; 5974 } 5975 case Type::STK_Bool: 5976 return CK_IntegralComplexToBoolean; 5977 case Type::STK_Floating: 5978 Src = ImpCastExprToType(Src.get(), 5979 SrcTy->castAs<ComplexType>()->getElementType(), 5980 CK_IntegralComplexToReal); 5981 return CK_IntegralToFloating; 5982 case Type::STK_CPointer: 5983 case Type::STK_ObjCObjectPointer: 5984 case Type::STK_BlockPointer: 5985 llvm_unreachable("valid complex int->pointer cast?"); 5986 case Type::STK_MemberPointer: 5987 llvm_unreachable("member pointer type in C"); 5988 } 5989 llvm_unreachable("Should have returned before this"); 5990 } 5991 5992 llvm_unreachable("Unhandled scalar cast"); 5993 } 5994 5995 static bool breakDownVectorType(QualType type, uint64_t &len, 5996 QualType &eltType) { 5997 // Vectors are simple. 5998 if (const VectorType *vecType = type->getAs<VectorType>()) { 5999 len = vecType->getNumElements(); 6000 eltType = vecType->getElementType(); 6001 assert(eltType->isScalarType()); 6002 return true; 6003 } 6004 6005 // We allow lax conversion to and from non-vector types, but only if 6006 // they're real types (i.e. non-complex, non-pointer scalar types). 6007 if (!type->isRealType()) return false; 6008 6009 len = 1; 6010 eltType = type; 6011 return true; 6012 } 6013 6014 /// Are the two types lax-compatible vector types? That is, given 6015 /// that one of them is a vector, do they have equal storage sizes, 6016 /// where the storage size is the number of elements times the element 6017 /// size? 6018 /// 6019 /// This will also return false if either of the types is neither a 6020 /// vector nor a real type. 6021 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6022 assert(destTy->isVectorType() || srcTy->isVectorType()); 6023 6024 // Disallow lax conversions between scalars and ExtVectors (these 6025 // conversions are allowed for other vector types because common headers 6026 // depend on them). Most scalar OP ExtVector cases are handled by the 6027 // splat path anyway, which does what we want (convert, not bitcast). 6028 // What this rules out for ExtVectors is crazy things like char4*float. 6029 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6030 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6031 6032 uint64_t srcLen, destLen; 6033 QualType srcEltTy, destEltTy; 6034 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6035 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6036 6037 // ASTContext::getTypeSize will return the size rounded up to a 6038 // power of 2, so instead of using that, we need to use the raw 6039 // element size multiplied by the element count. 6040 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6041 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6042 6043 return (srcLen * srcEltSize == destLen * destEltSize); 6044 } 6045 6046 /// Is this a legal conversion between two types, one of which is 6047 /// known to be a vector type? 6048 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6049 assert(destTy->isVectorType() || srcTy->isVectorType()); 6050 6051 if (!Context.getLangOpts().LaxVectorConversions) 6052 return false; 6053 return areLaxCompatibleVectorTypes(srcTy, destTy); 6054 } 6055 6056 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6057 CastKind &Kind) { 6058 assert(VectorTy->isVectorType() && "Not a vector type!"); 6059 6060 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6061 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6062 return Diag(R.getBegin(), 6063 Ty->isVectorType() ? 6064 diag::err_invalid_conversion_between_vectors : 6065 diag::err_invalid_conversion_between_vector_and_integer) 6066 << VectorTy << Ty << R; 6067 } else 6068 return Diag(R.getBegin(), 6069 diag::err_invalid_conversion_between_vector_and_scalar) 6070 << VectorTy << Ty << R; 6071 6072 Kind = CK_BitCast; 6073 return false; 6074 } 6075 6076 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6077 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6078 6079 if (DestElemTy == SplattedExpr->getType()) 6080 return SplattedExpr; 6081 6082 assert(DestElemTy->isFloatingType() || 6083 DestElemTy->isIntegralOrEnumerationType()); 6084 6085 CastKind CK; 6086 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6087 // OpenCL requires that we convert `true` boolean expressions to -1, but 6088 // only when splatting vectors. 6089 if (DestElemTy->isFloatingType()) { 6090 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6091 // in two steps: boolean to signed integral, then to floating. 6092 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6093 CK_BooleanToSignedIntegral); 6094 SplattedExpr = CastExprRes.get(); 6095 CK = CK_IntegralToFloating; 6096 } else { 6097 CK = CK_BooleanToSignedIntegral; 6098 } 6099 } else { 6100 ExprResult CastExprRes = SplattedExpr; 6101 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6102 if (CastExprRes.isInvalid()) 6103 return ExprError(); 6104 SplattedExpr = CastExprRes.get(); 6105 } 6106 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6107 } 6108 6109 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6110 Expr *CastExpr, CastKind &Kind) { 6111 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6112 6113 QualType SrcTy = CastExpr->getType(); 6114 6115 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6116 // an ExtVectorType. 6117 // In OpenCL, casts between vectors of different types are not allowed. 6118 // (See OpenCL 6.2). 6119 if (SrcTy->isVectorType()) { 6120 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6121 (getLangOpts().OpenCL && 6122 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6123 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6124 << DestTy << SrcTy << R; 6125 return ExprError(); 6126 } 6127 Kind = CK_BitCast; 6128 return CastExpr; 6129 } 6130 6131 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6132 // conversion will take place first from scalar to elt type, and then 6133 // splat from elt type to vector. 6134 if (SrcTy->isPointerType()) 6135 return Diag(R.getBegin(), 6136 diag::err_invalid_conversion_between_vector_and_scalar) 6137 << DestTy << SrcTy << R; 6138 6139 Kind = CK_VectorSplat; 6140 return prepareVectorSplat(DestTy, CastExpr); 6141 } 6142 6143 ExprResult 6144 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6145 Declarator &D, ParsedType &Ty, 6146 SourceLocation RParenLoc, Expr *CastExpr) { 6147 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6148 "ActOnCastExpr(): missing type or expr"); 6149 6150 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6151 if (D.isInvalidType()) 6152 return ExprError(); 6153 6154 if (getLangOpts().CPlusPlus) { 6155 // Check that there are no default arguments (C++ only). 6156 CheckExtraCXXDefaultArguments(D); 6157 } else { 6158 // Make sure any TypoExprs have been dealt with. 6159 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6160 if (!Res.isUsable()) 6161 return ExprError(); 6162 CastExpr = Res.get(); 6163 } 6164 6165 checkUnusedDeclAttributes(D); 6166 6167 QualType castType = castTInfo->getType(); 6168 Ty = CreateParsedType(castType, castTInfo); 6169 6170 bool isVectorLiteral = false; 6171 6172 // Check for an altivec or OpenCL literal, 6173 // i.e. all the elements are integer constants. 6174 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6175 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6176 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6177 && castType->isVectorType() && (PE || PLE)) { 6178 if (PLE && PLE->getNumExprs() == 0) { 6179 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6180 return ExprError(); 6181 } 6182 if (PE || PLE->getNumExprs() == 1) { 6183 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6184 if (!E->getType()->isVectorType()) 6185 isVectorLiteral = true; 6186 } 6187 else 6188 isVectorLiteral = true; 6189 } 6190 6191 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6192 // then handle it as such. 6193 if (isVectorLiteral) 6194 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6195 6196 // If the Expr being casted is a ParenListExpr, handle it specially. 6197 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6198 // sequence of BinOp comma operators. 6199 if (isa<ParenListExpr>(CastExpr)) { 6200 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6201 if (Result.isInvalid()) return ExprError(); 6202 CastExpr = Result.get(); 6203 } 6204 6205 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6206 !getSourceManager().isInSystemMacro(LParenLoc)) 6207 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6208 6209 CheckTollFreeBridgeCast(castType, CastExpr); 6210 6211 CheckObjCBridgeRelatedCast(castType, CastExpr); 6212 6213 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6214 6215 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6216 } 6217 6218 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6219 SourceLocation RParenLoc, Expr *E, 6220 TypeSourceInfo *TInfo) { 6221 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6222 "Expected paren or paren list expression"); 6223 6224 Expr **exprs; 6225 unsigned numExprs; 6226 Expr *subExpr; 6227 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6228 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6229 LiteralLParenLoc = PE->getLParenLoc(); 6230 LiteralRParenLoc = PE->getRParenLoc(); 6231 exprs = PE->getExprs(); 6232 numExprs = PE->getNumExprs(); 6233 } else { // isa<ParenExpr> by assertion at function entrance 6234 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6235 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6236 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6237 exprs = &subExpr; 6238 numExprs = 1; 6239 } 6240 6241 QualType Ty = TInfo->getType(); 6242 assert(Ty->isVectorType() && "Expected vector type"); 6243 6244 SmallVector<Expr *, 8> initExprs; 6245 const VectorType *VTy = Ty->getAs<VectorType>(); 6246 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6247 6248 // '(...)' form of vector initialization in AltiVec: the number of 6249 // initializers must be one or must match the size of the vector. 6250 // If a single value is specified in the initializer then it will be 6251 // replicated to all the components of the vector 6252 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6253 // The number of initializers must be one or must match the size of the 6254 // vector. If a single value is specified in the initializer then it will 6255 // be replicated to all the components of the vector 6256 if (numExprs == 1) { 6257 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6258 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6259 if (Literal.isInvalid()) 6260 return ExprError(); 6261 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6262 PrepareScalarCast(Literal, ElemTy)); 6263 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6264 } 6265 else if (numExprs < numElems) { 6266 Diag(E->getExprLoc(), 6267 diag::err_incorrect_number_of_vector_initializers); 6268 return ExprError(); 6269 } 6270 else 6271 initExprs.append(exprs, exprs + numExprs); 6272 } 6273 else { 6274 // For OpenCL, when the number of initializers is a single value, 6275 // it will be replicated to all components of the vector. 6276 if (getLangOpts().OpenCL && 6277 VTy->getVectorKind() == VectorType::GenericVector && 6278 numExprs == 1) { 6279 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6280 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6281 if (Literal.isInvalid()) 6282 return ExprError(); 6283 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6284 PrepareScalarCast(Literal, ElemTy)); 6285 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6286 } 6287 6288 initExprs.append(exprs, exprs + numExprs); 6289 } 6290 // FIXME: This means that pretty-printing the final AST will produce curly 6291 // braces instead of the original commas. 6292 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6293 initExprs, LiteralRParenLoc); 6294 initE->setType(Ty); 6295 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6296 } 6297 6298 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6299 /// the ParenListExpr into a sequence of comma binary operators. 6300 ExprResult 6301 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6302 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6303 if (!E) 6304 return OrigExpr; 6305 6306 ExprResult Result(E->getExpr(0)); 6307 6308 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6309 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6310 E->getExpr(i)); 6311 6312 if (Result.isInvalid()) return ExprError(); 6313 6314 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6315 } 6316 6317 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6318 SourceLocation R, 6319 MultiExprArg Val) { 6320 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6321 return expr; 6322 } 6323 6324 /// Emit a specialized diagnostic when one expression is a null pointer 6325 /// constant and the other is not a pointer. Returns true if a diagnostic is 6326 /// emitted. 6327 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6328 SourceLocation QuestionLoc) { 6329 Expr *NullExpr = LHSExpr; 6330 Expr *NonPointerExpr = RHSExpr; 6331 Expr::NullPointerConstantKind NullKind = 6332 NullExpr->isNullPointerConstant(Context, 6333 Expr::NPC_ValueDependentIsNotNull); 6334 6335 if (NullKind == Expr::NPCK_NotNull) { 6336 NullExpr = RHSExpr; 6337 NonPointerExpr = LHSExpr; 6338 NullKind = 6339 NullExpr->isNullPointerConstant(Context, 6340 Expr::NPC_ValueDependentIsNotNull); 6341 } 6342 6343 if (NullKind == Expr::NPCK_NotNull) 6344 return false; 6345 6346 if (NullKind == Expr::NPCK_ZeroExpression) 6347 return false; 6348 6349 if (NullKind == Expr::NPCK_ZeroLiteral) { 6350 // In this case, check to make sure that we got here from a "NULL" 6351 // string in the source code. 6352 NullExpr = NullExpr->IgnoreParenImpCasts(); 6353 SourceLocation loc = NullExpr->getExprLoc(); 6354 if (!findMacroSpelling(loc, "NULL")) 6355 return false; 6356 } 6357 6358 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6359 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6360 << NonPointerExpr->getType() << DiagType 6361 << NonPointerExpr->getSourceRange(); 6362 return true; 6363 } 6364 6365 /// Return false if the condition expression is valid, true otherwise. 6366 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6367 QualType CondTy = Cond->getType(); 6368 6369 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6370 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6371 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6372 << CondTy << Cond->getSourceRange(); 6373 return true; 6374 } 6375 6376 // C99 6.5.15p2 6377 if (CondTy->isScalarType()) return false; 6378 6379 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6380 << CondTy << Cond->getSourceRange(); 6381 return true; 6382 } 6383 6384 /// Handle when one or both operands are void type. 6385 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6386 ExprResult &RHS) { 6387 Expr *LHSExpr = LHS.get(); 6388 Expr *RHSExpr = RHS.get(); 6389 6390 if (!LHSExpr->getType()->isVoidType()) 6391 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6392 << RHSExpr->getSourceRange(); 6393 if (!RHSExpr->getType()->isVoidType()) 6394 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6395 << LHSExpr->getSourceRange(); 6396 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6397 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6398 return S.Context.VoidTy; 6399 } 6400 6401 /// Return false if the NullExpr can be promoted to PointerTy, 6402 /// true otherwise. 6403 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6404 QualType PointerTy) { 6405 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6406 !NullExpr.get()->isNullPointerConstant(S.Context, 6407 Expr::NPC_ValueDependentIsNull)) 6408 return true; 6409 6410 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6411 return false; 6412 } 6413 6414 /// Checks compatibility between two pointers and return the resulting 6415 /// type. 6416 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6417 ExprResult &RHS, 6418 SourceLocation Loc) { 6419 QualType LHSTy = LHS.get()->getType(); 6420 QualType RHSTy = RHS.get()->getType(); 6421 6422 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6423 // Two identical pointers types are always compatible. 6424 return LHSTy; 6425 } 6426 6427 QualType lhptee, rhptee; 6428 6429 // Get the pointee types. 6430 bool IsBlockPointer = false; 6431 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6432 lhptee = LHSBTy->getPointeeType(); 6433 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6434 IsBlockPointer = true; 6435 } else { 6436 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6437 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6438 } 6439 6440 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6441 // differently qualified versions of compatible types, the result type is 6442 // a pointer to an appropriately qualified version of the composite 6443 // type. 6444 6445 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6446 // clause doesn't make sense for our extensions. E.g. address space 2 should 6447 // be incompatible with address space 3: they may live on different devices or 6448 // anything. 6449 Qualifiers lhQual = lhptee.getQualifiers(); 6450 Qualifiers rhQual = rhptee.getQualifiers(); 6451 6452 LangAS ResultAddrSpace = LangAS::Default; 6453 LangAS LAddrSpace = lhQual.getAddressSpace(); 6454 LangAS RAddrSpace = rhQual.getAddressSpace(); 6455 6456 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6457 // spaces is disallowed. 6458 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6459 ResultAddrSpace = LAddrSpace; 6460 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6461 ResultAddrSpace = RAddrSpace; 6462 else { 6463 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6464 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6465 << RHS.get()->getSourceRange(); 6466 return QualType(); 6467 } 6468 6469 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6470 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6471 lhQual.removeCVRQualifiers(); 6472 rhQual.removeCVRQualifiers(); 6473 6474 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6475 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6476 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6477 // qual types are compatible iff 6478 // * corresponded types are compatible 6479 // * CVR qualifiers are equal 6480 // * address spaces are equal 6481 // Thus for conditional operator we merge CVR and address space unqualified 6482 // pointees and if there is a composite type we return a pointer to it with 6483 // merged qualifiers. 6484 LHSCastKind = 6485 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6486 RHSCastKind = 6487 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6488 lhQual.removeAddressSpace(); 6489 rhQual.removeAddressSpace(); 6490 6491 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6492 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6493 6494 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6495 6496 if (CompositeTy.isNull()) { 6497 // In this situation, we assume void* type. No especially good 6498 // reason, but this is what gcc does, and we do have to pick 6499 // to get a consistent AST. 6500 QualType incompatTy; 6501 incompatTy = S.Context.getPointerType( 6502 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6503 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6504 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6505 6506 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6507 // for casts between types with incompatible address space qualifiers. 6508 // For the following code the compiler produces casts between global and 6509 // local address spaces of the corresponded innermost pointees: 6510 // local int *global *a; 6511 // global int *global *b; 6512 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6513 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6514 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6515 << RHS.get()->getSourceRange(); 6516 6517 return incompatTy; 6518 } 6519 6520 // The pointer types are compatible. 6521 // In case of OpenCL ResultTy should have the address space qualifier 6522 // which is a superset of address spaces of both the 2nd and the 3rd 6523 // operands of the conditional operator. 6524 QualType ResultTy = [&, ResultAddrSpace]() { 6525 if (S.getLangOpts().OpenCL) { 6526 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6527 CompositeQuals.setAddressSpace(ResultAddrSpace); 6528 return S.Context 6529 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6530 .withCVRQualifiers(MergedCVRQual); 6531 } 6532 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6533 }(); 6534 if (IsBlockPointer) 6535 ResultTy = S.Context.getBlockPointerType(ResultTy); 6536 else 6537 ResultTy = S.Context.getPointerType(ResultTy); 6538 6539 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6540 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6541 return ResultTy; 6542 } 6543 6544 /// Return the resulting type when the operands are both block pointers. 6545 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6546 ExprResult &LHS, 6547 ExprResult &RHS, 6548 SourceLocation Loc) { 6549 QualType LHSTy = LHS.get()->getType(); 6550 QualType RHSTy = RHS.get()->getType(); 6551 6552 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6553 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6554 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6555 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6556 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6557 return destType; 6558 } 6559 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6560 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6561 << RHS.get()->getSourceRange(); 6562 return QualType(); 6563 } 6564 6565 // We have 2 block pointer types. 6566 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6567 } 6568 6569 /// Return the resulting type when the operands are both pointers. 6570 static QualType 6571 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6572 ExprResult &RHS, 6573 SourceLocation Loc) { 6574 // get the pointer types 6575 QualType LHSTy = LHS.get()->getType(); 6576 QualType RHSTy = RHS.get()->getType(); 6577 6578 // get the "pointed to" types 6579 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6580 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6581 6582 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6583 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6584 // Figure out necessary qualifiers (C99 6.5.15p6) 6585 QualType destPointee 6586 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6587 QualType destType = S.Context.getPointerType(destPointee); 6588 // Add qualifiers if necessary. 6589 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6590 // Promote to void*. 6591 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6592 return destType; 6593 } 6594 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6595 QualType destPointee 6596 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6597 QualType destType = S.Context.getPointerType(destPointee); 6598 // Add qualifiers if necessary. 6599 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6600 // Promote to void*. 6601 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6602 return destType; 6603 } 6604 6605 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6606 } 6607 6608 /// Return false if the first expression is not an integer and the second 6609 /// expression is not a pointer, true otherwise. 6610 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6611 Expr* PointerExpr, SourceLocation Loc, 6612 bool IsIntFirstExpr) { 6613 if (!PointerExpr->getType()->isPointerType() || 6614 !Int.get()->getType()->isIntegerType()) 6615 return false; 6616 6617 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6618 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6619 6620 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6621 << Expr1->getType() << Expr2->getType() 6622 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6623 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6624 CK_IntegralToPointer); 6625 return true; 6626 } 6627 6628 /// Simple conversion between integer and floating point types. 6629 /// 6630 /// Used when handling the OpenCL conditional operator where the 6631 /// condition is a vector while the other operands are scalar. 6632 /// 6633 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6634 /// types are either integer or floating type. Between the two 6635 /// operands, the type with the higher rank is defined as the "result 6636 /// type". The other operand needs to be promoted to the same type. No 6637 /// other type promotion is allowed. We cannot use 6638 /// UsualArithmeticConversions() for this purpose, since it always 6639 /// promotes promotable types. 6640 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6641 ExprResult &RHS, 6642 SourceLocation QuestionLoc) { 6643 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6644 if (LHS.isInvalid()) 6645 return QualType(); 6646 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6647 if (RHS.isInvalid()) 6648 return QualType(); 6649 6650 // For conversion purposes, we ignore any qualifiers. 6651 // For example, "const float" and "float" are equivalent. 6652 QualType LHSType = 6653 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6654 QualType RHSType = 6655 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6656 6657 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6658 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6659 << LHSType << LHS.get()->getSourceRange(); 6660 return QualType(); 6661 } 6662 6663 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6664 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6665 << RHSType << RHS.get()->getSourceRange(); 6666 return QualType(); 6667 } 6668 6669 // If both types are identical, no conversion is needed. 6670 if (LHSType == RHSType) 6671 return LHSType; 6672 6673 // Now handle "real" floating types (i.e. float, double, long double). 6674 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6675 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6676 /*IsCompAssign = */ false); 6677 6678 // Finally, we have two differing integer types. 6679 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6680 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6681 } 6682 6683 /// Convert scalar operands to a vector that matches the 6684 /// condition in length. 6685 /// 6686 /// Used when handling the OpenCL conditional operator where the 6687 /// condition is a vector while the other operands are scalar. 6688 /// 6689 /// We first compute the "result type" for the scalar operands 6690 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6691 /// into a vector of that type where the length matches the condition 6692 /// vector type. s6.11.6 requires that the element types of the result 6693 /// and the condition must have the same number of bits. 6694 static QualType 6695 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6696 QualType CondTy, SourceLocation QuestionLoc) { 6697 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6698 if (ResTy.isNull()) return QualType(); 6699 6700 const VectorType *CV = CondTy->getAs<VectorType>(); 6701 assert(CV); 6702 6703 // Determine the vector result type 6704 unsigned NumElements = CV->getNumElements(); 6705 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6706 6707 // Ensure that all types have the same number of bits 6708 if (S.Context.getTypeSize(CV->getElementType()) 6709 != S.Context.getTypeSize(ResTy)) { 6710 // Since VectorTy is created internally, it does not pretty print 6711 // with an OpenCL name. Instead, we just print a description. 6712 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6713 SmallString<64> Str; 6714 llvm::raw_svector_ostream OS(Str); 6715 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6716 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6717 << CondTy << OS.str(); 6718 return QualType(); 6719 } 6720 6721 // Convert operands to the vector result type 6722 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6723 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6724 6725 return VectorTy; 6726 } 6727 6728 /// Return false if this is a valid OpenCL condition vector 6729 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6730 SourceLocation QuestionLoc) { 6731 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6732 // integral type. 6733 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6734 assert(CondTy); 6735 QualType EleTy = CondTy->getElementType(); 6736 if (EleTy->isIntegerType()) return false; 6737 6738 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6739 << Cond->getType() << Cond->getSourceRange(); 6740 return true; 6741 } 6742 6743 /// Return false if the vector condition type and the vector 6744 /// result type are compatible. 6745 /// 6746 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6747 /// number of elements, and their element types have the same number 6748 /// of bits. 6749 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6750 SourceLocation QuestionLoc) { 6751 const VectorType *CV = CondTy->getAs<VectorType>(); 6752 const VectorType *RV = VecResTy->getAs<VectorType>(); 6753 assert(CV && RV); 6754 6755 if (CV->getNumElements() != RV->getNumElements()) { 6756 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6757 << CondTy << VecResTy; 6758 return true; 6759 } 6760 6761 QualType CVE = CV->getElementType(); 6762 QualType RVE = RV->getElementType(); 6763 6764 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6765 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6766 << CondTy << VecResTy; 6767 return true; 6768 } 6769 6770 return false; 6771 } 6772 6773 /// Return the resulting type for the conditional operator in 6774 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6775 /// s6.3.i) when the condition is a vector type. 6776 static QualType 6777 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6778 ExprResult &LHS, ExprResult &RHS, 6779 SourceLocation QuestionLoc) { 6780 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6781 if (Cond.isInvalid()) 6782 return QualType(); 6783 QualType CondTy = Cond.get()->getType(); 6784 6785 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6786 return QualType(); 6787 6788 // If either operand is a vector then find the vector type of the 6789 // result as specified in OpenCL v1.1 s6.3.i. 6790 if (LHS.get()->getType()->isVectorType() || 6791 RHS.get()->getType()->isVectorType()) { 6792 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6793 /*isCompAssign*/false, 6794 /*AllowBothBool*/true, 6795 /*AllowBoolConversions*/false); 6796 if (VecResTy.isNull()) return QualType(); 6797 // The result type must match the condition type as specified in 6798 // OpenCL v1.1 s6.11.6. 6799 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6800 return QualType(); 6801 return VecResTy; 6802 } 6803 6804 // Both operands are scalar. 6805 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6806 } 6807 6808 /// Return true if the Expr is block type 6809 static bool checkBlockType(Sema &S, const Expr *E) { 6810 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6811 QualType Ty = CE->getCallee()->getType(); 6812 if (Ty->isBlockPointerType()) { 6813 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6814 return true; 6815 } 6816 } 6817 return false; 6818 } 6819 6820 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6821 /// In that case, LHS = cond. 6822 /// C99 6.5.15 6823 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6824 ExprResult &RHS, ExprValueKind &VK, 6825 ExprObjectKind &OK, 6826 SourceLocation QuestionLoc) { 6827 6828 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6829 if (!LHSResult.isUsable()) return QualType(); 6830 LHS = LHSResult; 6831 6832 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6833 if (!RHSResult.isUsable()) return QualType(); 6834 RHS = RHSResult; 6835 6836 // C++ is sufficiently different to merit its own checker. 6837 if (getLangOpts().CPlusPlus) 6838 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6839 6840 VK = VK_RValue; 6841 OK = OK_Ordinary; 6842 6843 // The OpenCL operator with a vector condition is sufficiently 6844 // different to merit its own checker. 6845 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6846 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6847 6848 // First, check the condition. 6849 Cond = UsualUnaryConversions(Cond.get()); 6850 if (Cond.isInvalid()) 6851 return QualType(); 6852 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6853 return QualType(); 6854 6855 // Now check the two expressions. 6856 if (LHS.get()->getType()->isVectorType() || 6857 RHS.get()->getType()->isVectorType()) 6858 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6859 /*AllowBothBool*/true, 6860 /*AllowBoolConversions*/false); 6861 6862 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6863 if (LHS.isInvalid() || RHS.isInvalid()) 6864 return QualType(); 6865 6866 QualType LHSTy = LHS.get()->getType(); 6867 QualType RHSTy = RHS.get()->getType(); 6868 6869 // Diagnose attempts to convert between __float128 and long double where 6870 // such conversions currently can't be handled. 6871 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6872 Diag(QuestionLoc, 6873 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6874 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6875 return QualType(); 6876 } 6877 6878 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6879 // selection operator (?:). 6880 if (getLangOpts().OpenCL && 6881 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6882 return QualType(); 6883 } 6884 6885 // If both operands have arithmetic type, do the usual arithmetic conversions 6886 // to find a common type: C99 6.5.15p3,5. 6887 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6888 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6889 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6890 6891 return ResTy; 6892 } 6893 6894 // If both operands are the same structure or union type, the result is that 6895 // type. 6896 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6897 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6898 if (LHSRT->getDecl() == RHSRT->getDecl()) 6899 // "If both the operands have structure or union type, the result has 6900 // that type." This implies that CV qualifiers are dropped. 6901 return LHSTy.getUnqualifiedType(); 6902 // FIXME: Type of conditional expression must be complete in C mode. 6903 } 6904 6905 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6906 // The following || allows only one side to be void (a GCC-ism). 6907 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6908 return checkConditionalVoidType(*this, LHS, RHS); 6909 } 6910 6911 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6912 // the type of the other operand." 6913 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6914 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6915 6916 // All objective-c pointer type analysis is done here. 6917 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6918 QuestionLoc); 6919 if (LHS.isInvalid() || RHS.isInvalid()) 6920 return QualType(); 6921 if (!compositeType.isNull()) 6922 return compositeType; 6923 6924 6925 // Handle block pointer types. 6926 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6927 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6928 QuestionLoc); 6929 6930 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6931 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6932 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6933 QuestionLoc); 6934 6935 // GCC compatibility: soften pointer/integer mismatch. Note that 6936 // null pointers have been filtered out by this point. 6937 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6938 /*isIntFirstExpr=*/true)) 6939 return RHSTy; 6940 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6941 /*isIntFirstExpr=*/false)) 6942 return LHSTy; 6943 6944 // Emit a better diagnostic if one of the expressions is a null pointer 6945 // constant and the other is not a pointer type. In this case, the user most 6946 // likely forgot to take the address of the other expression. 6947 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6948 return QualType(); 6949 6950 // Otherwise, the operands are not compatible. 6951 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6952 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6953 << RHS.get()->getSourceRange(); 6954 return QualType(); 6955 } 6956 6957 /// FindCompositeObjCPointerType - Helper method to find composite type of 6958 /// two objective-c pointer types of the two input expressions. 6959 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6960 SourceLocation QuestionLoc) { 6961 QualType LHSTy = LHS.get()->getType(); 6962 QualType RHSTy = RHS.get()->getType(); 6963 6964 // Handle things like Class and struct objc_class*. Here we case the result 6965 // to the pseudo-builtin, because that will be implicitly cast back to the 6966 // redefinition type if an attempt is made to access its fields. 6967 if (LHSTy->isObjCClassType() && 6968 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6969 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6970 return LHSTy; 6971 } 6972 if (RHSTy->isObjCClassType() && 6973 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6974 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6975 return RHSTy; 6976 } 6977 // And the same for struct objc_object* / id 6978 if (LHSTy->isObjCIdType() && 6979 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6980 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6981 return LHSTy; 6982 } 6983 if (RHSTy->isObjCIdType() && 6984 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6985 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6986 return RHSTy; 6987 } 6988 // And the same for struct objc_selector* / SEL 6989 if (Context.isObjCSelType(LHSTy) && 6990 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6991 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6992 return LHSTy; 6993 } 6994 if (Context.isObjCSelType(RHSTy) && 6995 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6996 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6997 return RHSTy; 6998 } 6999 // Check constraints for Objective-C object pointers types. 7000 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7001 7002 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7003 // Two identical object pointer types are always compatible. 7004 return LHSTy; 7005 } 7006 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7007 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7008 QualType compositeType = LHSTy; 7009 7010 // If both operands are interfaces and either operand can be 7011 // assigned to the other, use that type as the composite 7012 // type. This allows 7013 // xxx ? (A*) a : (B*) b 7014 // where B is a subclass of A. 7015 // 7016 // Additionally, as for assignment, if either type is 'id' 7017 // allow silent coercion. Finally, if the types are 7018 // incompatible then make sure to use 'id' as the composite 7019 // type so the result is acceptable for sending messages to. 7020 7021 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7022 // It could return the composite type. 7023 if (!(compositeType = 7024 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7025 // Nothing more to do. 7026 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7027 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7028 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7029 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7030 } else if ((LHSTy->isObjCQualifiedIdType() || 7031 RHSTy->isObjCQualifiedIdType()) && 7032 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7033 // Need to handle "id<xx>" explicitly. 7034 // GCC allows qualified id and any Objective-C type to devolve to 7035 // id. Currently localizing to here until clear this should be 7036 // part of ObjCQualifiedIdTypesAreCompatible. 7037 compositeType = Context.getObjCIdType(); 7038 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7039 compositeType = Context.getObjCIdType(); 7040 } else { 7041 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7042 << LHSTy << RHSTy 7043 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7044 QualType incompatTy = Context.getObjCIdType(); 7045 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7046 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7047 return incompatTy; 7048 } 7049 // The object pointer types are compatible. 7050 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7051 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7052 return compositeType; 7053 } 7054 // Check Objective-C object pointer types and 'void *' 7055 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7056 if (getLangOpts().ObjCAutoRefCount) { 7057 // ARC forbids the implicit conversion of object pointers to 'void *', 7058 // so these types are not compatible. 7059 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7061 LHS = RHS = true; 7062 return QualType(); 7063 } 7064 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7065 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7066 QualType destPointee 7067 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7068 QualType destType = Context.getPointerType(destPointee); 7069 // Add qualifiers if necessary. 7070 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7071 // Promote to void*. 7072 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7073 return destType; 7074 } 7075 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7076 if (getLangOpts().ObjCAutoRefCount) { 7077 // ARC forbids the implicit conversion of object pointers to 'void *', 7078 // so these types are not compatible. 7079 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7080 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7081 LHS = RHS = true; 7082 return QualType(); 7083 } 7084 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7085 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7086 QualType destPointee 7087 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7088 QualType destType = Context.getPointerType(destPointee); 7089 // Add qualifiers if necessary. 7090 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7091 // Promote to void*. 7092 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7093 return destType; 7094 } 7095 return QualType(); 7096 } 7097 7098 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7099 /// ParenRange in parentheses. 7100 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7101 const PartialDiagnostic &Note, 7102 SourceRange ParenRange) { 7103 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7104 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7105 EndLoc.isValid()) { 7106 Self.Diag(Loc, Note) 7107 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7108 << FixItHint::CreateInsertion(EndLoc, ")"); 7109 } else { 7110 // We can't display the parentheses, so just show the bare note. 7111 Self.Diag(Loc, Note) << ParenRange; 7112 } 7113 } 7114 7115 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7116 return BinaryOperator::isAdditiveOp(Opc) || 7117 BinaryOperator::isMultiplicativeOp(Opc) || 7118 BinaryOperator::isShiftOp(Opc); 7119 } 7120 7121 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7122 /// expression, either using a built-in or overloaded operator, 7123 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7124 /// expression. 7125 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7126 Expr **RHSExprs) { 7127 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7128 E = E->IgnoreImpCasts(); 7129 E = E->IgnoreConversionOperator(); 7130 E = E->IgnoreImpCasts(); 7131 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7132 E = MTE->GetTemporaryExpr(); 7133 E = E->IgnoreImpCasts(); 7134 } 7135 7136 // Built-in binary operator. 7137 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7138 if (IsArithmeticOp(OP->getOpcode())) { 7139 *Opcode = OP->getOpcode(); 7140 *RHSExprs = OP->getRHS(); 7141 return true; 7142 } 7143 } 7144 7145 // Overloaded operator. 7146 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7147 if (Call->getNumArgs() != 2) 7148 return false; 7149 7150 // Make sure this is really a binary operator that is safe to pass into 7151 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7152 OverloadedOperatorKind OO = Call->getOperator(); 7153 if (OO < OO_Plus || OO > OO_Arrow || 7154 OO == OO_PlusPlus || OO == OO_MinusMinus) 7155 return false; 7156 7157 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7158 if (IsArithmeticOp(OpKind)) { 7159 *Opcode = OpKind; 7160 *RHSExprs = Call->getArg(1); 7161 return true; 7162 } 7163 } 7164 7165 return false; 7166 } 7167 7168 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7169 /// or is a logical expression such as (x==y) which has int type, but is 7170 /// commonly interpreted as boolean. 7171 static bool ExprLooksBoolean(Expr *E) { 7172 E = E->IgnoreParenImpCasts(); 7173 7174 if (E->getType()->isBooleanType()) 7175 return true; 7176 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7177 return OP->isComparisonOp() || OP->isLogicalOp(); 7178 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7179 return OP->getOpcode() == UO_LNot; 7180 if (E->getType()->isPointerType()) 7181 return true; 7182 // FIXME: What about overloaded operator calls returning "unspecified boolean 7183 // type"s (commonly pointer-to-members)? 7184 7185 return false; 7186 } 7187 7188 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7189 /// and binary operator are mixed in a way that suggests the programmer assumed 7190 /// the conditional operator has higher precedence, for example: 7191 /// "int x = a + someBinaryCondition ? 1 : 2". 7192 static void DiagnoseConditionalPrecedence(Sema &Self, 7193 SourceLocation OpLoc, 7194 Expr *Condition, 7195 Expr *LHSExpr, 7196 Expr *RHSExpr) { 7197 BinaryOperatorKind CondOpcode; 7198 Expr *CondRHS; 7199 7200 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7201 return; 7202 if (!ExprLooksBoolean(CondRHS)) 7203 return; 7204 7205 // The condition is an arithmetic binary expression, with a right- 7206 // hand side that looks boolean, so warn. 7207 7208 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7209 << Condition->getSourceRange() 7210 << BinaryOperator::getOpcodeStr(CondOpcode); 7211 7212 SuggestParentheses( 7213 Self, OpLoc, 7214 Self.PDiag(diag::note_precedence_silence) 7215 << BinaryOperator::getOpcodeStr(CondOpcode), 7216 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7217 7218 SuggestParentheses(Self, OpLoc, 7219 Self.PDiag(diag::note_precedence_conditional_first), 7220 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7221 } 7222 7223 /// Compute the nullability of a conditional expression. 7224 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7225 QualType LHSTy, QualType RHSTy, 7226 ASTContext &Ctx) { 7227 if (!ResTy->isAnyPointerType()) 7228 return ResTy; 7229 7230 auto GetNullability = [&Ctx](QualType Ty) { 7231 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7232 if (Kind) 7233 return *Kind; 7234 return NullabilityKind::Unspecified; 7235 }; 7236 7237 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7238 NullabilityKind MergedKind; 7239 7240 // Compute nullability of a binary conditional expression. 7241 if (IsBin) { 7242 if (LHSKind == NullabilityKind::NonNull) 7243 MergedKind = NullabilityKind::NonNull; 7244 else 7245 MergedKind = RHSKind; 7246 // Compute nullability of a normal conditional expression. 7247 } else { 7248 if (LHSKind == NullabilityKind::Nullable || 7249 RHSKind == NullabilityKind::Nullable) 7250 MergedKind = NullabilityKind::Nullable; 7251 else if (LHSKind == NullabilityKind::NonNull) 7252 MergedKind = RHSKind; 7253 else if (RHSKind == NullabilityKind::NonNull) 7254 MergedKind = LHSKind; 7255 else 7256 MergedKind = NullabilityKind::Unspecified; 7257 } 7258 7259 // Return if ResTy already has the correct nullability. 7260 if (GetNullability(ResTy) == MergedKind) 7261 return ResTy; 7262 7263 // Strip all nullability from ResTy. 7264 while (ResTy->getNullability(Ctx)) 7265 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7266 7267 // Create a new AttributedType with the new nullability kind. 7268 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7269 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7270 } 7271 7272 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7273 /// in the case of a the GNU conditional expr extension. 7274 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7275 SourceLocation ColonLoc, 7276 Expr *CondExpr, Expr *LHSExpr, 7277 Expr *RHSExpr) { 7278 if (!getLangOpts().CPlusPlus) { 7279 // C cannot handle TypoExpr nodes in the condition because it 7280 // doesn't handle dependent types properly, so make sure any TypoExprs have 7281 // been dealt with before checking the operands. 7282 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7283 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7284 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7285 7286 if (!CondResult.isUsable()) 7287 return ExprError(); 7288 7289 if (LHSExpr) { 7290 if (!LHSResult.isUsable()) 7291 return ExprError(); 7292 } 7293 7294 if (!RHSResult.isUsable()) 7295 return ExprError(); 7296 7297 CondExpr = CondResult.get(); 7298 LHSExpr = LHSResult.get(); 7299 RHSExpr = RHSResult.get(); 7300 } 7301 7302 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7303 // was the condition. 7304 OpaqueValueExpr *opaqueValue = nullptr; 7305 Expr *commonExpr = nullptr; 7306 if (!LHSExpr) { 7307 commonExpr = CondExpr; 7308 // Lower out placeholder types first. This is important so that we don't 7309 // try to capture a placeholder. This happens in few cases in C++; such 7310 // as Objective-C++'s dictionary subscripting syntax. 7311 if (commonExpr->hasPlaceholderType()) { 7312 ExprResult result = CheckPlaceholderExpr(commonExpr); 7313 if (!result.isUsable()) return ExprError(); 7314 commonExpr = result.get(); 7315 } 7316 // We usually want to apply unary conversions *before* saving, except 7317 // in the special case of a C++ l-value conditional. 7318 if (!(getLangOpts().CPlusPlus 7319 && !commonExpr->isTypeDependent() 7320 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7321 && commonExpr->isGLValue() 7322 && commonExpr->isOrdinaryOrBitFieldObject() 7323 && RHSExpr->isOrdinaryOrBitFieldObject() 7324 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7325 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7326 if (commonRes.isInvalid()) 7327 return ExprError(); 7328 commonExpr = commonRes.get(); 7329 } 7330 7331 // If the common expression is a class or array prvalue, materialize it 7332 // so that we can safely refer to it multiple times. 7333 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7334 commonExpr->getType()->isArrayType())) { 7335 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7336 if (MatExpr.isInvalid()) 7337 return ExprError(); 7338 commonExpr = MatExpr.get(); 7339 } 7340 7341 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7342 commonExpr->getType(), 7343 commonExpr->getValueKind(), 7344 commonExpr->getObjectKind(), 7345 commonExpr); 7346 LHSExpr = CondExpr = opaqueValue; 7347 } 7348 7349 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7350 ExprValueKind VK = VK_RValue; 7351 ExprObjectKind OK = OK_Ordinary; 7352 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7353 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7354 VK, OK, QuestionLoc); 7355 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7356 RHS.isInvalid()) 7357 return ExprError(); 7358 7359 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7360 RHS.get()); 7361 7362 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7363 7364 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7365 Context); 7366 7367 if (!commonExpr) 7368 return new (Context) 7369 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7370 RHS.get(), result, VK, OK); 7371 7372 return new (Context) BinaryConditionalOperator( 7373 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7374 ColonLoc, result, VK, OK); 7375 } 7376 7377 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7378 // being closely modeled after the C99 spec:-). The odd characteristic of this 7379 // routine is it effectively iqnores the qualifiers on the top level pointee. 7380 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7381 // FIXME: add a couple examples in this comment. 7382 static Sema::AssignConvertType 7383 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7384 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7385 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7386 7387 // get the "pointed to" type (ignoring qualifiers at the top level) 7388 const Type *lhptee, *rhptee; 7389 Qualifiers lhq, rhq; 7390 std::tie(lhptee, lhq) = 7391 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7392 std::tie(rhptee, rhq) = 7393 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7394 7395 Sema::AssignConvertType ConvTy = Sema::Compatible; 7396 7397 // C99 6.5.16.1p1: This following citation is common to constraints 7398 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7399 // qualifiers of the type *pointed to* by the right; 7400 7401 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7402 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7403 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7404 // Ignore lifetime for further calculation. 7405 lhq.removeObjCLifetime(); 7406 rhq.removeObjCLifetime(); 7407 } 7408 7409 if (!lhq.compatiblyIncludes(rhq)) { 7410 // Treat address-space mismatches as fatal. TODO: address subspaces 7411 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7412 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7413 7414 // It's okay to add or remove GC or lifetime qualifiers when converting to 7415 // and from void*. 7416 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7417 .compatiblyIncludes( 7418 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7419 && (lhptee->isVoidType() || rhptee->isVoidType())) 7420 ; // keep old 7421 7422 // Treat lifetime mismatches as fatal. 7423 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7424 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7425 7426 // For GCC/MS compatibility, other qualifier mismatches are treated 7427 // as still compatible in C. 7428 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7429 } 7430 7431 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7432 // incomplete type and the other is a pointer to a qualified or unqualified 7433 // version of void... 7434 if (lhptee->isVoidType()) { 7435 if (rhptee->isIncompleteOrObjectType()) 7436 return ConvTy; 7437 7438 // As an extension, we allow cast to/from void* to function pointer. 7439 assert(rhptee->isFunctionType()); 7440 return Sema::FunctionVoidPointer; 7441 } 7442 7443 if (rhptee->isVoidType()) { 7444 if (lhptee->isIncompleteOrObjectType()) 7445 return ConvTy; 7446 7447 // As an extension, we allow cast to/from void* to function pointer. 7448 assert(lhptee->isFunctionType()); 7449 return Sema::FunctionVoidPointer; 7450 } 7451 7452 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7453 // unqualified versions of compatible types, ... 7454 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7455 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7456 // Check if the pointee types are compatible ignoring the sign. 7457 // We explicitly check for char so that we catch "char" vs 7458 // "unsigned char" on systems where "char" is unsigned. 7459 if (lhptee->isCharType()) 7460 ltrans = S.Context.UnsignedCharTy; 7461 else if (lhptee->hasSignedIntegerRepresentation()) 7462 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7463 7464 if (rhptee->isCharType()) 7465 rtrans = S.Context.UnsignedCharTy; 7466 else if (rhptee->hasSignedIntegerRepresentation()) 7467 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7468 7469 if (ltrans == rtrans) { 7470 // Types are compatible ignoring the sign. Qualifier incompatibility 7471 // takes priority over sign incompatibility because the sign 7472 // warning can be disabled. 7473 if (ConvTy != Sema::Compatible) 7474 return ConvTy; 7475 7476 return Sema::IncompatiblePointerSign; 7477 } 7478 7479 // If we are a multi-level pointer, it's possible that our issue is simply 7480 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7481 // the eventual target type is the same and the pointers have the same 7482 // level of indirection, this must be the issue. 7483 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7484 do { 7485 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7486 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7487 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7488 7489 if (lhptee == rhptee) 7490 return Sema::IncompatibleNestedPointerQualifiers; 7491 } 7492 7493 // General pointer incompatibility takes priority over qualifiers. 7494 return Sema::IncompatiblePointer; 7495 } 7496 if (!S.getLangOpts().CPlusPlus && 7497 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7498 return Sema::IncompatiblePointer; 7499 return ConvTy; 7500 } 7501 7502 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7503 /// block pointer types are compatible or whether a block and normal pointer 7504 /// are compatible. It is more restrict than comparing two function pointer 7505 // types. 7506 static Sema::AssignConvertType 7507 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7508 QualType RHSType) { 7509 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7510 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7511 7512 QualType lhptee, rhptee; 7513 7514 // get the "pointed to" type (ignoring qualifiers at the top level) 7515 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7516 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7517 7518 // In C++, the types have to match exactly. 7519 if (S.getLangOpts().CPlusPlus) 7520 return Sema::IncompatibleBlockPointer; 7521 7522 Sema::AssignConvertType ConvTy = Sema::Compatible; 7523 7524 // For blocks we enforce that qualifiers are identical. 7525 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7526 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7527 if (S.getLangOpts().OpenCL) { 7528 LQuals.removeAddressSpace(); 7529 RQuals.removeAddressSpace(); 7530 } 7531 if (LQuals != RQuals) 7532 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7533 7534 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7535 // assignment. 7536 // The current behavior is similar to C++ lambdas. A block might be 7537 // assigned to a variable iff its return type and parameters are compatible 7538 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7539 // an assignment. Presumably it should behave in way that a function pointer 7540 // assignment does in C, so for each parameter and return type: 7541 // * CVR and address space of LHS should be a superset of CVR and address 7542 // space of RHS. 7543 // * unqualified types should be compatible. 7544 if (S.getLangOpts().OpenCL) { 7545 if (!S.Context.typesAreBlockPointerCompatible( 7546 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7547 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7548 return Sema::IncompatibleBlockPointer; 7549 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7550 return Sema::IncompatibleBlockPointer; 7551 7552 return ConvTy; 7553 } 7554 7555 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7556 /// for assignment compatibility. 7557 static Sema::AssignConvertType 7558 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7559 QualType RHSType) { 7560 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7561 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7562 7563 if (LHSType->isObjCBuiltinType()) { 7564 // Class is not compatible with ObjC object pointers. 7565 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7566 !RHSType->isObjCQualifiedClassType()) 7567 return Sema::IncompatiblePointer; 7568 return Sema::Compatible; 7569 } 7570 if (RHSType->isObjCBuiltinType()) { 7571 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7572 !LHSType->isObjCQualifiedClassType()) 7573 return Sema::IncompatiblePointer; 7574 return Sema::Compatible; 7575 } 7576 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7577 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7578 7579 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7580 // make an exception for id<P> 7581 !LHSType->isObjCQualifiedIdType()) 7582 return Sema::CompatiblePointerDiscardsQualifiers; 7583 7584 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7585 return Sema::Compatible; 7586 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7587 return Sema::IncompatibleObjCQualifiedId; 7588 return Sema::IncompatiblePointer; 7589 } 7590 7591 Sema::AssignConvertType 7592 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7593 QualType LHSType, QualType RHSType) { 7594 // Fake up an opaque expression. We don't actually care about what 7595 // cast operations are required, so if CheckAssignmentConstraints 7596 // adds casts to this they'll be wasted, but fortunately that doesn't 7597 // usually happen on valid code. 7598 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7599 ExprResult RHSPtr = &RHSExpr; 7600 CastKind K; 7601 7602 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7603 } 7604 7605 /// This helper function returns true if QT is a vector type that has element 7606 /// type ElementType. 7607 static bool isVector(QualType QT, QualType ElementType) { 7608 if (const VectorType *VT = QT->getAs<VectorType>()) 7609 return VT->getElementType() == ElementType; 7610 return false; 7611 } 7612 7613 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7614 /// has code to accommodate several GCC extensions when type checking 7615 /// pointers. Here are some objectionable examples that GCC considers warnings: 7616 /// 7617 /// int a, *pint; 7618 /// short *pshort; 7619 /// struct foo *pfoo; 7620 /// 7621 /// pint = pshort; // warning: assignment from incompatible pointer type 7622 /// a = pint; // warning: assignment makes integer from pointer without a cast 7623 /// pint = a; // warning: assignment makes pointer from integer without a cast 7624 /// pint = pfoo; // warning: assignment from incompatible pointer type 7625 /// 7626 /// As a result, the code for dealing with pointers is more complex than the 7627 /// C99 spec dictates. 7628 /// 7629 /// Sets 'Kind' for any result kind except Incompatible. 7630 Sema::AssignConvertType 7631 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7632 CastKind &Kind, bool ConvertRHS) { 7633 QualType RHSType = RHS.get()->getType(); 7634 QualType OrigLHSType = LHSType; 7635 7636 // Get canonical types. We're not formatting these types, just comparing 7637 // them. 7638 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7639 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7640 7641 // Common case: no conversion required. 7642 if (LHSType == RHSType) { 7643 Kind = CK_NoOp; 7644 return Compatible; 7645 } 7646 7647 // If we have an atomic type, try a non-atomic assignment, then just add an 7648 // atomic qualification step. 7649 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7650 Sema::AssignConvertType result = 7651 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7652 if (result != Compatible) 7653 return result; 7654 if (Kind != CK_NoOp && ConvertRHS) 7655 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7656 Kind = CK_NonAtomicToAtomic; 7657 return Compatible; 7658 } 7659 7660 // If the left-hand side is a reference type, then we are in a 7661 // (rare!) case where we've allowed the use of references in C, 7662 // e.g., as a parameter type in a built-in function. In this case, 7663 // just make sure that the type referenced is compatible with the 7664 // right-hand side type. The caller is responsible for adjusting 7665 // LHSType so that the resulting expression does not have reference 7666 // type. 7667 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7668 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7669 Kind = CK_LValueBitCast; 7670 return Compatible; 7671 } 7672 return Incompatible; 7673 } 7674 7675 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7676 // to the same ExtVector type. 7677 if (LHSType->isExtVectorType()) { 7678 if (RHSType->isExtVectorType()) 7679 return Incompatible; 7680 if (RHSType->isArithmeticType()) { 7681 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7682 if (ConvertRHS) 7683 RHS = prepareVectorSplat(LHSType, RHS.get()); 7684 Kind = CK_VectorSplat; 7685 return Compatible; 7686 } 7687 } 7688 7689 // Conversions to or from vector type. 7690 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7691 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7692 // Allow assignments of an AltiVec vector type to an equivalent GCC 7693 // vector type and vice versa 7694 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7695 Kind = CK_BitCast; 7696 return Compatible; 7697 } 7698 7699 // If we are allowing lax vector conversions, and LHS and RHS are both 7700 // vectors, the total size only needs to be the same. This is a bitcast; 7701 // no bits are changed but the result type is different. 7702 if (isLaxVectorConversion(RHSType, LHSType)) { 7703 Kind = CK_BitCast; 7704 return IncompatibleVectors; 7705 } 7706 } 7707 7708 // When the RHS comes from another lax conversion (e.g. binops between 7709 // scalars and vectors) the result is canonicalized as a vector. When the 7710 // LHS is also a vector, the lax is allowed by the condition above. Handle 7711 // the case where LHS is a scalar. 7712 if (LHSType->isScalarType()) { 7713 const VectorType *VecType = RHSType->getAs<VectorType>(); 7714 if (VecType && VecType->getNumElements() == 1 && 7715 isLaxVectorConversion(RHSType, LHSType)) { 7716 ExprResult *VecExpr = &RHS; 7717 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7718 Kind = CK_BitCast; 7719 return Compatible; 7720 } 7721 } 7722 7723 return Incompatible; 7724 } 7725 7726 // Diagnose attempts to convert between __float128 and long double where 7727 // such conversions currently can't be handled. 7728 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7729 return Incompatible; 7730 7731 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7732 // discards the imaginary part. 7733 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7734 !LHSType->getAs<ComplexType>()) 7735 return Incompatible; 7736 7737 // Arithmetic conversions. 7738 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7739 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7740 if (ConvertRHS) 7741 Kind = PrepareScalarCast(RHS, LHSType); 7742 return Compatible; 7743 } 7744 7745 // Conversions to normal pointers. 7746 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7747 // U* -> T* 7748 if (isa<PointerType>(RHSType)) { 7749 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7750 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7751 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7752 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7753 } 7754 7755 // int -> T* 7756 if (RHSType->isIntegerType()) { 7757 Kind = CK_IntegralToPointer; // FIXME: null? 7758 return IntToPointer; 7759 } 7760 7761 // C pointers are not compatible with ObjC object pointers, 7762 // with two exceptions: 7763 if (isa<ObjCObjectPointerType>(RHSType)) { 7764 // - conversions to void* 7765 if (LHSPointer->getPointeeType()->isVoidType()) { 7766 Kind = CK_BitCast; 7767 return Compatible; 7768 } 7769 7770 // - conversions from 'Class' to the redefinition type 7771 if (RHSType->isObjCClassType() && 7772 Context.hasSameType(LHSType, 7773 Context.getObjCClassRedefinitionType())) { 7774 Kind = CK_BitCast; 7775 return Compatible; 7776 } 7777 7778 Kind = CK_BitCast; 7779 return IncompatiblePointer; 7780 } 7781 7782 // U^ -> void* 7783 if (RHSType->getAs<BlockPointerType>()) { 7784 if (LHSPointer->getPointeeType()->isVoidType()) { 7785 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7786 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7787 ->getPointeeType() 7788 .getAddressSpace(); 7789 Kind = 7790 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7791 return Compatible; 7792 } 7793 } 7794 7795 return Incompatible; 7796 } 7797 7798 // Conversions to block pointers. 7799 if (isa<BlockPointerType>(LHSType)) { 7800 // U^ -> T^ 7801 if (RHSType->isBlockPointerType()) { 7802 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7803 ->getPointeeType() 7804 .getAddressSpace(); 7805 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7806 ->getPointeeType() 7807 .getAddressSpace(); 7808 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7809 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7810 } 7811 7812 // int or null -> T^ 7813 if (RHSType->isIntegerType()) { 7814 Kind = CK_IntegralToPointer; // FIXME: null 7815 return IntToBlockPointer; 7816 } 7817 7818 // id -> T^ 7819 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7820 Kind = CK_AnyPointerToBlockPointerCast; 7821 return Compatible; 7822 } 7823 7824 // void* -> T^ 7825 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7826 if (RHSPT->getPointeeType()->isVoidType()) { 7827 Kind = CK_AnyPointerToBlockPointerCast; 7828 return Compatible; 7829 } 7830 7831 return Incompatible; 7832 } 7833 7834 // Conversions to Objective-C pointers. 7835 if (isa<ObjCObjectPointerType>(LHSType)) { 7836 // A* -> B* 7837 if (RHSType->isObjCObjectPointerType()) { 7838 Kind = CK_BitCast; 7839 Sema::AssignConvertType result = 7840 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7841 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7842 result == Compatible && 7843 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7844 result = IncompatibleObjCWeakRef; 7845 return result; 7846 } 7847 7848 // int or null -> A* 7849 if (RHSType->isIntegerType()) { 7850 Kind = CK_IntegralToPointer; // FIXME: null 7851 return IntToPointer; 7852 } 7853 7854 // In general, C pointers are not compatible with ObjC object pointers, 7855 // with two exceptions: 7856 if (isa<PointerType>(RHSType)) { 7857 Kind = CK_CPointerToObjCPointerCast; 7858 7859 // - conversions from 'void*' 7860 if (RHSType->isVoidPointerType()) { 7861 return Compatible; 7862 } 7863 7864 // - conversions to 'Class' from its redefinition type 7865 if (LHSType->isObjCClassType() && 7866 Context.hasSameType(RHSType, 7867 Context.getObjCClassRedefinitionType())) { 7868 return Compatible; 7869 } 7870 7871 return IncompatiblePointer; 7872 } 7873 7874 // Only under strict condition T^ is compatible with an Objective-C pointer. 7875 if (RHSType->isBlockPointerType() && 7876 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7877 if (ConvertRHS) 7878 maybeExtendBlockObject(RHS); 7879 Kind = CK_BlockPointerToObjCPointerCast; 7880 return Compatible; 7881 } 7882 7883 return Incompatible; 7884 } 7885 7886 // Conversions from pointers that are not covered by the above. 7887 if (isa<PointerType>(RHSType)) { 7888 // T* -> _Bool 7889 if (LHSType == Context.BoolTy) { 7890 Kind = CK_PointerToBoolean; 7891 return Compatible; 7892 } 7893 7894 // T* -> int 7895 if (LHSType->isIntegerType()) { 7896 Kind = CK_PointerToIntegral; 7897 return PointerToInt; 7898 } 7899 7900 return Incompatible; 7901 } 7902 7903 // Conversions from Objective-C pointers that are not covered by the above. 7904 if (isa<ObjCObjectPointerType>(RHSType)) { 7905 // T* -> _Bool 7906 if (LHSType == Context.BoolTy) { 7907 Kind = CK_PointerToBoolean; 7908 return Compatible; 7909 } 7910 7911 // T* -> int 7912 if (LHSType->isIntegerType()) { 7913 Kind = CK_PointerToIntegral; 7914 return PointerToInt; 7915 } 7916 7917 return Incompatible; 7918 } 7919 7920 // struct A -> struct B 7921 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7922 if (Context.typesAreCompatible(LHSType, RHSType)) { 7923 Kind = CK_NoOp; 7924 return Compatible; 7925 } 7926 } 7927 7928 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7929 Kind = CK_IntToOCLSampler; 7930 return Compatible; 7931 } 7932 7933 return Incompatible; 7934 } 7935 7936 /// Constructs a transparent union from an expression that is 7937 /// used to initialize the transparent union. 7938 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7939 ExprResult &EResult, QualType UnionType, 7940 FieldDecl *Field) { 7941 // Build an initializer list that designates the appropriate member 7942 // of the transparent union. 7943 Expr *E = EResult.get(); 7944 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7945 E, SourceLocation()); 7946 Initializer->setType(UnionType); 7947 Initializer->setInitializedFieldInUnion(Field); 7948 7949 // Build a compound literal constructing a value of the transparent 7950 // union type from this initializer list. 7951 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7952 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7953 VK_RValue, Initializer, false); 7954 } 7955 7956 Sema::AssignConvertType 7957 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7958 ExprResult &RHS) { 7959 QualType RHSType = RHS.get()->getType(); 7960 7961 // If the ArgType is a Union type, we want to handle a potential 7962 // transparent_union GCC extension. 7963 const RecordType *UT = ArgType->getAsUnionType(); 7964 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7965 return Incompatible; 7966 7967 // The field to initialize within the transparent union. 7968 RecordDecl *UD = UT->getDecl(); 7969 FieldDecl *InitField = nullptr; 7970 // It's compatible if the expression matches any of the fields. 7971 for (auto *it : UD->fields()) { 7972 if (it->getType()->isPointerType()) { 7973 // If the transparent union contains a pointer type, we allow: 7974 // 1) void pointer 7975 // 2) null pointer constant 7976 if (RHSType->isPointerType()) 7977 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7978 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7979 InitField = it; 7980 break; 7981 } 7982 7983 if (RHS.get()->isNullPointerConstant(Context, 7984 Expr::NPC_ValueDependentIsNull)) { 7985 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7986 CK_NullToPointer); 7987 InitField = it; 7988 break; 7989 } 7990 } 7991 7992 CastKind Kind; 7993 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7994 == Compatible) { 7995 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7996 InitField = it; 7997 break; 7998 } 7999 } 8000 8001 if (!InitField) 8002 return Incompatible; 8003 8004 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8005 return Compatible; 8006 } 8007 8008 Sema::AssignConvertType 8009 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8010 bool Diagnose, 8011 bool DiagnoseCFAudited, 8012 bool ConvertRHS) { 8013 // We need to be able to tell the caller whether we diagnosed a problem, if 8014 // they ask us to issue diagnostics. 8015 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8016 8017 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8018 // we can't avoid *all* modifications at the moment, so we need some somewhere 8019 // to put the updated value. 8020 ExprResult LocalRHS = CallerRHS; 8021 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8022 8023 if (getLangOpts().CPlusPlus) { 8024 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8025 // C++ 5.17p3: If the left operand is not of class type, the 8026 // expression is implicitly converted (C++ 4) to the 8027 // cv-unqualified type of the left operand. 8028 QualType RHSType = RHS.get()->getType(); 8029 if (Diagnose) { 8030 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8031 AA_Assigning); 8032 } else { 8033 ImplicitConversionSequence ICS = 8034 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8035 /*SuppressUserConversions=*/false, 8036 /*AllowExplicit=*/false, 8037 /*InOverloadResolution=*/false, 8038 /*CStyle=*/false, 8039 /*AllowObjCWritebackConversion=*/false); 8040 if (ICS.isFailure()) 8041 return Incompatible; 8042 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8043 ICS, AA_Assigning); 8044 } 8045 if (RHS.isInvalid()) 8046 return Incompatible; 8047 Sema::AssignConvertType result = Compatible; 8048 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8049 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8050 result = IncompatibleObjCWeakRef; 8051 return result; 8052 } 8053 8054 // FIXME: Currently, we fall through and treat C++ classes like C 8055 // structures. 8056 // FIXME: We also fall through for atomics; not sure what should 8057 // happen there, though. 8058 } else if (RHS.get()->getType() == Context.OverloadTy) { 8059 // As a set of extensions to C, we support overloading on functions. These 8060 // functions need to be resolved here. 8061 DeclAccessPair DAP; 8062 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8063 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8064 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8065 else 8066 return Incompatible; 8067 } 8068 8069 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8070 // a null pointer constant. 8071 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8072 LHSType->isBlockPointerType()) && 8073 RHS.get()->isNullPointerConstant(Context, 8074 Expr::NPC_ValueDependentIsNull)) { 8075 if (Diagnose || ConvertRHS) { 8076 CastKind Kind; 8077 CXXCastPath Path; 8078 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8079 /*IgnoreBaseAccess=*/false, Diagnose); 8080 if (ConvertRHS) 8081 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8082 } 8083 return Compatible; 8084 } 8085 8086 // This check seems unnatural, however it is necessary to ensure the proper 8087 // conversion of functions/arrays. If the conversion were done for all 8088 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8089 // expressions that suppress this implicit conversion (&, sizeof). 8090 // 8091 // Suppress this for references: C++ 8.5.3p5. 8092 if (!LHSType->isReferenceType()) { 8093 // FIXME: We potentially allocate here even if ConvertRHS is false. 8094 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8095 if (RHS.isInvalid()) 8096 return Incompatible; 8097 } 8098 8099 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8100 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8101 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8102 if (PDecl && !PDecl->hasDefinition()) { 8103 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl; 8104 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8105 } 8106 } 8107 8108 CastKind Kind; 8109 Sema::AssignConvertType result = 8110 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8111 8112 // C99 6.5.16.1p2: The value of the right operand is converted to the 8113 // type of the assignment expression. 8114 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8115 // so that we can use references in built-in functions even in C. 8116 // The getNonReferenceType() call makes sure that the resulting expression 8117 // does not have reference type. 8118 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8119 QualType Ty = LHSType.getNonLValueExprType(Context); 8120 Expr *E = RHS.get(); 8121 8122 // Check for various Objective-C errors. If we are not reporting 8123 // diagnostics and just checking for errors, e.g., during overload 8124 // resolution, return Incompatible to indicate the failure. 8125 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8126 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8127 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8128 if (!Diagnose) 8129 return Incompatible; 8130 } 8131 if (getLangOpts().ObjC1 && 8132 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8133 E->getType(), E, Diagnose) || 8134 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8135 if (!Diagnose) 8136 return Incompatible; 8137 // Replace the expression with a corrected version and continue so we 8138 // can find further errors. 8139 RHS = E; 8140 return Compatible; 8141 } 8142 8143 if (ConvertRHS) 8144 RHS = ImpCastExprToType(E, Ty, Kind); 8145 } 8146 return result; 8147 } 8148 8149 namespace { 8150 /// The original operand to an operator, prior to the application of the usual 8151 /// arithmetic conversions and converting the arguments of a builtin operator 8152 /// candidate. 8153 struct OriginalOperand { 8154 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8155 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8156 Op = MTE->GetTemporaryExpr(); 8157 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8158 Op = BTE->getSubExpr(); 8159 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8160 Orig = ICE->getSubExprAsWritten(); 8161 Conversion = ICE->getConversionFunction(); 8162 } 8163 } 8164 8165 QualType getType() const { return Orig->getType(); } 8166 8167 Expr *Orig; 8168 NamedDecl *Conversion; 8169 }; 8170 } 8171 8172 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8173 ExprResult &RHS) { 8174 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8175 8176 Diag(Loc, diag::err_typecheck_invalid_operands) 8177 << OrigLHS.getType() << OrigRHS.getType() 8178 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8179 8180 // If a user-defined conversion was applied to either of the operands prior 8181 // to applying the built-in operator rules, tell the user about it. 8182 if (OrigLHS.Conversion) { 8183 Diag(OrigLHS.Conversion->getLocation(), 8184 diag::note_typecheck_invalid_operands_converted) 8185 << 0 << LHS.get()->getType(); 8186 } 8187 if (OrigRHS.Conversion) { 8188 Diag(OrigRHS.Conversion->getLocation(), 8189 diag::note_typecheck_invalid_operands_converted) 8190 << 1 << RHS.get()->getType(); 8191 } 8192 8193 return QualType(); 8194 } 8195 8196 // Diagnose cases where a scalar was implicitly converted to a vector and 8197 // diagnose the underlying types. Otherwise, diagnose the error 8198 // as invalid vector logical operands for non-C++ cases. 8199 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8200 ExprResult &RHS) { 8201 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8202 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8203 8204 bool LHSNatVec = LHSType->isVectorType(); 8205 bool RHSNatVec = RHSType->isVectorType(); 8206 8207 if (!(LHSNatVec && RHSNatVec)) { 8208 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8209 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8210 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8211 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8212 << Vector->getSourceRange(); 8213 return QualType(); 8214 } 8215 8216 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8217 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8218 << RHS.get()->getSourceRange(); 8219 8220 return QualType(); 8221 } 8222 8223 /// Try to convert a value of non-vector type to a vector type by converting 8224 /// the type to the element type of the vector and then performing a splat. 8225 /// If the language is OpenCL, we only use conversions that promote scalar 8226 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8227 /// for float->int. 8228 /// 8229 /// OpenCL V2.0 6.2.6.p2: 8230 /// An error shall occur if any scalar operand type has greater rank 8231 /// than the type of the vector element. 8232 /// 8233 /// \param scalar - if non-null, actually perform the conversions 8234 /// \return true if the operation fails (but without diagnosing the failure) 8235 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8236 QualType scalarTy, 8237 QualType vectorEltTy, 8238 QualType vectorTy, 8239 unsigned &DiagID) { 8240 // The conversion to apply to the scalar before splatting it, 8241 // if necessary. 8242 CastKind scalarCast = CK_NoOp; 8243 8244 if (vectorEltTy->isIntegralType(S.Context)) { 8245 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8246 (scalarTy->isIntegerType() && 8247 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8248 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8249 return true; 8250 } 8251 if (!scalarTy->isIntegralType(S.Context)) 8252 return true; 8253 scalarCast = CK_IntegralCast; 8254 } else if (vectorEltTy->isRealFloatingType()) { 8255 if (scalarTy->isRealFloatingType()) { 8256 if (S.getLangOpts().OpenCL && 8257 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8258 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8259 return true; 8260 } 8261 scalarCast = CK_FloatingCast; 8262 } 8263 else if (scalarTy->isIntegralType(S.Context)) 8264 scalarCast = CK_IntegralToFloating; 8265 else 8266 return true; 8267 } else { 8268 return true; 8269 } 8270 8271 // Adjust scalar if desired. 8272 if (scalar) { 8273 if (scalarCast != CK_NoOp) 8274 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8275 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8276 } 8277 return false; 8278 } 8279 8280 /// Convert vector E to a vector with the same number of elements but different 8281 /// element type. 8282 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8283 const auto *VecTy = E->getType()->getAs<VectorType>(); 8284 assert(VecTy && "Expression E must be a vector"); 8285 QualType NewVecTy = S.Context.getVectorType(ElementType, 8286 VecTy->getNumElements(), 8287 VecTy->getVectorKind()); 8288 8289 // Look through the implicit cast. Return the subexpression if its type is 8290 // NewVecTy. 8291 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8292 if (ICE->getSubExpr()->getType() == NewVecTy) 8293 return ICE->getSubExpr(); 8294 8295 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8296 return S.ImpCastExprToType(E, NewVecTy, Cast); 8297 } 8298 8299 /// Test if a (constant) integer Int can be casted to another integer type 8300 /// IntTy without losing precision. 8301 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8302 QualType OtherIntTy) { 8303 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8304 8305 // Reject cases where the value of the Int is unknown as that would 8306 // possibly cause truncation, but accept cases where the scalar can be 8307 // demoted without loss of precision. 8308 llvm::APSInt Result; 8309 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8310 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8311 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8312 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8313 8314 if (CstInt) { 8315 // If the scalar is constant and is of a higher order and has more active 8316 // bits that the vector element type, reject it. 8317 unsigned NumBits = IntSigned 8318 ? (Result.isNegative() ? Result.getMinSignedBits() 8319 : Result.getActiveBits()) 8320 : Result.getActiveBits(); 8321 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8322 return true; 8323 8324 // If the signedness of the scalar type and the vector element type 8325 // differs and the number of bits is greater than that of the vector 8326 // element reject it. 8327 return (IntSigned != OtherIntSigned && 8328 NumBits > S.Context.getIntWidth(OtherIntTy)); 8329 } 8330 8331 // Reject cases where the value of the scalar is not constant and it's 8332 // order is greater than that of the vector element type. 8333 return (Order < 0); 8334 } 8335 8336 /// Test if a (constant) integer Int can be casted to floating point type 8337 /// FloatTy without losing precision. 8338 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8339 QualType FloatTy) { 8340 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8341 8342 // Determine if the integer constant can be expressed as a floating point 8343 // number of the appropriate type. 8344 llvm::APSInt Result; 8345 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8346 uint64_t Bits = 0; 8347 if (CstInt) { 8348 // Reject constants that would be truncated if they were converted to 8349 // the floating point type. Test by simple to/from conversion. 8350 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8351 // could be avoided if there was a convertFromAPInt method 8352 // which could signal back if implicit truncation occurred. 8353 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8354 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8355 llvm::APFloat::rmTowardZero); 8356 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8357 !IntTy->hasSignedIntegerRepresentation()); 8358 bool Ignored = false; 8359 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8360 &Ignored); 8361 if (Result != ConvertBack) 8362 return true; 8363 } else { 8364 // Reject types that cannot be fully encoded into the mantissa of 8365 // the float. 8366 Bits = S.Context.getTypeSize(IntTy); 8367 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8368 S.Context.getFloatTypeSemantics(FloatTy)); 8369 if (Bits > FloatPrec) 8370 return true; 8371 } 8372 8373 return false; 8374 } 8375 8376 /// Attempt to convert and splat Scalar into a vector whose types matches 8377 /// Vector following GCC conversion rules. The rule is that implicit 8378 /// conversion can occur when Scalar can be casted to match Vector's element 8379 /// type without causing truncation of Scalar. 8380 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8381 ExprResult *Vector) { 8382 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8383 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8384 const VectorType *VT = VectorTy->getAs<VectorType>(); 8385 8386 assert(!isa<ExtVectorType>(VT) && 8387 "ExtVectorTypes should not be handled here!"); 8388 8389 QualType VectorEltTy = VT->getElementType(); 8390 8391 // Reject cases where the vector element type or the scalar element type are 8392 // not integral or floating point types. 8393 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8394 return true; 8395 8396 // The conversion to apply to the scalar before splatting it, 8397 // if necessary. 8398 CastKind ScalarCast = CK_NoOp; 8399 8400 // Accept cases where the vector elements are integers and the scalar is 8401 // an integer. 8402 // FIXME: Notionally if the scalar was a floating point value with a precise 8403 // integral representation, we could cast it to an appropriate integer 8404 // type and then perform the rest of the checks here. GCC will perform 8405 // this conversion in some cases as determined by the input language. 8406 // We should accept it on a language independent basis. 8407 if (VectorEltTy->isIntegralType(S.Context) && 8408 ScalarTy->isIntegralType(S.Context) && 8409 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8410 8411 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8412 return true; 8413 8414 ScalarCast = CK_IntegralCast; 8415 } else if (VectorEltTy->isRealFloatingType()) { 8416 if (ScalarTy->isRealFloatingType()) { 8417 8418 // Reject cases where the scalar type is not a constant and has a higher 8419 // Order than the vector element type. 8420 llvm::APFloat Result(0.0); 8421 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8422 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8423 if (!CstScalar && Order < 0) 8424 return true; 8425 8426 // If the scalar cannot be safely casted to the vector element type, 8427 // reject it. 8428 if (CstScalar) { 8429 bool Truncated = false; 8430 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8431 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8432 if (Truncated) 8433 return true; 8434 } 8435 8436 ScalarCast = CK_FloatingCast; 8437 } else if (ScalarTy->isIntegralType(S.Context)) { 8438 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8439 return true; 8440 8441 ScalarCast = CK_IntegralToFloating; 8442 } else 8443 return true; 8444 } 8445 8446 // Adjust scalar if desired. 8447 if (Scalar) { 8448 if (ScalarCast != CK_NoOp) 8449 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8450 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8451 } 8452 return false; 8453 } 8454 8455 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8456 SourceLocation Loc, bool IsCompAssign, 8457 bool AllowBothBool, 8458 bool AllowBoolConversions) { 8459 if (!IsCompAssign) { 8460 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8461 if (LHS.isInvalid()) 8462 return QualType(); 8463 } 8464 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8465 if (RHS.isInvalid()) 8466 return QualType(); 8467 8468 // For conversion purposes, we ignore any qualifiers. 8469 // For example, "const float" and "float" are equivalent. 8470 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8471 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8472 8473 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8474 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8475 assert(LHSVecType || RHSVecType); 8476 8477 // AltiVec-style "vector bool op vector bool" combinations are allowed 8478 // for some operators but not others. 8479 if (!AllowBothBool && 8480 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8481 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8482 return InvalidOperands(Loc, LHS, RHS); 8483 8484 // If the vector types are identical, return. 8485 if (Context.hasSameType(LHSType, RHSType)) 8486 return LHSType; 8487 8488 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8489 if (LHSVecType && RHSVecType && 8490 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8491 if (isa<ExtVectorType>(LHSVecType)) { 8492 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8493 return LHSType; 8494 } 8495 8496 if (!IsCompAssign) 8497 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8498 return RHSType; 8499 } 8500 8501 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8502 // can be mixed, with the result being the non-bool type. The non-bool 8503 // operand must have integer element type. 8504 if (AllowBoolConversions && LHSVecType && RHSVecType && 8505 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8506 (Context.getTypeSize(LHSVecType->getElementType()) == 8507 Context.getTypeSize(RHSVecType->getElementType()))) { 8508 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8509 LHSVecType->getElementType()->isIntegerType() && 8510 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8511 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8512 return LHSType; 8513 } 8514 if (!IsCompAssign && 8515 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8516 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8517 RHSVecType->getElementType()->isIntegerType()) { 8518 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8519 return RHSType; 8520 } 8521 } 8522 8523 // If there's a vector type and a scalar, try to convert the scalar to 8524 // the vector element type and splat. 8525 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8526 if (!RHSVecType) { 8527 if (isa<ExtVectorType>(LHSVecType)) { 8528 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8529 LHSVecType->getElementType(), LHSType, 8530 DiagID)) 8531 return LHSType; 8532 } else { 8533 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8534 return LHSType; 8535 } 8536 } 8537 if (!LHSVecType) { 8538 if (isa<ExtVectorType>(RHSVecType)) { 8539 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8540 LHSType, RHSVecType->getElementType(), 8541 RHSType, DiagID)) 8542 return RHSType; 8543 } else { 8544 if (LHS.get()->getValueKind() == VK_LValue || 8545 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8546 return RHSType; 8547 } 8548 } 8549 8550 // FIXME: The code below also handles conversion between vectors and 8551 // non-scalars, we should break this down into fine grained specific checks 8552 // and emit proper diagnostics. 8553 QualType VecType = LHSVecType ? LHSType : RHSType; 8554 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8555 QualType OtherType = LHSVecType ? RHSType : LHSType; 8556 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8557 if (isLaxVectorConversion(OtherType, VecType)) { 8558 // If we're allowing lax vector conversions, only the total (data) size 8559 // needs to be the same. For non compound assignment, if one of the types is 8560 // scalar, the result is always the vector type. 8561 if (!IsCompAssign) { 8562 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8563 return VecType; 8564 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8565 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8566 // type. Note that this is already done by non-compound assignments in 8567 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8568 // <1 x T> -> T. The result is also a vector type. 8569 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8570 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8571 ExprResult *RHSExpr = &RHS; 8572 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8573 return VecType; 8574 } 8575 } 8576 8577 // Okay, the expression is invalid. 8578 8579 // If there's a non-vector, non-real operand, diagnose that. 8580 if ((!RHSVecType && !RHSType->isRealType()) || 8581 (!LHSVecType && !LHSType->isRealType())) { 8582 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8583 << LHSType << RHSType 8584 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8585 return QualType(); 8586 } 8587 8588 // OpenCL V1.1 6.2.6.p1: 8589 // If the operands are of more than one vector type, then an error shall 8590 // occur. Implicit conversions between vector types are not permitted, per 8591 // section 6.2.1. 8592 if (getLangOpts().OpenCL && 8593 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8594 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8595 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8596 << RHSType; 8597 return QualType(); 8598 } 8599 8600 8601 // If there is a vector type that is not a ExtVector and a scalar, we reach 8602 // this point if scalar could not be converted to the vector's element type 8603 // without truncation. 8604 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8605 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8606 QualType Scalar = LHSVecType ? RHSType : LHSType; 8607 QualType Vector = LHSVecType ? LHSType : RHSType; 8608 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8609 Diag(Loc, 8610 diag::err_typecheck_vector_not_convertable_implict_truncation) 8611 << ScalarOrVector << Scalar << Vector; 8612 8613 return QualType(); 8614 } 8615 8616 // Otherwise, use the generic diagnostic. 8617 Diag(Loc, DiagID) 8618 << LHSType << RHSType 8619 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8620 return QualType(); 8621 } 8622 8623 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8624 // expression. These are mainly cases where the null pointer is used as an 8625 // integer instead of a pointer. 8626 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8627 SourceLocation Loc, bool IsCompare) { 8628 // The canonical way to check for a GNU null is with isNullPointerConstant, 8629 // but we use a bit of a hack here for speed; this is a relatively 8630 // hot path, and isNullPointerConstant is slow. 8631 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8632 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8633 8634 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8635 8636 // Avoid analyzing cases where the result will either be invalid (and 8637 // diagnosed as such) or entirely valid and not something to warn about. 8638 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8639 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8640 return; 8641 8642 // Comparison operations would not make sense with a null pointer no matter 8643 // what the other expression is. 8644 if (!IsCompare) { 8645 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8646 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8647 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8648 return; 8649 } 8650 8651 // The rest of the operations only make sense with a null pointer 8652 // if the other expression is a pointer. 8653 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8654 NonNullType->canDecayToPointerType()) 8655 return; 8656 8657 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8658 << LHSNull /* LHS is NULL */ << NonNullType 8659 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8660 } 8661 8662 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8663 ExprResult &RHS, 8664 SourceLocation Loc, bool IsDiv) { 8665 // Check for division/remainder by zero. 8666 llvm::APSInt RHSValue; 8667 if (!RHS.get()->isValueDependent() && 8668 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8669 S.DiagRuntimeBehavior(Loc, RHS.get(), 8670 S.PDiag(diag::warn_remainder_division_by_zero) 8671 << IsDiv << RHS.get()->getSourceRange()); 8672 } 8673 8674 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8675 SourceLocation Loc, 8676 bool IsCompAssign, bool IsDiv) { 8677 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8678 8679 if (LHS.get()->getType()->isVectorType() || 8680 RHS.get()->getType()->isVectorType()) 8681 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8682 /*AllowBothBool*/getLangOpts().AltiVec, 8683 /*AllowBoolConversions*/false); 8684 8685 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8686 if (LHS.isInvalid() || RHS.isInvalid()) 8687 return QualType(); 8688 8689 8690 if (compType.isNull() || !compType->isArithmeticType()) 8691 return InvalidOperands(Loc, LHS, RHS); 8692 if (IsDiv) 8693 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8694 return compType; 8695 } 8696 8697 QualType Sema::CheckRemainderOperands( 8698 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8699 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8700 8701 if (LHS.get()->getType()->isVectorType() || 8702 RHS.get()->getType()->isVectorType()) { 8703 if (LHS.get()->getType()->hasIntegerRepresentation() && 8704 RHS.get()->getType()->hasIntegerRepresentation()) 8705 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8706 /*AllowBothBool*/getLangOpts().AltiVec, 8707 /*AllowBoolConversions*/false); 8708 return InvalidOperands(Loc, LHS, RHS); 8709 } 8710 8711 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8712 if (LHS.isInvalid() || RHS.isInvalid()) 8713 return QualType(); 8714 8715 if (compType.isNull() || !compType->isIntegerType()) 8716 return InvalidOperands(Loc, LHS, RHS); 8717 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8718 return compType; 8719 } 8720 8721 /// Diagnose invalid arithmetic on two void pointers. 8722 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8723 Expr *LHSExpr, Expr *RHSExpr) { 8724 S.Diag(Loc, S.getLangOpts().CPlusPlus 8725 ? diag::err_typecheck_pointer_arith_void_type 8726 : diag::ext_gnu_void_ptr) 8727 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8728 << RHSExpr->getSourceRange(); 8729 } 8730 8731 /// Diagnose invalid arithmetic on a void pointer. 8732 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8733 Expr *Pointer) { 8734 S.Diag(Loc, S.getLangOpts().CPlusPlus 8735 ? diag::err_typecheck_pointer_arith_void_type 8736 : diag::ext_gnu_void_ptr) 8737 << 0 /* one pointer */ << Pointer->getSourceRange(); 8738 } 8739 8740 /// Diagnose invalid arithmetic on a null pointer. 8741 /// 8742 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8743 /// idiom, which we recognize as a GNU extension. 8744 /// 8745 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8746 Expr *Pointer, bool IsGNUIdiom) { 8747 if (IsGNUIdiom) 8748 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8749 << Pointer->getSourceRange(); 8750 else 8751 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8752 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8753 } 8754 8755 /// Diagnose invalid arithmetic on two function pointers. 8756 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8757 Expr *LHS, Expr *RHS) { 8758 assert(LHS->getType()->isAnyPointerType()); 8759 assert(RHS->getType()->isAnyPointerType()); 8760 S.Diag(Loc, S.getLangOpts().CPlusPlus 8761 ? diag::err_typecheck_pointer_arith_function_type 8762 : diag::ext_gnu_ptr_func_arith) 8763 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8764 // We only show the second type if it differs from the first. 8765 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8766 RHS->getType()) 8767 << RHS->getType()->getPointeeType() 8768 << LHS->getSourceRange() << RHS->getSourceRange(); 8769 } 8770 8771 /// Diagnose invalid arithmetic on a function pointer. 8772 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8773 Expr *Pointer) { 8774 assert(Pointer->getType()->isAnyPointerType()); 8775 S.Diag(Loc, S.getLangOpts().CPlusPlus 8776 ? diag::err_typecheck_pointer_arith_function_type 8777 : diag::ext_gnu_ptr_func_arith) 8778 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8779 << 0 /* one pointer, so only one type */ 8780 << Pointer->getSourceRange(); 8781 } 8782 8783 /// Emit error if Operand is incomplete pointer type 8784 /// 8785 /// \returns True if pointer has incomplete type 8786 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8787 Expr *Operand) { 8788 QualType ResType = Operand->getType(); 8789 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8790 ResType = ResAtomicType->getValueType(); 8791 8792 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8793 QualType PointeeTy = ResType->getPointeeType(); 8794 return S.RequireCompleteType(Loc, PointeeTy, 8795 diag::err_typecheck_arithmetic_incomplete_type, 8796 PointeeTy, Operand->getSourceRange()); 8797 } 8798 8799 /// Check the validity of an arithmetic pointer operand. 8800 /// 8801 /// If the operand has pointer type, this code will check for pointer types 8802 /// which are invalid in arithmetic operations. These will be diagnosed 8803 /// appropriately, including whether or not the use is supported as an 8804 /// extension. 8805 /// 8806 /// \returns True when the operand is valid to use (even if as an extension). 8807 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8808 Expr *Operand) { 8809 QualType ResType = Operand->getType(); 8810 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8811 ResType = ResAtomicType->getValueType(); 8812 8813 if (!ResType->isAnyPointerType()) return true; 8814 8815 QualType PointeeTy = ResType->getPointeeType(); 8816 if (PointeeTy->isVoidType()) { 8817 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8818 return !S.getLangOpts().CPlusPlus; 8819 } 8820 if (PointeeTy->isFunctionType()) { 8821 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8822 return !S.getLangOpts().CPlusPlus; 8823 } 8824 8825 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8826 8827 return true; 8828 } 8829 8830 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8831 /// operands. 8832 /// 8833 /// This routine will diagnose any invalid arithmetic on pointer operands much 8834 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8835 /// for emitting a single diagnostic even for operations where both LHS and RHS 8836 /// are (potentially problematic) pointers. 8837 /// 8838 /// \returns True when the operand is valid to use (even if as an extension). 8839 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8840 Expr *LHSExpr, Expr *RHSExpr) { 8841 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8842 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8843 if (!isLHSPointer && !isRHSPointer) return true; 8844 8845 QualType LHSPointeeTy, RHSPointeeTy; 8846 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8847 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8848 8849 // if both are pointers check if operation is valid wrt address spaces 8850 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8851 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8852 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8853 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8854 S.Diag(Loc, 8855 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8856 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8857 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8858 return false; 8859 } 8860 } 8861 8862 // Check for arithmetic on pointers to incomplete types. 8863 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8864 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8865 if (isLHSVoidPtr || isRHSVoidPtr) { 8866 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8867 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8868 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8869 8870 return !S.getLangOpts().CPlusPlus; 8871 } 8872 8873 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8874 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8875 if (isLHSFuncPtr || isRHSFuncPtr) { 8876 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8877 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8878 RHSExpr); 8879 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8880 8881 return !S.getLangOpts().CPlusPlus; 8882 } 8883 8884 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8885 return false; 8886 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8887 return false; 8888 8889 return true; 8890 } 8891 8892 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8893 /// literal. 8894 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8895 Expr *LHSExpr, Expr *RHSExpr) { 8896 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8897 Expr* IndexExpr = RHSExpr; 8898 if (!StrExpr) { 8899 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8900 IndexExpr = LHSExpr; 8901 } 8902 8903 bool IsStringPlusInt = StrExpr && 8904 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8905 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8906 return; 8907 8908 llvm::APSInt index; 8909 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8910 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8911 if (index.isNonNegative() && 8912 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8913 index.isUnsigned())) 8914 return; 8915 } 8916 8917 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8918 Self.Diag(OpLoc, diag::warn_string_plus_int) 8919 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8920 8921 // Only print a fixit for "str" + int, not for int + "str". 8922 if (IndexExpr == RHSExpr) { 8923 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8924 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8925 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8926 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8927 << FixItHint::CreateInsertion(EndLoc, "]"); 8928 } else 8929 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8930 } 8931 8932 /// Emit a warning when adding a char literal to a string. 8933 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8934 Expr *LHSExpr, Expr *RHSExpr) { 8935 const Expr *StringRefExpr = LHSExpr; 8936 const CharacterLiteral *CharExpr = 8937 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8938 8939 if (!CharExpr) { 8940 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8941 StringRefExpr = RHSExpr; 8942 } 8943 8944 if (!CharExpr || !StringRefExpr) 8945 return; 8946 8947 const QualType StringType = StringRefExpr->getType(); 8948 8949 // Return if not a PointerType. 8950 if (!StringType->isAnyPointerType()) 8951 return; 8952 8953 // Return if not a CharacterType. 8954 if (!StringType->getPointeeType()->isAnyCharacterType()) 8955 return; 8956 8957 ASTContext &Ctx = Self.getASTContext(); 8958 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8959 8960 const QualType CharType = CharExpr->getType(); 8961 if (!CharType->isAnyCharacterType() && 8962 CharType->isIntegerType() && 8963 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8964 Self.Diag(OpLoc, diag::warn_string_plus_char) 8965 << DiagRange << Ctx.CharTy; 8966 } else { 8967 Self.Diag(OpLoc, diag::warn_string_plus_char) 8968 << DiagRange << CharExpr->getType(); 8969 } 8970 8971 // Only print a fixit for str + char, not for char + str. 8972 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8973 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8974 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8975 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8976 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8977 << FixItHint::CreateInsertion(EndLoc, "]"); 8978 } else { 8979 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8980 } 8981 } 8982 8983 /// Emit error when two pointers are incompatible. 8984 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8985 Expr *LHSExpr, Expr *RHSExpr) { 8986 assert(LHSExpr->getType()->isAnyPointerType()); 8987 assert(RHSExpr->getType()->isAnyPointerType()); 8988 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8989 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8990 << RHSExpr->getSourceRange(); 8991 } 8992 8993 // C99 6.5.6 8994 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8995 SourceLocation Loc, BinaryOperatorKind Opc, 8996 QualType* CompLHSTy) { 8997 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8998 8999 if (LHS.get()->getType()->isVectorType() || 9000 RHS.get()->getType()->isVectorType()) { 9001 QualType compType = CheckVectorOperands( 9002 LHS, RHS, Loc, CompLHSTy, 9003 /*AllowBothBool*/getLangOpts().AltiVec, 9004 /*AllowBoolConversions*/getLangOpts().ZVector); 9005 if (CompLHSTy) *CompLHSTy = compType; 9006 return compType; 9007 } 9008 9009 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9010 if (LHS.isInvalid() || RHS.isInvalid()) 9011 return QualType(); 9012 9013 // Diagnose "string literal" '+' int and string '+' "char literal". 9014 if (Opc == BO_Add) { 9015 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9016 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9017 } 9018 9019 // handle the common case first (both operands are arithmetic). 9020 if (!compType.isNull() && compType->isArithmeticType()) { 9021 if (CompLHSTy) *CompLHSTy = compType; 9022 return compType; 9023 } 9024 9025 // Type-checking. Ultimately the pointer's going to be in PExp; 9026 // note that we bias towards the LHS being the pointer. 9027 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9028 9029 bool isObjCPointer; 9030 if (PExp->getType()->isPointerType()) { 9031 isObjCPointer = false; 9032 } else if (PExp->getType()->isObjCObjectPointerType()) { 9033 isObjCPointer = true; 9034 } else { 9035 std::swap(PExp, IExp); 9036 if (PExp->getType()->isPointerType()) { 9037 isObjCPointer = false; 9038 } else if (PExp->getType()->isObjCObjectPointerType()) { 9039 isObjCPointer = true; 9040 } else { 9041 return InvalidOperands(Loc, LHS, RHS); 9042 } 9043 } 9044 assert(PExp->getType()->isAnyPointerType()); 9045 9046 if (!IExp->getType()->isIntegerType()) 9047 return InvalidOperands(Loc, LHS, RHS); 9048 9049 // Adding to a null pointer results in undefined behavior. 9050 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9051 Context, Expr::NPC_ValueDependentIsNotNull)) { 9052 // In C++ adding zero to a null pointer is defined. 9053 llvm::APSInt KnownVal; 9054 if (!getLangOpts().CPlusPlus || 9055 (!IExp->isValueDependent() && 9056 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9057 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9058 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9059 Context, BO_Add, PExp, IExp); 9060 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9061 } 9062 } 9063 9064 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9065 return QualType(); 9066 9067 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9068 return QualType(); 9069 9070 // Check array bounds for pointer arithemtic 9071 CheckArrayAccess(PExp, IExp); 9072 9073 if (CompLHSTy) { 9074 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9075 if (LHSTy.isNull()) { 9076 LHSTy = LHS.get()->getType(); 9077 if (LHSTy->isPromotableIntegerType()) 9078 LHSTy = Context.getPromotedIntegerType(LHSTy); 9079 } 9080 *CompLHSTy = LHSTy; 9081 } 9082 9083 return PExp->getType(); 9084 } 9085 9086 // C99 6.5.6 9087 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9088 SourceLocation Loc, 9089 QualType* CompLHSTy) { 9090 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9091 9092 if (LHS.get()->getType()->isVectorType() || 9093 RHS.get()->getType()->isVectorType()) { 9094 QualType compType = CheckVectorOperands( 9095 LHS, RHS, Loc, CompLHSTy, 9096 /*AllowBothBool*/getLangOpts().AltiVec, 9097 /*AllowBoolConversions*/getLangOpts().ZVector); 9098 if (CompLHSTy) *CompLHSTy = compType; 9099 return compType; 9100 } 9101 9102 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9103 if (LHS.isInvalid() || RHS.isInvalid()) 9104 return QualType(); 9105 9106 // Enforce type constraints: C99 6.5.6p3. 9107 9108 // Handle the common case first (both operands are arithmetic). 9109 if (!compType.isNull() && compType->isArithmeticType()) { 9110 if (CompLHSTy) *CompLHSTy = compType; 9111 return compType; 9112 } 9113 9114 // Either ptr - int or ptr - ptr. 9115 if (LHS.get()->getType()->isAnyPointerType()) { 9116 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9117 9118 // Diagnose bad cases where we step over interface counts. 9119 if (LHS.get()->getType()->isObjCObjectPointerType() && 9120 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9121 return QualType(); 9122 9123 // The result type of a pointer-int computation is the pointer type. 9124 if (RHS.get()->getType()->isIntegerType()) { 9125 // Subtracting from a null pointer should produce a warning. 9126 // The last argument to the diagnose call says this doesn't match the 9127 // GNU int-to-pointer idiom. 9128 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9129 Expr::NPC_ValueDependentIsNotNull)) { 9130 // In C++ adding zero to a null pointer is defined. 9131 llvm::APSInt KnownVal; 9132 if (!getLangOpts().CPlusPlus || 9133 (!RHS.get()->isValueDependent() && 9134 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9135 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9136 } 9137 } 9138 9139 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9140 return QualType(); 9141 9142 // Check array bounds for pointer arithemtic 9143 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9144 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9145 9146 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9147 return LHS.get()->getType(); 9148 } 9149 9150 // Handle pointer-pointer subtractions. 9151 if (const PointerType *RHSPTy 9152 = RHS.get()->getType()->getAs<PointerType>()) { 9153 QualType rpointee = RHSPTy->getPointeeType(); 9154 9155 if (getLangOpts().CPlusPlus) { 9156 // Pointee types must be the same: C++ [expr.add] 9157 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9158 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9159 } 9160 } else { 9161 // Pointee types must be compatible C99 6.5.6p3 9162 if (!Context.typesAreCompatible( 9163 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9164 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9165 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9166 return QualType(); 9167 } 9168 } 9169 9170 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9171 LHS.get(), RHS.get())) 9172 return QualType(); 9173 9174 // FIXME: Add warnings for nullptr - ptr. 9175 9176 // The pointee type may have zero size. As an extension, a structure or 9177 // union may have zero size or an array may have zero length. In this 9178 // case subtraction does not make sense. 9179 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9180 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9181 if (ElementSize.isZero()) { 9182 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9183 << rpointee.getUnqualifiedType() 9184 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9185 } 9186 } 9187 9188 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9189 return Context.getPointerDiffType(); 9190 } 9191 } 9192 9193 return InvalidOperands(Loc, LHS, RHS); 9194 } 9195 9196 static bool isScopedEnumerationType(QualType T) { 9197 if (const EnumType *ET = T->getAs<EnumType>()) 9198 return ET->getDecl()->isScoped(); 9199 return false; 9200 } 9201 9202 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9203 SourceLocation Loc, BinaryOperatorKind Opc, 9204 QualType LHSType) { 9205 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9206 // so skip remaining warnings as we don't want to modify values within Sema. 9207 if (S.getLangOpts().OpenCL) 9208 return; 9209 9210 llvm::APSInt Right; 9211 // Check right/shifter operand 9212 if (RHS.get()->isValueDependent() || 9213 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9214 return; 9215 9216 if (Right.isNegative()) { 9217 S.DiagRuntimeBehavior(Loc, RHS.get(), 9218 S.PDiag(diag::warn_shift_negative) 9219 << RHS.get()->getSourceRange()); 9220 return; 9221 } 9222 llvm::APInt LeftBits(Right.getBitWidth(), 9223 S.Context.getTypeSize(LHS.get()->getType())); 9224 if (Right.uge(LeftBits)) { 9225 S.DiagRuntimeBehavior(Loc, RHS.get(), 9226 S.PDiag(diag::warn_shift_gt_typewidth) 9227 << RHS.get()->getSourceRange()); 9228 return; 9229 } 9230 if (Opc != BO_Shl) 9231 return; 9232 9233 // When left shifting an ICE which is signed, we can check for overflow which 9234 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9235 // integers have defined behavior modulo one more than the maximum value 9236 // representable in the result type, so never warn for those. 9237 llvm::APSInt Left; 9238 if (LHS.get()->isValueDependent() || 9239 LHSType->hasUnsignedIntegerRepresentation() || 9240 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9241 return; 9242 9243 // If LHS does not have a signed type and non-negative value 9244 // then, the behavior is undefined. Warn about it. 9245 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9246 S.DiagRuntimeBehavior(Loc, LHS.get(), 9247 S.PDiag(diag::warn_shift_lhs_negative) 9248 << LHS.get()->getSourceRange()); 9249 return; 9250 } 9251 9252 llvm::APInt ResultBits = 9253 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9254 if (LeftBits.uge(ResultBits)) 9255 return; 9256 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9257 Result = Result.shl(Right); 9258 9259 // Print the bit representation of the signed integer as an unsigned 9260 // hexadecimal number. 9261 SmallString<40> HexResult; 9262 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9263 9264 // If we are only missing a sign bit, this is less likely to result in actual 9265 // bugs -- if the result is cast back to an unsigned type, it will have the 9266 // expected value. Thus we place this behind a different warning that can be 9267 // turned off separately if needed. 9268 if (LeftBits == ResultBits - 1) { 9269 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9270 << HexResult << LHSType 9271 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9272 return; 9273 } 9274 9275 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9276 << HexResult.str() << Result.getMinSignedBits() << LHSType 9277 << Left.getBitWidth() << LHS.get()->getSourceRange() 9278 << RHS.get()->getSourceRange(); 9279 } 9280 9281 /// Return the resulting type when a vector is shifted 9282 /// by a scalar or vector shift amount. 9283 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9284 SourceLocation Loc, bool IsCompAssign) { 9285 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9286 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9287 !LHS.get()->getType()->isVectorType()) { 9288 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9289 << RHS.get()->getType() << LHS.get()->getType() 9290 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9291 return QualType(); 9292 } 9293 9294 if (!IsCompAssign) { 9295 LHS = S.UsualUnaryConversions(LHS.get()); 9296 if (LHS.isInvalid()) return QualType(); 9297 } 9298 9299 RHS = S.UsualUnaryConversions(RHS.get()); 9300 if (RHS.isInvalid()) return QualType(); 9301 9302 QualType LHSType = LHS.get()->getType(); 9303 // Note that LHS might be a scalar because the routine calls not only in 9304 // OpenCL case. 9305 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9306 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9307 9308 // Note that RHS might not be a vector. 9309 QualType RHSType = RHS.get()->getType(); 9310 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9311 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9312 9313 // The operands need to be integers. 9314 if (!LHSEleType->isIntegerType()) { 9315 S.Diag(Loc, diag::err_typecheck_expect_int) 9316 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9317 return QualType(); 9318 } 9319 9320 if (!RHSEleType->isIntegerType()) { 9321 S.Diag(Loc, diag::err_typecheck_expect_int) 9322 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9323 return QualType(); 9324 } 9325 9326 if (!LHSVecTy) { 9327 assert(RHSVecTy); 9328 if (IsCompAssign) 9329 return RHSType; 9330 if (LHSEleType != RHSEleType) { 9331 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9332 LHSEleType = RHSEleType; 9333 } 9334 QualType VecTy = 9335 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9336 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9337 LHSType = VecTy; 9338 } else if (RHSVecTy) { 9339 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9340 // are applied component-wise. So if RHS is a vector, then ensure 9341 // that the number of elements is the same as LHS... 9342 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9343 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9344 << LHS.get()->getType() << RHS.get()->getType() 9345 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9346 return QualType(); 9347 } 9348 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9349 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9350 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9351 if (LHSBT != RHSBT && 9352 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9353 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9354 << LHS.get()->getType() << RHS.get()->getType() 9355 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9356 } 9357 } 9358 } else { 9359 // ...else expand RHS to match the number of elements in LHS. 9360 QualType VecTy = 9361 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9362 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9363 } 9364 9365 return LHSType; 9366 } 9367 9368 // C99 6.5.7 9369 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9370 SourceLocation Loc, BinaryOperatorKind Opc, 9371 bool IsCompAssign) { 9372 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9373 9374 // Vector shifts promote their scalar inputs to vector type. 9375 if (LHS.get()->getType()->isVectorType() || 9376 RHS.get()->getType()->isVectorType()) { 9377 if (LangOpts.ZVector) { 9378 // The shift operators for the z vector extensions work basically 9379 // like general shifts, except that neither the LHS nor the RHS is 9380 // allowed to be a "vector bool". 9381 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9382 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9383 return InvalidOperands(Loc, LHS, RHS); 9384 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9385 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9386 return InvalidOperands(Loc, LHS, RHS); 9387 } 9388 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9389 } 9390 9391 // Shifts don't perform usual arithmetic conversions, they just do integer 9392 // promotions on each operand. C99 6.5.7p3 9393 9394 // For the LHS, do usual unary conversions, but then reset them away 9395 // if this is a compound assignment. 9396 ExprResult OldLHS = LHS; 9397 LHS = UsualUnaryConversions(LHS.get()); 9398 if (LHS.isInvalid()) 9399 return QualType(); 9400 QualType LHSType = LHS.get()->getType(); 9401 if (IsCompAssign) LHS = OldLHS; 9402 9403 // The RHS is simpler. 9404 RHS = UsualUnaryConversions(RHS.get()); 9405 if (RHS.isInvalid()) 9406 return QualType(); 9407 QualType RHSType = RHS.get()->getType(); 9408 9409 // C99 6.5.7p2: Each of the operands shall have integer type. 9410 if (!LHSType->hasIntegerRepresentation() || 9411 !RHSType->hasIntegerRepresentation()) 9412 return InvalidOperands(Loc, LHS, RHS); 9413 9414 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9415 // hasIntegerRepresentation() above instead of this. 9416 if (isScopedEnumerationType(LHSType) || 9417 isScopedEnumerationType(RHSType)) { 9418 return InvalidOperands(Loc, LHS, RHS); 9419 } 9420 // Sanity-check shift operands 9421 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9422 9423 // "The type of the result is that of the promoted left operand." 9424 return LHSType; 9425 } 9426 9427 /// If two different enums are compared, raise a warning. 9428 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9429 Expr *RHS) { 9430 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9431 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9432 9433 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9434 if (!LHSEnumType) 9435 return; 9436 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9437 if (!RHSEnumType) 9438 return; 9439 9440 // Ignore anonymous enums. 9441 if (!LHSEnumType->getDecl()->getIdentifier() && 9442 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9443 return; 9444 if (!RHSEnumType->getDecl()->getIdentifier() && 9445 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9446 return; 9447 9448 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9449 return; 9450 9451 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9452 << LHSStrippedType << RHSStrippedType 9453 << LHS->getSourceRange() << RHS->getSourceRange(); 9454 } 9455 9456 /// Diagnose bad pointer comparisons. 9457 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9458 ExprResult &LHS, ExprResult &RHS, 9459 bool IsError) { 9460 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9461 : diag::ext_typecheck_comparison_of_distinct_pointers) 9462 << LHS.get()->getType() << RHS.get()->getType() 9463 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9464 } 9465 9466 /// Returns false if the pointers are converted to a composite type, 9467 /// true otherwise. 9468 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9469 ExprResult &LHS, ExprResult &RHS) { 9470 // C++ [expr.rel]p2: 9471 // [...] Pointer conversions (4.10) and qualification 9472 // conversions (4.4) are performed on pointer operands (or on 9473 // a pointer operand and a null pointer constant) to bring 9474 // them to their composite pointer type. [...] 9475 // 9476 // C++ [expr.eq]p1 uses the same notion for (in)equality 9477 // comparisons of pointers. 9478 9479 QualType LHSType = LHS.get()->getType(); 9480 QualType RHSType = RHS.get()->getType(); 9481 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9482 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9483 9484 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9485 if (T.isNull()) { 9486 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9487 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9488 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9489 else 9490 S.InvalidOperands(Loc, LHS, RHS); 9491 return true; 9492 } 9493 9494 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9495 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9496 return false; 9497 } 9498 9499 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9500 ExprResult &LHS, 9501 ExprResult &RHS, 9502 bool IsError) { 9503 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9504 : diag::ext_typecheck_comparison_of_fptr_to_void) 9505 << LHS.get()->getType() << RHS.get()->getType() 9506 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9507 } 9508 9509 static bool isObjCObjectLiteral(ExprResult &E) { 9510 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9511 case Stmt::ObjCArrayLiteralClass: 9512 case Stmt::ObjCDictionaryLiteralClass: 9513 case Stmt::ObjCStringLiteralClass: 9514 case Stmt::ObjCBoxedExprClass: 9515 return true; 9516 default: 9517 // Note that ObjCBoolLiteral is NOT an object literal! 9518 return false; 9519 } 9520 } 9521 9522 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9523 const ObjCObjectPointerType *Type = 9524 LHS->getType()->getAs<ObjCObjectPointerType>(); 9525 9526 // If this is not actually an Objective-C object, bail out. 9527 if (!Type) 9528 return false; 9529 9530 // Get the LHS object's interface type. 9531 QualType InterfaceType = Type->getPointeeType(); 9532 9533 // If the RHS isn't an Objective-C object, bail out. 9534 if (!RHS->getType()->isObjCObjectPointerType()) 9535 return false; 9536 9537 // Try to find the -isEqual: method. 9538 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9539 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9540 InterfaceType, 9541 /*instance=*/true); 9542 if (!Method) { 9543 if (Type->isObjCIdType()) { 9544 // For 'id', just check the global pool. 9545 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9546 /*receiverId=*/true); 9547 } else { 9548 // Check protocols. 9549 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9550 /*instance=*/true); 9551 } 9552 } 9553 9554 if (!Method) 9555 return false; 9556 9557 QualType T = Method->parameters()[0]->getType(); 9558 if (!T->isObjCObjectPointerType()) 9559 return false; 9560 9561 QualType R = Method->getReturnType(); 9562 if (!R->isScalarType()) 9563 return false; 9564 9565 return true; 9566 } 9567 9568 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9569 FromE = FromE->IgnoreParenImpCasts(); 9570 switch (FromE->getStmtClass()) { 9571 default: 9572 break; 9573 case Stmt::ObjCStringLiteralClass: 9574 // "string literal" 9575 return LK_String; 9576 case Stmt::ObjCArrayLiteralClass: 9577 // "array literal" 9578 return LK_Array; 9579 case Stmt::ObjCDictionaryLiteralClass: 9580 // "dictionary literal" 9581 return LK_Dictionary; 9582 case Stmt::BlockExprClass: 9583 return LK_Block; 9584 case Stmt::ObjCBoxedExprClass: { 9585 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9586 switch (Inner->getStmtClass()) { 9587 case Stmt::IntegerLiteralClass: 9588 case Stmt::FloatingLiteralClass: 9589 case Stmt::CharacterLiteralClass: 9590 case Stmt::ObjCBoolLiteralExprClass: 9591 case Stmt::CXXBoolLiteralExprClass: 9592 // "numeric literal" 9593 return LK_Numeric; 9594 case Stmt::ImplicitCastExprClass: { 9595 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9596 // Boolean literals can be represented by implicit casts. 9597 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9598 return LK_Numeric; 9599 break; 9600 } 9601 default: 9602 break; 9603 } 9604 return LK_Boxed; 9605 } 9606 } 9607 return LK_None; 9608 } 9609 9610 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9611 ExprResult &LHS, ExprResult &RHS, 9612 BinaryOperator::Opcode Opc){ 9613 Expr *Literal; 9614 Expr *Other; 9615 if (isObjCObjectLiteral(LHS)) { 9616 Literal = LHS.get(); 9617 Other = RHS.get(); 9618 } else { 9619 Literal = RHS.get(); 9620 Other = LHS.get(); 9621 } 9622 9623 // Don't warn on comparisons against nil. 9624 Other = Other->IgnoreParenCasts(); 9625 if (Other->isNullPointerConstant(S.getASTContext(), 9626 Expr::NPC_ValueDependentIsNotNull)) 9627 return; 9628 9629 // This should be kept in sync with warn_objc_literal_comparison. 9630 // LK_String should always be after the other literals, since it has its own 9631 // warning flag. 9632 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9633 assert(LiteralKind != Sema::LK_Block); 9634 if (LiteralKind == Sema::LK_None) { 9635 llvm_unreachable("Unknown Objective-C object literal kind"); 9636 } 9637 9638 if (LiteralKind == Sema::LK_String) 9639 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9640 << Literal->getSourceRange(); 9641 else 9642 S.Diag(Loc, diag::warn_objc_literal_comparison) 9643 << LiteralKind << Literal->getSourceRange(); 9644 9645 if (BinaryOperator::isEqualityOp(Opc) && 9646 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9647 SourceLocation Start = LHS.get()->getBeginLoc(); 9648 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9649 CharSourceRange OpRange = 9650 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9651 9652 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9653 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9654 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9655 << FixItHint::CreateInsertion(End, "]"); 9656 } 9657 } 9658 9659 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9660 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9661 ExprResult &RHS, SourceLocation Loc, 9662 BinaryOperatorKind Opc) { 9663 // Check that left hand side is !something. 9664 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9665 if (!UO || UO->getOpcode() != UO_LNot) return; 9666 9667 // Only check if the right hand side is non-bool arithmetic type. 9668 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9669 9670 // Make sure that the something in !something is not bool. 9671 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9672 if (SubExpr->isKnownToHaveBooleanValue()) return; 9673 9674 // Emit warning. 9675 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9676 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9677 << Loc << IsBitwiseOp; 9678 9679 // First note suggest !(x < y) 9680 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9681 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9682 FirstClose = S.getLocForEndOfToken(FirstClose); 9683 if (FirstClose.isInvalid()) 9684 FirstOpen = SourceLocation(); 9685 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9686 << IsBitwiseOp 9687 << FixItHint::CreateInsertion(FirstOpen, "(") 9688 << FixItHint::CreateInsertion(FirstClose, ")"); 9689 9690 // Second note suggests (!x) < y 9691 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9692 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9693 SecondClose = S.getLocForEndOfToken(SecondClose); 9694 if (SecondClose.isInvalid()) 9695 SecondOpen = SourceLocation(); 9696 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9697 << FixItHint::CreateInsertion(SecondOpen, "(") 9698 << FixItHint::CreateInsertion(SecondClose, ")"); 9699 } 9700 9701 // Get the decl for a simple expression: a reference to a variable, 9702 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9703 static ValueDecl *getCompareDecl(Expr *E) { 9704 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9705 return DR->getDecl(); 9706 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9707 if (Ivar->isFreeIvar()) 9708 return Ivar->getDecl(); 9709 } 9710 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9711 if (Mem->isImplicitAccess()) 9712 return Mem->getMemberDecl(); 9713 } 9714 return nullptr; 9715 } 9716 9717 /// Diagnose some forms of syntactically-obvious tautological comparison. 9718 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9719 Expr *LHS, Expr *RHS, 9720 BinaryOperatorKind Opc) { 9721 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9722 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9723 9724 QualType LHSType = LHS->getType(); 9725 QualType RHSType = RHS->getType(); 9726 if (LHSType->hasFloatingRepresentation() || 9727 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9728 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9729 S.inTemplateInstantiation()) 9730 return; 9731 9732 // Comparisons between two array types are ill-formed for operator<=>, so 9733 // we shouldn't emit any additional warnings about it. 9734 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9735 return; 9736 9737 // For non-floating point types, check for self-comparisons of the form 9738 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9739 // often indicate logic errors in the program. 9740 // 9741 // NOTE: Don't warn about comparison expressions resulting from macro 9742 // expansion. Also don't warn about comparisons which are only self 9743 // comparisons within a template instantiation. The warnings should catch 9744 // obvious cases in the definition of the template anyways. The idea is to 9745 // warn when the typed comparison operator will always evaluate to the same 9746 // result. 9747 ValueDecl *DL = getCompareDecl(LHSStripped); 9748 ValueDecl *DR = getCompareDecl(RHSStripped); 9749 if (DL && DR && declaresSameEntity(DL, DR)) { 9750 StringRef Result; 9751 switch (Opc) { 9752 case BO_EQ: case BO_LE: case BO_GE: 9753 Result = "true"; 9754 break; 9755 case BO_NE: case BO_LT: case BO_GT: 9756 Result = "false"; 9757 break; 9758 case BO_Cmp: 9759 Result = "'std::strong_ordering::equal'"; 9760 break; 9761 default: 9762 break; 9763 } 9764 S.DiagRuntimeBehavior(Loc, nullptr, 9765 S.PDiag(diag::warn_comparison_always) 9766 << 0 /*self-comparison*/ << !Result.empty() 9767 << Result); 9768 } else if (DL && DR && 9769 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9770 !DL->isWeak() && !DR->isWeak()) { 9771 // What is it always going to evaluate to? 9772 StringRef Result; 9773 switch(Opc) { 9774 case BO_EQ: // e.g. array1 == array2 9775 Result = "false"; 9776 break; 9777 case BO_NE: // e.g. array1 != array2 9778 Result = "true"; 9779 break; 9780 default: // e.g. array1 <= array2 9781 // The best we can say is 'a constant' 9782 break; 9783 } 9784 S.DiagRuntimeBehavior(Loc, nullptr, 9785 S.PDiag(diag::warn_comparison_always) 9786 << 1 /*array comparison*/ 9787 << !Result.empty() << Result); 9788 } 9789 9790 if (isa<CastExpr>(LHSStripped)) 9791 LHSStripped = LHSStripped->IgnoreParenCasts(); 9792 if (isa<CastExpr>(RHSStripped)) 9793 RHSStripped = RHSStripped->IgnoreParenCasts(); 9794 9795 // Warn about comparisons against a string constant (unless the other 9796 // operand is null); the user probably wants strcmp. 9797 Expr *LiteralString = nullptr; 9798 Expr *LiteralStringStripped = nullptr; 9799 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9800 !RHSStripped->isNullPointerConstant(S.Context, 9801 Expr::NPC_ValueDependentIsNull)) { 9802 LiteralString = LHS; 9803 LiteralStringStripped = LHSStripped; 9804 } else if ((isa<StringLiteral>(RHSStripped) || 9805 isa<ObjCEncodeExpr>(RHSStripped)) && 9806 !LHSStripped->isNullPointerConstant(S.Context, 9807 Expr::NPC_ValueDependentIsNull)) { 9808 LiteralString = RHS; 9809 LiteralStringStripped = RHSStripped; 9810 } 9811 9812 if (LiteralString) { 9813 S.DiagRuntimeBehavior(Loc, nullptr, 9814 S.PDiag(diag::warn_stringcompare) 9815 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9816 << LiteralString->getSourceRange()); 9817 } 9818 } 9819 9820 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9821 switch (CK) { 9822 default: { 9823 #ifndef NDEBUG 9824 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9825 << "\n"; 9826 #endif 9827 llvm_unreachable("unhandled cast kind"); 9828 } 9829 case CK_UserDefinedConversion: 9830 return ICK_Identity; 9831 case CK_LValueToRValue: 9832 return ICK_Lvalue_To_Rvalue; 9833 case CK_ArrayToPointerDecay: 9834 return ICK_Array_To_Pointer; 9835 case CK_FunctionToPointerDecay: 9836 return ICK_Function_To_Pointer; 9837 case CK_IntegralCast: 9838 return ICK_Integral_Conversion; 9839 case CK_FloatingCast: 9840 return ICK_Floating_Conversion; 9841 case CK_IntegralToFloating: 9842 case CK_FloatingToIntegral: 9843 return ICK_Floating_Integral; 9844 case CK_IntegralComplexCast: 9845 case CK_FloatingComplexCast: 9846 case CK_FloatingComplexToIntegralComplex: 9847 case CK_IntegralComplexToFloatingComplex: 9848 return ICK_Complex_Conversion; 9849 case CK_FloatingComplexToReal: 9850 case CK_FloatingRealToComplex: 9851 case CK_IntegralComplexToReal: 9852 case CK_IntegralRealToComplex: 9853 return ICK_Complex_Real; 9854 } 9855 } 9856 9857 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9858 QualType FromType, 9859 SourceLocation Loc) { 9860 // Check for a narrowing implicit conversion. 9861 StandardConversionSequence SCS; 9862 SCS.setAsIdentityConversion(); 9863 SCS.setToType(0, FromType); 9864 SCS.setToType(1, ToType); 9865 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9866 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9867 9868 APValue PreNarrowingValue; 9869 QualType PreNarrowingType; 9870 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9871 PreNarrowingType, 9872 /*IgnoreFloatToIntegralConversion*/ true)) { 9873 case NK_Dependent_Narrowing: 9874 // Implicit conversion to a narrower type, but the expression is 9875 // value-dependent so we can't tell whether it's actually narrowing. 9876 case NK_Not_Narrowing: 9877 return false; 9878 9879 case NK_Constant_Narrowing: 9880 // Implicit conversion to a narrower type, and the value is not a constant 9881 // expression. 9882 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9883 << /*Constant*/ 1 9884 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9885 return true; 9886 9887 case NK_Variable_Narrowing: 9888 // Implicit conversion to a narrower type, and the value is not a constant 9889 // expression. 9890 case NK_Type_Narrowing: 9891 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9892 << /*Constant*/ 0 << FromType << ToType; 9893 // TODO: It's not a constant expression, but what if the user intended it 9894 // to be? Can we produce notes to help them figure out why it isn't? 9895 return true; 9896 } 9897 llvm_unreachable("unhandled case in switch"); 9898 } 9899 9900 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9901 ExprResult &LHS, 9902 ExprResult &RHS, 9903 SourceLocation Loc) { 9904 using CCT = ComparisonCategoryType; 9905 9906 QualType LHSType = LHS.get()->getType(); 9907 QualType RHSType = RHS.get()->getType(); 9908 // Dig out the original argument type and expression before implicit casts 9909 // were applied. These are the types/expressions we need to check the 9910 // [expr.spaceship] requirements against. 9911 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9912 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9913 QualType LHSStrippedType = LHSStripped.get()->getType(); 9914 QualType RHSStrippedType = RHSStripped.get()->getType(); 9915 9916 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9917 // other is not, the program is ill-formed. 9918 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9919 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9920 return QualType(); 9921 } 9922 9923 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9924 RHSStrippedType->isEnumeralType(); 9925 if (NumEnumArgs == 1) { 9926 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9927 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9928 if (OtherTy->hasFloatingRepresentation()) { 9929 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9930 return QualType(); 9931 } 9932 } 9933 if (NumEnumArgs == 2) { 9934 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 9935 // type E, the operator yields the result of converting the operands 9936 // to the underlying type of E and applying <=> to the converted operands. 9937 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 9938 S.InvalidOperands(Loc, LHS, RHS); 9939 return QualType(); 9940 } 9941 QualType IntType = 9942 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 9943 assert(IntType->isArithmeticType()); 9944 9945 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 9946 // promote the boolean type, and all other promotable integer types, to 9947 // avoid this. 9948 if (IntType->isPromotableIntegerType()) 9949 IntType = S.Context.getPromotedIntegerType(IntType); 9950 9951 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 9952 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 9953 LHSType = RHSType = IntType; 9954 } 9955 9956 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 9957 // usual arithmetic conversions are applied to the operands. 9958 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9959 if (LHS.isInvalid() || RHS.isInvalid()) 9960 return QualType(); 9961 if (Type.isNull()) 9962 return S.InvalidOperands(Loc, LHS, RHS); 9963 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9964 9965 bool HasNarrowing = checkThreeWayNarrowingConversion( 9966 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 9967 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 9968 RHS.get()->getBeginLoc()); 9969 if (HasNarrowing) 9970 return QualType(); 9971 9972 assert(!Type.isNull() && "composite type for <=> has not been set"); 9973 9974 auto TypeKind = [&]() { 9975 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 9976 if (CT->getElementType()->hasFloatingRepresentation()) 9977 return CCT::WeakEquality; 9978 return CCT::StrongEquality; 9979 } 9980 if (Type->isIntegralOrEnumerationType()) 9981 return CCT::StrongOrdering; 9982 if (Type->hasFloatingRepresentation()) 9983 return CCT::PartialOrdering; 9984 llvm_unreachable("other types are unimplemented"); 9985 }(); 9986 9987 return S.CheckComparisonCategoryType(TypeKind, Loc); 9988 } 9989 9990 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9991 ExprResult &RHS, 9992 SourceLocation Loc, 9993 BinaryOperatorKind Opc) { 9994 if (Opc == BO_Cmp) 9995 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 9996 9997 // C99 6.5.8p3 / C99 6.5.9p4 9998 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9999 if (LHS.isInvalid() || RHS.isInvalid()) 10000 return QualType(); 10001 if (Type.isNull()) 10002 return S.InvalidOperands(Loc, LHS, RHS); 10003 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10004 10005 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10006 10007 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10008 return S.InvalidOperands(Loc, LHS, RHS); 10009 10010 // Check for comparisons of floating point operands using != and ==. 10011 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10012 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10013 10014 // The result of comparisons is 'bool' in C++, 'int' in C. 10015 return S.Context.getLogicalOperationType(); 10016 } 10017 10018 // C99 6.5.8, C++ [expr.rel] 10019 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10020 SourceLocation Loc, 10021 BinaryOperatorKind Opc) { 10022 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10023 bool IsThreeWay = Opc == BO_Cmp; 10024 auto IsAnyPointerType = [](ExprResult E) { 10025 QualType Ty = E.get()->getType(); 10026 return Ty->isPointerType() || Ty->isMemberPointerType(); 10027 }; 10028 10029 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10030 // type, array-to-pointer, ..., conversions are performed on both operands to 10031 // bring them to their composite type. 10032 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10033 // any type-related checks. 10034 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10035 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10036 if (LHS.isInvalid()) 10037 return QualType(); 10038 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10039 if (RHS.isInvalid()) 10040 return QualType(); 10041 } else { 10042 LHS = DefaultLvalueConversion(LHS.get()); 10043 if (LHS.isInvalid()) 10044 return QualType(); 10045 RHS = DefaultLvalueConversion(RHS.get()); 10046 if (RHS.isInvalid()) 10047 return QualType(); 10048 } 10049 10050 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10051 10052 // Handle vector comparisons separately. 10053 if (LHS.get()->getType()->isVectorType() || 10054 RHS.get()->getType()->isVectorType()) 10055 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10056 10057 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10058 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10059 10060 QualType LHSType = LHS.get()->getType(); 10061 QualType RHSType = RHS.get()->getType(); 10062 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10063 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10064 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10065 10066 const Expr::NullPointerConstantKind LHSNullKind = 10067 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10068 const Expr::NullPointerConstantKind RHSNullKind = 10069 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10070 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10071 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10072 10073 auto computeResultTy = [&]() { 10074 if (Opc != BO_Cmp) 10075 return Context.getLogicalOperationType(); 10076 assert(getLangOpts().CPlusPlus); 10077 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10078 10079 QualType CompositeTy = LHS.get()->getType(); 10080 assert(!CompositeTy->isReferenceType()); 10081 10082 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10083 return CheckComparisonCategoryType(Kind, Loc); 10084 }; 10085 10086 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10087 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10088 // result is of type std::strong_equality 10089 if (CompositeTy->isFunctionPointerType() || 10090 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10091 // FIXME: consider making the function pointer case produce 10092 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10093 // and direction polls 10094 return buildResultTy(ComparisonCategoryType::StrongEquality); 10095 10096 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10097 // pointer type, p <=> q is of type std::strong_ordering. 10098 if (CompositeTy->isPointerType()) { 10099 // P0946R0: Comparisons between a null pointer constant and an object 10100 // pointer result in std::strong_equality 10101 if (LHSIsNull != RHSIsNull) 10102 return buildResultTy(ComparisonCategoryType::StrongEquality); 10103 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10104 } 10105 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10106 // TODO: Extend support for operator<=> to ObjC types. 10107 return InvalidOperands(Loc, LHS, RHS); 10108 }; 10109 10110 10111 if (!IsRelational && LHSIsNull != RHSIsNull) { 10112 bool IsEquality = Opc == BO_EQ; 10113 if (RHSIsNull) 10114 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10115 RHS.get()->getSourceRange()); 10116 else 10117 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10118 LHS.get()->getSourceRange()); 10119 } 10120 10121 if ((LHSType->isIntegerType() && !LHSIsNull) || 10122 (RHSType->isIntegerType() && !RHSIsNull)) { 10123 // Skip normal pointer conversion checks in this case; we have better 10124 // diagnostics for this below. 10125 } else if (getLangOpts().CPlusPlus) { 10126 // Equality comparison of a function pointer to a void pointer is invalid, 10127 // but we allow it as an extension. 10128 // FIXME: If we really want to allow this, should it be part of composite 10129 // pointer type computation so it works in conditionals too? 10130 if (!IsRelational && 10131 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10132 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10133 // This is a gcc extension compatibility comparison. 10134 // In a SFINAE context, we treat this as a hard error to maintain 10135 // conformance with the C++ standard. 10136 diagnoseFunctionPointerToVoidComparison( 10137 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10138 10139 if (isSFINAEContext()) 10140 return QualType(); 10141 10142 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10143 return computeResultTy(); 10144 } 10145 10146 // C++ [expr.eq]p2: 10147 // If at least one operand is a pointer [...] bring them to their 10148 // composite pointer type. 10149 // C++ [expr.spaceship]p6 10150 // If at least one of the operands is of pointer type, [...] bring them 10151 // to their composite pointer type. 10152 // C++ [expr.rel]p2: 10153 // If both operands are pointers, [...] bring them to their composite 10154 // pointer type. 10155 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10156 (IsRelational ? 2 : 1) && 10157 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10158 RHSType->isObjCObjectPointerType()))) { 10159 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10160 return QualType(); 10161 return computeResultTy(); 10162 } 10163 } else if (LHSType->isPointerType() && 10164 RHSType->isPointerType()) { // C99 6.5.8p2 10165 // All of the following pointer-related warnings are GCC extensions, except 10166 // when handling null pointer constants. 10167 QualType LCanPointeeTy = 10168 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10169 QualType RCanPointeeTy = 10170 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10171 10172 // C99 6.5.9p2 and C99 6.5.8p2 10173 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10174 RCanPointeeTy.getUnqualifiedType())) { 10175 // Valid unless a relational comparison of function pointers 10176 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10177 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10178 << LHSType << RHSType << LHS.get()->getSourceRange() 10179 << RHS.get()->getSourceRange(); 10180 } 10181 } else if (!IsRelational && 10182 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10183 // Valid unless comparison between non-null pointer and function pointer 10184 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10185 && !LHSIsNull && !RHSIsNull) 10186 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10187 /*isError*/false); 10188 } else { 10189 // Invalid 10190 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10191 } 10192 if (LCanPointeeTy != RCanPointeeTy) { 10193 // Treat NULL constant as a special case in OpenCL. 10194 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10195 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10196 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10197 Diag(Loc, 10198 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10199 << LHSType << RHSType << 0 /* comparison */ 10200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10201 } 10202 } 10203 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10204 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10205 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10206 : CK_BitCast; 10207 if (LHSIsNull && !RHSIsNull) 10208 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10209 else 10210 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10211 } 10212 return computeResultTy(); 10213 } 10214 10215 if (getLangOpts().CPlusPlus) { 10216 // C++ [expr.eq]p4: 10217 // Two operands of type std::nullptr_t or one operand of type 10218 // std::nullptr_t and the other a null pointer constant compare equal. 10219 if (!IsRelational && LHSIsNull && RHSIsNull) { 10220 if (LHSType->isNullPtrType()) { 10221 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10222 return computeResultTy(); 10223 } 10224 if (RHSType->isNullPtrType()) { 10225 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10226 return computeResultTy(); 10227 } 10228 } 10229 10230 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10231 // These aren't covered by the composite pointer type rules. 10232 if (!IsRelational && RHSType->isNullPtrType() && 10233 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10234 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10235 return computeResultTy(); 10236 } 10237 if (!IsRelational && LHSType->isNullPtrType() && 10238 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10239 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10240 return computeResultTy(); 10241 } 10242 10243 if (IsRelational && 10244 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10245 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10246 // HACK: Relational comparison of nullptr_t against a pointer type is 10247 // invalid per DR583, but we allow it within std::less<> and friends, 10248 // since otherwise common uses of it break. 10249 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10250 // friends to have std::nullptr_t overload candidates. 10251 DeclContext *DC = CurContext; 10252 if (isa<FunctionDecl>(DC)) 10253 DC = DC->getParent(); 10254 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10255 if (CTSD->isInStdNamespace() && 10256 llvm::StringSwitch<bool>(CTSD->getName()) 10257 .Cases("less", "less_equal", "greater", "greater_equal", true) 10258 .Default(false)) { 10259 if (RHSType->isNullPtrType()) 10260 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10261 else 10262 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10263 return computeResultTy(); 10264 } 10265 } 10266 } 10267 10268 // C++ [expr.eq]p2: 10269 // If at least one operand is a pointer to member, [...] bring them to 10270 // their composite pointer type. 10271 if (!IsRelational && 10272 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10273 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10274 return QualType(); 10275 else 10276 return computeResultTy(); 10277 } 10278 } 10279 10280 // Handle block pointer types. 10281 if (!IsRelational && LHSType->isBlockPointerType() && 10282 RHSType->isBlockPointerType()) { 10283 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10284 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10285 10286 if (!LHSIsNull && !RHSIsNull && 10287 !Context.typesAreCompatible(lpointee, rpointee)) { 10288 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10289 << LHSType << RHSType << LHS.get()->getSourceRange() 10290 << RHS.get()->getSourceRange(); 10291 } 10292 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10293 return computeResultTy(); 10294 } 10295 10296 // Allow block pointers to be compared with null pointer constants. 10297 if (!IsRelational 10298 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10299 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10300 if (!LHSIsNull && !RHSIsNull) { 10301 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10302 ->getPointeeType()->isVoidType()) 10303 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10304 ->getPointeeType()->isVoidType()))) 10305 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10306 << LHSType << RHSType << LHS.get()->getSourceRange() 10307 << RHS.get()->getSourceRange(); 10308 } 10309 if (LHSIsNull && !RHSIsNull) 10310 LHS = ImpCastExprToType(LHS.get(), RHSType, 10311 RHSType->isPointerType() ? CK_BitCast 10312 : CK_AnyPointerToBlockPointerCast); 10313 else 10314 RHS = ImpCastExprToType(RHS.get(), LHSType, 10315 LHSType->isPointerType() ? CK_BitCast 10316 : CK_AnyPointerToBlockPointerCast); 10317 return computeResultTy(); 10318 } 10319 10320 if (LHSType->isObjCObjectPointerType() || 10321 RHSType->isObjCObjectPointerType()) { 10322 const PointerType *LPT = LHSType->getAs<PointerType>(); 10323 const PointerType *RPT = RHSType->getAs<PointerType>(); 10324 if (LPT || RPT) { 10325 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10326 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10327 10328 if (!LPtrToVoid && !RPtrToVoid && 10329 !Context.typesAreCompatible(LHSType, RHSType)) { 10330 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10331 /*isError*/false); 10332 } 10333 if (LHSIsNull && !RHSIsNull) { 10334 Expr *E = LHS.get(); 10335 if (getLangOpts().ObjCAutoRefCount) 10336 CheckObjCConversion(SourceRange(), RHSType, E, 10337 CCK_ImplicitConversion); 10338 LHS = ImpCastExprToType(E, RHSType, 10339 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10340 } 10341 else { 10342 Expr *E = RHS.get(); 10343 if (getLangOpts().ObjCAutoRefCount) 10344 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10345 /*Diagnose=*/true, 10346 /*DiagnoseCFAudited=*/false, Opc); 10347 RHS = ImpCastExprToType(E, LHSType, 10348 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10349 } 10350 return computeResultTy(); 10351 } 10352 if (LHSType->isObjCObjectPointerType() && 10353 RHSType->isObjCObjectPointerType()) { 10354 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10355 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10356 /*isError*/false); 10357 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10358 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10359 10360 if (LHSIsNull && !RHSIsNull) 10361 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10362 else 10363 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10364 return computeResultTy(); 10365 } 10366 10367 if (!IsRelational && LHSType->isBlockPointerType() && 10368 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10369 LHS = ImpCastExprToType(LHS.get(), RHSType, 10370 CK_BlockPointerToObjCPointerCast); 10371 return computeResultTy(); 10372 } else if (!IsRelational && 10373 LHSType->isBlockCompatibleObjCPointerType(Context) && 10374 RHSType->isBlockPointerType()) { 10375 RHS = ImpCastExprToType(RHS.get(), LHSType, 10376 CK_BlockPointerToObjCPointerCast); 10377 return computeResultTy(); 10378 } 10379 } 10380 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10381 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10382 unsigned DiagID = 0; 10383 bool isError = false; 10384 if (LangOpts.DebuggerSupport) { 10385 // Under a debugger, allow the comparison of pointers to integers, 10386 // since users tend to want to compare addresses. 10387 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10388 (RHSIsNull && RHSType->isIntegerType())) { 10389 if (IsRelational) { 10390 isError = getLangOpts().CPlusPlus; 10391 DiagID = 10392 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10393 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10394 } 10395 } else if (getLangOpts().CPlusPlus) { 10396 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10397 isError = true; 10398 } else if (IsRelational) 10399 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10400 else 10401 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10402 10403 if (DiagID) { 10404 Diag(Loc, DiagID) 10405 << LHSType << RHSType << LHS.get()->getSourceRange() 10406 << RHS.get()->getSourceRange(); 10407 if (isError) 10408 return QualType(); 10409 } 10410 10411 if (LHSType->isIntegerType()) 10412 LHS = ImpCastExprToType(LHS.get(), RHSType, 10413 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10414 else 10415 RHS = ImpCastExprToType(RHS.get(), LHSType, 10416 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10417 return computeResultTy(); 10418 } 10419 10420 // Handle block pointers. 10421 if (!IsRelational && RHSIsNull 10422 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10423 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10424 return computeResultTy(); 10425 } 10426 if (!IsRelational && LHSIsNull 10427 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10428 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10429 return computeResultTy(); 10430 } 10431 10432 if (getLangOpts().OpenCLVersion >= 200) { 10433 if (LHSIsNull && RHSType->isQueueT()) { 10434 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10435 return computeResultTy(); 10436 } 10437 10438 if (LHSType->isQueueT() && RHSIsNull) { 10439 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10440 return computeResultTy(); 10441 } 10442 } 10443 10444 return InvalidOperands(Loc, LHS, RHS); 10445 } 10446 10447 // Return a signed ext_vector_type that is of identical size and number of 10448 // elements. For floating point vectors, return an integer type of identical 10449 // size and number of elements. In the non ext_vector_type case, search from 10450 // the largest type to the smallest type to avoid cases where long long == long, 10451 // where long gets picked over long long. 10452 QualType Sema::GetSignedVectorType(QualType V) { 10453 const VectorType *VTy = V->getAs<VectorType>(); 10454 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10455 10456 if (isa<ExtVectorType>(VTy)) { 10457 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10458 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10459 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10460 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10461 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10462 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10463 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10464 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10465 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10466 "Unhandled vector element size in vector compare"); 10467 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10468 } 10469 10470 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10471 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10472 VectorType::GenericVector); 10473 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10474 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10475 VectorType::GenericVector); 10476 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10477 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10478 VectorType::GenericVector); 10479 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10480 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10481 VectorType::GenericVector); 10482 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10483 "Unhandled vector element size in vector compare"); 10484 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10485 VectorType::GenericVector); 10486 } 10487 10488 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10489 /// operates on extended vector types. Instead of producing an IntTy result, 10490 /// like a scalar comparison, a vector comparison produces a vector of integer 10491 /// types. 10492 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10493 SourceLocation Loc, 10494 BinaryOperatorKind Opc) { 10495 // Check to make sure we're operating on vectors of the same type and width, 10496 // Allowing one side to be a scalar of element type. 10497 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10498 /*AllowBothBool*/true, 10499 /*AllowBoolConversions*/getLangOpts().ZVector); 10500 if (vType.isNull()) 10501 return vType; 10502 10503 QualType LHSType = LHS.get()->getType(); 10504 10505 // If AltiVec, the comparison results in a numeric type, i.e. 10506 // bool for C++, int for C 10507 if (getLangOpts().AltiVec && 10508 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10509 return Context.getLogicalOperationType(); 10510 10511 // For non-floating point types, check for self-comparisons of the form 10512 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10513 // often indicate logic errors in the program. 10514 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10515 10516 // Check for comparisons of floating point operands using != and ==. 10517 if (BinaryOperator::isEqualityOp(Opc) && 10518 LHSType->hasFloatingRepresentation()) { 10519 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10520 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10521 } 10522 10523 // Return a signed type for the vector. 10524 return GetSignedVectorType(vType); 10525 } 10526 10527 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10528 SourceLocation Loc) { 10529 // Ensure that either both operands are of the same vector type, or 10530 // one operand is of a vector type and the other is of its element type. 10531 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10532 /*AllowBothBool*/true, 10533 /*AllowBoolConversions*/false); 10534 if (vType.isNull()) 10535 return InvalidOperands(Loc, LHS, RHS); 10536 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10537 vType->hasFloatingRepresentation()) 10538 return InvalidOperands(Loc, LHS, RHS); 10539 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10540 // usage of the logical operators && and || with vectors in C. This 10541 // check could be notionally dropped. 10542 if (!getLangOpts().CPlusPlus && 10543 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10544 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10545 10546 return GetSignedVectorType(LHS.get()->getType()); 10547 } 10548 10549 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10550 SourceLocation Loc, 10551 BinaryOperatorKind Opc) { 10552 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10553 10554 bool IsCompAssign = 10555 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10556 10557 if (LHS.get()->getType()->isVectorType() || 10558 RHS.get()->getType()->isVectorType()) { 10559 if (LHS.get()->getType()->hasIntegerRepresentation() && 10560 RHS.get()->getType()->hasIntegerRepresentation()) 10561 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10562 /*AllowBothBool*/true, 10563 /*AllowBoolConversions*/getLangOpts().ZVector); 10564 return InvalidOperands(Loc, LHS, RHS); 10565 } 10566 10567 if (Opc == BO_And) 10568 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10569 10570 ExprResult LHSResult = LHS, RHSResult = RHS; 10571 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10572 IsCompAssign); 10573 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10574 return QualType(); 10575 LHS = LHSResult.get(); 10576 RHS = RHSResult.get(); 10577 10578 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10579 return compType; 10580 return InvalidOperands(Loc, LHS, RHS); 10581 } 10582 10583 // C99 6.5.[13,14] 10584 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10585 SourceLocation Loc, 10586 BinaryOperatorKind Opc) { 10587 // Check vector operands differently. 10588 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10589 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10590 10591 // Diagnose cases where the user write a logical and/or but probably meant a 10592 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10593 // is a constant. 10594 if (LHS.get()->getType()->isIntegerType() && 10595 !LHS.get()->getType()->isBooleanType() && 10596 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10597 // Don't warn in macros or template instantiations. 10598 !Loc.isMacroID() && !inTemplateInstantiation()) { 10599 // If the RHS can be constant folded, and if it constant folds to something 10600 // that isn't 0 or 1 (which indicate a potential logical operation that 10601 // happened to fold to true/false) then warn. 10602 // Parens on the RHS are ignored. 10603 llvm::APSInt Result; 10604 if (RHS.get()->EvaluateAsInt(Result, Context)) 10605 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10606 !RHS.get()->getExprLoc().isMacroID()) || 10607 (Result != 0 && Result != 1)) { 10608 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10609 << RHS.get()->getSourceRange() 10610 << (Opc == BO_LAnd ? "&&" : "||"); 10611 // Suggest replacing the logical operator with the bitwise version 10612 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10613 << (Opc == BO_LAnd ? "&" : "|") 10614 << FixItHint::CreateReplacement(SourceRange( 10615 Loc, getLocForEndOfToken(Loc)), 10616 Opc == BO_LAnd ? "&" : "|"); 10617 if (Opc == BO_LAnd) 10618 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10619 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10620 << FixItHint::CreateRemoval( 10621 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10622 RHS.get()->getEndLoc())); 10623 } 10624 } 10625 10626 if (!Context.getLangOpts().CPlusPlus) { 10627 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10628 // not operate on the built-in scalar and vector float types. 10629 if (Context.getLangOpts().OpenCL && 10630 Context.getLangOpts().OpenCLVersion < 120) { 10631 if (LHS.get()->getType()->isFloatingType() || 10632 RHS.get()->getType()->isFloatingType()) 10633 return InvalidOperands(Loc, LHS, RHS); 10634 } 10635 10636 LHS = UsualUnaryConversions(LHS.get()); 10637 if (LHS.isInvalid()) 10638 return QualType(); 10639 10640 RHS = UsualUnaryConversions(RHS.get()); 10641 if (RHS.isInvalid()) 10642 return QualType(); 10643 10644 if (!LHS.get()->getType()->isScalarType() || 10645 !RHS.get()->getType()->isScalarType()) 10646 return InvalidOperands(Loc, LHS, RHS); 10647 10648 return Context.IntTy; 10649 } 10650 10651 // The following is safe because we only use this method for 10652 // non-overloadable operands. 10653 10654 // C++ [expr.log.and]p1 10655 // C++ [expr.log.or]p1 10656 // The operands are both contextually converted to type bool. 10657 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10658 if (LHSRes.isInvalid()) 10659 return InvalidOperands(Loc, LHS, RHS); 10660 LHS = LHSRes; 10661 10662 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10663 if (RHSRes.isInvalid()) 10664 return InvalidOperands(Loc, LHS, RHS); 10665 RHS = RHSRes; 10666 10667 // C++ [expr.log.and]p2 10668 // C++ [expr.log.or]p2 10669 // The result is a bool. 10670 return Context.BoolTy; 10671 } 10672 10673 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10674 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10675 if (!ME) return false; 10676 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10677 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10678 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10679 if (!Base) return false; 10680 return Base->getMethodDecl() != nullptr; 10681 } 10682 10683 /// Is the given expression (which must be 'const') a reference to a 10684 /// variable which was originally non-const, but which has become 10685 /// 'const' due to being captured within a block? 10686 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10687 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10688 assert(E->isLValue() && E->getType().isConstQualified()); 10689 E = E->IgnoreParens(); 10690 10691 // Must be a reference to a declaration from an enclosing scope. 10692 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10693 if (!DRE) return NCCK_None; 10694 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10695 10696 // The declaration must be a variable which is not declared 'const'. 10697 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10698 if (!var) return NCCK_None; 10699 if (var->getType().isConstQualified()) return NCCK_None; 10700 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10701 10702 // Decide whether the first capture was for a block or a lambda. 10703 DeclContext *DC = S.CurContext, *Prev = nullptr; 10704 // Decide whether the first capture was for a block or a lambda. 10705 while (DC) { 10706 // For init-capture, it is possible that the variable belongs to the 10707 // template pattern of the current context. 10708 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10709 if (var->isInitCapture() && 10710 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10711 break; 10712 if (DC == var->getDeclContext()) 10713 break; 10714 Prev = DC; 10715 DC = DC->getParent(); 10716 } 10717 // Unless we have an init-capture, we've gone one step too far. 10718 if (!var->isInitCapture()) 10719 DC = Prev; 10720 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10721 } 10722 10723 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10724 Ty = Ty.getNonReferenceType(); 10725 if (IsDereference && Ty->isPointerType()) 10726 Ty = Ty->getPointeeType(); 10727 return !Ty.isConstQualified(); 10728 } 10729 10730 // Update err_typecheck_assign_const and note_typecheck_assign_const 10731 // when this enum is changed. 10732 enum { 10733 ConstFunction, 10734 ConstVariable, 10735 ConstMember, 10736 ConstMethod, 10737 NestedConstMember, 10738 ConstUnknown, // Keep as last element 10739 }; 10740 10741 /// Emit the "read-only variable not assignable" error and print notes to give 10742 /// more information about why the variable is not assignable, such as pointing 10743 /// to the declaration of a const variable, showing that a method is const, or 10744 /// that the function is returning a const reference. 10745 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10746 SourceLocation Loc) { 10747 SourceRange ExprRange = E->getSourceRange(); 10748 10749 // Only emit one error on the first const found. All other consts will emit 10750 // a note to the error. 10751 bool DiagnosticEmitted = false; 10752 10753 // Track if the current expression is the result of a dereference, and if the 10754 // next checked expression is the result of a dereference. 10755 bool IsDereference = false; 10756 bool NextIsDereference = false; 10757 10758 // Loop to process MemberExpr chains. 10759 while (true) { 10760 IsDereference = NextIsDereference; 10761 10762 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10763 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10764 NextIsDereference = ME->isArrow(); 10765 const ValueDecl *VD = ME->getMemberDecl(); 10766 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10767 // Mutable fields can be modified even if the class is const. 10768 if (Field->isMutable()) { 10769 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10770 break; 10771 } 10772 10773 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10774 if (!DiagnosticEmitted) { 10775 S.Diag(Loc, diag::err_typecheck_assign_const) 10776 << ExprRange << ConstMember << false /*static*/ << Field 10777 << Field->getType(); 10778 DiagnosticEmitted = true; 10779 } 10780 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10781 << ConstMember << false /*static*/ << Field << Field->getType() 10782 << Field->getSourceRange(); 10783 } 10784 E = ME->getBase(); 10785 continue; 10786 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10787 if (VDecl->getType().isConstQualified()) { 10788 if (!DiagnosticEmitted) { 10789 S.Diag(Loc, diag::err_typecheck_assign_const) 10790 << ExprRange << ConstMember << true /*static*/ << VDecl 10791 << VDecl->getType(); 10792 DiagnosticEmitted = true; 10793 } 10794 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10795 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10796 << VDecl->getSourceRange(); 10797 } 10798 // Static fields do not inherit constness from parents. 10799 break; 10800 } 10801 break; // End MemberExpr 10802 } else if (const ArraySubscriptExpr *ASE = 10803 dyn_cast<ArraySubscriptExpr>(E)) { 10804 E = ASE->getBase()->IgnoreParenImpCasts(); 10805 continue; 10806 } else if (const ExtVectorElementExpr *EVE = 10807 dyn_cast<ExtVectorElementExpr>(E)) { 10808 E = EVE->getBase()->IgnoreParenImpCasts(); 10809 continue; 10810 } 10811 break; 10812 } 10813 10814 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10815 // Function calls 10816 const FunctionDecl *FD = CE->getDirectCallee(); 10817 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10818 if (!DiagnosticEmitted) { 10819 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10820 << ConstFunction << FD; 10821 DiagnosticEmitted = true; 10822 } 10823 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10824 diag::note_typecheck_assign_const) 10825 << ConstFunction << FD << FD->getReturnType() 10826 << FD->getReturnTypeSourceRange(); 10827 } 10828 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10829 // Point to variable declaration. 10830 if (const ValueDecl *VD = DRE->getDecl()) { 10831 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10832 if (!DiagnosticEmitted) { 10833 S.Diag(Loc, diag::err_typecheck_assign_const) 10834 << ExprRange << ConstVariable << VD << VD->getType(); 10835 DiagnosticEmitted = true; 10836 } 10837 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10838 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10839 } 10840 } 10841 } else if (isa<CXXThisExpr>(E)) { 10842 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10843 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10844 if (MD->isConst()) { 10845 if (!DiagnosticEmitted) { 10846 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10847 << ConstMethod << MD; 10848 DiagnosticEmitted = true; 10849 } 10850 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10851 << ConstMethod << MD << MD->getSourceRange(); 10852 } 10853 } 10854 } 10855 } 10856 10857 if (DiagnosticEmitted) 10858 return; 10859 10860 // Can't determine a more specific message, so display the generic error. 10861 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10862 } 10863 10864 enum OriginalExprKind { 10865 OEK_Variable, 10866 OEK_Member, 10867 OEK_LValue 10868 }; 10869 10870 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10871 const RecordType *Ty, 10872 SourceLocation Loc, SourceRange Range, 10873 OriginalExprKind OEK, 10874 bool &DiagnosticEmitted, 10875 bool IsNested = false) { 10876 // We walk the record hierarchy breadth-first to ensure that we print 10877 // diagnostics in field nesting order. 10878 // First, check every field for constness. 10879 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10880 if (Field->getType().isConstQualified()) { 10881 if (!DiagnosticEmitted) { 10882 S.Diag(Loc, diag::err_typecheck_assign_const) 10883 << Range << NestedConstMember << OEK << VD 10884 << IsNested << Field; 10885 DiagnosticEmitted = true; 10886 } 10887 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10888 << NestedConstMember << IsNested << Field 10889 << Field->getType() << Field->getSourceRange(); 10890 } 10891 } 10892 // Then, recurse. 10893 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10894 QualType FTy = Field->getType(); 10895 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10896 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10897 OEK, DiagnosticEmitted, true); 10898 } 10899 } 10900 10901 /// Emit an error for the case where a record we are trying to assign to has a 10902 /// const-qualified field somewhere in its hierarchy. 10903 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10904 SourceLocation Loc) { 10905 QualType Ty = E->getType(); 10906 assert(Ty->isRecordType() && "lvalue was not record?"); 10907 SourceRange Range = E->getSourceRange(); 10908 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10909 bool DiagEmitted = false; 10910 10911 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10912 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10913 Range, OEK_Member, DiagEmitted); 10914 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10915 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10916 Range, OEK_Variable, DiagEmitted); 10917 else 10918 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10919 Range, OEK_LValue, DiagEmitted); 10920 if (!DiagEmitted) 10921 DiagnoseConstAssignment(S, E, Loc); 10922 } 10923 10924 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10925 /// emit an error and return true. If so, return false. 10926 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10927 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10928 10929 S.CheckShadowingDeclModification(E, Loc); 10930 10931 SourceLocation OrigLoc = Loc; 10932 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10933 &Loc); 10934 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10935 IsLV = Expr::MLV_InvalidMessageExpression; 10936 if (IsLV == Expr::MLV_Valid) 10937 return false; 10938 10939 unsigned DiagID = 0; 10940 bool NeedType = false; 10941 switch (IsLV) { // C99 6.5.16p2 10942 case Expr::MLV_ConstQualified: 10943 // Use a specialized diagnostic when we're assigning to an object 10944 // from an enclosing function or block. 10945 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10946 if (NCCK == NCCK_Block) 10947 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10948 else 10949 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10950 break; 10951 } 10952 10953 // In ARC, use some specialized diagnostics for occasions where we 10954 // infer 'const'. These are always pseudo-strong variables. 10955 if (S.getLangOpts().ObjCAutoRefCount) { 10956 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10957 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10958 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10959 10960 // Use the normal diagnostic if it's pseudo-__strong but the 10961 // user actually wrote 'const'. 10962 if (var->isARCPseudoStrong() && 10963 (!var->getTypeSourceInfo() || 10964 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10965 // There are two pseudo-strong cases: 10966 // - self 10967 ObjCMethodDecl *method = S.getCurMethodDecl(); 10968 if (method && var == method->getSelfDecl()) 10969 DiagID = method->isClassMethod() 10970 ? diag::err_typecheck_arc_assign_self_class_method 10971 : diag::err_typecheck_arc_assign_self; 10972 10973 // - fast enumeration variables 10974 else 10975 DiagID = diag::err_typecheck_arr_assign_enumeration; 10976 10977 SourceRange Assign; 10978 if (Loc != OrigLoc) 10979 Assign = SourceRange(OrigLoc, OrigLoc); 10980 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10981 // We need to preserve the AST regardless, so migration tool 10982 // can do its job. 10983 return false; 10984 } 10985 } 10986 } 10987 10988 // If none of the special cases above are triggered, then this is a 10989 // simple const assignment. 10990 if (DiagID == 0) { 10991 DiagnoseConstAssignment(S, E, Loc); 10992 return true; 10993 } 10994 10995 break; 10996 case Expr::MLV_ConstAddrSpace: 10997 DiagnoseConstAssignment(S, E, Loc); 10998 return true; 10999 case Expr::MLV_ConstQualifiedField: 11000 DiagnoseRecursiveConstFields(S, E, Loc); 11001 return true; 11002 case Expr::MLV_ArrayType: 11003 case Expr::MLV_ArrayTemporary: 11004 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11005 NeedType = true; 11006 break; 11007 case Expr::MLV_NotObjectType: 11008 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11009 NeedType = true; 11010 break; 11011 case Expr::MLV_LValueCast: 11012 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11013 break; 11014 case Expr::MLV_Valid: 11015 llvm_unreachable("did not take early return for MLV_Valid"); 11016 case Expr::MLV_InvalidExpression: 11017 case Expr::MLV_MemberFunction: 11018 case Expr::MLV_ClassTemporary: 11019 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11020 break; 11021 case Expr::MLV_IncompleteType: 11022 case Expr::MLV_IncompleteVoidType: 11023 return S.RequireCompleteType(Loc, E->getType(), 11024 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11025 case Expr::MLV_DuplicateVectorComponents: 11026 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11027 break; 11028 case Expr::MLV_NoSetterProperty: 11029 llvm_unreachable("readonly properties should be processed differently"); 11030 case Expr::MLV_InvalidMessageExpression: 11031 DiagID = diag::err_readonly_message_assignment; 11032 break; 11033 case Expr::MLV_SubObjCPropertySetting: 11034 DiagID = diag::err_no_subobject_property_setting; 11035 break; 11036 } 11037 11038 SourceRange Assign; 11039 if (Loc != OrigLoc) 11040 Assign = SourceRange(OrigLoc, OrigLoc); 11041 if (NeedType) 11042 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11043 else 11044 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11045 return true; 11046 } 11047 11048 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11049 SourceLocation Loc, 11050 Sema &Sema) { 11051 if (Sema.inTemplateInstantiation()) 11052 return; 11053 if (Sema.isUnevaluatedContext()) 11054 return; 11055 if (Loc.isInvalid() || Loc.isMacroID()) 11056 return; 11057 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11058 return; 11059 11060 // C / C++ fields 11061 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11062 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11063 if (ML && MR) { 11064 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11065 return; 11066 const ValueDecl *LHSDecl = 11067 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11068 const ValueDecl *RHSDecl = 11069 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11070 if (LHSDecl != RHSDecl) 11071 return; 11072 if (LHSDecl->getType().isVolatileQualified()) 11073 return; 11074 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11075 if (RefTy->getPointeeType().isVolatileQualified()) 11076 return; 11077 11078 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11079 } 11080 11081 // Objective-C instance variables 11082 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11083 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11084 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11085 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11086 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11087 if (RL && RR && RL->getDecl() == RR->getDecl()) 11088 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11089 } 11090 } 11091 11092 // C99 6.5.16.1 11093 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11094 SourceLocation Loc, 11095 QualType CompoundType) { 11096 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11097 11098 // Verify that LHS is a modifiable lvalue, and emit error if not. 11099 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11100 return QualType(); 11101 11102 QualType LHSType = LHSExpr->getType(); 11103 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11104 CompoundType; 11105 // OpenCL v1.2 s6.1.1.1 p2: 11106 // The half data type can only be used to declare a pointer to a buffer that 11107 // contains half values 11108 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11109 LHSType->isHalfType()) { 11110 Diag(Loc, diag::err_opencl_half_load_store) << 1 11111 << LHSType.getUnqualifiedType(); 11112 return QualType(); 11113 } 11114 11115 AssignConvertType ConvTy; 11116 if (CompoundType.isNull()) { 11117 Expr *RHSCheck = RHS.get(); 11118 11119 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11120 11121 QualType LHSTy(LHSType); 11122 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11123 if (RHS.isInvalid()) 11124 return QualType(); 11125 // Special case of NSObject attributes on c-style pointer types. 11126 if (ConvTy == IncompatiblePointer && 11127 ((Context.isObjCNSObjectType(LHSType) && 11128 RHSType->isObjCObjectPointerType()) || 11129 (Context.isObjCNSObjectType(RHSType) && 11130 LHSType->isObjCObjectPointerType()))) 11131 ConvTy = Compatible; 11132 11133 if (ConvTy == Compatible && 11134 LHSType->isObjCObjectType()) 11135 Diag(Loc, diag::err_objc_object_assignment) 11136 << LHSType; 11137 11138 // If the RHS is a unary plus or minus, check to see if they = and + are 11139 // right next to each other. If so, the user may have typo'd "x =+ 4" 11140 // instead of "x += 4". 11141 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11142 RHSCheck = ICE->getSubExpr(); 11143 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11144 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11145 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11146 // Only if the two operators are exactly adjacent. 11147 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11148 // And there is a space or other character before the subexpr of the 11149 // unary +/-. We don't want to warn on "x=-1". 11150 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11151 UO->getSubExpr()->getBeginLoc().isFileID()) { 11152 Diag(Loc, diag::warn_not_compound_assign) 11153 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11154 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11155 } 11156 } 11157 11158 if (ConvTy == Compatible) { 11159 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11160 // Warn about retain cycles where a block captures the LHS, but 11161 // not if the LHS is a simple variable into which the block is 11162 // being stored...unless that variable can be captured by reference! 11163 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11164 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11165 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11166 checkRetainCycles(LHSExpr, RHS.get()); 11167 } 11168 11169 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11170 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11171 // It is safe to assign a weak reference into a strong variable. 11172 // Although this code can still have problems: 11173 // id x = self.weakProp; 11174 // id y = self.weakProp; 11175 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11176 // paths through the function. This should be revisited if 11177 // -Wrepeated-use-of-weak is made flow-sensitive. 11178 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11179 // variable, which will be valid for the current autorelease scope. 11180 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11181 RHS.get()->getBeginLoc())) 11182 getCurFunction()->markSafeWeakUse(RHS.get()); 11183 11184 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11185 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11186 } 11187 } 11188 } else { 11189 // Compound assignment "x += y" 11190 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11191 } 11192 11193 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11194 RHS.get(), AA_Assigning)) 11195 return QualType(); 11196 11197 CheckForNullPointerDereference(*this, LHSExpr); 11198 11199 // C99 6.5.16p3: The type of an assignment expression is the type of the 11200 // left operand unless the left operand has qualified type, in which case 11201 // it is the unqualified version of the type of the left operand. 11202 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11203 // is converted to the type of the assignment expression (above). 11204 // C++ 5.17p1: the type of the assignment expression is that of its left 11205 // operand. 11206 return (getLangOpts().CPlusPlus 11207 ? LHSType : LHSType.getUnqualifiedType()); 11208 } 11209 11210 // Only ignore explicit casts to void. 11211 static bool IgnoreCommaOperand(const Expr *E) { 11212 E = E->IgnoreParens(); 11213 11214 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11215 if (CE->getCastKind() == CK_ToVoid) { 11216 return true; 11217 } 11218 } 11219 11220 return false; 11221 } 11222 11223 // Look for instances where it is likely the comma operator is confused with 11224 // another operator. There is a whitelist of acceptable expressions for the 11225 // left hand side of the comma operator, otherwise emit a warning. 11226 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11227 // No warnings in macros 11228 if (Loc.isMacroID()) 11229 return; 11230 11231 // Don't warn in template instantiations. 11232 if (inTemplateInstantiation()) 11233 return; 11234 11235 // Scope isn't fine-grained enough to whitelist the specific cases, so 11236 // instead, skip more than needed, then call back into here with the 11237 // CommaVisitor in SemaStmt.cpp. 11238 // The whitelisted locations are the initialization and increment portions 11239 // of a for loop. The additional checks are on the condition of 11240 // if statements, do/while loops, and for loops. 11241 const unsigned ForIncrementFlags = 11242 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 11243 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11244 const unsigned ScopeFlags = getCurScope()->getFlags(); 11245 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11246 (ScopeFlags & ForInitFlags) == ForInitFlags) 11247 return; 11248 11249 // If there are multiple comma operators used together, get the RHS of the 11250 // of the comma operator as the LHS. 11251 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11252 if (BO->getOpcode() != BO_Comma) 11253 break; 11254 LHS = BO->getRHS(); 11255 } 11256 11257 // Only allow some expressions on LHS to not warn. 11258 if (IgnoreCommaOperand(LHS)) 11259 return; 11260 11261 Diag(Loc, diag::warn_comma_operator); 11262 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11263 << LHS->getSourceRange() 11264 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11265 LangOpts.CPlusPlus ? "static_cast<void>(" 11266 : "(void)(") 11267 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11268 ")"); 11269 } 11270 11271 // C99 6.5.17 11272 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11273 SourceLocation Loc) { 11274 LHS = S.CheckPlaceholderExpr(LHS.get()); 11275 RHS = S.CheckPlaceholderExpr(RHS.get()); 11276 if (LHS.isInvalid() || RHS.isInvalid()) 11277 return QualType(); 11278 11279 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11280 // operands, but not unary promotions. 11281 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11282 11283 // So we treat the LHS as a ignored value, and in C++ we allow the 11284 // containing site to determine what should be done with the RHS. 11285 LHS = S.IgnoredValueConversions(LHS.get()); 11286 if (LHS.isInvalid()) 11287 return QualType(); 11288 11289 S.DiagnoseUnusedExprResult(LHS.get()); 11290 11291 if (!S.getLangOpts().CPlusPlus) { 11292 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11293 if (RHS.isInvalid()) 11294 return QualType(); 11295 if (!RHS.get()->getType()->isVoidType()) 11296 S.RequireCompleteType(Loc, RHS.get()->getType(), 11297 diag::err_incomplete_type); 11298 } 11299 11300 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11301 S.DiagnoseCommaOperator(LHS.get(), Loc); 11302 11303 return RHS.get()->getType(); 11304 } 11305 11306 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11307 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11308 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11309 ExprValueKind &VK, 11310 ExprObjectKind &OK, 11311 SourceLocation OpLoc, 11312 bool IsInc, bool IsPrefix) { 11313 if (Op->isTypeDependent()) 11314 return S.Context.DependentTy; 11315 11316 QualType ResType = Op->getType(); 11317 // Atomic types can be used for increment / decrement where the non-atomic 11318 // versions can, so ignore the _Atomic() specifier for the purpose of 11319 // checking. 11320 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11321 ResType = ResAtomicType->getValueType(); 11322 11323 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11324 11325 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11326 // Decrement of bool is not allowed. 11327 if (!IsInc) { 11328 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11329 return QualType(); 11330 } 11331 // Increment of bool sets it to true, but is deprecated. 11332 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11333 : diag::warn_increment_bool) 11334 << Op->getSourceRange(); 11335 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11336 // Error on enum increments and decrements in C++ mode 11337 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11338 return QualType(); 11339 } else if (ResType->isRealType()) { 11340 // OK! 11341 } else if (ResType->isPointerType()) { 11342 // C99 6.5.2.4p2, 6.5.6p2 11343 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11344 return QualType(); 11345 } else if (ResType->isObjCObjectPointerType()) { 11346 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11347 // Otherwise, we just need a complete type. 11348 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11349 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11350 return QualType(); 11351 } else if (ResType->isAnyComplexType()) { 11352 // C99 does not support ++/-- on complex types, we allow as an extension. 11353 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11354 << ResType << Op->getSourceRange(); 11355 } else if (ResType->isPlaceholderType()) { 11356 ExprResult PR = S.CheckPlaceholderExpr(Op); 11357 if (PR.isInvalid()) return QualType(); 11358 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11359 IsInc, IsPrefix); 11360 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11361 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11362 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11363 (ResType->getAs<VectorType>()->getVectorKind() != 11364 VectorType::AltiVecBool)) { 11365 // The z vector extensions allow ++ and -- for non-bool vectors. 11366 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11367 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11368 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11369 } else { 11370 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11371 << ResType << int(IsInc) << Op->getSourceRange(); 11372 return QualType(); 11373 } 11374 // At this point, we know we have a real, complex or pointer type. 11375 // Now make sure the operand is a modifiable lvalue. 11376 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11377 return QualType(); 11378 // In C++, a prefix increment is the same type as the operand. Otherwise 11379 // (in C or with postfix), the increment is the unqualified type of the 11380 // operand. 11381 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11382 VK = VK_LValue; 11383 OK = Op->getObjectKind(); 11384 return ResType; 11385 } else { 11386 VK = VK_RValue; 11387 return ResType.getUnqualifiedType(); 11388 } 11389 } 11390 11391 11392 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11393 /// This routine allows us to typecheck complex/recursive expressions 11394 /// where the declaration is needed for type checking. We only need to 11395 /// handle cases when the expression references a function designator 11396 /// or is an lvalue. Here are some examples: 11397 /// - &(x) => x 11398 /// - &*****f => f for f a function designator. 11399 /// - &s.xx => s 11400 /// - &s.zz[1].yy -> s, if zz is an array 11401 /// - *(x + 1) -> x, if x is an array 11402 /// - &"123"[2] -> 0 11403 /// - & __real__ x -> x 11404 static ValueDecl *getPrimaryDecl(Expr *E) { 11405 switch (E->getStmtClass()) { 11406 case Stmt::DeclRefExprClass: 11407 return cast<DeclRefExpr>(E)->getDecl(); 11408 case Stmt::MemberExprClass: 11409 // If this is an arrow operator, the address is an offset from 11410 // the base's value, so the object the base refers to is 11411 // irrelevant. 11412 if (cast<MemberExpr>(E)->isArrow()) 11413 return nullptr; 11414 // Otherwise, the expression refers to a part of the base 11415 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11416 case Stmt::ArraySubscriptExprClass: { 11417 // FIXME: This code shouldn't be necessary! We should catch the implicit 11418 // promotion of register arrays earlier. 11419 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11420 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11421 if (ICE->getSubExpr()->getType()->isArrayType()) 11422 return getPrimaryDecl(ICE->getSubExpr()); 11423 } 11424 return nullptr; 11425 } 11426 case Stmt::UnaryOperatorClass: { 11427 UnaryOperator *UO = cast<UnaryOperator>(E); 11428 11429 switch(UO->getOpcode()) { 11430 case UO_Real: 11431 case UO_Imag: 11432 case UO_Extension: 11433 return getPrimaryDecl(UO->getSubExpr()); 11434 default: 11435 return nullptr; 11436 } 11437 } 11438 case Stmt::ParenExprClass: 11439 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11440 case Stmt::ImplicitCastExprClass: 11441 // If the result of an implicit cast is an l-value, we care about 11442 // the sub-expression; otherwise, the result here doesn't matter. 11443 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11444 default: 11445 return nullptr; 11446 } 11447 } 11448 11449 namespace { 11450 enum { 11451 AO_Bit_Field = 0, 11452 AO_Vector_Element = 1, 11453 AO_Property_Expansion = 2, 11454 AO_Register_Variable = 3, 11455 AO_No_Error = 4 11456 }; 11457 } 11458 /// Diagnose invalid operand for address of operations. 11459 /// 11460 /// \param Type The type of operand which cannot have its address taken. 11461 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11462 Expr *E, unsigned Type) { 11463 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11464 } 11465 11466 /// CheckAddressOfOperand - The operand of & must be either a function 11467 /// designator or an lvalue designating an object. If it is an lvalue, the 11468 /// object cannot be declared with storage class register or be a bit field. 11469 /// Note: The usual conversions are *not* applied to the operand of the & 11470 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11471 /// In C++, the operand might be an overloaded function name, in which case 11472 /// we allow the '&' but retain the overloaded-function type. 11473 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11474 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11475 if (PTy->getKind() == BuiltinType::Overload) { 11476 Expr *E = OrigOp.get()->IgnoreParens(); 11477 if (!isa<OverloadExpr>(E)) { 11478 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11479 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11480 << OrigOp.get()->getSourceRange(); 11481 return QualType(); 11482 } 11483 11484 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11485 if (isa<UnresolvedMemberExpr>(Ovl)) 11486 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11487 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11488 << OrigOp.get()->getSourceRange(); 11489 return QualType(); 11490 } 11491 11492 return Context.OverloadTy; 11493 } 11494 11495 if (PTy->getKind() == BuiltinType::UnknownAny) 11496 return Context.UnknownAnyTy; 11497 11498 if (PTy->getKind() == BuiltinType::BoundMember) { 11499 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11500 << OrigOp.get()->getSourceRange(); 11501 return QualType(); 11502 } 11503 11504 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11505 if (OrigOp.isInvalid()) return QualType(); 11506 } 11507 11508 if (OrigOp.get()->isTypeDependent()) 11509 return Context.DependentTy; 11510 11511 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11512 11513 // Make sure to ignore parentheses in subsequent checks 11514 Expr *op = OrigOp.get()->IgnoreParens(); 11515 11516 // In OpenCL captures for blocks called as lambda functions 11517 // are located in the private address space. Blocks used in 11518 // enqueue_kernel can be located in a different address space 11519 // depending on a vendor implementation. Thus preventing 11520 // taking an address of the capture to avoid invalid AS casts. 11521 if (LangOpts.OpenCL) { 11522 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11523 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11524 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11525 return QualType(); 11526 } 11527 } 11528 11529 if (getLangOpts().C99) { 11530 // Implement C99-only parts of addressof rules. 11531 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11532 if (uOp->getOpcode() == UO_Deref) 11533 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11534 // (assuming the deref expression is valid). 11535 return uOp->getSubExpr()->getType(); 11536 } 11537 // Technically, there should be a check for array subscript 11538 // expressions here, but the result of one is always an lvalue anyway. 11539 } 11540 ValueDecl *dcl = getPrimaryDecl(op); 11541 11542 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11543 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11544 op->getBeginLoc())) 11545 return QualType(); 11546 11547 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11548 unsigned AddressOfError = AO_No_Error; 11549 11550 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11551 bool sfinae = (bool)isSFINAEContext(); 11552 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11553 : diag::ext_typecheck_addrof_temporary) 11554 << op->getType() << op->getSourceRange(); 11555 if (sfinae) 11556 return QualType(); 11557 // Materialize the temporary as an lvalue so that we can take its address. 11558 OrigOp = op = 11559 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11560 } else if (isa<ObjCSelectorExpr>(op)) { 11561 return Context.getPointerType(op->getType()); 11562 } else if (lval == Expr::LV_MemberFunction) { 11563 // If it's an instance method, make a member pointer. 11564 // The expression must have exactly the form &A::foo. 11565 11566 // If the underlying expression isn't a decl ref, give up. 11567 if (!isa<DeclRefExpr>(op)) { 11568 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11569 << OrigOp.get()->getSourceRange(); 11570 return QualType(); 11571 } 11572 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11573 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11574 11575 // The id-expression was parenthesized. 11576 if (OrigOp.get() != DRE) { 11577 Diag(OpLoc, diag::err_parens_pointer_member_function) 11578 << OrigOp.get()->getSourceRange(); 11579 11580 // The method was named without a qualifier. 11581 } else if (!DRE->getQualifier()) { 11582 if (MD->getParent()->getName().empty()) 11583 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11584 << op->getSourceRange(); 11585 else { 11586 SmallString<32> Str; 11587 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11588 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11589 << op->getSourceRange() 11590 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11591 } 11592 } 11593 11594 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11595 if (isa<CXXDestructorDecl>(MD)) 11596 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11597 11598 QualType MPTy = Context.getMemberPointerType( 11599 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11600 // Under the MS ABI, lock down the inheritance model now. 11601 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11602 (void)isCompleteType(OpLoc, MPTy); 11603 return MPTy; 11604 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11605 // C99 6.5.3.2p1 11606 // The operand must be either an l-value or a function designator 11607 if (!op->getType()->isFunctionType()) { 11608 // Use a special diagnostic for loads from property references. 11609 if (isa<PseudoObjectExpr>(op)) { 11610 AddressOfError = AO_Property_Expansion; 11611 } else { 11612 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11613 << op->getType() << op->getSourceRange(); 11614 return QualType(); 11615 } 11616 } 11617 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11618 // The operand cannot be a bit-field 11619 AddressOfError = AO_Bit_Field; 11620 } else if (op->getObjectKind() == OK_VectorComponent) { 11621 // The operand cannot be an element of a vector 11622 AddressOfError = AO_Vector_Element; 11623 } else if (dcl) { // C99 6.5.3.2p1 11624 // We have an lvalue with a decl. Make sure the decl is not declared 11625 // with the register storage-class specifier. 11626 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11627 // in C++ it is not error to take address of a register 11628 // variable (c++03 7.1.1P3) 11629 if (vd->getStorageClass() == SC_Register && 11630 !getLangOpts().CPlusPlus) { 11631 AddressOfError = AO_Register_Variable; 11632 } 11633 } else if (isa<MSPropertyDecl>(dcl)) { 11634 AddressOfError = AO_Property_Expansion; 11635 } else if (isa<FunctionTemplateDecl>(dcl)) { 11636 return Context.OverloadTy; 11637 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11638 // Okay: we can take the address of a field. 11639 // Could be a pointer to member, though, if there is an explicit 11640 // scope qualifier for the class. 11641 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11642 DeclContext *Ctx = dcl->getDeclContext(); 11643 if (Ctx && Ctx->isRecord()) { 11644 if (dcl->getType()->isReferenceType()) { 11645 Diag(OpLoc, 11646 diag::err_cannot_form_pointer_to_member_of_reference_type) 11647 << dcl->getDeclName() << dcl->getType(); 11648 return QualType(); 11649 } 11650 11651 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11652 Ctx = Ctx->getParent(); 11653 11654 QualType MPTy = Context.getMemberPointerType( 11655 op->getType(), 11656 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11657 // Under the MS ABI, lock down the inheritance model now. 11658 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11659 (void)isCompleteType(OpLoc, MPTy); 11660 return MPTy; 11661 } 11662 } 11663 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11664 !isa<BindingDecl>(dcl)) 11665 llvm_unreachable("Unknown/unexpected decl type"); 11666 } 11667 11668 if (AddressOfError != AO_No_Error) { 11669 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11670 return QualType(); 11671 } 11672 11673 if (lval == Expr::LV_IncompleteVoidType) { 11674 // Taking the address of a void variable is technically illegal, but we 11675 // allow it in cases which are otherwise valid. 11676 // Example: "extern void x; void* y = &x;". 11677 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11678 } 11679 11680 // If the operand has type "type", the result has type "pointer to type". 11681 if (op->getType()->isObjCObjectType()) 11682 return Context.getObjCObjectPointerType(op->getType()); 11683 11684 CheckAddressOfPackedMember(op); 11685 11686 return Context.getPointerType(op->getType()); 11687 } 11688 11689 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11690 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11691 if (!DRE) 11692 return; 11693 const Decl *D = DRE->getDecl(); 11694 if (!D) 11695 return; 11696 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11697 if (!Param) 11698 return; 11699 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11700 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11701 return; 11702 if (FunctionScopeInfo *FD = S.getCurFunction()) 11703 if (!FD->ModifiedNonNullParams.count(Param)) 11704 FD->ModifiedNonNullParams.insert(Param); 11705 } 11706 11707 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11708 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11709 SourceLocation OpLoc) { 11710 if (Op->isTypeDependent()) 11711 return S.Context.DependentTy; 11712 11713 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11714 if (ConvResult.isInvalid()) 11715 return QualType(); 11716 Op = ConvResult.get(); 11717 QualType OpTy = Op->getType(); 11718 QualType Result; 11719 11720 if (isa<CXXReinterpretCastExpr>(Op)) { 11721 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11722 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11723 Op->getSourceRange()); 11724 } 11725 11726 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11727 { 11728 Result = PT->getPointeeType(); 11729 } 11730 else if (const ObjCObjectPointerType *OPT = 11731 OpTy->getAs<ObjCObjectPointerType>()) 11732 Result = OPT->getPointeeType(); 11733 else { 11734 ExprResult PR = S.CheckPlaceholderExpr(Op); 11735 if (PR.isInvalid()) return QualType(); 11736 if (PR.get() != Op) 11737 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11738 } 11739 11740 if (Result.isNull()) { 11741 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11742 << OpTy << Op->getSourceRange(); 11743 return QualType(); 11744 } 11745 11746 // Note that per both C89 and C99, indirection is always legal, even if Result 11747 // is an incomplete type or void. It would be possible to warn about 11748 // dereferencing a void pointer, but it's completely well-defined, and such a 11749 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11750 // for pointers to 'void' but is fine for any other pointer type: 11751 // 11752 // C++ [expr.unary.op]p1: 11753 // [...] the expression to which [the unary * operator] is applied shall 11754 // be a pointer to an object type, or a pointer to a function type 11755 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11756 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11757 << OpTy << Op->getSourceRange(); 11758 11759 // Dereferences are usually l-values... 11760 VK = VK_LValue; 11761 11762 // ...except that certain expressions are never l-values in C. 11763 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11764 VK = VK_RValue; 11765 11766 return Result; 11767 } 11768 11769 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11770 BinaryOperatorKind Opc; 11771 switch (Kind) { 11772 default: llvm_unreachable("Unknown binop!"); 11773 case tok::periodstar: Opc = BO_PtrMemD; break; 11774 case tok::arrowstar: Opc = BO_PtrMemI; break; 11775 case tok::star: Opc = BO_Mul; break; 11776 case tok::slash: Opc = BO_Div; break; 11777 case tok::percent: Opc = BO_Rem; break; 11778 case tok::plus: Opc = BO_Add; break; 11779 case tok::minus: Opc = BO_Sub; break; 11780 case tok::lessless: Opc = BO_Shl; break; 11781 case tok::greatergreater: Opc = BO_Shr; break; 11782 case tok::lessequal: Opc = BO_LE; break; 11783 case tok::less: Opc = BO_LT; break; 11784 case tok::greaterequal: Opc = BO_GE; break; 11785 case tok::greater: Opc = BO_GT; break; 11786 case tok::exclaimequal: Opc = BO_NE; break; 11787 case tok::equalequal: Opc = BO_EQ; break; 11788 case tok::spaceship: Opc = BO_Cmp; break; 11789 case tok::amp: Opc = BO_And; break; 11790 case tok::caret: Opc = BO_Xor; break; 11791 case tok::pipe: Opc = BO_Or; break; 11792 case tok::ampamp: Opc = BO_LAnd; break; 11793 case tok::pipepipe: Opc = BO_LOr; break; 11794 case tok::equal: Opc = BO_Assign; break; 11795 case tok::starequal: Opc = BO_MulAssign; break; 11796 case tok::slashequal: Opc = BO_DivAssign; break; 11797 case tok::percentequal: Opc = BO_RemAssign; break; 11798 case tok::plusequal: Opc = BO_AddAssign; break; 11799 case tok::minusequal: Opc = BO_SubAssign; break; 11800 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11801 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11802 case tok::ampequal: Opc = BO_AndAssign; break; 11803 case tok::caretequal: Opc = BO_XorAssign; break; 11804 case tok::pipeequal: Opc = BO_OrAssign; break; 11805 case tok::comma: Opc = BO_Comma; break; 11806 } 11807 return Opc; 11808 } 11809 11810 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11811 tok::TokenKind Kind) { 11812 UnaryOperatorKind Opc; 11813 switch (Kind) { 11814 default: llvm_unreachable("Unknown unary op!"); 11815 case tok::plusplus: Opc = UO_PreInc; break; 11816 case tok::minusminus: Opc = UO_PreDec; break; 11817 case tok::amp: Opc = UO_AddrOf; break; 11818 case tok::star: Opc = UO_Deref; break; 11819 case tok::plus: Opc = UO_Plus; break; 11820 case tok::minus: Opc = UO_Minus; break; 11821 case tok::tilde: Opc = UO_Not; break; 11822 case tok::exclaim: Opc = UO_LNot; break; 11823 case tok::kw___real: Opc = UO_Real; break; 11824 case tok::kw___imag: Opc = UO_Imag; break; 11825 case tok::kw___extension__: Opc = UO_Extension; break; 11826 } 11827 return Opc; 11828 } 11829 11830 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11831 /// This warning suppressed in the event of macro expansions. 11832 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11833 SourceLocation OpLoc, bool IsBuiltin) { 11834 if (S.inTemplateInstantiation()) 11835 return; 11836 if (S.isUnevaluatedContext()) 11837 return; 11838 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11839 return; 11840 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11841 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11842 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11843 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11844 if (!LHSDeclRef || !RHSDeclRef || 11845 LHSDeclRef->getLocation().isMacroID() || 11846 RHSDeclRef->getLocation().isMacroID()) 11847 return; 11848 const ValueDecl *LHSDecl = 11849 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11850 const ValueDecl *RHSDecl = 11851 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11852 if (LHSDecl != RHSDecl) 11853 return; 11854 if (LHSDecl->getType().isVolatileQualified()) 11855 return; 11856 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11857 if (RefTy->getPointeeType().isVolatileQualified()) 11858 return; 11859 11860 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11861 : diag::warn_self_assignment_overloaded) 11862 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11863 << RHSExpr->getSourceRange(); 11864 } 11865 11866 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11867 /// is usually indicative of introspection within the Objective-C pointer. 11868 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11869 SourceLocation OpLoc) { 11870 if (!S.getLangOpts().ObjC1) 11871 return; 11872 11873 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11874 const Expr *LHS = L.get(); 11875 const Expr *RHS = R.get(); 11876 11877 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11878 ObjCPointerExpr = LHS; 11879 OtherExpr = RHS; 11880 } 11881 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11882 ObjCPointerExpr = RHS; 11883 OtherExpr = LHS; 11884 } 11885 11886 // This warning is deliberately made very specific to reduce false 11887 // positives with logic that uses '&' for hashing. This logic mainly 11888 // looks for code trying to introspect into tagged pointers, which 11889 // code should generally never do. 11890 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11891 unsigned Diag = diag::warn_objc_pointer_masking; 11892 // Determine if we are introspecting the result of performSelectorXXX. 11893 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11894 // Special case messages to -performSelector and friends, which 11895 // can return non-pointer values boxed in a pointer value. 11896 // Some clients may wish to silence warnings in this subcase. 11897 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11898 Selector S = ME->getSelector(); 11899 StringRef SelArg0 = S.getNameForSlot(0); 11900 if (SelArg0.startswith("performSelector")) 11901 Diag = diag::warn_objc_pointer_masking_performSelector; 11902 } 11903 11904 S.Diag(OpLoc, Diag) 11905 << ObjCPointerExpr->getSourceRange(); 11906 } 11907 } 11908 11909 static NamedDecl *getDeclFromExpr(Expr *E) { 11910 if (!E) 11911 return nullptr; 11912 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11913 return DRE->getDecl(); 11914 if (auto *ME = dyn_cast<MemberExpr>(E)) 11915 return ME->getMemberDecl(); 11916 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11917 return IRE->getDecl(); 11918 return nullptr; 11919 } 11920 11921 // This helper function promotes a binary operator's operands (which are of a 11922 // half vector type) to a vector of floats and then truncates the result to 11923 // a vector of either half or short. 11924 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11925 BinaryOperatorKind Opc, QualType ResultTy, 11926 ExprValueKind VK, ExprObjectKind OK, 11927 bool IsCompAssign, SourceLocation OpLoc, 11928 FPOptions FPFeatures) { 11929 auto &Context = S.getASTContext(); 11930 assert((isVector(ResultTy, Context.HalfTy) || 11931 isVector(ResultTy, Context.ShortTy)) && 11932 "Result must be a vector of half or short"); 11933 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11934 isVector(RHS.get()->getType(), Context.HalfTy) && 11935 "both operands expected to be a half vector"); 11936 11937 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11938 QualType BinOpResTy = RHS.get()->getType(); 11939 11940 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11941 // change BinOpResTy to a vector of ints. 11942 if (isVector(ResultTy, Context.ShortTy)) 11943 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11944 11945 if (IsCompAssign) 11946 return new (Context) CompoundAssignOperator( 11947 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11948 OpLoc, FPFeatures); 11949 11950 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11951 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11952 VK, OK, OpLoc, FPFeatures); 11953 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11954 } 11955 11956 static std::pair<ExprResult, ExprResult> 11957 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11958 Expr *RHSExpr) { 11959 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11960 if (!S.getLangOpts().CPlusPlus) { 11961 // C cannot handle TypoExpr nodes on either side of a binop because it 11962 // doesn't handle dependent types properly, so make sure any TypoExprs have 11963 // been dealt with before checking the operands. 11964 LHS = S.CorrectDelayedTyposInExpr(LHS); 11965 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11966 if (Opc != BO_Assign) 11967 return ExprResult(E); 11968 // Avoid correcting the RHS to the same Expr as the LHS. 11969 Decl *D = getDeclFromExpr(E); 11970 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11971 }); 11972 } 11973 return std::make_pair(LHS, RHS); 11974 } 11975 11976 /// Returns true if conversion between vectors of halfs and vectors of floats 11977 /// is needed. 11978 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11979 QualType SrcType) { 11980 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11981 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11982 isVector(SrcType, Ctx.HalfTy); 11983 } 11984 11985 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11986 /// operator @p Opc at location @c TokLoc. This routine only supports 11987 /// built-in operations; ActOnBinOp handles overloaded operators. 11988 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11989 BinaryOperatorKind Opc, 11990 Expr *LHSExpr, Expr *RHSExpr) { 11991 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11992 // The syntax only allows initializer lists on the RHS of assignment, 11993 // so we don't need to worry about accepting invalid code for 11994 // non-assignment operators. 11995 // C++11 5.17p9: 11996 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11997 // of x = {} is x = T(). 11998 InitializationKind Kind = InitializationKind::CreateDirectList( 11999 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12000 InitializedEntity Entity = 12001 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12002 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12003 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12004 if (Init.isInvalid()) 12005 return Init; 12006 RHSExpr = Init.get(); 12007 } 12008 12009 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12010 QualType ResultTy; // Result type of the binary operator. 12011 // The following two variables are used for compound assignment operators 12012 QualType CompLHSTy; // Type of LHS after promotions for computation 12013 QualType CompResultTy; // Type of computation result 12014 ExprValueKind VK = VK_RValue; 12015 ExprObjectKind OK = OK_Ordinary; 12016 bool ConvertHalfVec = false; 12017 12018 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12019 if (!LHS.isUsable() || !RHS.isUsable()) 12020 return ExprError(); 12021 12022 if (getLangOpts().OpenCL) { 12023 QualType LHSTy = LHSExpr->getType(); 12024 QualType RHSTy = RHSExpr->getType(); 12025 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12026 // the ATOMIC_VAR_INIT macro. 12027 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12028 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12029 if (BO_Assign == Opc) 12030 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12031 else 12032 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12033 return ExprError(); 12034 } 12035 12036 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12037 // only with a builtin functions and therefore should be disallowed here. 12038 if (LHSTy->isImageType() || RHSTy->isImageType() || 12039 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12040 LHSTy->isPipeType() || RHSTy->isPipeType() || 12041 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12042 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12043 return ExprError(); 12044 } 12045 } 12046 12047 switch (Opc) { 12048 case BO_Assign: 12049 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12050 if (getLangOpts().CPlusPlus && 12051 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12052 VK = LHS.get()->getValueKind(); 12053 OK = LHS.get()->getObjectKind(); 12054 } 12055 if (!ResultTy.isNull()) { 12056 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12057 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12058 } 12059 RecordModifiableNonNullParam(*this, LHS.get()); 12060 break; 12061 case BO_PtrMemD: 12062 case BO_PtrMemI: 12063 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12064 Opc == BO_PtrMemI); 12065 break; 12066 case BO_Mul: 12067 case BO_Div: 12068 ConvertHalfVec = true; 12069 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12070 Opc == BO_Div); 12071 break; 12072 case BO_Rem: 12073 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12074 break; 12075 case BO_Add: 12076 ConvertHalfVec = true; 12077 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12078 break; 12079 case BO_Sub: 12080 ConvertHalfVec = true; 12081 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12082 break; 12083 case BO_Shl: 12084 case BO_Shr: 12085 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12086 break; 12087 case BO_LE: 12088 case BO_LT: 12089 case BO_GE: 12090 case BO_GT: 12091 ConvertHalfVec = true; 12092 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12093 break; 12094 case BO_EQ: 12095 case BO_NE: 12096 ConvertHalfVec = true; 12097 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12098 break; 12099 case BO_Cmp: 12100 ConvertHalfVec = true; 12101 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12102 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12103 break; 12104 case BO_And: 12105 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12106 LLVM_FALLTHROUGH; 12107 case BO_Xor: 12108 case BO_Or: 12109 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12110 break; 12111 case BO_LAnd: 12112 case BO_LOr: 12113 ConvertHalfVec = true; 12114 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12115 break; 12116 case BO_MulAssign: 12117 case BO_DivAssign: 12118 ConvertHalfVec = true; 12119 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12120 Opc == BO_DivAssign); 12121 CompLHSTy = CompResultTy; 12122 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12123 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12124 break; 12125 case BO_RemAssign: 12126 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12127 CompLHSTy = CompResultTy; 12128 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12129 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12130 break; 12131 case BO_AddAssign: 12132 ConvertHalfVec = true; 12133 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12134 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12135 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12136 break; 12137 case BO_SubAssign: 12138 ConvertHalfVec = true; 12139 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12140 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12141 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12142 break; 12143 case BO_ShlAssign: 12144 case BO_ShrAssign: 12145 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12146 CompLHSTy = CompResultTy; 12147 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12148 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12149 break; 12150 case BO_AndAssign: 12151 case BO_OrAssign: // fallthrough 12152 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12153 LLVM_FALLTHROUGH; 12154 case BO_XorAssign: 12155 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12156 CompLHSTy = CompResultTy; 12157 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12158 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12159 break; 12160 case BO_Comma: 12161 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12162 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12163 VK = RHS.get()->getValueKind(); 12164 OK = RHS.get()->getObjectKind(); 12165 } 12166 break; 12167 } 12168 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12169 return ExprError(); 12170 12171 // Some of the binary operations require promoting operands of half vector to 12172 // float vectors and truncating the result back to half vector. For now, we do 12173 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12174 // arm64). 12175 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12176 isVector(LHS.get()->getType(), Context.HalfTy) && 12177 "both sides are half vectors or neither sides are"); 12178 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12179 LHS.get()->getType()); 12180 12181 // Check for array bounds violations for both sides of the BinaryOperator 12182 CheckArrayAccess(LHS.get()); 12183 CheckArrayAccess(RHS.get()); 12184 12185 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12186 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12187 &Context.Idents.get("object_setClass"), 12188 SourceLocation(), LookupOrdinaryName); 12189 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12190 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12191 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12192 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12193 "object_setClass(") 12194 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12195 ",") 12196 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12197 } 12198 else 12199 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12200 } 12201 else if (const ObjCIvarRefExpr *OIRE = 12202 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12203 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12204 12205 // Opc is not a compound assignment if CompResultTy is null. 12206 if (CompResultTy.isNull()) { 12207 if (ConvertHalfVec) 12208 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12209 OpLoc, FPFeatures); 12210 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12211 OK, OpLoc, FPFeatures); 12212 } 12213 12214 // Handle compound assignments. 12215 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12216 OK_ObjCProperty) { 12217 VK = VK_LValue; 12218 OK = LHS.get()->getObjectKind(); 12219 } 12220 12221 if (ConvertHalfVec) 12222 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12223 OpLoc, FPFeatures); 12224 12225 return new (Context) CompoundAssignOperator( 12226 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12227 OpLoc, FPFeatures); 12228 } 12229 12230 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12231 /// operators are mixed in a way that suggests that the programmer forgot that 12232 /// comparison operators have higher precedence. The most typical example of 12233 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12234 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12235 SourceLocation OpLoc, Expr *LHSExpr, 12236 Expr *RHSExpr) { 12237 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12238 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12239 12240 // Check that one of the sides is a comparison operator and the other isn't. 12241 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12242 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12243 if (isLeftComp == isRightComp) 12244 return; 12245 12246 // Bitwise operations are sometimes used as eager logical ops. 12247 // Don't diagnose this. 12248 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12249 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12250 if (isLeftBitwise || isRightBitwise) 12251 return; 12252 12253 SourceRange DiagRange = isLeftComp 12254 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12255 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12256 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12257 SourceRange ParensRange = 12258 isLeftComp 12259 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12260 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12261 12262 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12263 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12264 SuggestParentheses(Self, OpLoc, 12265 Self.PDiag(diag::note_precedence_silence) << OpStr, 12266 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12267 SuggestParentheses(Self, OpLoc, 12268 Self.PDiag(diag::note_precedence_bitwise_first) 12269 << BinaryOperator::getOpcodeStr(Opc), 12270 ParensRange); 12271 } 12272 12273 /// It accepts a '&&' expr that is inside a '||' one. 12274 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12275 /// in parentheses. 12276 static void 12277 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12278 BinaryOperator *Bop) { 12279 assert(Bop->getOpcode() == BO_LAnd); 12280 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12281 << Bop->getSourceRange() << OpLoc; 12282 SuggestParentheses(Self, Bop->getOperatorLoc(), 12283 Self.PDiag(diag::note_precedence_silence) 12284 << Bop->getOpcodeStr(), 12285 Bop->getSourceRange()); 12286 } 12287 12288 /// Returns true if the given expression can be evaluated as a constant 12289 /// 'true'. 12290 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12291 bool Res; 12292 return !E->isValueDependent() && 12293 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12294 } 12295 12296 /// Returns true if the given expression can be evaluated as a constant 12297 /// 'false'. 12298 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12299 bool Res; 12300 return !E->isValueDependent() && 12301 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12302 } 12303 12304 /// Look for '&&' in the left hand of a '||' expr. 12305 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12306 Expr *LHSExpr, Expr *RHSExpr) { 12307 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12308 if (Bop->getOpcode() == BO_LAnd) { 12309 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12310 if (EvaluatesAsFalse(S, RHSExpr)) 12311 return; 12312 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12313 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12314 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12315 } else if (Bop->getOpcode() == BO_LOr) { 12316 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12317 // If it's "a || b && 1 || c" we didn't warn earlier for 12318 // "a || b && 1", but warn now. 12319 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12320 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12321 } 12322 } 12323 } 12324 } 12325 12326 /// Look for '&&' in the right hand of a '||' expr. 12327 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12328 Expr *LHSExpr, Expr *RHSExpr) { 12329 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12330 if (Bop->getOpcode() == BO_LAnd) { 12331 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12332 if (EvaluatesAsFalse(S, LHSExpr)) 12333 return; 12334 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12335 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12336 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12337 } 12338 } 12339 } 12340 12341 /// Look for bitwise op in the left or right hand of a bitwise op with 12342 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12343 /// the '&' expression in parentheses. 12344 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12345 SourceLocation OpLoc, Expr *SubExpr) { 12346 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12347 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12348 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12349 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12350 << Bop->getSourceRange() << OpLoc; 12351 SuggestParentheses(S, Bop->getOperatorLoc(), 12352 S.PDiag(diag::note_precedence_silence) 12353 << Bop->getOpcodeStr(), 12354 Bop->getSourceRange()); 12355 } 12356 } 12357 } 12358 12359 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12360 Expr *SubExpr, StringRef Shift) { 12361 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12362 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12363 StringRef Op = Bop->getOpcodeStr(); 12364 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12365 << Bop->getSourceRange() << OpLoc << Shift << Op; 12366 SuggestParentheses(S, Bop->getOperatorLoc(), 12367 S.PDiag(diag::note_precedence_silence) << Op, 12368 Bop->getSourceRange()); 12369 } 12370 } 12371 } 12372 12373 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12374 Expr *LHSExpr, Expr *RHSExpr) { 12375 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12376 if (!OCE) 12377 return; 12378 12379 FunctionDecl *FD = OCE->getDirectCallee(); 12380 if (!FD || !FD->isOverloadedOperator()) 12381 return; 12382 12383 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12384 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12385 return; 12386 12387 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12388 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12389 << (Kind == OO_LessLess); 12390 SuggestParentheses(S, OCE->getOperatorLoc(), 12391 S.PDiag(diag::note_precedence_silence) 12392 << (Kind == OO_LessLess ? "<<" : ">>"), 12393 OCE->getSourceRange()); 12394 SuggestParentheses( 12395 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12396 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12397 } 12398 12399 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12400 /// precedence. 12401 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12402 SourceLocation OpLoc, Expr *LHSExpr, 12403 Expr *RHSExpr){ 12404 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12405 if (BinaryOperator::isBitwiseOp(Opc)) 12406 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12407 12408 // Diagnose "arg1 & arg2 | arg3" 12409 if ((Opc == BO_Or || Opc == BO_Xor) && 12410 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12411 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12412 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12413 } 12414 12415 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12416 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12417 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12418 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12419 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12420 } 12421 12422 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12423 || Opc == BO_Shr) { 12424 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12425 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12426 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12427 } 12428 12429 // Warn on overloaded shift operators and comparisons, such as: 12430 // cout << 5 == 4; 12431 if (BinaryOperator::isComparisonOp(Opc)) 12432 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12433 } 12434 12435 // Binary Operators. 'Tok' is the token for the operator. 12436 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12437 tok::TokenKind Kind, 12438 Expr *LHSExpr, Expr *RHSExpr) { 12439 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12440 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12441 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12442 12443 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12444 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12445 12446 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12447 } 12448 12449 /// Build an overloaded binary operator expression in the given scope. 12450 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12451 BinaryOperatorKind Opc, 12452 Expr *LHS, Expr *RHS) { 12453 switch (Opc) { 12454 case BO_Assign: 12455 case BO_DivAssign: 12456 case BO_RemAssign: 12457 case BO_SubAssign: 12458 case BO_AndAssign: 12459 case BO_OrAssign: 12460 case BO_XorAssign: 12461 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12462 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12463 break; 12464 default: 12465 break; 12466 } 12467 12468 // Find all of the overloaded operators visible from this 12469 // point. We perform both an operator-name lookup from the local 12470 // scope and an argument-dependent lookup based on the types of 12471 // the arguments. 12472 UnresolvedSet<16> Functions; 12473 OverloadedOperatorKind OverOp 12474 = BinaryOperator::getOverloadedOperator(Opc); 12475 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12476 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12477 RHS->getType(), Functions); 12478 12479 // Build the (potentially-overloaded, potentially-dependent) 12480 // binary operation. 12481 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12482 } 12483 12484 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12485 BinaryOperatorKind Opc, 12486 Expr *LHSExpr, Expr *RHSExpr) { 12487 ExprResult LHS, RHS; 12488 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12489 if (!LHS.isUsable() || !RHS.isUsable()) 12490 return ExprError(); 12491 LHSExpr = LHS.get(); 12492 RHSExpr = RHS.get(); 12493 12494 // We want to end up calling one of checkPseudoObjectAssignment 12495 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12496 // both expressions are overloadable or either is type-dependent), 12497 // or CreateBuiltinBinOp (in any other case). We also want to get 12498 // any placeholder types out of the way. 12499 12500 // Handle pseudo-objects in the LHS. 12501 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12502 // Assignments with a pseudo-object l-value need special analysis. 12503 if (pty->getKind() == BuiltinType::PseudoObject && 12504 BinaryOperator::isAssignmentOp(Opc)) 12505 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12506 12507 // Don't resolve overloads if the other type is overloadable. 12508 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12509 // We can't actually test that if we still have a placeholder, 12510 // though. Fortunately, none of the exceptions we see in that 12511 // code below are valid when the LHS is an overload set. Note 12512 // that an overload set can be dependently-typed, but it never 12513 // instantiates to having an overloadable type. 12514 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12515 if (resolvedRHS.isInvalid()) return ExprError(); 12516 RHSExpr = resolvedRHS.get(); 12517 12518 if (RHSExpr->isTypeDependent() || 12519 RHSExpr->getType()->isOverloadableType()) 12520 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12521 } 12522 12523 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12524 // template, diagnose the missing 'template' keyword instead of diagnosing 12525 // an invalid use of a bound member function. 12526 // 12527 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12528 // to C++1z [over.over]/1.4, but we already checked for that case above. 12529 if (Opc == BO_LT && inTemplateInstantiation() && 12530 (pty->getKind() == BuiltinType::BoundMember || 12531 pty->getKind() == BuiltinType::Overload)) { 12532 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12533 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12534 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12535 return isa<FunctionTemplateDecl>(ND); 12536 })) { 12537 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12538 : OE->getNameLoc(), 12539 diag::err_template_kw_missing) 12540 << OE->getName().getAsString() << ""; 12541 return ExprError(); 12542 } 12543 } 12544 12545 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12546 if (LHS.isInvalid()) return ExprError(); 12547 LHSExpr = LHS.get(); 12548 } 12549 12550 // Handle pseudo-objects in the RHS. 12551 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12552 // An overload in the RHS can potentially be resolved by the type 12553 // being assigned to. 12554 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12555 if (getLangOpts().CPlusPlus && 12556 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12557 LHSExpr->getType()->isOverloadableType())) 12558 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12559 12560 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12561 } 12562 12563 // Don't resolve overloads if the other type is overloadable. 12564 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12565 LHSExpr->getType()->isOverloadableType()) 12566 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12567 12568 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12569 if (!resolvedRHS.isUsable()) return ExprError(); 12570 RHSExpr = resolvedRHS.get(); 12571 } 12572 12573 if (getLangOpts().CPlusPlus) { 12574 // If either expression is type-dependent, always build an 12575 // overloaded op. 12576 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12577 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12578 12579 // Otherwise, build an overloaded op if either expression has an 12580 // overloadable type. 12581 if (LHSExpr->getType()->isOverloadableType() || 12582 RHSExpr->getType()->isOverloadableType()) 12583 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12584 } 12585 12586 // Build a built-in binary operation. 12587 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12588 } 12589 12590 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12591 if (T.isNull() || T->isDependentType()) 12592 return false; 12593 12594 if (!T->isPromotableIntegerType()) 12595 return true; 12596 12597 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12598 } 12599 12600 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12601 UnaryOperatorKind Opc, 12602 Expr *InputExpr) { 12603 ExprResult Input = InputExpr; 12604 ExprValueKind VK = VK_RValue; 12605 ExprObjectKind OK = OK_Ordinary; 12606 QualType resultType; 12607 bool CanOverflow = false; 12608 12609 bool ConvertHalfVec = false; 12610 if (getLangOpts().OpenCL) { 12611 QualType Ty = InputExpr->getType(); 12612 // The only legal unary operation for atomics is '&'. 12613 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12614 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12615 // only with a builtin functions and therefore should be disallowed here. 12616 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12617 || Ty->isBlockPointerType())) { 12618 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12619 << InputExpr->getType() 12620 << Input.get()->getSourceRange()); 12621 } 12622 } 12623 switch (Opc) { 12624 case UO_PreInc: 12625 case UO_PreDec: 12626 case UO_PostInc: 12627 case UO_PostDec: 12628 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12629 OpLoc, 12630 Opc == UO_PreInc || 12631 Opc == UO_PostInc, 12632 Opc == UO_PreInc || 12633 Opc == UO_PreDec); 12634 CanOverflow = isOverflowingIntegerType(Context, resultType); 12635 break; 12636 case UO_AddrOf: 12637 resultType = CheckAddressOfOperand(Input, OpLoc); 12638 RecordModifiableNonNullParam(*this, InputExpr); 12639 break; 12640 case UO_Deref: { 12641 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12642 if (Input.isInvalid()) return ExprError(); 12643 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12644 break; 12645 } 12646 case UO_Plus: 12647 case UO_Minus: 12648 CanOverflow = Opc == UO_Minus && 12649 isOverflowingIntegerType(Context, Input.get()->getType()); 12650 Input = UsualUnaryConversions(Input.get()); 12651 if (Input.isInvalid()) return ExprError(); 12652 // Unary plus and minus require promoting an operand of half vector to a 12653 // float vector and truncating the result back to a half vector. For now, we 12654 // do this only when HalfArgsAndReturns is set (that is, when the target is 12655 // arm or arm64). 12656 ConvertHalfVec = 12657 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12658 12659 // If the operand is a half vector, promote it to a float vector. 12660 if (ConvertHalfVec) 12661 Input = convertVector(Input.get(), Context.FloatTy, *this); 12662 resultType = Input.get()->getType(); 12663 if (resultType->isDependentType()) 12664 break; 12665 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12666 break; 12667 else if (resultType->isVectorType() && 12668 // The z vector extensions don't allow + or - with bool vectors. 12669 (!Context.getLangOpts().ZVector || 12670 resultType->getAs<VectorType>()->getVectorKind() != 12671 VectorType::AltiVecBool)) 12672 break; 12673 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12674 Opc == UO_Plus && 12675 resultType->isPointerType()) 12676 break; 12677 12678 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12679 << resultType << Input.get()->getSourceRange()); 12680 12681 case UO_Not: // bitwise complement 12682 Input = UsualUnaryConversions(Input.get()); 12683 if (Input.isInvalid()) 12684 return ExprError(); 12685 resultType = Input.get()->getType(); 12686 12687 if (resultType->isDependentType()) 12688 break; 12689 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12690 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12691 // C99 does not support '~' for complex conjugation. 12692 Diag(OpLoc, diag::ext_integer_complement_complex) 12693 << resultType << Input.get()->getSourceRange(); 12694 else if (resultType->hasIntegerRepresentation()) 12695 break; 12696 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12697 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12698 // on vector float types. 12699 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12700 if (!T->isIntegerType()) 12701 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12702 << resultType << Input.get()->getSourceRange()); 12703 } else { 12704 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12705 << resultType << Input.get()->getSourceRange()); 12706 } 12707 break; 12708 12709 case UO_LNot: // logical negation 12710 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12711 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12712 if (Input.isInvalid()) return ExprError(); 12713 resultType = Input.get()->getType(); 12714 12715 // Though we still have to promote half FP to float... 12716 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12717 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12718 resultType = Context.FloatTy; 12719 } 12720 12721 if (resultType->isDependentType()) 12722 break; 12723 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12724 // C99 6.5.3.3p1: ok, fallthrough; 12725 if (Context.getLangOpts().CPlusPlus) { 12726 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12727 // operand contextually converted to bool. 12728 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12729 ScalarTypeToBooleanCastKind(resultType)); 12730 } else if (Context.getLangOpts().OpenCL && 12731 Context.getLangOpts().OpenCLVersion < 120) { 12732 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12733 // operate on scalar float types. 12734 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12735 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12736 << resultType << Input.get()->getSourceRange()); 12737 } 12738 } else if (resultType->isExtVectorType()) { 12739 if (Context.getLangOpts().OpenCL && 12740 Context.getLangOpts().OpenCLVersion < 120) { 12741 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12742 // operate on vector float types. 12743 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12744 if (!T->isIntegerType()) 12745 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12746 << resultType << Input.get()->getSourceRange()); 12747 } 12748 // Vector logical not returns the signed variant of the operand type. 12749 resultType = GetSignedVectorType(resultType); 12750 break; 12751 } else { 12752 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12753 // type in C++. We should allow that here too. 12754 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12755 << resultType << Input.get()->getSourceRange()); 12756 } 12757 12758 // LNot always has type int. C99 6.5.3.3p5. 12759 // In C++, it's bool. C++ 5.3.1p8 12760 resultType = Context.getLogicalOperationType(); 12761 break; 12762 case UO_Real: 12763 case UO_Imag: 12764 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12765 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12766 // complex l-values to ordinary l-values and all other values to r-values. 12767 if (Input.isInvalid()) return ExprError(); 12768 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12769 if (Input.get()->getValueKind() != VK_RValue && 12770 Input.get()->getObjectKind() == OK_Ordinary) 12771 VK = Input.get()->getValueKind(); 12772 } else if (!getLangOpts().CPlusPlus) { 12773 // In C, a volatile scalar is read by __imag. In C++, it is not. 12774 Input = DefaultLvalueConversion(Input.get()); 12775 } 12776 break; 12777 case UO_Extension: 12778 resultType = Input.get()->getType(); 12779 VK = Input.get()->getValueKind(); 12780 OK = Input.get()->getObjectKind(); 12781 break; 12782 case UO_Coawait: 12783 // It's unnecessary to represent the pass-through operator co_await in the 12784 // AST; just return the input expression instead. 12785 assert(!Input.get()->getType()->isDependentType() && 12786 "the co_await expression must be non-dependant before " 12787 "building operator co_await"); 12788 return Input; 12789 } 12790 if (resultType.isNull() || Input.isInvalid()) 12791 return ExprError(); 12792 12793 // Check for array bounds violations in the operand of the UnaryOperator, 12794 // except for the '*' and '&' operators that have to be handled specially 12795 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12796 // that are explicitly defined as valid by the standard). 12797 if (Opc != UO_AddrOf && Opc != UO_Deref) 12798 CheckArrayAccess(Input.get()); 12799 12800 auto *UO = new (Context) 12801 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12802 // Convert the result back to a half vector. 12803 if (ConvertHalfVec) 12804 return convertVector(UO, Context.HalfTy, *this); 12805 return UO; 12806 } 12807 12808 /// Determine whether the given expression is a qualified member 12809 /// access expression, of a form that could be turned into a pointer to member 12810 /// with the address-of operator. 12811 bool Sema::isQualifiedMemberAccess(Expr *E) { 12812 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12813 if (!DRE->getQualifier()) 12814 return false; 12815 12816 ValueDecl *VD = DRE->getDecl(); 12817 if (!VD->isCXXClassMember()) 12818 return false; 12819 12820 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12821 return true; 12822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12823 return Method->isInstance(); 12824 12825 return false; 12826 } 12827 12828 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12829 if (!ULE->getQualifier()) 12830 return false; 12831 12832 for (NamedDecl *D : ULE->decls()) { 12833 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12834 if (Method->isInstance()) 12835 return true; 12836 } else { 12837 // Overload set does not contain methods. 12838 break; 12839 } 12840 } 12841 12842 return false; 12843 } 12844 12845 return false; 12846 } 12847 12848 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12849 UnaryOperatorKind Opc, Expr *Input) { 12850 // First things first: handle placeholders so that the 12851 // overloaded-operator check considers the right type. 12852 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12853 // Increment and decrement of pseudo-object references. 12854 if (pty->getKind() == BuiltinType::PseudoObject && 12855 UnaryOperator::isIncrementDecrementOp(Opc)) 12856 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12857 12858 // extension is always a builtin operator. 12859 if (Opc == UO_Extension) 12860 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12861 12862 // & gets special logic for several kinds of placeholder. 12863 // The builtin code knows what to do. 12864 if (Opc == UO_AddrOf && 12865 (pty->getKind() == BuiltinType::Overload || 12866 pty->getKind() == BuiltinType::UnknownAny || 12867 pty->getKind() == BuiltinType::BoundMember)) 12868 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12869 12870 // Anything else needs to be handled now. 12871 ExprResult Result = CheckPlaceholderExpr(Input); 12872 if (Result.isInvalid()) return ExprError(); 12873 Input = Result.get(); 12874 } 12875 12876 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12877 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12878 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12879 // Find all of the overloaded operators visible from this 12880 // point. We perform both an operator-name lookup from the local 12881 // scope and an argument-dependent lookup based on the types of 12882 // the arguments. 12883 UnresolvedSet<16> Functions; 12884 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12885 if (S && OverOp != OO_None) 12886 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12887 Functions); 12888 12889 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12890 } 12891 12892 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12893 } 12894 12895 // Unary Operators. 'Tok' is the token for the operator. 12896 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12897 tok::TokenKind Op, Expr *Input) { 12898 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12899 } 12900 12901 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12902 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12903 LabelDecl *TheDecl) { 12904 TheDecl->markUsed(Context); 12905 // Create the AST node. The address of a label always has type 'void*'. 12906 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12907 Context.getPointerType(Context.VoidTy)); 12908 } 12909 12910 /// Given the last statement in a statement-expression, check whether 12911 /// the result is a producing expression (like a call to an 12912 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12913 /// release out of the full-expression. Otherwise, return null. 12914 /// Cannot fail. 12915 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12916 // Should always be wrapped with one of these. 12917 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12918 if (!cleanups) return nullptr; 12919 12920 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12921 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12922 return nullptr; 12923 12924 // Splice out the cast. This shouldn't modify any interesting 12925 // features of the statement. 12926 Expr *producer = cast->getSubExpr(); 12927 assert(producer->getType() == cast->getType()); 12928 assert(producer->getValueKind() == cast->getValueKind()); 12929 cleanups->setSubExpr(producer); 12930 return cleanups; 12931 } 12932 12933 void Sema::ActOnStartStmtExpr() { 12934 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12935 } 12936 12937 void Sema::ActOnStmtExprError() { 12938 // Note that function is also called by TreeTransform when leaving a 12939 // StmtExpr scope without rebuilding anything. 12940 12941 DiscardCleanupsInEvaluationContext(); 12942 PopExpressionEvaluationContext(); 12943 } 12944 12945 ExprResult 12946 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12947 SourceLocation RPLoc) { // "({..})" 12948 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12949 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12950 12951 if (hasAnyUnrecoverableErrorsInThisFunction()) 12952 DiscardCleanupsInEvaluationContext(); 12953 assert(!Cleanup.exprNeedsCleanups() && 12954 "cleanups within StmtExpr not correctly bound!"); 12955 PopExpressionEvaluationContext(); 12956 12957 // FIXME: there are a variety of strange constraints to enforce here, for 12958 // example, it is not possible to goto into a stmt expression apparently. 12959 // More semantic analysis is needed. 12960 12961 // If there are sub-stmts in the compound stmt, take the type of the last one 12962 // as the type of the stmtexpr. 12963 QualType Ty = Context.VoidTy; 12964 bool StmtExprMayBindToTemp = false; 12965 if (!Compound->body_empty()) { 12966 Stmt *LastStmt = Compound->body_back(); 12967 LabelStmt *LastLabelStmt = nullptr; 12968 // If LastStmt is a label, skip down through into the body. 12969 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12970 LastLabelStmt = Label; 12971 LastStmt = Label->getSubStmt(); 12972 } 12973 12974 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12975 // Do function/array conversion on the last expression, but not 12976 // lvalue-to-rvalue. However, initialize an unqualified type. 12977 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12978 if (LastExpr.isInvalid()) 12979 return ExprError(); 12980 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12981 12982 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12983 // In ARC, if the final expression ends in a consume, splice 12984 // the consume out and bind it later. In the alternate case 12985 // (when dealing with a retainable type), the result 12986 // initialization will create a produce. In both cases the 12987 // result will be +1, and we'll need to balance that out with 12988 // a bind. 12989 if (Expr *rebuiltLastStmt 12990 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12991 LastExpr = rebuiltLastStmt; 12992 } else { 12993 LastExpr = PerformCopyInitialization( 12994 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 12995 SourceLocation(), LastExpr); 12996 } 12997 12998 if (LastExpr.isInvalid()) 12999 return ExprError(); 13000 if (LastExpr.get() != nullptr) { 13001 if (!LastLabelStmt) 13002 Compound->setLastStmt(LastExpr.get()); 13003 else 13004 LastLabelStmt->setSubStmt(LastExpr.get()); 13005 StmtExprMayBindToTemp = true; 13006 } 13007 } 13008 } 13009 } 13010 13011 // FIXME: Check that expression type is complete/non-abstract; statement 13012 // expressions are not lvalues. 13013 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13014 if (StmtExprMayBindToTemp) 13015 return MaybeBindToTemporary(ResStmtExpr); 13016 return ResStmtExpr; 13017 } 13018 13019 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13020 TypeSourceInfo *TInfo, 13021 ArrayRef<OffsetOfComponent> Components, 13022 SourceLocation RParenLoc) { 13023 QualType ArgTy = TInfo->getType(); 13024 bool Dependent = ArgTy->isDependentType(); 13025 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13026 13027 // We must have at least one component that refers to the type, and the first 13028 // one is known to be a field designator. Verify that the ArgTy represents 13029 // a struct/union/class. 13030 if (!Dependent && !ArgTy->isRecordType()) 13031 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13032 << ArgTy << TypeRange); 13033 13034 // Type must be complete per C99 7.17p3 because a declaring a variable 13035 // with an incomplete type would be ill-formed. 13036 if (!Dependent 13037 && RequireCompleteType(BuiltinLoc, ArgTy, 13038 diag::err_offsetof_incomplete_type, TypeRange)) 13039 return ExprError(); 13040 13041 bool DidWarnAboutNonPOD = false; 13042 QualType CurrentType = ArgTy; 13043 SmallVector<OffsetOfNode, 4> Comps; 13044 SmallVector<Expr*, 4> Exprs; 13045 for (const OffsetOfComponent &OC : Components) { 13046 if (OC.isBrackets) { 13047 // Offset of an array sub-field. TODO: Should we allow vector elements? 13048 if (!CurrentType->isDependentType()) { 13049 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13050 if(!AT) 13051 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13052 << CurrentType); 13053 CurrentType = AT->getElementType(); 13054 } else 13055 CurrentType = Context.DependentTy; 13056 13057 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13058 if (IdxRval.isInvalid()) 13059 return ExprError(); 13060 Expr *Idx = IdxRval.get(); 13061 13062 // The expression must be an integral expression. 13063 // FIXME: An integral constant expression? 13064 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13065 !Idx->getType()->isIntegerType()) 13066 return ExprError( 13067 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13068 << Idx->getSourceRange()); 13069 13070 // Record this array index. 13071 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13072 Exprs.push_back(Idx); 13073 continue; 13074 } 13075 13076 // Offset of a field. 13077 if (CurrentType->isDependentType()) { 13078 // We have the offset of a field, but we can't look into the dependent 13079 // type. Just record the identifier of the field. 13080 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13081 CurrentType = Context.DependentTy; 13082 continue; 13083 } 13084 13085 // We need to have a complete type to look into. 13086 if (RequireCompleteType(OC.LocStart, CurrentType, 13087 diag::err_offsetof_incomplete_type)) 13088 return ExprError(); 13089 13090 // Look for the designated field. 13091 const RecordType *RC = CurrentType->getAs<RecordType>(); 13092 if (!RC) 13093 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13094 << CurrentType); 13095 RecordDecl *RD = RC->getDecl(); 13096 13097 // C++ [lib.support.types]p5: 13098 // The macro offsetof accepts a restricted set of type arguments in this 13099 // International Standard. type shall be a POD structure or a POD union 13100 // (clause 9). 13101 // C++11 [support.types]p4: 13102 // If type is not a standard-layout class (Clause 9), the results are 13103 // undefined. 13104 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13105 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13106 unsigned DiagID = 13107 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13108 : diag::ext_offsetof_non_pod_type; 13109 13110 if (!IsSafe && !DidWarnAboutNonPOD && 13111 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13112 PDiag(DiagID) 13113 << SourceRange(Components[0].LocStart, OC.LocEnd) 13114 << CurrentType)) 13115 DidWarnAboutNonPOD = true; 13116 } 13117 13118 // Look for the field. 13119 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13120 LookupQualifiedName(R, RD); 13121 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13122 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13123 if (!MemberDecl) { 13124 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13125 MemberDecl = IndirectMemberDecl->getAnonField(); 13126 } 13127 13128 if (!MemberDecl) 13129 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13130 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13131 OC.LocEnd)); 13132 13133 // C99 7.17p3: 13134 // (If the specified member is a bit-field, the behavior is undefined.) 13135 // 13136 // We diagnose this as an error. 13137 if (MemberDecl->isBitField()) { 13138 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13139 << MemberDecl->getDeclName() 13140 << SourceRange(BuiltinLoc, RParenLoc); 13141 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13142 return ExprError(); 13143 } 13144 13145 RecordDecl *Parent = MemberDecl->getParent(); 13146 if (IndirectMemberDecl) 13147 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13148 13149 // If the member was found in a base class, introduce OffsetOfNodes for 13150 // the base class indirections. 13151 CXXBasePaths Paths; 13152 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13153 Paths)) { 13154 if (Paths.getDetectedVirtual()) { 13155 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13156 << MemberDecl->getDeclName() 13157 << SourceRange(BuiltinLoc, RParenLoc); 13158 return ExprError(); 13159 } 13160 13161 CXXBasePath &Path = Paths.front(); 13162 for (const CXXBasePathElement &B : Path) 13163 Comps.push_back(OffsetOfNode(B.Base)); 13164 } 13165 13166 if (IndirectMemberDecl) { 13167 for (auto *FI : IndirectMemberDecl->chain()) { 13168 assert(isa<FieldDecl>(FI)); 13169 Comps.push_back(OffsetOfNode(OC.LocStart, 13170 cast<FieldDecl>(FI), OC.LocEnd)); 13171 } 13172 } else 13173 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13174 13175 CurrentType = MemberDecl->getType().getNonReferenceType(); 13176 } 13177 13178 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13179 Comps, Exprs, RParenLoc); 13180 } 13181 13182 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13183 SourceLocation BuiltinLoc, 13184 SourceLocation TypeLoc, 13185 ParsedType ParsedArgTy, 13186 ArrayRef<OffsetOfComponent> Components, 13187 SourceLocation RParenLoc) { 13188 13189 TypeSourceInfo *ArgTInfo; 13190 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13191 if (ArgTy.isNull()) 13192 return ExprError(); 13193 13194 if (!ArgTInfo) 13195 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13196 13197 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13198 } 13199 13200 13201 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13202 Expr *CondExpr, 13203 Expr *LHSExpr, Expr *RHSExpr, 13204 SourceLocation RPLoc) { 13205 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13206 13207 ExprValueKind VK = VK_RValue; 13208 ExprObjectKind OK = OK_Ordinary; 13209 QualType resType; 13210 bool ValueDependent = false; 13211 bool CondIsTrue = false; 13212 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13213 resType = Context.DependentTy; 13214 ValueDependent = true; 13215 } else { 13216 // The conditional expression is required to be a constant expression. 13217 llvm::APSInt condEval(32); 13218 ExprResult CondICE 13219 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13220 diag::err_typecheck_choose_expr_requires_constant, false); 13221 if (CondICE.isInvalid()) 13222 return ExprError(); 13223 CondExpr = CondICE.get(); 13224 CondIsTrue = condEval.getZExtValue(); 13225 13226 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13227 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13228 13229 resType = ActiveExpr->getType(); 13230 ValueDependent = ActiveExpr->isValueDependent(); 13231 VK = ActiveExpr->getValueKind(); 13232 OK = ActiveExpr->getObjectKind(); 13233 } 13234 13235 return new (Context) 13236 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13237 CondIsTrue, resType->isDependentType(), ValueDependent); 13238 } 13239 13240 //===----------------------------------------------------------------------===// 13241 // Clang Extensions. 13242 //===----------------------------------------------------------------------===// 13243 13244 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13245 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13246 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13247 13248 if (LangOpts.CPlusPlus) { 13249 Decl *ManglingContextDecl; 13250 if (MangleNumberingContext *MCtx = 13251 getCurrentMangleNumberContext(Block->getDeclContext(), 13252 ManglingContextDecl)) { 13253 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13254 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13255 } 13256 } 13257 13258 PushBlockScope(CurScope, Block); 13259 CurContext->addDecl(Block); 13260 if (CurScope) 13261 PushDeclContext(CurScope, Block); 13262 else 13263 CurContext = Block; 13264 13265 getCurBlock()->HasImplicitReturnType = true; 13266 13267 // Enter a new evaluation context to insulate the block from any 13268 // cleanups from the enclosing full-expression. 13269 PushExpressionEvaluationContext( 13270 ExpressionEvaluationContext::PotentiallyEvaluated); 13271 } 13272 13273 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13274 Scope *CurScope) { 13275 assert(ParamInfo.getIdentifier() == nullptr && 13276 "block-id should have no identifier!"); 13277 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13278 BlockScopeInfo *CurBlock = getCurBlock(); 13279 13280 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13281 QualType T = Sig->getType(); 13282 13283 // FIXME: We should allow unexpanded parameter packs here, but that would, 13284 // in turn, make the block expression contain unexpanded parameter packs. 13285 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13286 // Drop the parameters. 13287 FunctionProtoType::ExtProtoInfo EPI; 13288 EPI.HasTrailingReturn = false; 13289 EPI.TypeQuals |= DeclSpec::TQ_const; 13290 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13291 Sig = Context.getTrivialTypeSourceInfo(T); 13292 } 13293 13294 // GetTypeForDeclarator always produces a function type for a block 13295 // literal signature. Furthermore, it is always a FunctionProtoType 13296 // unless the function was written with a typedef. 13297 assert(T->isFunctionType() && 13298 "GetTypeForDeclarator made a non-function block signature"); 13299 13300 // Look for an explicit signature in that function type. 13301 FunctionProtoTypeLoc ExplicitSignature; 13302 13303 if ((ExplicitSignature = 13304 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13305 13306 // Check whether that explicit signature was synthesized by 13307 // GetTypeForDeclarator. If so, don't save that as part of the 13308 // written signature. 13309 if (ExplicitSignature.getLocalRangeBegin() == 13310 ExplicitSignature.getLocalRangeEnd()) { 13311 // This would be much cheaper if we stored TypeLocs instead of 13312 // TypeSourceInfos. 13313 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13314 unsigned Size = Result.getFullDataSize(); 13315 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13316 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13317 13318 ExplicitSignature = FunctionProtoTypeLoc(); 13319 } 13320 } 13321 13322 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13323 CurBlock->FunctionType = T; 13324 13325 const FunctionType *Fn = T->getAs<FunctionType>(); 13326 QualType RetTy = Fn->getReturnType(); 13327 bool isVariadic = 13328 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13329 13330 CurBlock->TheDecl->setIsVariadic(isVariadic); 13331 13332 // Context.DependentTy is used as a placeholder for a missing block 13333 // return type. TODO: what should we do with declarators like: 13334 // ^ * { ... } 13335 // If the answer is "apply template argument deduction".... 13336 if (RetTy != Context.DependentTy) { 13337 CurBlock->ReturnType = RetTy; 13338 CurBlock->TheDecl->setBlockMissingReturnType(false); 13339 CurBlock->HasImplicitReturnType = false; 13340 } 13341 13342 // Push block parameters from the declarator if we had them. 13343 SmallVector<ParmVarDecl*, 8> Params; 13344 if (ExplicitSignature) { 13345 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13346 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13347 if (Param->getIdentifier() == nullptr && 13348 !Param->isImplicit() && 13349 !Param->isInvalidDecl() && 13350 !getLangOpts().CPlusPlus) 13351 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13352 Params.push_back(Param); 13353 } 13354 13355 // Fake up parameter variables if we have a typedef, like 13356 // ^ fntype { ... } 13357 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13358 for (const auto &I : Fn->param_types()) { 13359 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13360 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13361 Params.push_back(Param); 13362 } 13363 } 13364 13365 // Set the parameters on the block decl. 13366 if (!Params.empty()) { 13367 CurBlock->TheDecl->setParams(Params); 13368 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13369 /*CheckParameterNames=*/false); 13370 } 13371 13372 // Finally we can process decl attributes. 13373 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13374 13375 // Put the parameter variables in scope. 13376 for (auto AI : CurBlock->TheDecl->parameters()) { 13377 AI->setOwningFunction(CurBlock->TheDecl); 13378 13379 // If this has an identifier, add it to the scope stack. 13380 if (AI->getIdentifier()) { 13381 CheckShadow(CurBlock->TheScope, AI); 13382 13383 PushOnScopeChains(AI, CurBlock->TheScope); 13384 } 13385 } 13386 } 13387 13388 /// ActOnBlockError - If there is an error parsing a block, this callback 13389 /// is invoked to pop the information about the block from the action impl. 13390 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13391 // Leave the expression-evaluation context. 13392 DiscardCleanupsInEvaluationContext(); 13393 PopExpressionEvaluationContext(); 13394 13395 // Pop off CurBlock, handle nested blocks. 13396 PopDeclContext(); 13397 PopFunctionScopeInfo(); 13398 } 13399 13400 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13401 /// literal was successfully completed. ^(int x){...} 13402 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13403 Stmt *Body, Scope *CurScope) { 13404 // If blocks are disabled, emit an error. 13405 if (!LangOpts.Blocks) 13406 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13407 13408 // Leave the expression-evaluation context. 13409 if (hasAnyUnrecoverableErrorsInThisFunction()) 13410 DiscardCleanupsInEvaluationContext(); 13411 assert(!Cleanup.exprNeedsCleanups() && 13412 "cleanups within block not correctly bound!"); 13413 PopExpressionEvaluationContext(); 13414 13415 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13416 13417 if (BSI->HasImplicitReturnType) 13418 deduceClosureReturnType(*BSI); 13419 13420 PopDeclContext(); 13421 13422 QualType RetTy = Context.VoidTy; 13423 if (!BSI->ReturnType.isNull()) 13424 RetTy = BSI->ReturnType; 13425 13426 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13427 QualType BlockTy; 13428 13429 // Set the captured variables on the block. 13430 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13431 SmallVector<BlockDecl::Capture, 4> Captures; 13432 for (Capture &Cap : BSI->Captures) { 13433 if (Cap.isThisCapture()) 13434 continue; 13435 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13436 Cap.isNested(), Cap.getInitExpr()); 13437 Captures.push_back(NewCap); 13438 } 13439 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13440 13441 // If the user wrote a function type in some form, try to use that. 13442 if (!BSI->FunctionType.isNull()) { 13443 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13444 13445 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13446 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13447 13448 // Turn protoless block types into nullary block types. 13449 if (isa<FunctionNoProtoType>(FTy)) { 13450 FunctionProtoType::ExtProtoInfo EPI; 13451 EPI.ExtInfo = Ext; 13452 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13453 13454 // Otherwise, if we don't need to change anything about the function type, 13455 // preserve its sugar structure. 13456 } else if (FTy->getReturnType() == RetTy && 13457 (!NoReturn || FTy->getNoReturnAttr())) { 13458 BlockTy = BSI->FunctionType; 13459 13460 // Otherwise, make the minimal modifications to the function type. 13461 } else { 13462 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13463 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13464 EPI.TypeQuals = 0; // FIXME: silently? 13465 EPI.ExtInfo = Ext; 13466 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13467 } 13468 13469 // If we don't have a function type, just build one from nothing. 13470 } else { 13471 FunctionProtoType::ExtProtoInfo EPI; 13472 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13473 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13474 } 13475 13476 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13477 BlockTy = Context.getBlockPointerType(BlockTy); 13478 13479 // If needed, diagnose invalid gotos and switches in the block. 13480 if (getCurFunction()->NeedsScopeChecking() && 13481 !PP.isCodeCompletionEnabled()) 13482 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13483 13484 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13485 13486 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13487 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13488 13489 // Try to apply the named return value optimization. We have to check again 13490 // if we can do this, though, because blocks keep return statements around 13491 // to deduce an implicit return type. 13492 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13493 !BSI->TheDecl->isDependentContext()) 13494 computeNRVO(Body, BSI); 13495 13496 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13497 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13498 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13499 13500 // If the block isn't obviously global, i.e. it captures anything at 13501 // all, then we need to do a few things in the surrounding context: 13502 if (Result->getBlockDecl()->hasCaptures()) { 13503 // First, this expression has a new cleanup object. 13504 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13505 Cleanup.setExprNeedsCleanups(true); 13506 13507 // It also gets a branch-protected scope if any of the captured 13508 // variables needs destruction. 13509 for (const auto &CI : Result->getBlockDecl()->captures()) { 13510 const VarDecl *var = CI.getVariable(); 13511 if (var->getType().isDestructedType() != QualType::DK_none) { 13512 setFunctionHasBranchProtectedScope(); 13513 break; 13514 } 13515 } 13516 } 13517 13518 return Result; 13519 } 13520 13521 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13522 SourceLocation RPLoc) { 13523 TypeSourceInfo *TInfo; 13524 GetTypeFromParser(Ty, &TInfo); 13525 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13526 } 13527 13528 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13529 Expr *E, TypeSourceInfo *TInfo, 13530 SourceLocation RPLoc) { 13531 Expr *OrigExpr = E; 13532 bool IsMS = false; 13533 13534 // CUDA device code does not support varargs. 13535 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13536 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13537 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13538 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13539 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13540 } 13541 } 13542 13543 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13544 // as Microsoft ABI on an actual Microsoft platform, where 13545 // __builtin_ms_va_list and __builtin_va_list are the same.) 13546 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13547 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13548 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13549 if (Context.hasSameType(MSVaListType, E->getType())) { 13550 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13551 return ExprError(); 13552 IsMS = true; 13553 } 13554 } 13555 13556 // Get the va_list type 13557 QualType VaListType = Context.getBuiltinVaListType(); 13558 if (!IsMS) { 13559 if (VaListType->isArrayType()) { 13560 // Deal with implicit array decay; for example, on x86-64, 13561 // va_list is an array, but it's supposed to decay to 13562 // a pointer for va_arg. 13563 VaListType = Context.getArrayDecayedType(VaListType); 13564 // Make sure the input expression also decays appropriately. 13565 ExprResult Result = UsualUnaryConversions(E); 13566 if (Result.isInvalid()) 13567 return ExprError(); 13568 E = Result.get(); 13569 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13570 // If va_list is a record type and we are compiling in C++ mode, 13571 // check the argument using reference binding. 13572 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13573 Context, Context.getLValueReferenceType(VaListType), false); 13574 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13575 if (Init.isInvalid()) 13576 return ExprError(); 13577 E = Init.getAs<Expr>(); 13578 } else { 13579 // Otherwise, the va_list argument must be an l-value because 13580 // it is modified by va_arg. 13581 if (!E->isTypeDependent() && 13582 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13583 return ExprError(); 13584 } 13585 } 13586 13587 if (!IsMS && !E->isTypeDependent() && 13588 !Context.hasSameType(VaListType, E->getType())) 13589 return ExprError( 13590 Diag(E->getBeginLoc(), 13591 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13592 << OrigExpr->getType() << E->getSourceRange()); 13593 13594 if (!TInfo->getType()->isDependentType()) { 13595 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13596 diag::err_second_parameter_to_va_arg_incomplete, 13597 TInfo->getTypeLoc())) 13598 return ExprError(); 13599 13600 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13601 TInfo->getType(), 13602 diag::err_second_parameter_to_va_arg_abstract, 13603 TInfo->getTypeLoc())) 13604 return ExprError(); 13605 13606 if (!TInfo->getType().isPODType(Context)) { 13607 Diag(TInfo->getTypeLoc().getBeginLoc(), 13608 TInfo->getType()->isObjCLifetimeType() 13609 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13610 : diag::warn_second_parameter_to_va_arg_not_pod) 13611 << TInfo->getType() 13612 << TInfo->getTypeLoc().getSourceRange(); 13613 } 13614 13615 // Check for va_arg where arguments of the given type will be promoted 13616 // (i.e. this va_arg is guaranteed to have undefined behavior). 13617 QualType PromoteType; 13618 if (TInfo->getType()->isPromotableIntegerType()) { 13619 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13620 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13621 PromoteType = QualType(); 13622 } 13623 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13624 PromoteType = Context.DoubleTy; 13625 if (!PromoteType.isNull()) 13626 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13627 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13628 << TInfo->getType() 13629 << PromoteType 13630 << TInfo->getTypeLoc().getSourceRange()); 13631 } 13632 13633 QualType T = TInfo->getType().getNonLValueExprType(Context); 13634 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13635 } 13636 13637 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13638 // The type of __null will be int or long, depending on the size of 13639 // pointers on the target. 13640 QualType Ty; 13641 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13642 if (pw == Context.getTargetInfo().getIntWidth()) 13643 Ty = Context.IntTy; 13644 else if (pw == Context.getTargetInfo().getLongWidth()) 13645 Ty = Context.LongTy; 13646 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13647 Ty = Context.LongLongTy; 13648 else { 13649 llvm_unreachable("I don't know size of pointer!"); 13650 } 13651 13652 return new (Context) GNUNullExpr(Ty, TokenLoc); 13653 } 13654 13655 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13656 bool Diagnose) { 13657 if (!getLangOpts().ObjC1) 13658 return false; 13659 13660 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13661 if (!PT) 13662 return false; 13663 13664 if (!PT->isObjCIdType()) { 13665 // Check if the destination is the 'NSString' interface. 13666 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13667 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13668 return false; 13669 } 13670 13671 // Ignore any parens, implicit casts (should only be 13672 // array-to-pointer decays), and not-so-opaque values. The last is 13673 // important for making this trigger for property assignments. 13674 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13675 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13676 if (OV->getSourceExpr()) 13677 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13678 13679 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13680 if (!SL || !SL->isAscii()) 13681 return false; 13682 if (Diagnose) { 13683 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13684 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13685 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13686 } 13687 return true; 13688 } 13689 13690 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13691 const Expr *SrcExpr) { 13692 if (!DstType->isFunctionPointerType() || 13693 !SrcExpr->getType()->isFunctionType()) 13694 return false; 13695 13696 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13697 if (!DRE) 13698 return false; 13699 13700 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13701 if (!FD) 13702 return false; 13703 13704 return !S.checkAddressOfFunctionIsAvailable(FD, 13705 /*Complain=*/true, 13706 SrcExpr->getBeginLoc()); 13707 } 13708 13709 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13710 SourceLocation Loc, 13711 QualType DstType, QualType SrcType, 13712 Expr *SrcExpr, AssignmentAction Action, 13713 bool *Complained) { 13714 if (Complained) 13715 *Complained = false; 13716 13717 // Decode the result (notice that AST's are still created for extensions). 13718 bool CheckInferredResultType = false; 13719 bool isInvalid = false; 13720 unsigned DiagKind = 0; 13721 FixItHint Hint; 13722 ConversionFixItGenerator ConvHints; 13723 bool MayHaveConvFixit = false; 13724 bool MayHaveFunctionDiff = false; 13725 const ObjCInterfaceDecl *IFace = nullptr; 13726 const ObjCProtocolDecl *PDecl = nullptr; 13727 13728 switch (ConvTy) { 13729 case Compatible: 13730 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13731 return false; 13732 13733 case PointerToInt: 13734 DiagKind = diag::ext_typecheck_convert_pointer_int; 13735 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13736 MayHaveConvFixit = true; 13737 break; 13738 case IntToPointer: 13739 DiagKind = diag::ext_typecheck_convert_int_pointer; 13740 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13741 MayHaveConvFixit = true; 13742 break; 13743 case IncompatiblePointer: 13744 if (Action == AA_Passing_CFAudited) 13745 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13746 else if (SrcType->isFunctionPointerType() && 13747 DstType->isFunctionPointerType()) 13748 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13749 else 13750 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13751 13752 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13753 SrcType->isObjCObjectPointerType(); 13754 if (Hint.isNull() && !CheckInferredResultType) { 13755 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13756 } 13757 else if (CheckInferredResultType) { 13758 SrcType = SrcType.getUnqualifiedType(); 13759 DstType = DstType.getUnqualifiedType(); 13760 } 13761 MayHaveConvFixit = true; 13762 break; 13763 case IncompatiblePointerSign: 13764 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13765 break; 13766 case FunctionVoidPointer: 13767 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13768 break; 13769 case IncompatiblePointerDiscardsQualifiers: { 13770 // Perform array-to-pointer decay if necessary. 13771 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13772 13773 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13774 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13775 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13776 DiagKind = diag::err_typecheck_incompatible_address_space; 13777 break; 13778 13779 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13780 DiagKind = diag::err_typecheck_incompatible_ownership; 13781 break; 13782 } 13783 13784 llvm_unreachable("unknown error case for discarding qualifiers!"); 13785 // fallthrough 13786 } 13787 case CompatiblePointerDiscardsQualifiers: 13788 // If the qualifiers lost were because we were applying the 13789 // (deprecated) C++ conversion from a string literal to a char* 13790 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13791 // Ideally, this check would be performed in 13792 // checkPointerTypesForAssignment. However, that would require a 13793 // bit of refactoring (so that the second argument is an 13794 // expression, rather than a type), which should be done as part 13795 // of a larger effort to fix checkPointerTypesForAssignment for 13796 // C++ semantics. 13797 if (getLangOpts().CPlusPlus && 13798 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13799 return false; 13800 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13801 break; 13802 case IncompatibleNestedPointerQualifiers: 13803 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13804 break; 13805 case IntToBlockPointer: 13806 DiagKind = diag::err_int_to_block_pointer; 13807 break; 13808 case IncompatibleBlockPointer: 13809 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13810 break; 13811 case IncompatibleObjCQualifiedId: { 13812 if (SrcType->isObjCQualifiedIdType()) { 13813 const ObjCObjectPointerType *srcOPT = 13814 SrcType->getAs<ObjCObjectPointerType>(); 13815 for (auto *srcProto : srcOPT->quals()) { 13816 PDecl = srcProto; 13817 break; 13818 } 13819 if (const ObjCInterfaceType *IFaceT = 13820 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13821 IFace = IFaceT->getDecl(); 13822 } 13823 else if (DstType->isObjCQualifiedIdType()) { 13824 const ObjCObjectPointerType *dstOPT = 13825 DstType->getAs<ObjCObjectPointerType>(); 13826 for (auto *dstProto : dstOPT->quals()) { 13827 PDecl = dstProto; 13828 break; 13829 } 13830 if (const ObjCInterfaceType *IFaceT = 13831 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13832 IFace = IFaceT->getDecl(); 13833 } 13834 DiagKind = diag::warn_incompatible_qualified_id; 13835 break; 13836 } 13837 case IncompatibleVectors: 13838 DiagKind = diag::warn_incompatible_vectors; 13839 break; 13840 case IncompatibleObjCWeakRef: 13841 DiagKind = diag::err_arc_weak_unavailable_assign; 13842 break; 13843 case Incompatible: 13844 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13845 if (Complained) 13846 *Complained = true; 13847 return true; 13848 } 13849 13850 DiagKind = diag::err_typecheck_convert_incompatible; 13851 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13852 MayHaveConvFixit = true; 13853 isInvalid = true; 13854 MayHaveFunctionDiff = true; 13855 break; 13856 } 13857 13858 QualType FirstType, SecondType; 13859 switch (Action) { 13860 case AA_Assigning: 13861 case AA_Initializing: 13862 // The destination type comes first. 13863 FirstType = DstType; 13864 SecondType = SrcType; 13865 break; 13866 13867 case AA_Returning: 13868 case AA_Passing: 13869 case AA_Passing_CFAudited: 13870 case AA_Converting: 13871 case AA_Sending: 13872 case AA_Casting: 13873 // The source type comes first. 13874 FirstType = SrcType; 13875 SecondType = DstType; 13876 break; 13877 } 13878 13879 PartialDiagnostic FDiag = PDiag(DiagKind); 13880 if (Action == AA_Passing_CFAudited) 13881 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13882 else 13883 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13884 13885 // If we can fix the conversion, suggest the FixIts. 13886 assert(ConvHints.isNull() || Hint.isNull()); 13887 if (!ConvHints.isNull()) { 13888 for (FixItHint &H : ConvHints.Hints) 13889 FDiag << H; 13890 } else { 13891 FDiag << Hint; 13892 } 13893 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13894 13895 if (MayHaveFunctionDiff) 13896 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13897 13898 Diag(Loc, FDiag); 13899 if (DiagKind == diag::warn_incompatible_qualified_id && 13900 PDecl && IFace && !IFace->hasDefinition()) 13901 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13902 << IFace << PDecl; 13903 13904 if (SecondType == Context.OverloadTy) 13905 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13906 FirstType, /*TakingAddress=*/true); 13907 13908 if (CheckInferredResultType) 13909 EmitRelatedResultTypeNote(SrcExpr); 13910 13911 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13912 EmitRelatedResultTypeNoteForReturn(DstType); 13913 13914 if (Complained) 13915 *Complained = true; 13916 return isInvalid; 13917 } 13918 13919 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13920 llvm::APSInt *Result) { 13921 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13922 public: 13923 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13924 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13925 } 13926 } Diagnoser; 13927 13928 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13929 } 13930 13931 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13932 llvm::APSInt *Result, 13933 unsigned DiagID, 13934 bool AllowFold) { 13935 class IDDiagnoser : public VerifyICEDiagnoser { 13936 unsigned DiagID; 13937 13938 public: 13939 IDDiagnoser(unsigned DiagID) 13940 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13941 13942 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13943 S.Diag(Loc, DiagID) << SR; 13944 } 13945 } Diagnoser(DiagID); 13946 13947 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13948 } 13949 13950 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13951 SourceRange SR) { 13952 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13953 } 13954 13955 ExprResult 13956 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13957 VerifyICEDiagnoser &Diagnoser, 13958 bool AllowFold) { 13959 SourceLocation DiagLoc = E->getBeginLoc(); 13960 13961 if (getLangOpts().CPlusPlus11) { 13962 // C++11 [expr.const]p5: 13963 // If an expression of literal class type is used in a context where an 13964 // integral constant expression is required, then that class type shall 13965 // have a single non-explicit conversion function to an integral or 13966 // unscoped enumeration type 13967 ExprResult Converted; 13968 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13969 public: 13970 CXX11ConvertDiagnoser(bool Silent) 13971 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13972 Silent, true) {} 13973 13974 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13975 QualType T) override { 13976 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13977 } 13978 13979 SemaDiagnosticBuilder diagnoseIncomplete( 13980 Sema &S, SourceLocation Loc, QualType T) override { 13981 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13982 } 13983 13984 SemaDiagnosticBuilder diagnoseExplicitConv( 13985 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13986 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13987 } 13988 13989 SemaDiagnosticBuilder noteExplicitConv( 13990 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13991 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13992 << ConvTy->isEnumeralType() << ConvTy; 13993 } 13994 13995 SemaDiagnosticBuilder diagnoseAmbiguous( 13996 Sema &S, SourceLocation Loc, QualType T) override { 13997 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13998 } 13999 14000 SemaDiagnosticBuilder noteAmbiguous( 14001 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14002 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14003 << ConvTy->isEnumeralType() << ConvTy; 14004 } 14005 14006 SemaDiagnosticBuilder diagnoseConversion( 14007 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14008 llvm_unreachable("conversion functions are permitted"); 14009 } 14010 } ConvertDiagnoser(Diagnoser.Suppress); 14011 14012 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14013 ConvertDiagnoser); 14014 if (Converted.isInvalid()) 14015 return Converted; 14016 E = Converted.get(); 14017 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14018 return ExprError(); 14019 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14020 // An ICE must be of integral or unscoped enumeration type. 14021 if (!Diagnoser.Suppress) 14022 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14023 return ExprError(); 14024 } 14025 14026 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14027 // in the non-ICE case. 14028 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14029 if (Result) 14030 *Result = E->EvaluateKnownConstInt(Context); 14031 return E; 14032 } 14033 14034 Expr::EvalResult EvalResult; 14035 SmallVector<PartialDiagnosticAt, 8> Notes; 14036 EvalResult.Diag = &Notes; 14037 14038 // Try to evaluate the expression, and produce diagnostics explaining why it's 14039 // not a constant expression as a side-effect. 14040 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14041 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14042 14043 // In C++11, we can rely on diagnostics being produced for any expression 14044 // which is not a constant expression. If no diagnostics were produced, then 14045 // this is a constant expression. 14046 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14047 if (Result) 14048 *Result = EvalResult.Val.getInt(); 14049 return E; 14050 } 14051 14052 // If our only note is the usual "invalid subexpression" note, just point 14053 // the caret at its location rather than producing an essentially 14054 // redundant note. 14055 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14056 diag::note_invalid_subexpr_in_const_expr) { 14057 DiagLoc = Notes[0].first; 14058 Notes.clear(); 14059 } 14060 14061 if (!Folded || !AllowFold) { 14062 if (!Diagnoser.Suppress) { 14063 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14064 for (const PartialDiagnosticAt &Note : Notes) 14065 Diag(Note.first, Note.second); 14066 } 14067 14068 return ExprError(); 14069 } 14070 14071 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14072 for (const PartialDiagnosticAt &Note : Notes) 14073 Diag(Note.first, Note.second); 14074 14075 if (Result) 14076 *Result = EvalResult.Val.getInt(); 14077 return E; 14078 } 14079 14080 namespace { 14081 // Handle the case where we conclude a expression which we speculatively 14082 // considered to be unevaluated is actually evaluated. 14083 class TransformToPE : public TreeTransform<TransformToPE> { 14084 typedef TreeTransform<TransformToPE> BaseTransform; 14085 14086 public: 14087 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14088 14089 // Make sure we redo semantic analysis 14090 bool AlwaysRebuild() { return true; } 14091 14092 // Make sure we handle LabelStmts correctly. 14093 // FIXME: This does the right thing, but maybe we need a more general 14094 // fix to TreeTransform? 14095 StmtResult TransformLabelStmt(LabelStmt *S) { 14096 S->getDecl()->setStmt(nullptr); 14097 return BaseTransform::TransformLabelStmt(S); 14098 } 14099 14100 // We need to special-case DeclRefExprs referring to FieldDecls which 14101 // are not part of a member pointer formation; normal TreeTransforming 14102 // doesn't catch this case because of the way we represent them in the AST. 14103 // FIXME: This is a bit ugly; is it really the best way to handle this 14104 // case? 14105 // 14106 // Error on DeclRefExprs referring to FieldDecls. 14107 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14108 if (isa<FieldDecl>(E->getDecl()) && 14109 !SemaRef.isUnevaluatedContext()) 14110 return SemaRef.Diag(E->getLocation(), 14111 diag::err_invalid_non_static_member_use) 14112 << E->getDecl() << E->getSourceRange(); 14113 14114 return BaseTransform::TransformDeclRefExpr(E); 14115 } 14116 14117 // Exception: filter out member pointer formation 14118 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14119 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14120 return E; 14121 14122 return BaseTransform::TransformUnaryOperator(E); 14123 } 14124 14125 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14126 // Lambdas never need to be transformed. 14127 return E; 14128 } 14129 }; 14130 } 14131 14132 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14133 assert(isUnevaluatedContext() && 14134 "Should only transform unevaluated expressions"); 14135 ExprEvalContexts.back().Context = 14136 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14137 if (isUnevaluatedContext()) 14138 return E; 14139 return TransformToPE(*this).TransformExpr(E); 14140 } 14141 14142 void 14143 Sema::PushExpressionEvaluationContext( 14144 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14145 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14146 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14147 LambdaContextDecl, ExprContext); 14148 Cleanup.reset(); 14149 if (!MaybeODRUseExprs.empty()) 14150 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14151 } 14152 14153 void 14154 Sema::PushExpressionEvaluationContext( 14155 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14156 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14157 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14158 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14159 } 14160 14161 void Sema::PopExpressionEvaluationContext() { 14162 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14163 unsigned NumTypos = Rec.NumTypos; 14164 14165 if (!Rec.Lambdas.empty()) { 14166 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14167 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14168 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14169 unsigned D; 14170 if (Rec.isUnevaluated()) { 14171 // C++11 [expr.prim.lambda]p2: 14172 // A lambda-expression shall not appear in an unevaluated operand 14173 // (Clause 5). 14174 D = diag::err_lambda_unevaluated_operand; 14175 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14176 // C++1y [expr.const]p2: 14177 // A conditional-expression e is a core constant expression unless the 14178 // evaluation of e, following the rules of the abstract machine, would 14179 // evaluate [...] a lambda-expression. 14180 D = diag::err_lambda_in_constant_expression; 14181 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14182 // C++17 [expr.prim.lamda]p2: 14183 // A lambda-expression shall not appear [...] in a template-argument. 14184 D = diag::err_lambda_in_invalid_context; 14185 } else 14186 llvm_unreachable("Couldn't infer lambda error message."); 14187 14188 for (const auto *L : Rec.Lambdas) 14189 Diag(L->getBeginLoc(), D); 14190 } else { 14191 // Mark the capture expressions odr-used. This was deferred 14192 // during lambda expression creation. 14193 for (auto *Lambda : Rec.Lambdas) { 14194 for (auto *C : Lambda->capture_inits()) 14195 MarkDeclarationsReferencedInExpr(C); 14196 } 14197 } 14198 } 14199 14200 // When are coming out of an unevaluated context, clear out any 14201 // temporaries that we may have created as part of the evaluation of 14202 // the expression in that context: they aren't relevant because they 14203 // will never be constructed. 14204 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14205 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14206 ExprCleanupObjects.end()); 14207 Cleanup = Rec.ParentCleanup; 14208 CleanupVarDeclMarking(); 14209 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14210 // Otherwise, merge the contexts together. 14211 } else { 14212 Cleanup.mergeFrom(Rec.ParentCleanup); 14213 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14214 Rec.SavedMaybeODRUseExprs.end()); 14215 } 14216 14217 // Pop the current expression evaluation context off the stack. 14218 ExprEvalContexts.pop_back(); 14219 14220 if (!ExprEvalContexts.empty()) 14221 ExprEvalContexts.back().NumTypos += NumTypos; 14222 else 14223 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14224 "last ExpressionEvaluationContextRecord"); 14225 } 14226 14227 void Sema::DiscardCleanupsInEvaluationContext() { 14228 ExprCleanupObjects.erase( 14229 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14230 ExprCleanupObjects.end()); 14231 Cleanup.reset(); 14232 MaybeODRUseExprs.clear(); 14233 } 14234 14235 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14236 if (!E->getType()->isVariablyModifiedType()) 14237 return E; 14238 return TransformToPotentiallyEvaluated(E); 14239 } 14240 14241 /// Are we within a context in which some evaluation could be performed (be it 14242 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14243 /// captured by C++'s idea of an "unevaluated context". 14244 static bool isEvaluatableContext(Sema &SemaRef) { 14245 switch (SemaRef.ExprEvalContexts.back().Context) { 14246 case Sema::ExpressionEvaluationContext::Unevaluated: 14247 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14248 // Expressions in this context are never evaluated. 14249 return false; 14250 14251 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14252 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14253 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14254 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14255 // Expressions in this context could be evaluated. 14256 return true; 14257 14258 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14259 // Referenced declarations will only be used if the construct in the 14260 // containing expression is used, at which point we'll be given another 14261 // turn to mark them. 14262 return false; 14263 } 14264 llvm_unreachable("Invalid context"); 14265 } 14266 14267 /// Are we within a context in which references to resolved functions or to 14268 /// variables result in odr-use? 14269 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14270 // An expression in a template is not really an expression until it's been 14271 // instantiated, so it doesn't trigger odr-use. 14272 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14273 return false; 14274 14275 switch (SemaRef.ExprEvalContexts.back().Context) { 14276 case Sema::ExpressionEvaluationContext::Unevaluated: 14277 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14278 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14279 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14280 return false; 14281 14282 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14283 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14284 return true; 14285 14286 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14287 return false; 14288 } 14289 llvm_unreachable("Invalid context"); 14290 } 14291 14292 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14293 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14294 return Func->isConstexpr() && 14295 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14296 } 14297 14298 /// Mark a function referenced, and check whether it is odr-used 14299 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14300 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14301 bool MightBeOdrUse) { 14302 assert(Func && "No function?"); 14303 14304 Func->setReferenced(); 14305 14306 // C++11 [basic.def.odr]p3: 14307 // A function whose name appears as a potentially-evaluated expression is 14308 // odr-used if it is the unique lookup result or the selected member of a 14309 // set of overloaded functions [...]. 14310 // 14311 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14312 // can just check that here. 14313 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14314 14315 // Determine whether we require a function definition to exist, per 14316 // C++11 [temp.inst]p3: 14317 // Unless a function template specialization has been explicitly 14318 // instantiated or explicitly specialized, the function template 14319 // specialization is implicitly instantiated when the specialization is 14320 // referenced in a context that requires a function definition to exist. 14321 // 14322 // That is either when this is an odr-use, or when a usage of a constexpr 14323 // function occurs within an evaluatable context. 14324 bool NeedDefinition = 14325 OdrUse || (isEvaluatableContext(*this) && 14326 isImplicitlyDefinableConstexprFunction(Func)); 14327 14328 // C++14 [temp.expl.spec]p6: 14329 // If a template [...] is explicitly specialized then that specialization 14330 // shall be declared before the first use of that specialization that would 14331 // cause an implicit instantiation to take place, in every translation unit 14332 // in which such a use occurs 14333 if (NeedDefinition && 14334 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14335 Func->getMemberSpecializationInfo())) 14336 checkSpecializationVisibility(Loc, Func); 14337 14338 // C++14 [except.spec]p17: 14339 // An exception-specification is considered to be needed when: 14340 // - the function is odr-used or, if it appears in an unevaluated operand, 14341 // would be odr-used if the expression were potentially-evaluated; 14342 // 14343 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14344 // function is a pure virtual function we're calling, and in that case the 14345 // function was selected by overload resolution and we need to resolve its 14346 // exception specification for a different reason. 14347 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14348 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14349 ResolveExceptionSpec(Loc, FPT); 14350 14351 // If we don't need to mark the function as used, and we don't need to 14352 // try to provide a definition, there's nothing more to do. 14353 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14354 (!NeedDefinition || Func->getBody())) 14355 return; 14356 14357 // Note that this declaration has been used. 14358 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14359 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14360 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14361 if (Constructor->isDefaultConstructor()) { 14362 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14363 return; 14364 DefineImplicitDefaultConstructor(Loc, Constructor); 14365 } else if (Constructor->isCopyConstructor()) { 14366 DefineImplicitCopyConstructor(Loc, Constructor); 14367 } else if (Constructor->isMoveConstructor()) { 14368 DefineImplicitMoveConstructor(Loc, Constructor); 14369 } 14370 } else if (Constructor->getInheritedConstructor()) { 14371 DefineInheritingConstructor(Loc, Constructor); 14372 } 14373 } else if (CXXDestructorDecl *Destructor = 14374 dyn_cast<CXXDestructorDecl>(Func)) { 14375 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14376 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14377 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14378 return; 14379 DefineImplicitDestructor(Loc, Destructor); 14380 } 14381 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14382 MarkVTableUsed(Loc, Destructor->getParent()); 14383 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14384 if (MethodDecl->isOverloadedOperator() && 14385 MethodDecl->getOverloadedOperator() == OO_Equal) { 14386 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14387 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14388 if (MethodDecl->isCopyAssignmentOperator()) 14389 DefineImplicitCopyAssignment(Loc, MethodDecl); 14390 else if (MethodDecl->isMoveAssignmentOperator()) 14391 DefineImplicitMoveAssignment(Loc, MethodDecl); 14392 } 14393 } else if (isa<CXXConversionDecl>(MethodDecl) && 14394 MethodDecl->getParent()->isLambda()) { 14395 CXXConversionDecl *Conversion = 14396 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14397 if (Conversion->isLambdaToBlockPointerConversion()) 14398 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14399 else 14400 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14401 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14402 MarkVTableUsed(Loc, MethodDecl->getParent()); 14403 } 14404 14405 // Recursive functions should be marked when used from another function. 14406 // FIXME: Is this really right? 14407 if (CurContext == Func) return; 14408 14409 // Implicit instantiation of function templates and member functions of 14410 // class templates. 14411 if (Func->isImplicitlyInstantiable()) { 14412 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14413 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14414 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14415 if (FirstInstantiation) { 14416 PointOfInstantiation = Loc; 14417 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14418 } else if (TSK != TSK_ImplicitInstantiation) { 14419 // Use the point of use as the point of instantiation, instead of the 14420 // point of explicit instantiation (which we track as the actual point of 14421 // instantiation). This gives better backtraces in diagnostics. 14422 PointOfInstantiation = Loc; 14423 } 14424 14425 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14426 Func->isConstexpr()) { 14427 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14428 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14429 CodeSynthesisContexts.size()) 14430 PendingLocalImplicitInstantiations.push_back( 14431 std::make_pair(Func, PointOfInstantiation)); 14432 else if (Func->isConstexpr()) 14433 // Do not defer instantiations of constexpr functions, to avoid the 14434 // expression evaluator needing to call back into Sema if it sees a 14435 // call to such a function. 14436 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14437 else { 14438 Func->setInstantiationIsPending(true); 14439 PendingInstantiations.push_back(std::make_pair(Func, 14440 PointOfInstantiation)); 14441 // Notify the consumer that a function was implicitly instantiated. 14442 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14443 } 14444 } 14445 } else { 14446 // Walk redefinitions, as some of them may be instantiable. 14447 for (auto i : Func->redecls()) { 14448 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14449 MarkFunctionReferenced(Loc, i, OdrUse); 14450 } 14451 } 14452 14453 if (!OdrUse) return; 14454 14455 // Keep track of used but undefined functions. 14456 if (!Func->isDefined()) { 14457 if (mightHaveNonExternalLinkage(Func)) 14458 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14459 else if (Func->getMostRecentDecl()->isInlined() && 14460 !LangOpts.GNUInline && 14461 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14462 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14463 else if (isExternalWithNoLinkageType(Func)) 14464 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14465 } 14466 14467 Func->markUsed(Context); 14468 } 14469 14470 static void 14471 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14472 ValueDecl *var, DeclContext *DC) { 14473 DeclContext *VarDC = var->getDeclContext(); 14474 14475 // If the parameter still belongs to the translation unit, then 14476 // we're actually just using one parameter in the declaration of 14477 // the next. 14478 if (isa<ParmVarDecl>(var) && 14479 isa<TranslationUnitDecl>(VarDC)) 14480 return; 14481 14482 // For C code, don't diagnose about capture if we're not actually in code 14483 // right now; it's impossible to write a non-constant expression outside of 14484 // function context, so we'll get other (more useful) diagnostics later. 14485 // 14486 // For C++, things get a bit more nasty... it would be nice to suppress this 14487 // diagnostic for certain cases like using a local variable in an array bound 14488 // for a member of a local class, but the correct predicate is not obvious. 14489 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14490 return; 14491 14492 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14493 unsigned ContextKind = 3; // unknown 14494 if (isa<CXXMethodDecl>(VarDC) && 14495 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14496 ContextKind = 2; 14497 } else if (isa<FunctionDecl>(VarDC)) { 14498 ContextKind = 0; 14499 } else if (isa<BlockDecl>(VarDC)) { 14500 ContextKind = 1; 14501 } 14502 14503 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14504 << var << ValueKind << ContextKind << VarDC; 14505 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14506 << var; 14507 14508 // FIXME: Add additional diagnostic info about class etc. which prevents 14509 // capture. 14510 } 14511 14512 14513 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14514 bool &SubCapturesAreNested, 14515 QualType &CaptureType, 14516 QualType &DeclRefType) { 14517 // Check whether we've already captured it. 14518 if (CSI->CaptureMap.count(Var)) { 14519 // If we found a capture, any subcaptures are nested. 14520 SubCapturesAreNested = true; 14521 14522 // Retrieve the capture type for this variable. 14523 CaptureType = CSI->getCapture(Var).getCaptureType(); 14524 14525 // Compute the type of an expression that refers to this variable. 14526 DeclRefType = CaptureType.getNonReferenceType(); 14527 14528 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14529 // are mutable in the sense that user can change their value - they are 14530 // private instances of the captured declarations. 14531 const Capture &Cap = CSI->getCapture(Var); 14532 if (Cap.isCopyCapture() && 14533 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14534 !(isa<CapturedRegionScopeInfo>(CSI) && 14535 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14536 DeclRefType.addConst(); 14537 return true; 14538 } 14539 return false; 14540 } 14541 14542 // Only block literals, captured statements, and lambda expressions can 14543 // capture; other scopes don't work. 14544 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14545 SourceLocation Loc, 14546 const bool Diagnose, Sema &S) { 14547 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14548 return getLambdaAwareParentOfDeclContext(DC); 14549 else if (Var->hasLocalStorage()) { 14550 if (Diagnose) 14551 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14552 } 14553 return nullptr; 14554 } 14555 14556 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14557 // certain types of variables (unnamed, variably modified types etc.) 14558 // so check for eligibility. 14559 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14560 SourceLocation Loc, 14561 const bool Diagnose, Sema &S) { 14562 14563 bool IsBlock = isa<BlockScopeInfo>(CSI); 14564 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14565 14566 // Lambdas are not allowed to capture unnamed variables 14567 // (e.g. anonymous unions). 14568 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14569 // assuming that's the intent. 14570 if (IsLambda && !Var->getDeclName()) { 14571 if (Diagnose) { 14572 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14573 S.Diag(Var->getLocation(), diag::note_declared_at); 14574 } 14575 return false; 14576 } 14577 14578 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14579 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14580 if (Diagnose) { 14581 S.Diag(Loc, diag::err_ref_vm_type); 14582 S.Diag(Var->getLocation(), diag::note_previous_decl) 14583 << Var->getDeclName(); 14584 } 14585 return false; 14586 } 14587 // Prohibit structs with flexible array members too. 14588 // We cannot capture what is in the tail end of the struct. 14589 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14590 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14591 if (Diagnose) { 14592 if (IsBlock) 14593 S.Diag(Loc, diag::err_ref_flexarray_type); 14594 else 14595 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14596 << Var->getDeclName(); 14597 S.Diag(Var->getLocation(), diag::note_previous_decl) 14598 << Var->getDeclName(); 14599 } 14600 return false; 14601 } 14602 } 14603 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14604 // Lambdas and captured statements are not allowed to capture __block 14605 // variables; they don't support the expected semantics. 14606 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14607 if (Diagnose) { 14608 S.Diag(Loc, diag::err_capture_block_variable) 14609 << Var->getDeclName() << !IsLambda; 14610 S.Diag(Var->getLocation(), diag::note_previous_decl) 14611 << Var->getDeclName(); 14612 } 14613 return false; 14614 } 14615 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14616 if (S.getLangOpts().OpenCL && IsBlock && 14617 Var->getType()->isBlockPointerType()) { 14618 if (Diagnose) 14619 S.Diag(Loc, diag::err_opencl_block_ref_block); 14620 return false; 14621 } 14622 14623 return true; 14624 } 14625 14626 // Returns true if the capture by block was successful. 14627 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14628 SourceLocation Loc, 14629 const bool BuildAndDiagnose, 14630 QualType &CaptureType, 14631 QualType &DeclRefType, 14632 const bool Nested, 14633 Sema &S) { 14634 Expr *CopyExpr = nullptr; 14635 bool ByRef = false; 14636 14637 // Blocks are not allowed to capture arrays. 14638 if (CaptureType->isArrayType()) { 14639 if (BuildAndDiagnose) { 14640 S.Diag(Loc, diag::err_ref_array_type); 14641 S.Diag(Var->getLocation(), diag::note_previous_decl) 14642 << Var->getDeclName(); 14643 } 14644 return false; 14645 } 14646 14647 // Forbid the block-capture of autoreleasing variables. 14648 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14649 if (BuildAndDiagnose) { 14650 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14651 << /*block*/ 0; 14652 S.Diag(Var->getLocation(), diag::note_previous_decl) 14653 << Var->getDeclName(); 14654 } 14655 return false; 14656 } 14657 14658 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14659 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14660 // This function finds out whether there is an AttributedType of kind 14661 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14662 // attr_objc_ownership implies __autoreleasing was explicitly specified 14663 // rather than being added implicitly by the compiler. 14664 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14665 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14666 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14667 return true; 14668 14669 // Peel off AttributedTypes that are not of kind objc_ownership. 14670 Ty = AttrTy->getModifiedType(); 14671 } 14672 14673 return false; 14674 }; 14675 14676 QualType PointeeTy = PT->getPointeeType(); 14677 14678 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14679 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14680 !IsObjCOwnershipAttributedType(PointeeTy)) { 14681 if (BuildAndDiagnose) { 14682 SourceLocation VarLoc = Var->getLocation(); 14683 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14684 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14685 } 14686 } 14687 } 14688 14689 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14690 if (HasBlocksAttr || CaptureType->isReferenceType() || 14691 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14692 // Block capture by reference does not change the capture or 14693 // declaration reference types. 14694 ByRef = true; 14695 } else { 14696 // Block capture by copy introduces 'const'. 14697 CaptureType = CaptureType.getNonReferenceType().withConst(); 14698 DeclRefType = CaptureType; 14699 14700 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14701 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14702 // The capture logic needs the destructor, so make sure we mark it. 14703 // Usually this is unnecessary because most local variables have 14704 // their destructors marked at declaration time, but parameters are 14705 // an exception because it's technically only the call site that 14706 // actually requires the destructor. 14707 if (isa<ParmVarDecl>(Var)) 14708 S.FinalizeVarWithDestructor(Var, Record); 14709 14710 // Enter a new evaluation context to insulate the copy 14711 // full-expression. 14712 EnterExpressionEvaluationContext scope( 14713 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14714 14715 // According to the blocks spec, the capture of a variable from 14716 // the stack requires a const copy constructor. This is not true 14717 // of the copy/move done to move a __block variable to the heap. 14718 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14719 DeclRefType.withConst(), 14720 VK_LValue, Loc); 14721 14722 ExprResult Result 14723 = S.PerformCopyInitialization( 14724 InitializedEntity::InitializeBlock(Var->getLocation(), 14725 CaptureType, false), 14726 Loc, DeclRef); 14727 14728 // Build a full-expression copy expression if initialization 14729 // succeeded and used a non-trivial constructor. Recover from 14730 // errors by pretending that the copy isn't necessary. 14731 if (!Result.isInvalid() && 14732 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14733 ->isTrivial()) { 14734 Result = S.MaybeCreateExprWithCleanups(Result); 14735 CopyExpr = Result.get(); 14736 } 14737 } 14738 } 14739 } 14740 14741 // Actually capture the variable. 14742 if (BuildAndDiagnose) 14743 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14744 SourceLocation(), CaptureType, CopyExpr); 14745 14746 return true; 14747 14748 } 14749 14750 14751 /// Capture the given variable in the captured region. 14752 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14753 VarDecl *Var, 14754 SourceLocation Loc, 14755 const bool BuildAndDiagnose, 14756 QualType &CaptureType, 14757 QualType &DeclRefType, 14758 const bool RefersToCapturedVariable, 14759 Sema &S) { 14760 // By default, capture variables by reference. 14761 bool ByRef = true; 14762 // Using an LValue reference type is consistent with Lambdas (see below). 14763 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14764 if (S.isOpenMPCapturedDecl(Var)) { 14765 bool HasConst = DeclRefType.isConstQualified(); 14766 DeclRefType = DeclRefType.getUnqualifiedType(); 14767 // Don't lose diagnostics about assignments to const. 14768 if (HasConst) 14769 DeclRefType.addConst(); 14770 } 14771 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14772 } 14773 14774 if (ByRef) 14775 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14776 else 14777 CaptureType = DeclRefType; 14778 14779 Expr *CopyExpr = nullptr; 14780 if (BuildAndDiagnose) { 14781 // The current implementation assumes that all variables are captured 14782 // by references. Since there is no capture by copy, no expression 14783 // evaluation will be needed. 14784 RecordDecl *RD = RSI->TheRecordDecl; 14785 14786 FieldDecl *Field 14787 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14788 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14789 nullptr, false, ICIS_NoInit); 14790 Field->setImplicit(true); 14791 Field->setAccess(AS_private); 14792 RD->addDecl(Field); 14793 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14794 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14795 14796 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14797 DeclRefType, VK_LValue, Loc); 14798 Var->setReferenced(true); 14799 Var->markUsed(S.Context); 14800 } 14801 14802 // Actually capture the variable. 14803 if (BuildAndDiagnose) 14804 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14805 SourceLocation(), CaptureType, CopyExpr); 14806 14807 14808 return true; 14809 } 14810 14811 /// Create a field within the lambda class for the variable 14812 /// being captured. 14813 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14814 QualType FieldType, QualType DeclRefType, 14815 SourceLocation Loc, 14816 bool RefersToCapturedVariable) { 14817 CXXRecordDecl *Lambda = LSI->Lambda; 14818 14819 // Build the non-static data member. 14820 FieldDecl *Field 14821 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14822 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14823 nullptr, false, ICIS_NoInit); 14824 Field->setImplicit(true); 14825 Field->setAccess(AS_private); 14826 Lambda->addDecl(Field); 14827 } 14828 14829 /// Capture the given variable in the lambda. 14830 static bool captureInLambda(LambdaScopeInfo *LSI, 14831 VarDecl *Var, 14832 SourceLocation Loc, 14833 const bool BuildAndDiagnose, 14834 QualType &CaptureType, 14835 QualType &DeclRefType, 14836 const bool RefersToCapturedVariable, 14837 const Sema::TryCaptureKind Kind, 14838 SourceLocation EllipsisLoc, 14839 const bool IsTopScope, 14840 Sema &S) { 14841 14842 // Determine whether we are capturing by reference or by value. 14843 bool ByRef = false; 14844 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14845 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14846 } else { 14847 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14848 } 14849 14850 // Compute the type of the field that will capture this variable. 14851 if (ByRef) { 14852 // C++11 [expr.prim.lambda]p15: 14853 // An entity is captured by reference if it is implicitly or 14854 // explicitly captured but not captured by copy. It is 14855 // unspecified whether additional unnamed non-static data 14856 // members are declared in the closure type for entities 14857 // captured by reference. 14858 // 14859 // FIXME: It is not clear whether we want to build an lvalue reference 14860 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14861 // to do the former, while EDG does the latter. Core issue 1249 will 14862 // clarify, but for now we follow GCC because it's a more permissive and 14863 // easily defensible position. 14864 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14865 } else { 14866 // C++11 [expr.prim.lambda]p14: 14867 // For each entity captured by copy, an unnamed non-static 14868 // data member is declared in the closure type. The 14869 // declaration order of these members is unspecified. The type 14870 // of such a data member is the type of the corresponding 14871 // captured entity if the entity is not a reference to an 14872 // object, or the referenced type otherwise. [Note: If the 14873 // captured entity is a reference to a function, the 14874 // corresponding data member is also a reference to a 14875 // function. - end note ] 14876 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14877 if (!RefType->getPointeeType()->isFunctionType()) 14878 CaptureType = RefType->getPointeeType(); 14879 } 14880 14881 // Forbid the lambda copy-capture of autoreleasing variables. 14882 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14883 if (BuildAndDiagnose) { 14884 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14885 S.Diag(Var->getLocation(), diag::note_previous_decl) 14886 << Var->getDeclName(); 14887 } 14888 return false; 14889 } 14890 14891 // Make sure that by-copy captures are of a complete and non-abstract type. 14892 if (BuildAndDiagnose) { 14893 if (!CaptureType->isDependentType() && 14894 S.RequireCompleteType(Loc, CaptureType, 14895 diag::err_capture_of_incomplete_type, 14896 Var->getDeclName())) 14897 return false; 14898 14899 if (S.RequireNonAbstractType(Loc, CaptureType, 14900 diag::err_capture_of_abstract_type)) 14901 return false; 14902 } 14903 } 14904 14905 // Capture this variable in the lambda. 14906 if (BuildAndDiagnose) 14907 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14908 RefersToCapturedVariable); 14909 14910 // Compute the type of a reference to this captured variable. 14911 if (ByRef) 14912 DeclRefType = CaptureType.getNonReferenceType(); 14913 else { 14914 // C++ [expr.prim.lambda]p5: 14915 // The closure type for a lambda-expression has a public inline 14916 // function call operator [...]. This function call operator is 14917 // declared const (9.3.1) if and only if the lambda-expression's 14918 // parameter-declaration-clause is not followed by mutable. 14919 DeclRefType = CaptureType.getNonReferenceType(); 14920 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14921 DeclRefType.addConst(); 14922 } 14923 14924 // Add the capture. 14925 if (BuildAndDiagnose) 14926 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14927 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14928 14929 return true; 14930 } 14931 14932 bool Sema::tryCaptureVariable( 14933 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14934 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14935 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14936 // An init-capture is notionally from the context surrounding its 14937 // declaration, but its parent DC is the lambda class. 14938 DeclContext *VarDC = Var->getDeclContext(); 14939 if (Var->isInitCapture()) 14940 VarDC = VarDC->getParent(); 14941 14942 DeclContext *DC = CurContext; 14943 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14944 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14945 // We need to sync up the Declaration Context with the 14946 // FunctionScopeIndexToStopAt 14947 if (FunctionScopeIndexToStopAt) { 14948 unsigned FSIndex = FunctionScopes.size() - 1; 14949 while (FSIndex != MaxFunctionScopesIndex) { 14950 DC = getLambdaAwareParentOfDeclContext(DC); 14951 --FSIndex; 14952 } 14953 } 14954 14955 14956 // If the variable is declared in the current context, there is no need to 14957 // capture it. 14958 if (VarDC == DC) return true; 14959 14960 // Capture global variables if it is required to use private copy of this 14961 // variable. 14962 bool IsGlobal = !Var->hasLocalStorage(); 14963 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 14964 return true; 14965 Var = Var->getCanonicalDecl(); 14966 14967 // Walk up the stack to determine whether we can capture the variable, 14968 // performing the "simple" checks that don't depend on type. We stop when 14969 // we've either hit the declared scope of the variable or find an existing 14970 // capture of that variable. We start from the innermost capturing-entity 14971 // (the DC) and ensure that all intervening capturing-entities 14972 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14973 // declcontext can either capture the variable or have already captured 14974 // the variable. 14975 CaptureType = Var->getType(); 14976 DeclRefType = CaptureType.getNonReferenceType(); 14977 bool Nested = false; 14978 bool Explicit = (Kind != TryCapture_Implicit); 14979 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14980 do { 14981 // Only block literals, captured statements, and lambda expressions can 14982 // capture; other scopes don't work. 14983 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14984 ExprLoc, 14985 BuildAndDiagnose, 14986 *this); 14987 // We need to check for the parent *first* because, if we *have* 14988 // private-captured a global variable, we need to recursively capture it in 14989 // intermediate blocks, lambdas, etc. 14990 if (!ParentDC) { 14991 if (IsGlobal) { 14992 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14993 break; 14994 } 14995 return true; 14996 } 14997 14998 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14999 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15000 15001 15002 // Check whether we've already captured it. 15003 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15004 DeclRefType)) { 15005 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15006 break; 15007 } 15008 // If we are instantiating a generic lambda call operator body, 15009 // we do not want to capture new variables. What was captured 15010 // during either a lambdas transformation or initial parsing 15011 // should be used. 15012 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15013 if (BuildAndDiagnose) { 15014 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15015 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15016 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15017 Diag(Var->getLocation(), diag::note_previous_decl) 15018 << Var->getDeclName(); 15019 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15020 } else 15021 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15022 } 15023 return true; 15024 } 15025 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15026 // certain types of variables (unnamed, variably modified types etc.) 15027 // so check for eligibility. 15028 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15029 return true; 15030 15031 // Try to capture variable-length arrays types. 15032 if (Var->getType()->isVariablyModifiedType()) { 15033 // We're going to walk down into the type and look for VLA 15034 // expressions. 15035 QualType QTy = Var->getType(); 15036 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15037 QTy = PVD->getOriginalType(); 15038 captureVariablyModifiedType(Context, QTy, CSI); 15039 } 15040 15041 if (getLangOpts().OpenMP) { 15042 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15043 // OpenMP private variables should not be captured in outer scope, so 15044 // just break here. Similarly, global variables that are captured in a 15045 // target region should not be captured outside the scope of the region. 15046 if (RSI->CapRegionKind == CR_OpenMP) { 15047 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15048 auto IsTargetCap = !IsOpenMPPrivateDecl && 15049 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15050 // When we detect target captures we are looking from inside the 15051 // target region, therefore we need to propagate the capture from the 15052 // enclosing region. Therefore, the capture is not initially nested. 15053 if (IsTargetCap) 15054 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15055 15056 if (IsTargetCap || IsOpenMPPrivateDecl) { 15057 Nested = !IsTargetCap; 15058 DeclRefType = DeclRefType.getUnqualifiedType(); 15059 CaptureType = Context.getLValueReferenceType(DeclRefType); 15060 break; 15061 } 15062 } 15063 } 15064 } 15065 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15066 // No capture-default, and this is not an explicit capture 15067 // so cannot capture this variable. 15068 if (BuildAndDiagnose) { 15069 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15070 Diag(Var->getLocation(), diag::note_previous_decl) 15071 << Var->getDeclName(); 15072 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15073 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15074 diag::note_lambda_decl); 15075 // FIXME: If we error out because an outer lambda can not implicitly 15076 // capture a variable that an inner lambda explicitly captures, we 15077 // should have the inner lambda do the explicit capture - because 15078 // it makes for cleaner diagnostics later. This would purely be done 15079 // so that the diagnostic does not misleadingly claim that a variable 15080 // can not be captured by a lambda implicitly even though it is captured 15081 // explicitly. Suggestion: 15082 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15083 // at the function head 15084 // - cache the StartingDeclContext - this must be a lambda 15085 // - captureInLambda in the innermost lambda the variable. 15086 } 15087 return true; 15088 } 15089 15090 FunctionScopesIndex--; 15091 DC = ParentDC; 15092 Explicit = false; 15093 } while (!VarDC->Equals(DC)); 15094 15095 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15096 // computing the type of the capture at each step, checking type-specific 15097 // requirements, and adding captures if requested. 15098 // If the variable had already been captured previously, we start capturing 15099 // at the lambda nested within that one. 15100 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15101 ++I) { 15102 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15103 15104 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15105 if (!captureInBlock(BSI, Var, ExprLoc, 15106 BuildAndDiagnose, CaptureType, 15107 DeclRefType, Nested, *this)) 15108 return true; 15109 Nested = true; 15110 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15111 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15112 BuildAndDiagnose, CaptureType, 15113 DeclRefType, Nested, *this)) 15114 return true; 15115 Nested = true; 15116 } else { 15117 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15118 if (!captureInLambda(LSI, Var, ExprLoc, 15119 BuildAndDiagnose, CaptureType, 15120 DeclRefType, Nested, Kind, EllipsisLoc, 15121 /*IsTopScope*/I == N - 1, *this)) 15122 return true; 15123 Nested = true; 15124 } 15125 } 15126 return false; 15127 } 15128 15129 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15130 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15131 QualType CaptureType; 15132 QualType DeclRefType; 15133 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15134 /*BuildAndDiagnose=*/true, CaptureType, 15135 DeclRefType, nullptr); 15136 } 15137 15138 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15139 QualType CaptureType; 15140 QualType DeclRefType; 15141 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15142 /*BuildAndDiagnose=*/false, CaptureType, 15143 DeclRefType, nullptr); 15144 } 15145 15146 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15147 QualType CaptureType; 15148 QualType DeclRefType; 15149 15150 // Determine whether we can capture this variable. 15151 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15152 /*BuildAndDiagnose=*/false, CaptureType, 15153 DeclRefType, nullptr)) 15154 return QualType(); 15155 15156 return DeclRefType; 15157 } 15158 15159 15160 15161 // If either the type of the variable or the initializer is dependent, 15162 // return false. Otherwise, determine whether the variable is a constant 15163 // expression. Use this if you need to know if a variable that might or 15164 // might not be dependent is truly a constant expression. 15165 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15166 ASTContext &Context) { 15167 15168 if (Var->getType()->isDependentType()) 15169 return false; 15170 const VarDecl *DefVD = nullptr; 15171 Var->getAnyInitializer(DefVD); 15172 if (!DefVD) 15173 return false; 15174 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15175 Expr *Init = cast<Expr>(Eval->Value); 15176 if (Init->isValueDependent()) 15177 return false; 15178 return IsVariableAConstantExpression(Var, Context); 15179 } 15180 15181 15182 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15183 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15184 // an object that satisfies the requirements for appearing in a 15185 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15186 // is immediately applied." This function handles the lvalue-to-rvalue 15187 // conversion part. 15188 MaybeODRUseExprs.erase(E->IgnoreParens()); 15189 15190 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15191 // to a variable that is a constant expression, and if so, identify it as 15192 // a reference to a variable that does not involve an odr-use of that 15193 // variable. 15194 if (LambdaScopeInfo *LSI = getCurLambda()) { 15195 Expr *SansParensExpr = E->IgnoreParens(); 15196 VarDecl *Var = nullptr; 15197 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15198 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15199 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15200 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15201 15202 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15203 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15204 } 15205 } 15206 15207 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15208 Res = CorrectDelayedTyposInExpr(Res); 15209 15210 if (!Res.isUsable()) 15211 return Res; 15212 15213 // If a constant-expression is a reference to a variable where we delay 15214 // deciding whether it is an odr-use, just assume we will apply the 15215 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15216 // (a non-type template argument), we have special handling anyway. 15217 UpdateMarkingForLValueToRValue(Res.get()); 15218 return Res; 15219 } 15220 15221 void Sema::CleanupVarDeclMarking() { 15222 for (Expr *E : MaybeODRUseExprs) { 15223 VarDecl *Var; 15224 SourceLocation Loc; 15225 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15226 Var = cast<VarDecl>(DRE->getDecl()); 15227 Loc = DRE->getLocation(); 15228 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15229 Var = cast<VarDecl>(ME->getMemberDecl()); 15230 Loc = ME->getMemberLoc(); 15231 } else { 15232 llvm_unreachable("Unexpected expression"); 15233 } 15234 15235 MarkVarDeclODRUsed(Var, Loc, *this, 15236 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15237 } 15238 15239 MaybeODRUseExprs.clear(); 15240 } 15241 15242 15243 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15244 VarDecl *Var, Expr *E) { 15245 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15246 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15247 Var->setReferenced(); 15248 15249 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15250 15251 bool OdrUseContext = isOdrUseContext(SemaRef); 15252 bool UsableInConstantExpr = 15253 Var->isUsableInConstantExpressions(SemaRef.Context); 15254 bool NeedDefinition = 15255 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15256 15257 VarTemplateSpecializationDecl *VarSpec = 15258 dyn_cast<VarTemplateSpecializationDecl>(Var); 15259 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15260 "Can't instantiate a partial template specialization."); 15261 15262 // If this might be a member specialization of a static data member, check 15263 // the specialization is visible. We already did the checks for variable 15264 // template specializations when we created them. 15265 if (NeedDefinition && TSK != TSK_Undeclared && 15266 !isa<VarTemplateSpecializationDecl>(Var)) 15267 SemaRef.checkSpecializationVisibility(Loc, Var); 15268 15269 // Perform implicit instantiation of static data members, static data member 15270 // templates of class templates, and variable template specializations. Delay 15271 // instantiations of variable templates, except for those that could be used 15272 // in a constant expression. 15273 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15274 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15275 // instantiation declaration if a variable is usable in a constant 15276 // expression (among other cases). 15277 bool TryInstantiating = 15278 TSK == TSK_ImplicitInstantiation || 15279 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15280 15281 if (TryInstantiating) { 15282 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15283 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15284 if (FirstInstantiation) { 15285 PointOfInstantiation = Loc; 15286 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15287 } 15288 15289 bool InstantiationDependent = false; 15290 bool IsNonDependent = 15291 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15292 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15293 : true; 15294 15295 // Do not instantiate specializations that are still type-dependent. 15296 if (IsNonDependent) { 15297 if (UsableInConstantExpr) { 15298 // Do not defer instantiations of variables that could be used in a 15299 // constant expression. 15300 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15301 } else if (FirstInstantiation || 15302 isa<VarTemplateSpecializationDecl>(Var)) { 15303 // FIXME: For a specialization of a variable template, we don't 15304 // distinguish between "declaration and type implicitly instantiated" 15305 // and "implicit instantiation of definition requested", so we have 15306 // no direct way to avoid enqueueing the pending instantiation 15307 // multiple times. 15308 SemaRef.PendingInstantiations 15309 .push_back(std::make_pair(Var, PointOfInstantiation)); 15310 } 15311 } 15312 } 15313 } 15314 15315 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15316 // the requirements for appearing in a constant expression (5.19) and, if 15317 // it is an object, the lvalue-to-rvalue conversion (4.1) 15318 // is immediately applied." We check the first part here, and 15319 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15320 // Note that we use the C++11 definition everywhere because nothing in 15321 // C++03 depends on whether we get the C++03 version correct. The second 15322 // part does not apply to references, since they are not objects. 15323 if (OdrUseContext && E && 15324 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15325 // A reference initialized by a constant expression can never be 15326 // odr-used, so simply ignore it. 15327 if (!Var->getType()->isReferenceType() || 15328 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15329 SemaRef.MaybeODRUseExprs.insert(E); 15330 } else if (OdrUseContext) { 15331 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15332 /*MaxFunctionScopeIndex ptr*/ nullptr); 15333 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15334 // If this is a dependent context, we don't need to mark variables as 15335 // odr-used, but we may still need to track them for lambda capture. 15336 // FIXME: Do we also need to do this inside dependent typeid expressions 15337 // (which are modeled as unevaluated at this point)? 15338 const bool RefersToEnclosingScope = 15339 (SemaRef.CurContext != Var->getDeclContext() && 15340 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15341 if (RefersToEnclosingScope) { 15342 LambdaScopeInfo *const LSI = 15343 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15344 if (LSI && (!LSI->CallOperator || 15345 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15346 // If a variable could potentially be odr-used, defer marking it so 15347 // until we finish analyzing the full expression for any 15348 // lvalue-to-rvalue 15349 // or discarded value conversions that would obviate odr-use. 15350 // Add it to the list of potential captures that will be analyzed 15351 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15352 // unless the variable is a reference that was initialized by a constant 15353 // expression (this will never need to be captured or odr-used). 15354 assert(E && "Capture variable should be used in an expression."); 15355 if (!Var->getType()->isReferenceType() || 15356 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15357 LSI->addPotentialCapture(E->IgnoreParens()); 15358 } 15359 } 15360 } 15361 } 15362 15363 /// Mark a variable referenced, and check whether it is odr-used 15364 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15365 /// used directly for normal expressions referring to VarDecl. 15366 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15367 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15368 } 15369 15370 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15371 Decl *D, Expr *E, bool MightBeOdrUse) { 15372 if (SemaRef.isInOpenMPDeclareTargetContext()) 15373 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15374 15375 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15376 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15377 return; 15378 } 15379 15380 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15381 15382 // If this is a call to a method via a cast, also mark the method in the 15383 // derived class used in case codegen can devirtualize the call. 15384 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15385 if (!ME) 15386 return; 15387 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15388 if (!MD) 15389 return; 15390 // Only attempt to devirtualize if this is truly a virtual call. 15391 bool IsVirtualCall = MD->isVirtual() && 15392 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15393 if (!IsVirtualCall) 15394 return; 15395 15396 // If it's possible to devirtualize the call, mark the called function 15397 // referenced. 15398 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15399 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15400 if (DM) 15401 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15402 } 15403 15404 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15405 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15406 // TODO: update this with DR# once a defect report is filed. 15407 // C++11 defect. The address of a pure member should not be an ODR use, even 15408 // if it's a qualified reference. 15409 bool OdrUse = true; 15410 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15411 if (Method->isVirtual() && 15412 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15413 OdrUse = false; 15414 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15415 } 15416 15417 /// Perform reference-marking and odr-use handling for a MemberExpr. 15418 void Sema::MarkMemberReferenced(MemberExpr *E) { 15419 // C++11 [basic.def.odr]p2: 15420 // A non-overloaded function whose name appears as a potentially-evaluated 15421 // expression or a member of a set of candidate functions, if selected by 15422 // overload resolution when referred to from a potentially-evaluated 15423 // expression, is odr-used, unless it is a pure virtual function and its 15424 // name is not explicitly qualified. 15425 bool MightBeOdrUse = true; 15426 if (E->performsVirtualDispatch(getLangOpts())) { 15427 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15428 if (Method->isPure()) 15429 MightBeOdrUse = false; 15430 } 15431 SourceLocation Loc = 15432 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15433 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15434 } 15435 15436 /// Perform marking for a reference to an arbitrary declaration. It 15437 /// marks the declaration referenced, and performs odr-use checking for 15438 /// functions and variables. This method should not be used when building a 15439 /// normal expression which refers to a variable. 15440 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15441 bool MightBeOdrUse) { 15442 if (MightBeOdrUse) { 15443 if (auto *VD = dyn_cast<VarDecl>(D)) { 15444 MarkVariableReferenced(Loc, VD); 15445 return; 15446 } 15447 } 15448 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15449 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15450 return; 15451 } 15452 D->setReferenced(); 15453 } 15454 15455 namespace { 15456 // Mark all of the declarations used by a type as referenced. 15457 // FIXME: Not fully implemented yet! We need to have a better understanding 15458 // of when we're entering a context we should not recurse into. 15459 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15460 // TreeTransforms rebuilding the type in a new context. Rather than 15461 // duplicating the TreeTransform logic, we should consider reusing it here. 15462 // Currently that causes problems when rebuilding LambdaExprs. 15463 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15464 Sema &S; 15465 SourceLocation Loc; 15466 15467 public: 15468 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15469 15470 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15471 15472 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15473 }; 15474 } 15475 15476 bool MarkReferencedDecls::TraverseTemplateArgument( 15477 const TemplateArgument &Arg) { 15478 { 15479 // A non-type template argument is a constant-evaluated context. 15480 EnterExpressionEvaluationContext Evaluated( 15481 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15482 if (Arg.getKind() == TemplateArgument::Declaration) { 15483 if (Decl *D = Arg.getAsDecl()) 15484 S.MarkAnyDeclReferenced(Loc, D, true); 15485 } else if (Arg.getKind() == TemplateArgument::Expression) { 15486 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15487 } 15488 } 15489 15490 return Inherited::TraverseTemplateArgument(Arg); 15491 } 15492 15493 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15494 MarkReferencedDecls Marker(*this, Loc); 15495 Marker.TraverseType(T); 15496 } 15497 15498 namespace { 15499 /// Helper class that marks all of the declarations referenced by 15500 /// potentially-evaluated subexpressions as "referenced". 15501 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15502 Sema &S; 15503 bool SkipLocalVariables; 15504 15505 public: 15506 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15507 15508 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15509 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15510 15511 void VisitDeclRefExpr(DeclRefExpr *E) { 15512 // If we were asked not to visit local variables, don't. 15513 if (SkipLocalVariables) { 15514 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15515 if (VD->hasLocalStorage()) 15516 return; 15517 } 15518 15519 S.MarkDeclRefReferenced(E); 15520 } 15521 15522 void VisitMemberExpr(MemberExpr *E) { 15523 S.MarkMemberReferenced(E); 15524 Inherited::VisitMemberExpr(E); 15525 } 15526 15527 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15528 S.MarkFunctionReferenced( 15529 E->getBeginLoc(), 15530 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15531 Visit(E->getSubExpr()); 15532 } 15533 15534 void VisitCXXNewExpr(CXXNewExpr *E) { 15535 if (E->getOperatorNew()) 15536 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15537 if (E->getOperatorDelete()) 15538 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15539 Inherited::VisitCXXNewExpr(E); 15540 } 15541 15542 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15543 if (E->getOperatorDelete()) 15544 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15545 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15546 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15547 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15548 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15549 } 15550 15551 Inherited::VisitCXXDeleteExpr(E); 15552 } 15553 15554 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15555 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15556 Inherited::VisitCXXConstructExpr(E); 15557 } 15558 15559 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15560 Visit(E->getExpr()); 15561 } 15562 15563 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15564 Inherited::VisitImplicitCastExpr(E); 15565 15566 if (E->getCastKind() == CK_LValueToRValue) 15567 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15568 } 15569 }; 15570 } 15571 15572 /// Mark any declarations that appear within this expression or any 15573 /// potentially-evaluated subexpressions as "referenced". 15574 /// 15575 /// \param SkipLocalVariables If true, don't mark local variables as 15576 /// 'referenced'. 15577 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15578 bool SkipLocalVariables) { 15579 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15580 } 15581 15582 /// Emit a diagnostic that describes an effect on the run-time behavior 15583 /// of the program being compiled. 15584 /// 15585 /// This routine emits the given diagnostic when the code currently being 15586 /// type-checked is "potentially evaluated", meaning that there is a 15587 /// possibility that the code will actually be executable. Code in sizeof() 15588 /// expressions, code used only during overload resolution, etc., are not 15589 /// potentially evaluated. This routine will suppress such diagnostics or, 15590 /// in the absolutely nutty case of potentially potentially evaluated 15591 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15592 /// later. 15593 /// 15594 /// This routine should be used for all diagnostics that describe the run-time 15595 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15596 /// Failure to do so will likely result in spurious diagnostics or failures 15597 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15598 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15599 const PartialDiagnostic &PD) { 15600 switch (ExprEvalContexts.back().Context) { 15601 case ExpressionEvaluationContext::Unevaluated: 15602 case ExpressionEvaluationContext::UnevaluatedList: 15603 case ExpressionEvaluationContext::UnevaluatedAbstract: 15604 case ExpressionEvaluationContext::DiscardedStatement: 15605 // The argument will never be evaluated, so don't complain. 15606 break; 15607 15608 case ExpressionEvaluationContext::ConstantEvaluated: 15609 // Relevant diagnostics should be produced by constant evaluation. 15610 break; 15611 15612 case ExpressionEvaluationContext::PotentiallyEvaluated: 15613 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15614 if (Statement && getCurFunctionOrMethodDecl()) { 15615 FunctionScopes.back()->PossiblyUnreachableDiags. 15616 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15617 return true; 15618 } 15619 15620 // The initializer of a constexpr variable or of the first declaration of a 15621 // static data member is not syntactically a constant evaluated constant, 15622 // but nonetheless is always required to be a constant expression, so we 15623 // can skip diagnosing. 15624 // FIXME: Using the mangling context here is a hack. 15625 if (auto *VD = dyn_cast_or_null<VarDecl>( 15626 ExprEvalContexts.back().ManglingContextDecl)) { 15627 if (VD->isConstexpr() || 15628 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15629 break; 15630 // FIXME: For any other kind of variable, we should build a CFG for its 15631 // initializer and check whether the context in question is reachable. 15632 } 15633 15634 Diag(Loc, PD); 15635 return true; 15636 } 15637 15638 return false; 15639 } 15640 15641 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15642 CallExpr *CE, FunctionDecl *FD) { 15643 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15644 return false; 15645 15646 // If we're inside a decltype's expression, don't check for a valid return 15647 // type or construct temporaries until we know whether this is the last call. 15648 if (ExprEvalContexts.back().ExprContext == 15649 ExpressionEvaluationContextRecord::EK_Decltype) { 15650 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15651 return false; 15652 } 15653 15654 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15655 FunctionDecl *FD; 15656 CallExpr *CE; 15657 15658 public: 15659 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15660 : FD(FD), CE(CE) { } 15661 15662 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15663 if (!FD) { 15664 S.Diag(Loc, diag::err_call_incomplete_return) 15665 << T << CE->getSourceRange(); 15666 return; 15667 } 15668 15669 S.Diag(Loc, diag::err_call_function_incomplete_return) 15670 << CE->getSourceRange() << FD->getDeclName() << T; 15671 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15672 << FD->getDeclName(); 15673 } 15674 } Diagnoser(FD, CE); 15675 15676 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15677 return true; 15678 15679 return false; 15680 } 15681 15682 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15683 // will prevent this condition from triggering, which is what we want. 15684 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15685 SourceLocation Loc; 15686 15687 unsigned diagnostic = diag::warn_condition_is_assignment; 15688 bool IsOrAssign = false; 15689 15690 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15691 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15692 return; 15693 15694 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15695 15696 // Greylist some idioms by putting them into a warning subcategory. 15697 if (ObjCMessageExpr *ME 15698 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15699 Selector Sel = ME->getSelector(); 15700 15701 // self = [<foo> init...] 15702 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15703 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15704 15705 // <foo> = [<bar> nextObject] 15706 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15707 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15708 } 15709 15710 Loc = Op->getOperatorLoc(); 15711 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15712 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15713 return; 15714 15715 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15716 Loc = Op->getOperatorLoc(); 15717 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15718 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15719 else { 15720 // Not an assignment. 15721 return; 15722 } 15723 15724 Diag(Loc, diagnostic) << E->getSourceRange(); 15725 15726 SourceLocation Open = E->getBeginLoc(); 15727 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15728 Diag(Loc, diag::note_condition_assign_silence) 15729 << FixItHint::CreateInsertion(Open, "(") 15730 << FixItHint::CreateInsertion(Close, ")"); 15731 15732 if (IsOrAssign) 15733 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15734 << FixItHint::CreateReplacement(Loc, "!="); 15735 else 15736 Diag(Loc, diag::note_condition_assign_to_comparison) 15737 << FixItHint::CreateReplacement(Loc, "=="); 15738 } 15739 15740 /// Redundant parentheses over an equality comparison can indicate 15741 /// that the user intended an assignment used as condition. 15742 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15743 // Don't warn if the parens came from a macro. 15744 SourceLocation parenLoc = ParenE->getBeginLoc(); 15745 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15746 return; 15747 // Don't warn for dependent expressions. 15748 if (ParenE->isTypeDependent()) 15749 return; 15750 15751 Expr *E = ParenE->IgnoreParens(); 15752 15753 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15754 if (opE->getOpcode() == BO_EQ && 15755 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15756 == Expr::MLV_Valid) { 15757 SourceLocation Loc = opE->getOperatorLoc(); 15758 15759 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15760 SourceRange ParenERange = ParenE->getSourceRange(); 15761 Diag(Loc, diag::note_equality_comparison_silence) 15762 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15763 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15764 Diag(Loc, diag::note_equality_comparison_to_assign) 15765 << FixItHint::CreateReplacement(Loc, "="); 15766 } 15767 } 15768 15769 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15770 bool IsConstexpr) { 15771 DiagnoseAssignmentAsCondition(E); 15772 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15773 DiagnoseEqualityWithExtraParens(parenE); 15774 15775 ExprResult result = CheckPlaceholderExpr(E); 15776 if (result.isInvalid()) return ExprError(); 15777 E = result.get(); 15778 15779 if (!E->isTypeDependent()) { 15780 if (getLangOpts().CPlusPlus) 15781 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15782 15783 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15784 if (ERes.isInvalid()) 15785 return ExprError(); 15786 E = ERes.get(); 15787 15788 QualType T = E->getType(); 15789 if (!T->isScalarType()) { // C99 6.8.4.1p1 15790 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15791 << T << E->getSourceRange(); 15792 return ExprError(); 15793 } 15794 CheckBoolLikeConversion(E, Loc); 15795 } 15796 15797 return E; 15798 } 15799 15800 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15801 Expr *SubExpr, ConditionKind CK) { 15802 // Empty conditions are valid in for-statements. 15803 if (!SubExpr) 15804 return ConditionResult(); 15805 15806 ExprResult Cond; 15807 switch (CK) { 15808 case ConditionKind::Boolean: 15809 Cond = CheckBooleanCondition(Loc, SubExpr); 15810 break; 15811 15812 case ConditionKind::ConstexprIf: 15813 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15814 break; 15815 15816 case ConditionKind::Switch: 15817 Cond = CheckSwitchCondition(Loc, SubExpr); 15818 break; 15819 } 15820 if (Cond.isInvalid()) 15821 return ConditionError(); 15822 15823 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15824 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15825 if (!FullExpr.get()) 15826 return ConditionError(); 15827 15828 return ConditionResult(*this, nullptr, FullExpr, 15829 CK == ConditionKind::ConstexprIf); 15830 } 15831 15832 namespace { 15833 /// A visitor for rebuilding a call to an __unknown_any expression 15834 /// to have an appropriate type. 15835 struct RebuildUnknownAnyFunction 15836 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15837 15838 Sema &S; 15839 15840 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15841 15842 ExprResult VisitStmt(Stmt *S) { 15843 llvm_unreachable("unexpected statement!"); 15844 } 15845 15846 ExprResult VisitExpr(Expr *E) { 15847 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15848 << E->getSourceRange(); 15849 return ExprError(); 15850 } 15851 15852 /// Rebuild an expression which simply semantically wraps another 15853 /// expression which it shares the type and value kind of. 15854 template <class T> ExprResult rebuildSugarExpr(T *E) { 15855 ExprResult SubResult = Visit(E->getSubExpr()); 15856 if (SubResult.isInvalid()) return ExprError(); 15857 15858 Expr *SubExpr = SubResult.get(); 15859 E->setSubExpr(SubExpr); 15860 E->setType(SubExpr->getType()); 15861 E->setValueKind(SubExpr->getValueKind()); 15862 assert(E->getObjectKind() == OK_Ordinary); 15863 return E; 15864 } 15865 15866 ExprResult VisitParenExpr(ParenExpr *E) { 15867 return rebuildSugarExpr(E); 15868 } 15869 15870 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15871 return rebuildSugarExpr(E); 15872 } 15873 15874 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15875 ExprResult SubResult = Visit(E->getSubExpr()); 15876 if (SubResult.isInvalid()) return ExprError(); 15877 15878 Expr *SubExpr = SubResult.get(); 15879 E->setSubExpr(SubExpr); 15880 E->setType(S.Context.getPointerType(SubExpr->getType())); 15881 assert(E->getValueKind() == VK_RValue); 15882 assert(E->getObjectKind() == OK_Ordinary); 15883 return E; 15884 } 15885 15886 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15887 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15888 15889 E->setType(VD->getType()); 15890 15891 assert(E->getValueKind() == VK_RValue); 15892 if (S.getLangOpts().CPlusPlus && 15893 !(isa<CXXMethodDecl>(VD) && 15894 cast<CXXMethodDecl>(VD)->isInstance())) 15895 E->setValueKind(VK_LValue); 15896 15897 return E; 15898 } 15899 15900 ExprResult VisitMemberExpr(MemberExpr *E) { 15901 return resolveDecl(E, E->getMemberDecl()); 15902 } 15903 15904 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15905 return resolveDecl(E, E->getDecl()); 15906 } 15907 }; 15908 } 15909 15910 /// Given a function expression of unknown-any type, try to rebuild it 15911 /// to have a function type. 15912 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15913 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15914 if (Result.isInvalid()) return ExprError(); 15915 return S.DefaultFunctionArrayConversion(Result.get()); 15916 } 15917 15918 namespace { 15919 /// A visitor for rebuilding an expression of type __unknown_anytype 15920 /// into one which resolves the type directly on the referring 15921 /// expression. Strict preservation of the original source 15922 /// structure is not a goal. 15923 struct RebuildUnknownAnyExpr 15924 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15925 15926 Sema &S; 15927 15928 /// The current destination type. 15929 QualType DestType; 15930 15931 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15932 : S(S), DestType(CastType) {} 15933 15934 ExprResult VisitStmt(Stmt *S) { 15935 llvm_unreachable("unexpected statement!"); 15936 } 15937 15938 ExprResult VisitExpr(Expr *E) { 15939 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15940 << E->getSourceRange(); 15941 return ExprError(); 15942 } 15943 15944 ExprResult VisitCallExpr(CallExpr *E); 15945 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15946 15947 /// Rebuild an expression which simply semantically wraps another 15948 /// expression which it shares the type and value kind of. 15949 template <class T> ExprResult rebuildSugarExpr(T *E) { 15950 ExprResult SubResult = Visit(E->getSubExpr()); 15951 if (SubResult.isInvalid()) return ExprError(); 15952 Expr *SubExpr = SubResult.get(); 15953 E->setSubExpr(SubExpr); 15954 E->setType(SubExpr->getType()); 15955 E->setValueKind(SubExpr->getValueKind()); 15956 assert(E->getObjectKind() == OK_Ordinary); 15957 return E; 15958 } 15959 15960 ExprResult VisitParenExpr(ParenExpr *E) { 15961 return rebuildSugarExpr(E); 15962 } 15963 15964 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15965 return rebuildSugarExpr(E); 15966 } 15967 15968 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15969 const PointerType *Ptr = DestType->getAs<PointerType>(); 15970 if (!Ptr) { 15971 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15972 << E->getSourceRange(); 15973 return ExprError(); 15974 } 15975 15976 if (isa<CallExpr>(E->getSubExpr())) { 15977 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15978 << E->getSourceRange(); 15979 return ExprError(); 15980 } 15981 15982 assert(E->getValueKind() == VK_RValue); 15983 assert(E->getObjectKind() == OK_Ordinary); 15984 E->setType(DestType); 15985 15986 // Build the sub-expression as if it were an object of the pointee type. 15987 DestType = Ptr->getPointeeType(); 15988 ExprResult SubResult = Visit(E->getSubExpr()); 15989 if (SubResult.isInvalid()) return ExprError(); 15990 E->setSubExpr(SubResult.get()); 15991 return E; 15992 } 15993 15994 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15995 15996 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15997 15998 ExprResult VisitMemberExpr(MemberExpr *E) { 15999 return resolveDecl(E, E->getMemberDecl()); 16000 } 16001 16002 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16003 return resolveDecl(E, E->getDecl()); 16004 } 16005 }; 16006 } 16007 16008 /// Rebuilds a call expression which yielded __unknown_anytype. 16009 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16010 Expr *CalleeExpr = E->getCallee(); 16011 16012 enum FnKind { 16013 FK_MemberFunction, 16014 FK_FunctionPointer, 16015 FK_BlockPointer 16016 }; 16017 16018 FnKind Kind; 16019 QualType CalleeType = CalleeExpr->getType(); 16020 if (CalleeType == S.Context.BoundMemberTy) { 16021 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16022 Kind = FK_MemberFunction; 16023 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16024 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16025 CalleeType = Ptr->getPointeeType(); 16026 Kind = FK_FunctionPointer; 16027 } else { 16028 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16029 Kind = FK_BlockPointer; 16030 } 16031 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16032 16033 // Verify that this is a legal result type of a function. 16034 if (DestType->isArrayType() || DestType->isFunctionType()) { 16035 unsigned diagID = diag::err_func_returning_array_function; 16036 if (Kind == FK_BlockPointer) 16037 diagID = diag::err_block_returning_array_function; 16038 16039 S.Diag(E->getExprLoc(), diagID) 16040 << DestType->isFunctionType() << DestType; 16041 return ExprError(); 16042 } 16043 16044 // Otherwise, go ahead and set DestType as the call's result. 16045 E->setType(DestType.getNonLValueExprType(S.Context)); 16046 E->setValueKind(Expr::getValueKindForType(DestType)); 16047 assert(E->getObjectKind() == OK_Ordinary); 16048 16049 // Rebuild the function type, replacing the result type with DestType. 16050 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16051 if (Proto) { 16052 // __unknown_anytype(...) is a special case used by the debugger when 16053 // it has no idea what a function's signature is. 16054 // 16055 // We want to build this call essentially under the K&R 16056 // unprototyped rules, but making a FunctionNoProtoType in C++ 16057 // would foul up all sorts of assumptions. However, we cannot 16058 // simply pass all arguments as variadic arguments, nor can we 16059 // portably just call the function under a non-variadic type; see 16060 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16061 // However, it turns out that in practice it is generally safe to 16062 // call a function declared as "A foo(B,C,D);" under the prototype 16063 // "A foo(B,C,D,...);". The only known exception is with the 16064 // Windows ABI, where any variadic function is implicitly cdecl 16065 // regardless of its normal CC. Therefore we change the parameter 16066 // types to match the types of the arguments. 16067 // 16068 // This is a hack, but it is far superior to moving the 16069 // corresponding target-specific code from IR-gen to Sema/AST. 16070 16071 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16072 SmallVector<QualType, 8> ArgTypes; 16073 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16074 ArgTypes.reserve(E->getNumArgs()); 16075 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16076 Expr *Arg = E->getArg(i); 16077 QualType ArgType = Arg->getType(); 16078 if (E->isLValue()) { 16079 ArgType = S.Context.getLValueReferenceType(ArgType); 16080 } else if (E->isXValue()) { 16081 ArgType = S.Context.getRValueReferenceType(ArgType); 16082 } 16083 ArgTypes.push_back(ArgType); 16084 } 16085 ParamTypes = ArgTypes; 16086 } 16087 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16088 Proto->getExtProtoInfo()); 16089 } else { 16090 DestType = S.Context.getFunctionNoProtoType(DestType, 16091 FnType->getExtInfo()); 16092 } 16093 16094 // Rebuild the appropriate pointer-to-function type. 16095 switch (Kind) { 16096 case FK_MemberFunction: 16097 // Nothing to do. 16098 break; 16099 16100 case FK_FunctionPointer: 16101 DestType = S.Context.getPointerType(DestType); 16102 break; 16103 16104 case FK_BlockPointer: 16105 DestType = S.Context.getBlockPointerType(DestType); 16106 break; 16107 } 16108 16109 // Finally, we can recurse. 16110 ExprResult CalleeResult = Visit(CalleeExpr); 16111 if (!CalleeResult.isUsable()) return ExprError(); 16112 E->setCallee(CalleeResult.get()); 16113 16114 // Bind a temporary if necessary. 16115 return S.MaybeBindToTemporary(E); 16116 } 16117 16118 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16119 // Verify that this is a legal result type of a call. 16120 if (DestType->isArrayType() || DestType->isFunctionType()) { 16121 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16122 << DestType->isFunctionType() << DestType; 16123 return ExprError(); 16124 } 16125 16126 // Rewrite the method result type if available. 16127 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16128 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16129 Method->setReturnType(DestType); 16130 } 16131 16132 // Change the type of the message. 16133 E->setType(DestType.getNonReferenceType()); 16134 E->setValueKind(Expr::getValueKindForType(DestType)); 16135 16136 return S.MaybeBindToTemporary(E); 16137 } 16138 16139 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16140 // The only case we should ever see here is a function-to-pointer decay. 16141 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16142 assert(E->getValueKind() == VK_RValue); 16143 assert(E->getObjectKind() == OK_Ordinary); 16144 16145 E->setType(DestType); 16146 16147 // Rebuild the sub-expression as the pointee (function) type. 16148 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16149 16150 ExprResult Result = Visit(E->getSubExpr()); 16151 if (!Result.isUsable()) return ExprError(); 16152 16153 E->setSubExpr(Result.get()); 16154 return E; 16155 } else if (E->getCastKind() == CK_LValueToRValue) { 16156 assert(E->getValueKind() == VK_RValue); 16157 assert(E->getObjectKind() == OK_Ordinary); 16158 16159 assert(isa<BlockPointerType>(E->getType())); 16160 16161 E->setType(DestType); 16162 16163 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16164 DestType = S.Context.getLValueReferenceType(DestType); 16165 16166 ExprResult Result = Visit(E->getSubExpr()); 16167 if (!Result.isUsable()) return ExprError(); 16168 16169 E->setSubExpr(Result.get()); 16170 return E; 16171 } else { 16172 llvm_unreachable("Unhandled cast type!"); 16173 } 16174 } 16175 16176 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16177 ExprValueKind ValueKind = VK_LValue; 16178 QualType Type = DestType; 16179 16180 // We know how to make this work for certain kinds of decls: 16181 16182 // - functions 16183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16184 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16185 DestType = Ptr->getPointeeType(); 16186 ExprResult Result = resolveDecl(E, VD); 16187 if (Result.isInvalid()) return ExprError(); 16188 return S.ImpCastExprToType(Result.get(), Type, 16189 CK_FunctionToPointerDecay, VK_RValue); 16190 } 16191 16192 if (!Type->isFunctionType()) { 16193 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16194 << VD << E->getSourceRange(); 16195 return ExprError(); 16196 } 16197 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16198 // We must match the FunctionDecl's type to the hack introduced in 16199 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16200 // type. See the lengthy commentary in that routine. 16201 QualType FDT = FD->getType(); 16202 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16203 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16205 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16206 SourceLocation Loc = FD->getLocation(); 16207 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16208 FD->getDeclContext(), 16209 Loc, Loc, FD->getNameInfo().getName(), 16210 DestType, FD->getTypeSourceInfo(), 16211 SC_None, false/*isInlineSpecified*/, 16212 FD->hasPrototype(), 16213 false/*isConstexprSpecified*/); 16214 16215 if (FD->getQualifier()) 16216 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16217 16218 SmallVector<ParmVarDecl*, 16> Params; 16219 for (const auto &AI : FT->param_types()) { 16220 ParmVarDecl *Param = 16221 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16222 Param->setScopeInfo(0, Params.size()); 16223 Params.push_back(Param); 16224 } 16225 NewFD->setParams(Params); 16226 DRE->setDecl(NewFD); 16227 VD = DRE->getDecl(); 16228 } 16229 } 16230 16231 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16232 if (MD->isInstance()) { 16233 ValueKind = VK_RValue; 16234 Type = S.Context.BoundMemberTy; 16235 } 16236 16237 // Function references aren't l-values in C. 16238 if (!S.getLangOpts().CPlusPlus) 16239 ValueKind = VK_RValue; 16240 16241 // - variables 16242 } else if (isa<VarDecl>(VD)) { 16243 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16244 Type = RefTy->getPointeeType(); 16245 } else if (Type->isFunctionType()) { 16246 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16247 << VD << E->getSourceRange(); 16248 return ExprError(); 16249 } 16250 16251 // - nothing else 16252 } else { 16253 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16254 << VD << E->getSourceRange(); 16255 return ExprError(); 16256 } 16257 16258 // Modifying the declaration like this is friendly to IR-gen but 16259 // also really dangerous. 16260 VD->setType(DestType); 16261 E->setType(Type); 16262 E->setValueKind(ValueKind); 16263 return E; 16264 } 16265 16266 /// Check a cast of an unknown-any type. We intentionally only 16267 /// trigger this for C-style casts. 16268 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16269 Expr *CastExpr, CastKind &CastKind, 16270 ExprValueKind &VK, CXXCastPath &Path) { 16271 // The type we're casting to must be either void or complete. 16272 if (!CastType->isVoidType() && 16273 RequireCompleteType(TypeRange.getBegin(), CastType, 16274 diag::err_typecheck_cast_to_incomplete)) 16275 return ExprError(); 16276 16277 // Rewrite the casted expression from scratch. 16278 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16279 if (!result.isUsable()) return ExprError(); 16280 16281 CastExpr = result.get(); 16282 VK = CastExpr->getValueKind(); 16283 CastKind = CK_NoOp; 16284 16285 return CastExpr; 16286 } 16287 16288 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16289 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16290 } 16291 16292 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16293 Expr *arg, QualType ¶mType) { 16294 // If the syntactic form of the argument is not an explicit cast of 16295 // any sort, just do default argument promotion. 16296 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16297 if (!castArg) { 16298 ExprResult result = DefaultArgumentPromotion(arg); 16299 if (result.isInvalid()) return ExprError(); 16300 paramType = result.get()->getType(); 16301 return result; 16302 } 16303 16304 // Otherwise, use the type that was written in the explicit cast. 16305 assert(!arg->hasPlaceholderType()); 16306 paramType = castArg->getTypeAsWritten(); 16307 16308 // Copy-initialize a parameter of that type. 16309 InitializedEntity entity = 16310 InitializedEntity::InitializeParameter(Context, paramType, 16311 /*consumed*/ false); 16312 return PerformCopyInitialization(entity, callLoc, arg); 16313 } 16314 16315 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16316 Expr *orig = E; 16317 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16318 while (true) { 16319 E = E->IgnoreParenImpCasts(); 16320 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16321 E = call->getCallee(); 16322 diagID = diag::err_uncasted_call_of_unknown_any; 16323 } else { 16324 break; 16325 } 16326 } 16327 16328 SourceLocation loc; 16329 NamedDecl *d; 16330 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16331 loc = ref->getLocation(); 16332 d = ref->getDecl(); 16333 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16334 loc = mem->getMemberLoc(); 16335 d = mem->getMemberDecl(); 16336 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16337 diagID = diag::err_uncasted_call_of_unknown_any; 16338 loc = msg->getSelectorStartLoc(); 16339 d = msg->getMethodDecl(); 16340 if (!d) { 16341 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16342 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16343 << orig->getSourceRange(); 16344 return ExprError(); 16345 } 16346 } else { 16347 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16348 << E->getSourceRange(); 16349 return ExprError(); 16350 } 16351 16352 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16353 16354 // Never recoverable. 16355 return ExprError(); 16356 } 16357 16358 /// Check for operands with placeholder types and complain if found. 16359 /// Returns ExprError() if there was an error and no recovery was possible. 16360 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16361 if (!getLangOpts().CPlusPlus) { 16362 // C cannot handle TypoExpr nodes on either side of a binop because it 16363 // doesn't handle dependent types properly, so make sure any TypoExprs have 16364 // been dealt with before checking the operands. 16365 ExprResult Result = CorrectDelayedTyposInExpr(E); 16366 if (!Result.isUsable()) return ExprError(); 16367 E = Result.get(); 16368 } 16369 16370 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16371 if (!placeholderType) return E; 16372 16373 switch (placeholderType->getKind()) { 16374 16375 // Overloaded expressions. 16376 case BuiltinType::Overload: { 16377 // Try to resolve a single function template specialization. 16378 // This is obligatory. 16379 ExprResult Result = E; 16380 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16381 return Result; 16382 16383 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16384 // leaves Result unchanged on failure. 16385 Result = E; 16386 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16387 return Result; 16388 16389 // If that failed, try to recover with a call. 16390 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16391 /*complain*/ true); 16392 return Result; 16393 } 16394 16395 // Bound member functions. 16396 case BuiltinType::BoundMember: { 16397 ExprResult result = E; 16398 const Expr *BME = E->IgnoreParens(); 16399 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16400 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16401 if (isa<CXXPseudoDestructorExpr>(BME)) { 16402 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16403 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16404 if (ME->getMemberNameInfo().getName().getNameKind() == 16405 DeclarationName::CXXDestructorName) 16406 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16407 } 16408 tryToRecoverWithCall(result, PD, 16409 /*complain*/ true); 16410 return result; 16411 } 16412 16413 // ARC unbridged casts. 16414 case BuiltinType::ARCUnbridgedCast: { 16415 Expr *realCast = stripARCUnbridgedCast(E); 16416 diagnoseARCUnbridgedCast(realCast); 16417 return realCast; 16418 } 16419 16420 // Expressions of unknown type. 16421 case BuiltinType::UnknownAny: 16422 return diagnoseUnknownAnyExpr(*this, E); 16423 16424 // Pseudo-objects. 16425 case BuiltinType::PseudoObject: 16426 return checkPseudoObjectRValue(E); 16427 16428 case BuiltinType::BuiltinFn: { 16429 // Accept __noop without parens by implicitly converting it to a call expr. 16430 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16431 if (DRE) { 16432 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16433 if (FD->getBuiltinID() == Builtin::BI__noop) { 16434 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16435 CK_BuiltinFnToFnPtr).get(); 16436 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16437 VK_RValue, SourceLocation()); 16438 } 16439 } 16440 16441 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16442 return ExprError(); 16443 } 16444 16445 // Expressions of unknown type. 16446 case BuiltinType::OMPArraySection: 16447 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16448 return ExprError(); 16449 16450 // Everything else should be impossible. 16451 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16452 case BuiltinType::Id: 16453 #include "clang/Basic/OpenCLImageTypes.def" 16454 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16455 #define PLACEHOLDER_TYPE(Id, SingletonId) 16456 #include "clang/AST/BuiltinTypes.def" 16457 break; 16458 } 16459 16460 llvm_unreachable("invalid placeholder type!"); 16461 } 16462 16463 bool Sema::CheckCaseExpression(Expr *E) { 16464 if (E->isTypeDependent()) 16465 return true; 16466 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16467 return E->getType()->isIntegralOrEnumerationType(); 16468 return false; 16469 } 16470 16471 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16472 ExprResult 16473 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16474 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16475 "Unknown Objective-C Boolean value!"); 16476 QualType BoolT = Context.ObjCBuiltinBoolTy; 16477 if (!Context.getBOOLDecl()) { 16478 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16479 Sema::LookupOrdinaryName); 16480 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16481 NamedDecl *ND = Result.getFoundDecl(); 16482 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16483 Context.setBOOLDecl(TD); 16484 } 16485 } 16486 if (Context.getBOOLDecl()) 16487 BoolT = Context.getBOOLType(); 16488 return new (Context) 16489 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16490 } 16491 16492 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16493 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16494 SourceLocation RParen) { 16495 16496 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16497 16498 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16499 [&](const AvailabilitySpec &Spec) { 16500 return Spec.getPlatform() == Platform; 16501 }); 16502 16503 VersionTuple Version; 16504 if (Spec != AvailSpecs.end()) 16505 Version = Spec->getVersion(); 16506 16507 // The use of `@available` in the enclosing function should be analyzed to 16508 // warn when it's used inappropriately (i.e. not if(@available)). 16509 if (getCurFunctionOrMethodDecl()) 16510 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16511 else if (getCurBlock() || getCurLambda()) 16512 getCurFunction()->HasPotentialAvailabilityViolations = true; 16513 16514 return new (Context) 16515 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16516 } 16517