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/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (const auto *A = D->getAttr<UnusedAttr>()) { 80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 81 // should diagnose them. 82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 83 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 84 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 85 if (DC && !DC->hasAttr<UnusedAttr>()) 86 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 87 } 88 } 89 } 90 91 /// \brief Emit a note explaining that this function is deleted. 92 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 93 assert(Decl->isDeleted()); 94 95 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 96 97 if (Method && Method->isDeleted() && Method->isDefaulted()) { 98 // If the method was explicitly defaulted, point at that declaration. 99 if (!Method->isImplicit()) 100 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 101 102 // Try to diagnose why this special member function was implicitly 103 // deleted. This might fail, if that reason no longer applies. 104 CXXSpecialMember CSM = getSpecialMember(Method); 105 if (CSM != CXXInvalid) 106 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 107 108 return; 109 } 110 111 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 112 if (Ctor && Ctor->isInheritingConstructor()) 113 return NoteDeletedInheritingConstructor(Ctor); 114 115 Diag(Decl->getLocation(), diag::note_availability_specified_here) 116 << Decl << true; 117 } 118 119 /// \brief Determine whether a FunctionDecl was ever declared with an 120 /// explicit storage class. 121 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 122 for (auto I : D->redecls()) { 123 if (I->getStorageClass() != SC_None) 124 return true; 125 } 126 return false; 127 } 128 129 /// \brief Check whether we're in an extern inline function and referring to a 130 /// variable or function with internal linkage (C11 6.7.4p3). 131 /// 132 /// This is only a warning because we used to silently accept this code, but 133 /// in many cases it will not behave correctly. This is not enabled in C++ mode 134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 135 /// and so while there may still be user mistakes, most of the time we can't 136 /// prove that there are errors. 137 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 138 const NamedDecl *D, 139 SourceLocation Loc) { 140 // This is disabled under C++; there are too many ways for this to fire in 141 // contexts where the warning is a false positive, or where it is technically 142 // correct but benign. 143 if (S.getLangOpts().CPlusPlus) 144 return; 145 146 // Check if this is an inlined function or method. 147 FunctionDecl *Current = S.getCurFunctionDecl(); 148 if (!Current) 149 return; 150 if (!Current->isInlined()) 151 return; 152 if (!Current->isExternallyVisible()) 153 return; 154 155 // Check if the decl has internal linkage. 156 if (D->getFormalLinkage() != InternalLinkage) 157 return; 158 159 // Downgrade from ExtWarn to Extension if 160 // (1) the supposedly external inline function is in the main file, 161 // and probably won't be included anywhere else. 162 // (2) the thing we're referencing is a pure function. 163 // (3) the thing we're referencing is another inline function. 164 // This last can give us false negatives, but it's better than warning on 165 // wrappers for simple C library functions. 166 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 167 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 168 if (!DowngradeWarning && UsedFn) 169 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 170 171 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 172 : diag::ext_internal_in_extern_inline) 173 << /*IsVar=*/!UsedFn << D; 174 175 S.MaybeSuggestAddingStaticToDecl(Current); 176 177 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 178 << D; 179 } 180 181 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 182 const FunctionDecl *First = Cur->getFirstDecl(); 183 184 // Suggest "static" on the function, if possible. 185 if (!hasAnyExplicitStorageClass(First)) { 186 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 187 Diag(DeclBegin, diag::note_convert_inline_to_static) 188 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 189 } 190 } 191 192 /// \brief Determine whether the use of this declaration is valid, and 193 /// emit any corresponding diagnostics. 194 /// 195 /// This routine diagnoses various problems with referencing 196 /// declarations that can occur when using a declaration. For example, 197 /// it might warn if a deprecated or unavailable declaration is being 198 /// used, or produce an error (and return true) if a C++0x deleted 199 /// function is being used. 200 /// 201 /// \returns true if there was an error (this declaration cannot be 202 /// referenced), false otherwise. 203 /// 204 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 205 const ObjCInterfaceDecl *UnknownObjCClass, 206 bool ObjCPropertyAccess, 207 bool AvoidPartialAvailabilityChecks) { 208 SourceLocation Loc = Locs.front(); 209 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 210 // If there were any diagnostics suppressed by template argument deduction, 211 // emit them now. 212 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 213 if (Pos != SuppressedDiagnostics.end()) { 214 for (const PartialDiagnosticAt &Suppressed : Pos->second) 215 Diag(Suppressed.first, Suppressed.second); 216 217 // Clear out the list of suppressed diagnostics, so that we don't emit 218 // them again for this specialization. However, we don't obsolete this 219 // entry from the table, because we want to avoid ever emitting these 220 // diagnostics again. 221 Pos->second.clear(); 222 } 223 224 // C++ [basic.start.main]p3: 225 // The function 'main' shall not be used within a program. 226 if (cast<FunctionDecl>(D)->isMain()) 227 Diag(Loc, diag::ext_main_used); 228 } 229 230 // See if this is an auto-typed variable whose initializer we are parsing. 231 if (ParsingInitForAutoVars.count(D)) { 232 if (isa<BindingDecl>(D)) { 233 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 234 << D->getDeclName(); 235 } else { 236 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 237 << D->getDeclName() << cast<VarDecl>(D)->getType(); 238 } 239 return true; 240 } 241 242 // See if this is a deleted function. 243 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 244 if (FD->isDeleted()) { 245 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 246 if (Ctor && Ctor->isInheritingConstructor()) 247 Diag(Loc, diag::err_deleted_inherited_ctor_use) 248 << Ctor->getParent() 249 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 250 else 251 Diag(Loc, diag::err_deleted_function_use); 252 NoteDeletedFunction(FD); 253 return true; 254 } 255 256 // If the function has a deduced return type, and we can't deduce it, 257 // then we can't use it either. 258 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 259 DeduceReturnType(FD, Loc)) 260 return true; 261 262 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 263 return true; 264 } 265 266 auto getReferencedObjCProp = [](const NamedDecl *D) -> 267 const ObjCPropertyDecl * { 268 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 269 return MD->findPropertyDecl(); 270 return nullptr; 271 }; 272 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 273 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 274 return true; 275 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 276 return true; 277 } 278 279 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 280 // Only the variables omp_in and omp_out are allowed in the combiner. 281 // Only the variables omp_priv and omp_orig are allowed in the 282 // initializer-clause. 283 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 284 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 285 isa<VarDecl>(D)) { 286 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 287 << getCurFunction()->HasOMPDeclareReductionCombiner; 288 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 289 return true; 290 } 291 292 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 293 AvoidPartialAvailabilityChecks); 294 295 DiagnoseUnusedOfDecl(*this, D, Loc); 296 297 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 298 299 return false; 300 } 301 302 /// \brief Retrieve the message suffix that should be added to a 303 /// diagnostic complaining about the given function being deleted or 304 /// unavailable. 305 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 306 std::string Message; 307 if (FD->getAvailability(&Message)) 308 return ": " + Message; 309 310 return std::string(); 311 } 312 313 /// DiagnoseSentinelCalls - This routine checks whether a call or 314 /// message-send is to a declaration with the sentinel attribute, and 315 /// if so, it checks that the requirements of the sentinel are 316 /// satisfied. 317 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 318 ArrayRef<Expr *> Args) { 319 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 320 if (!attr) 321 return; 322 323 // The number of formal parameters of the declaration. 324 unsigned numFormalParams; 325 326 // The kind of declaration. This is also an index into a %select in 327 // the diagnostic. 328 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 329 330 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 331 numFormalParams = MD->param_size(); 332 calleeType = CT_Method; 333 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 334 numFormalParams = FD->param_size(); 335 calleeType = CT_Function; 336 } else if (isa<VarDecl>(D)) { 337 QualType type = cast<ValueDecl>(D)->getType(); 338 const FunctionType *fn = nullptr; 339 if (const PointerType *ptr = type->getAs<PointerType>()) { 340 fn = ptr->getPointeeType()->getAs<FunctionType>(); 341 if (!fn) return; 342 calleeType = CT_Function; 343 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 344 fn = ptr->getPointeeType()->castAs<FunctionType>(); 345 calleeType = CT_Block; 346 } else { 347 return; 348 } 349 350 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 351 numFormalParams = proto->getNumParams(); 352 } else { 353 numFormalParams = 0; 354 } 355 } else { 356 return; 357 } 358 359 // "nullPos" is the number of formal parameters at the end which 360 // effectively count as part of the variadic arguments. This is 361 // useful if you would prefer to not have *any* formal parameters, 362 // but the language forces you to have at least one. 363 unsigned nullPos = attr->getNullPos(); 364 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 365 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 366 367 // The number of arguments which should follow the sentinel. 368 unsigned numArgsAfterSentinel = attr->getSentinel(); 369 370 // If there aren't enough arguments for all the formal parameters, 371 // the sentinel, and the args after the sentinel, complain. 372 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 373 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 374 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 375 return; 376 } 377 378 // Otherwise, find the sentinel expression. 379 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 380 if (!sentinelExpr) return; 381 if (sentinelExpr->isValueDependent()) return; 382 if (Context.isSentinelNullExpr(sentinelExpr)) return; 383 384 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 385 // or 'NULL' if those are actually defined in the context. Only use 386 // 'nil' for ObjC methods, where it's much more likely that the 387 // variadic arguments form a list of object pointers. 388 SourceLocation MissingNilLoc 389 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 390 std::string NullValue; 391 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 392 NullValue = "nil"; 393 else if (getLangOpts().CPlusPlus11) 394 NullValue = "nullptr"; 395 else if (PP.isMacroDefined("NULL")) 396 NullValue = "NULL"; 397 else 398 NullValue = "(void*) 0"; 399 400 if (MissingNilLoc.isInvalid()) 401 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 402 else 403 Diag(MissingNilLoc, diag::warn_missing_sentinel) 404 << int(calleeType) 405 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 406 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 407 } 408 409 SourceRange Sema::getExprRange(Expr *E) const { 410 return E ? E->getSourceRange() : SourceRange(); 411 } 412 413 //===----------------------------------------------------------------------===// 414 // Standard Promotions and Conversions 415 //===----------------------------------------------------------------------===// 416 417 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 418 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 419 // Handle any placeholder expressions which made it here. 420 if (E->getType()->isPlaceholderType()) { 421 ExprResult result = CheckPlaceholderExpr(E); 422 if (result.isInvalid()) return ExprError(); 423 E = result.get(); 424 } 425 426 QualType Ty = E->getType(); 427 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 428 429 if (Ty->isFunctionType()) { 430 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 431 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 432 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 433 return ExprError(); 434 435 E = ImpCastExprToType(E, Context.getPointerType(Ty), 436 CK_FunctionToPointerDecay).get(); 437 } else if (Ty->isArrayType()) { 438 // In C90 mode, arrays only promote to pointers if the array expression is 439 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 440 // type 'array of type' is converted to an expression that has type 'pointer 441 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 442 // that has type 'array of type' ...". The relevant change is "an lvalue" 443 // (C90) to "an expression" (C99). 444 // 445 // C++ 4.2p1: 446 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 447 // T" can be converted to an rvalue of type "pointer to T". 448 // 449 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 450 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 451 CK_ArrayToPointerDecay).get(); 452 } 453 return E; 454 } 455 456 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 457 // Check to see if we are dereferencing a null pointer. If so, 458 // and if not volatile-qualified, this is undefined behavior that the 459 // optimizer will delete, so warn about it. People sometimes try to use this 460 // to get a deterministic trap and are surprised by clang's behavior. This 461 // only handles the pattern "*null", which is a very syntactic check. 462 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 463 if (UO->getOpcode() == UO_Deref && 464 UO->getSubExpr()->IgnoreParenCasts()-> 465 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 466 !UO->getType().isVolatileQualified()) { 467 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 468 S.PDiag(diag::warn_indirection_through_null) 469 << UO->getSubExpr()->getSourceRange()); 470 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 471 S.PDiag(diag::note_indirection_through_null)); 472 } 473 } 474 475 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 476 SourceLocation AssignLoc, 477 const Expr* RHS) { 478 const ObjCIvarDecl *IV = OIRE->getDecl(); 479 if (!IV) 480 return; 481 482 DeclarationName MemberName = IV->getDeclName(); 483 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 484 if (!Member || !Member->isStr("isa")) 485 return; 486 487 const Expr *Base = OIRE->getBase(); 488 QualType BaseType = Base->getType(); 489 if (OIRE->isArrow()) 490 BaseType = BaseType->getPointeeType(); 491 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 492 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 493 ObjCInterfaceDecl *ClassDeclared = nullptr; 494 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 495 if (!ClassDeclared->getSuperClass() 496 && (*ClassDeclared->ivar_begin()) == IV) { 497 if (RHS) { 498 NamedDecl *ObjectSetClass = 499 S.LookupSingleName(S.TUScope, 500 &S.Context.Idents.get("object_setClass"), 501 SourceLocation(), S.LookupOrdinaryName); 502 if (ObjectSetClass) { 503 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 504 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 505 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 506 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 507 AssignLoc), ",") << 508 FixItHint::CreateInsertion(RHSLocEnd, ")"); 509 } 510 else 511 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 512 } else { 513 NamedDecl *ObjectGetClass = 514 S.LookupSingleName(S.TUScope, 515 &S.Context.Idents.get("object_getClass"), 516 SourceLocation(), S.LookupOrdinaryName); 517 if (ObjectGetClass) 518 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 519 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 520 FixItHint::CreateReplacement( 521 SourceRange(OIRE->getOpLoc(), 522 OIRE->getLocEnd()), ")"); 523 else 524 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 525 } 526 S.Diag(IV->getLocation(), diag::note_ivar_decl); 527 } 528 } 529 } 530 531 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 532 // Handle any placeholder expressions which made it here. 533 if (E->getType()->isPlaceholderType()) { 534 ExprResult result = CheckPlaceholderExpr(E); 535 if (result.isInvalid()) return ExprError(); 536 E = result.get(); 537 } 538 539 // C++ [conv.lval]p1: 540 // A glvalue of a non-function, non-array type T can be 541 // converted to a prvalue. 542 if (!E->isGLValue()) return E; 543 544 QualType T = E->getType(); 545 assert(!T.isNull() && "r-value conversion on typeless expression?"); 546 547 // We don't want to throw lvalue-to-rvalue casts on top of 548 // expressions of certain types in C++. 549 if (getLangOpts().CPlusPlus && 550 (E->getType() == Context.OverloadTy || 551 T->isDependentType() || 552 T->isRecordType())) 553 return E; 554 555 // The C standard is actually really unclear on this point, and 556 // DR106 tells us what the result should be but not why. It's 557 // generally best to say that void types just doesn't undergo 558 // lvalue-to-rvalue at all. Note that expressions of unqualified 559 // 'void' type are never l-values, but qualified void can be. 560 if (T->isVoidType()) 561 return E; 562 563 // OpenCL usually rejects direct accesses to values of 'half' type. 564 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 565 T->isHalfType()) { 566 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 567 << 0 << T; 568 return ExprError(); 569 } 570 571 CheckForNullPointerDereference(*this, E); 572 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 573 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 574 &Context.Idents.get("object_getClass"), 575 SourceLocation(), LookupOrdinaryName); 576 if (ObjectGetClass) 577 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 578 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 579 FixItHint::CreateReplacement( 580 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 581 else 582 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 583 } 584 else if (const ObjCIvarRefExpr *OIRE = 585 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 586 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 587 588 // C++ [conv.lval]p1: 589 // [...] If T is a non-class type, the type of the prvalue is the 590 // cv-unqualified version of T. Otherwise, the type of the 591 // rvalue is T. 592 // 593 // C99 6.3.2.1p2: 594 // If the lvalue has qualified type, the value has the unqualified 595 // version of the type of the lvalue; otherwise, the value has the 596 // type of the lvalue. 597 if (T.hasQualifiers()) 598 T = T.getUnqualifiedType(); 599 600 // Under the MS ABI, lock down the inheritance model now. 601 if (T->isMemberPointerType() && 602 Context.getTargetInfo().getCXXABI().isMicrosoft()) 603 (void)isCompleteType(E->getExprLoc(), T); 604 605 UpdateMarkingForLValueToRValue(E); 606 607 // Loading a __weak object implicitly retains the value, so we need a cleanup to 608 // balance that. 609 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 610 Cleanup.setExprNeedsCleanups(true); 611 612 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 613 nullptr, VK_RValue); 614 615 // C11 6.3.2.1p2: 616 // ... if the lvalue has atomic type, the value has the non-atomic version 617 // of the type of the lvalue ... 618 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 619 T = Atomic->getValueType().getUnqualifiedType(); 620 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 621 nullptr, VK_RValue); 622 } 623 624 return Res; 625 } 626 627 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 628 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 629 if (Res.isInvalid()) 630 return ExprError(); 631 Res = DefaultLvalueConversion(Res.get()); 632 if (Res.isInvalid()) 633 return ExprError(); 634 return Res; 635 } 636 637 /// CallExprUnaryConversions - a special case of an unary conversion 638 /// performed on a function designator of a call expression. 639 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 640 QualType Ty = E->getType(); 641 ExprResult Res = E; 642 // Only do implicit cast for a function type, but not for a pointer 643 // to function type. 644 if (Ty->isFunctionType()) { 645 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 646 CK_FunctionToPointerDecay).get(); 647 if (Res.isInvalid()) 648 return ExprError(); 649 } 650 Res = DefaultLvalueConversion(Res.get()); 651 if (Res.isInvalid()) 652 return ExprError(); 653 return Res.get(); 654 } 655 656 /// UsualUnaryConversions - Performs various conversions that are common to most 657 /// operators (C99 6.3). The conversions of array and function types are 658 /// sometimes suppressed. For example, the array->pointer conversion doesn't 659 /// apply if the array is an argument to the sizeof or address (&) operators. 660 /// In these instances, this routine should *not* be called. 661 ExprResult Sema::UsualUnaryConversions(Expr *E) { 662 // First, convert to an r-value. 663 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 664 if (Res.isInvalid()) 665 return ExprError(); 666 E = Res.get(); 667 668 QualType Ty = E->getType(); 669 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 670 671 // Half FP have to be promoted to float unless it is natively supported 672 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 673 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 674 675 // Try to perform integral promotions if the object has a theoretically 676 // promotable type. 677 if (Ty->isIntegralOrUnscopedEnumerationType()) { 678 // C99 6.3.1.1p2: 679 // 680 // The following may be used in an expression wherever an int or 681 // unsigned int may be used: 682 // - an object or expression with an integer type whose integer 683 // conversion rank is less than or equal to the rank of int 684 // and unsigned int. 685 // - A bit-field of type _Bool, int, signed int, or unsigned int. 686 // 687 // If an int can represent all values of the original type, the 688 // value is converted to an int; otherwise, it is converted to an 689 // unsigned int. These are called the integer promotions. All 690 // other types are unchanged by the integer promotions. 691 692 QualType PTy = Context.isPromotableBitField(E); 693 if (!PTy.isNull()) { 694 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 695 return E; 696 } 697 if (Ty->isPromotableIntegerType()) { 698 QualType PT = Context.getPromotedIntegerType(Ty); 699 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 700 return E; 701 } 702 } 703 return E; 704 } 705 706 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 707 /// do not have a prototype. Arguments that have type float or __fp16 708 /// are promoted to double. All other argument types are converted by 709 /// UsualUnaryConversions(). 710 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 711 QualType Ty = E->getType(); 712 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 713 714 ExprResult Res = UsualUnaryConversions(E); 715 if (Res.isInvalid()) 716 return ExprError(); 717 E = Res.get(); 718 719 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 720 // promote to double. 721 // Note that default argument promotion applies only to float (and 722 // half/fp16); it does not apply to _Float16. 723 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 724 if (BTy && (BTy->getKind() == BuiltinType::Half || 725 BTy->getKind() == BuiltinType::Float)) { 726 if (getLangOpts().OpenCL && 727 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 728 if (BTy->getKind() == BuiltinType::Half) { 729 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 730 } 731 } else { 732 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 733 } 734 } 735 736 // C++ performs lvalue-to-rvalue conversion as a default argument 737 // promotion, even on class types, but note: 738 // C++11 [conv.lval]p2: 739 // When an lvalue-to-rvalue conversion occurs in an unevaluated 740 // operand or a subexpression thereof the value contained in the 741 // referenced object is not accessed. Otherwise, if the glvalue 742 // has a class type, the conversion copy-initializes a temporary 743 // of type T from the glvalue and the result of the conversion 744 // is a prvalue for the temporary. 745 // FIXME: add some way to gate this entire thing for correctness in 746 // potentially potentially evaluated contexts. 747 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 748 ExprResult Temp = PerformCopyInitialization( 749 InitializedEntity::InitializeTemporary(E->getType()), 750 E->getExprLoc(), E); 751 if (Temp.isInvalid()) 752 return ExprError(); 753 E = Temp.get(); 754 } 755 756 return E; 757 } 758 759 /// Determine the degree of POD-ness for an expression. 760 /// Incomplete types are considered POD, since this check can be performed 761 /// when we're in an unevaluated context. 762 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 763 if (Ty->isIncompleteType()) { 764 // C++11 [expr.call]p7: 765 // After these conversions, if the argument does not have arithmetic, 766 // enumeration, pointer, pointer to member, or class type, the program 767 // is ill-formed. 768 // 769 // Since we've already performed array-to-pointer and function-to-pointer 770 // decay, the only such type in C++ is cv void. This also handles 771 // initializer lists as variadic arguments. 772 if (Ty->isVoidType()) 773 return VAK_Invalid; 774 775 if (Ty->isObjCObjectType()) 776 return VAK_Invalid; 777 return VAK_Valid; 778 } 779 780 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 781 return VAK_Invalid; 782 783 if (Ty.isCXX98PODType(Context)) 784 return VAK_Valid; 785 786 // C++11 [expr.call]p7: 787 // Passing a potentially-evaluated argument of class type (Clause 9) 788 // having a non-trivial copy constructor, a non-trivial move constructor, 789 // or a non-trivial destructor, with no corresponding parameter, 790 // is conditionally-supported with implementation-defined semantics. 791 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 792 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 793 if (!Record->hasNonTrivialCopyConstructor() && 794 !Record->hasNonTrivialMoveConstructor() && 795 !Record->hasNonTrivialDestructor()) 796 return VAK_ValidInCXX11; 797 798 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 799 return VAK_Valid; 800 801 if (Ty->isObjCObjectType()) 802 return VAK_Invalid; 803 804 if (getLangOpts().MSVCCompat) 805 return VAK_MSVCUndefined; 806 807 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 808 // permitted to reject them. We should consider doing so. 809 return VAK_Undefined; 810 } 811 812 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 813 // Don't allow one to pass an Objective-C interface to a vararg. 814 const QualType &Ty = E->getType(); 815 VarArgKind VAK = isValidVarArgType(Ty); 816 817 // Complain about passing non-POD types through varargs. 818 switch (VAK) { 819 case VAK_ValidInCXX11: 820 DiagRuntimeBehavior( 821 E->getLocStart(), nullptr, 822 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 823 << Ty << CT); 824 LLVM_FALLTHROUGH; 825 case VAK_Valid: 826 if (Ty->isRecordType()) { 827 // This is unlikely to be what the user intended. If the class has a 828 // 'c_str' member function, the user probably meant to call that. 829 DiagRuntimeBehavior(E->getLocStart(), nullptr, 830 PDiag(diag::warn_pass_class_arg_to_vararg) 831 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 832 } 833 break; 834 835 case VAK_Undefined: 836 case VAK_MSVCUndefined: 837 DiagRuntimeBehavior( 838 E->getLocStart(), 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->getLocStart(), 846 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT; 847 else if (Ty->isObjCObjectType()) 848 DiagRuntimeBehavior( 849 E->getLocStart(), nullptr, 850 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 851 << Ty << CT); 852 else 853 Diag(E->getLocStart(), 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->getLocStart()); 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(), 899 E->getLocStart(), None, 900 E->getLocEnd()); 901 if (Call.isInvalid()) 902 return ExprError(); 903 904 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 905 Call.get(), E); 906 if (Comma.isInvalid()) 907 return ExprError(); 908 return Comma.get(); 909 } 910 911 if (!getLangOpts().CPlusPlus && 912 RequireCompleteType(E->getExprLoc(), E->getType(), 913 diag::err_call_incomplete_argument)) 914 return ExprError(); 915 916 return E; 917 } 918 919 /// \brief Converts an integer to complex float type. Helper function of 920 /// UsualArithmeticConversions() 921 /// 922 /// \return false if the integer expression is an integer type and is 923 /// successfully converted to the complex type. 924 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 925 ExprResult &ComplexExpr, 926 QualType IntTy, 927 QualType ComplexTy, 928 bool SkipCast) { 929 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 930 if (SkipCast) return false; 931 if (IntTy->isIntegerType()) { 932 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 933 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 934 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 935 CK_FloatingRealToComplex); 936 } else { 937 assert(IntTy->isComplexIntegerType()); 938 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 939 CK_IntegralComplexToFloatingComplex); 940 } 941 return false; 942 } 943 944 /// \brief Handle arithmetic conversion with complex types. Helper function of 945 /// UsualArithmeticConversions() 946 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 947 ExprResult &RHS, QualType LHSType, 948 QualType RHSType, 949 bool IsCompAssign) { 950 // if we have an integer operand, the result is the complex type. 951 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 952 /*skipCast*/false)) 953 return LHSType; 954 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 955 /*skipCast*/IsCompAssign)) 956 return RHSType; 957 958 // This handles complex/complex, complex/float, or float/complex. 959 // When both operands are complex, the shorter operand is converted to the 960 // type of the longer, and that is the type of the result. This corresponds 961 // to what is done when combining two real floating-point operands. 962 // The fun begins when size promotion occur across type domains. 963 // From H&S 6.3.4: When one operand is complex and the other is a real 964 // floating-point type, the less precise type is converted, within it's 965 // real or complex domain, to the precision of the other type. For example, 966 // when combining a "long double" with a "double _Complex", the 967 // "double _Complex" is promoted to "long double _Complex". 968 969 // Compute the rank of the two types, regardless of whether they are complex. 970 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 971 972 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 973 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 974 QualType LHSElementType = 975 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 976 QualType RHSElementType = 977 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 978 979 QualType ResultType = S.Context.getComplexType(LHSElementType); 980 if (Order < 0) { 981 // Promote the precision of the LHS if not an assignment. 982 ResultType = S.Context.getComplexType(RHSElementType); 983 if (!IsCompAssign) { 984 if (LHSComplexType) 985 LHS = 986 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 987 else 988 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 989 } 990 } else if (Order > 0) { 991 // Promote the precision of the RHS. 992 if (RHSComplexType) 993 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 994 else 995 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 996 } 997 return ResultType; 998 } 999 1000 /// \brief Handle arithmetic conversion from integer to float. Helper function 1001 /// of UsualArithmeticConversions() 1002 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1003 ExprResult &IntExpr, 1004 QualType FloatTy, QualType IntTy, 1005 bool ConvertFloat, bool ConvertInt) { 1006 if (IntTy->isIntegerType()) { 1007 if (ConvertInt) 1008 // Convert intExpr to the lhs floating point type. 1009 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1010 CK_IntegralToFloating); 1011 return FloatTy; 1012 } 1013 1014 // Convert both sides to the appropriate complex float. 1015 assert(IntTy->isComplexIntegerType()); 1016 QualType result = S.Context.getComplexType(FloatTy); 1017 1018 // _Complex int -> _Complex float 1019 if (ConvertInt) 1020 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1021 CK_IntegralComplexToFloatingComplex); 1022 1023 // float -> _Complex float 1024 if (ConvertFloat) 1025 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1026 CK_FloatingRealToComplex); 1027 1028 return result; 1029 } 1030 1031 /// \brief Handle arithmethic conversion with floating point types. Helper 1032 /// function of UsualArithmeticConversions() 1033 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1034 ExprResult &RHS, QualType LHSType, 1035 QualType RHSType, bool IsCompAssign) { 1036 bool LHSFloat = LHSType->isRealFloatingType(); 1037 bool RHSFloat = RHSType->isRealFloatingType(); 1038 1039 // If we have two real floating types, convert the smaller operand 1040 // to the bigger result. 1041 if (LHSFloat && RHSFloat) { 1042 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1043 if (order > 0) { 1044 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1045 return LHSType; 1046 } 1047 1048 assert(order < 0 && "illegal float comparison"); 1049 if (!IsCompAssign) 1050 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1051 return RHSType; 1052 } 1053 1054 if (LHSFloat) { 1055 // Half FP has to be promoted to float unless it is natively supported 1056 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1057 LHSType = S.Context.FloatTy; 1058 1059 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1060 /*convertFloat=*/!IsCompAssign, 1061 /*convertInt=*/ true); 1062 } 1063 assert(RHSFloat); 1064 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1065 /*convertInt=*/ true, 1066 /*convertFloat=*/!IsCompAssign); 1067 } 1068 1069 /// \brief Diagnose attempts to convert between __float128 and long double if 1070 /// there is no support for such conversion. Helper function of 1071 /// UsualArithmeticConversions(). 1072 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1073 QualType RHSType) { 1074 /* No issue converting if at least one of the types is not a floating point 1075 type or the two types have the same rank. 1076 */ 1077 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1078 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1079 return false; 1080 1081 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1082 "The remaining types must be floating point types."); 1083 1084 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1085 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1086 1087 QualType LHSElemType = LHSComplex ? 1088 LHSComplex->getElementType() : LHSType; 1089 QualType RHSElemType = RHSComplex ? 1090 RHSComplex->getElementType() : RHSType; 1091 1092 // No issue if the two types have the same representation 1093 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1094 &S.Context.getFloatTypeSemantics(RHSElemType)) 1095 return false; 1096 1097 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1098 RHSElemType == S.Context.LongDoubleTy); 1099 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1100 RHSElemType == S.Context.Float128Ty); 1101 1102 // We've handled the situation where __float128 and long double have the same 1103 // representation. We allow all conversions for all possible long double types 1104 // except PPC's double double. 1105 return Float128AndLongDouble && 1106 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1107 &llvm::APFloat::PPCDoubleDouble()); 1108 } 1109 1110 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1111 1112 namespace { 1113 /// These helper callbacks are placed in an anonymous namespace to 1114 /// permit their use as function template parameters. 1115 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1116 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1117 } 1118 1119 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1120 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1121 CK_IntegralComplexCast); 1122 } 1123 } 1124 1125 /// \brief Handle integer arithmetic conversions. Helper function of 1126 /// UsualArithmeticConversions() 1127 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1128 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 // The rules for this case are in C99 6.3.1.8 1132 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1133 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1134 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1135 if (LHSSigned == RHSSigned) { 1136 // Same signedness; use the higher-ranked type 1137 if (order >= 0) { 1138 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1139 return LHSType; 1140 } else if (!IsCompAssign) 1141 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1142 return RHSType; 1143 } else if (order != (LHSSigned ? 1 : -1)) { 1144 // The unsigned type has greater than or equal rank to the 1145 // signed type, so use the unsigned type 1146 if (RHSSigned) { 1147 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1148 return LHSType; 1149 } else if (!IsCompAssign) 1150 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1151 return RHSType; 1152 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1153 // The two types are different widths; if we are here, that 1154 // means the signed type is larger than the unsigned type, so 1155 // use the signed type. 1156 if (LHSSigned) { 1157 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1158 return LHSType; 1159 } else if (!IsCompAssign) 1160 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1161 return RHSType; 1162 } else { 1163 // The signed type is higher-ranked than the unsigned type, 1164 // but isn't actually any bigger (like unsigned int and long 1165 // on most 32-bit systems). Use the unsigned type corresponding 1166 // to the signed type. 1167 QualType result = 1168 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1169 RHS = (*doRHSCast)(S, RHS.get(), result); 1170 if (!IsCompAssign) 1171 LHS = (*doLHSCast)(S, LHS.get(), result); 1172 return result; 1173 } 1174 } 1175 1176 /// \brief Handle conversions with GCC complex int extension. Helper function 1177 /// of UsualArithmeticConversions() 1178 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1179 ExprResult &RHS, QualType LHSType, 1180 QualType RHSType, 1181 bool IsCompAssign) { 1182 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1183 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1184 1185 if (LHSComplexInt && RHSComplexInt) { 1186 QualType LHSEltType = LHSComplexInt->getElementType(); 1187 QualType RHSEltType = RHSComplexInt->getElementType(); 1188 QualType ScalarType = 1189 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1190 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1191 1192 return S.Context.getComplexType(ScalarType); 1193 } 1194 1195 if (LHSComplexInt) { 1196 QualType LHSEltType = LHSComplexInt->getElementType(); 1197 QualType ScalarType = 1198 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1199 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1200 QualType ComplexType = S.Context.getComplexType(ScalarType); 1201 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1202 CK_IntegralRealToComplex); 1203 1204 return ComplexType; 1205 } 1206 1207 assert(RHSComplexInt); 1208 1209 QualType RHSEltType = RHSComplexInt->getElementType(); 1210 QualType ScalarType = 1211 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1212 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1213 QualType ComplexType = S.Context.getComplexType(ScalarType); 1214 1215 if (!IsCompAssign) 1216 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1217 CK_IntegralRealToComplex); 1218 return ComplexType; 1219 } 1220 1221 /// UsualArithmeticConversions - Performs various conversions that are common to 1222 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1223 /// routine returns the first non-arithmetic type found. The client is 1224 /// responsible for emitting appropriate error diagnostics. 1225 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1226 bool IsCompAssign) { 1227 if (!IsCompAssign) { 1228 LHS = UsualUnaryConversions(LHS.get()); 1229 if (LHS.isInvalid()) 1230 return QualType(); 1231 } 1232 1233 RHS = UsualUnaryConversions(RHS.get()); 1234 if (RHS.isInvalid()) 1235 return QualType(); 1236 1237 // For conversion purposes, we ignore any qualifiers. 1238 // For example, "const float" and "float" are equivalent. 1239 QualType LHSType = 1240 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1241 QualType RHSType = 1242 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1243 1244 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1245 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1246 LHSType = AtomicLHS->getValueType(); 1247 1248 // If both types are identical, no conversion is needed. 1249 if (LHSType == RHSType) 1250 return LHSType; 1251 1252 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1253 // The caller can deal with this (e.g. pointer + int). 1254 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1255 return QualType(); 1256 1257 // Apply unary and bitfield promotions to the LHS's type. 1258 QualType LHSUnpromotedType = LHSType; 1259 if (LHSType->isPromotableIntegerType()) 1260 LHSType = Context.getPromotedIntegerType(LHSType); 1261 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1262 if (!LHSBitfieldPromoteTy.isNull()) 1263 LHSType = LHSBitfieldPromoteTy; 1264 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1265 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1266 1267 // If both types are identical, no conversion is needed. 1268 if (LHSType == RHSType) 1269 return LHSType; 1270 1271 // At this point, we have two different arithmetic types. 1272 1273 // Diagnose attempts to convert between __float128 and long double where 1274 // such conversions currently can't be handled. 1275 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1276 return QualType(); 1277 1278 // Handle complex types first (C99 6.3.1.8p1). 1279 if (LHSType->isComplexType() || RHSType->isComplexType()) 1280 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1281 IsCompAssign); 1282 1283 // Now handle "real" floating types (i.e. float, double, long double). 1284 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1285 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1286 IsCompAssign); 1287 1288 // Handle GCC complex int extension. 1289 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1290 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1291 IsCompAssign); 1292 1293 // Finally, we have two differing integer types. 1294 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1295 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1296 } 1297 1298 1299 //===----------------------------------------------------------------------===// 1300 // Semantic Analysis for various Expression Types 1301 //===----------------------------------------------------------------------===// 1302 1303 1304 ExprResult 1305 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1306 SourceLocation DefaultLoc, 1307 SourceLocation RParenLoc, 1308 Expr *ControllingExpr, 1309 ArrayRef<ParsedType> ArgTypes, 1310 ArrayRef<Expr *> ArgExprs) { 1311 unsigned NumAssocs = ArgTypes.size(); 1312 assert(NumAssocs == ArgExprs.size()); 1313 1314 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1315 for (unsigned i = 0; i < NumAssocs; ++i) { 1316 if (ArgTypes[i]) 1317 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1318 else 1319 Types[i] = nullptr; 1320 } 1321 1322 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1323 ControllingExpr, 1324 llvm::makeArrayRef(Types, NumAssocs), 1325 ArgExprs); 1326 delete [] Types; 1327 return ER; 1328 } 1329 1330 ExprResult 1331 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1332 SourceLocation DefaultLoc, 1333 SourceLocation RParenLoc, 1334 Expr *ControllingExpr, 1335 ArrayRef<TypeSourceInfo *> Types, 1336 ArrayRef<Expr *> Exprs) { 1337 unsigned NumAssocs = Types.size(); 1338 assert(NumAssocs == Exprs.size()); 1339 1340 // Decay and strip qualifiers for the controlling expression type, and handle 1341 // placeholder type replacement. See committee discussion from WG14 DR423. 1342 { 1343 EnterExpressionEvaluationContext Unevaluated( 1344 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1345 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1346 if (R.isInvalid()) 1347 return ExprError(); 1348 ControllingExpr = R.get(); 1349 } 1350 1351 // The controlling expression is an unevaluated operand, so side effects are 1352 // likely unintended. 1353 if (!inTemplateInstantiation() && 1354 ControllingExpr->HasSideEffects(Context, false)) 1355 Diag(ControllingExpr->getExprLoc(), 1356 diag::warn_side_effects_unevaluated_context); 1357 1358 bool TypeErrorFound = false, 1359 IsResultDependent = ControllingExpr->isTypeDependent(), 1360 ContainsUnexpandedParameterPack 1361 = ControllingExpr->containsUnexpandedParameterPack(); 1362 1363 for (unsigned i = 0; i < NumAssocs; ++i) { 1364 if (Exprs[i]->containsUnexpandedParameterPack()) 1365 ContainsUnexpandedParameterPack = true; 1366 1367 if (Types[i]) { 1368 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1369 ContainsUnexpandedParameterPack = true; 1370 1371 if (Types[i]->getType()->isDependentType()) { 1372 IsResultDependent = true; 1373 } else { 1374 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1375 // complete object type other than a variably modified type." 1376 unsigned D = 0; 1377 if (Types[i]->getType()->isIncompleteType()) 1378 D = diag::err_assoc_type_incomplete; 1379 else if (!Types[i]->getType()->isObjectType()) 1380 D = diag::err_assoc_type_nonobject; 1381 else if (Types[i]->getType()->isVariablyModifiedType()) 1382 D = diag::err_assoc_type_variably_modified; 1383 1384 if (D != 0) { 1385 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1386 << Types[i]->getTypeLoc().getSourceRange() 1387 << Types[i]->getType(); 1388 TypeErrorFound = true; 1389 } 1390 1391 // C11 6.5.1.1p2 "No two generic associations in the same generic 1392 // selection shall specify compatible types." 1393 for (unsigned j = i+1; j < NumAssocs; ++j) 1394 if (Types[j] && !Types[j]->getType()->isDependentType() && 1395 Context.typesAreCompatible(Types[i]->getType(), 1396 Types[j]->getType())) { 1397 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1398 diag::err_assoc_compatible_types) 1399 << Types[j]->getTypeLoc().getSourceRange() 1400 << Types[j]->getType() 1401 << Types[i]->getType(); 1402 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1403 diag::note_compat_assoc) 1404 << Types[i]->getTypeLoc().getSourceRange() 1405 << Types[i]->getType(); 1406 TypeErrorFound = true; 1407 } 1408 } 1409 } 1410 } 1411 if (TypeErrorFound) 1412 return ExprError(); 1413 1414 // If we determined that the generic selection is result-dependent, don't 1415 // try to compute the result expression. 1416 if (IsResultDependent) 1417 return new (Context) GenericSelectionExpr( 1418 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1419 ContainsUnexpandedParameterPack); 1420 1421 SmallVector<unsigned, 1> CompatIndices; 1422 unsigned DefaultIndex = -1U; 1423 for (unsigned i = 0; i < NumAssocs; ++i) { 1424 if (!Types[i]) 1425 DefaultIndex = i; 1426 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1427 Types[i]->getType())) 1428 CompatIndices.push_back(i); 1429 } 1430 1431 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1432 // type compatible with at most one of the types named in its generic 1433 // association list." 1434 if (CompatIndices.size() > 1) { 1435 // We strip parens here because the controlling expression is typically 1436 // parenthesized in macro definitions. 1437 ControllingExpr = ControllingExpr->IgnoreParens(); 1438 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1439 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1440 << (unsigned) CompatIndices.size(); 1441 for (unsigned I : CompatIndices) { 1442 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1443 diag::note_compat_assoc) 1444 << Types[I]->getTypeLoc().getSourceRange() 1445 << Types[I]->getType(); 1446 } 1447 return ExprError(); 1448 } 1449 1450 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1451 // its controlling expression shall have type compatible with exactly one of 1452 // the types named in its generic association list." 1453 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1454 // We strip parens here because the controlling expression is typically 1455 // parenthesized in macro definitions. 1456 ControllingExpr = ControllingExpr->IgnoreParens(); 1457 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1458 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1459 return ExprError(); 1460 } 1461 1462 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1463 // type name that is compatible with the type of the controlling expression, 1464 // then the result expression of the generic selection is the expression 1465 // in that generic association. Otherwise, the result expression of the 1466 // generic selection is the expression in the default generic association." 1467 unsigned ResultIndex = 1468 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1469 1470 return new (Context) GenericSelectionExpr( 1471 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1472 ContainsUnexpandedParameterPack, ResultIndex); 1473 } 1474 1475 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1476 /// location of the token and the offset of the ud-suffix within it. 1477 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1478 unsigned Offset) { 1479 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1480 S.getLangOpts()); 1481 } 1482 1483 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1484 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1485 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1486 IdentifierInfo *UDSuffix, 1487 SourceLocation UDSuffixLoc, 1488 ArrayRef<Expr*> Args, 1489 SourceLocation LitEndLoc) { 1490 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1491 1492 QualType ArgTy[2]; 1493 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1494 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1495 if (ArgTy[ArgIdx]->isArrayType()) 1496 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1497 } 1498 1499 DeclarationName OpName = 1500 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1501 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1502 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1503 1504 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1505 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1506 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1507 /*AllowStringTemplate*/ false, 1508 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1509 return ExprError(); 1510 1511 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1512 } 1513 1514 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1515 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1516 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1517 /// multiple tokens. However, the common case is that StringToks points to one 1518 /// string. 1519 /// 1520 ExprResult 1521 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1522 assert(!StringToks.empty() && "Must have at least one string!"); 1523 1524 StringLiteralParser Literal(StringToks, PP); 1525 if (Literal.hadError) 1526 return ExprError(); 1527 1528 SmallVector<SourceLocation, 4> StringTokLocs; 1529 for (const Token &Tok : StringToks) 1530 StringTokLocs.push_back(Tok.getLocation()); 1531 1532 QualType CharTy = Context.CharTy; 1533 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1534 if (Literal.isWide()) { 1535 CharTy = Context.getWideCharType(); 1536 Kind = StringLiteral::Wide; 1537 } else if (Literal.isUTF8()) { 1538 Kind = StringLiteral::UTF8; 1539 } else if (Literal.isUTF16()) { 1540 CharTy = Context.Char16Ty; 1541 Kind = StringLiteral::UTF16; 1542 } else if (Literal.isUTF32()) { 1543 CharTy = Context.Char32Ty; 1544 Kind = StringLiteral::UTF32; 1545 } else if (Literal.isPascal()) { 1546 CharTy = Context.UnsignedCharTy; 1547 } 1548 1549 QualType CharTyConst = CharTy; 1550 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1551 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1552 CharTyConst.addConst(); 1553 1554 // Get an array type for the string, according to C99 6.4.5. This includes 1555 // the nul terminator character as well as the string length for pascal 1556 // strings. 1557 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1558 llvm::APInt(32, Literal.GetNumStringChars()+1), 1559 ArrayType::Normal, 0); 1560 1561 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1562 if (getLangOpts().OpenCL) { 1563 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1564 } 1565 1566 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1567 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1568 Kind, Literal.Pascal, StrTy, 1569 &StringTokLocs[0], 1570 StringTokLocs.size()); 1571 if (Literal.getUDSuffix().empty()) 1572 return Lit; 1573 1574 // We're building a user-defined literal. 1575 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1576 SourceLocation UDSuffixLoc = 1577 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1578 Literal.getUDSuffixOffset()); 1579 1580 // Make sure we're allowed user-defined literals here. 1581 if (!UDLScope) 1582 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1583 1584 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1585 // operator "" X (str, len) 1586 QualType SizeType = Context.getSizeType(); 1587 1588 DeclarationName OpName = 1589 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1590 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1591 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1592 1593 QualType ArgTy[] = { 1594 Context.getArrayDecayedType(StrTy), SizeType 1595 }; 1596 1597 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1598 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1599 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1600 /*AllowStringTemplate*/ true, 1601 /*DiagnoseMissing*/ true)) { 1602 1603 case LOLR_Cooked: { 1604 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1605 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1606 StringTokLocs[0]); 1607 Expr *Args[] = { Lit, LenArg }; 1608 1609 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1610 } 1611 1612 case LOLR_StringTemplate: { 1613 TemplateArgumentListInfo ExplicitArgs; 1614 1615 unsigned CharBits = Context.getIntWidth(CharTy); 1616 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1617 llvm::APSInt Value(CharBits, CharIsUnsigned); 1618 1619 TemplateArgument TypeArg(CharTy); 1620 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1621 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1622 1623 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1624 Value = Lit->getCodeUnit(I); 1625 TemplateArgument Arg(Context, Value, CharTy); 1626 TemplateArgumentLocInfo ArgInfo; 1627 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1628 } 1629 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1630 &ExplicitArgs); 1631 } 1632 case LOLR_Raw: 1633 case LOLR_Template: 1634 case LOLR_ErrorNoDiagnostic: 1635 llvm_unreachable("unexpected literal operator lookup result"); 1636 case LOLR_Error: 1637 return ExprError(); 1638 } 1639 llvm_unreachable("unexpected literal operator lookup result"); 1640 } 1641 1642 ExprResult 1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1644 SourceLocation Loc, 1645 const CXXScopeSpec *SS) { 1646 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1647 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1648 } 1649 1650 /// BuildDeclRefExpr - Build an expression that references a 1651 /// declaration that does not require a closure capture. 1652 ExprResult 1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1654 const DeclarationNameInfo &NameInfo, 1655 const CXXScopeSpec *SS, NamedDecl *FoundD, 1656 const TemplateArgumentListInfo *TemplateArgs) { 1657 bool RefersToCapturedVariable = 1658 isa<VarDecl>(D) && 1659 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1660 1661 DeclRefExpr *E; 1662 if (isa<VarTemplateSpecializationDecl>(D)) { 1663 VarTemplateSpecializationDecl *VarSpec = 1664 cast<VarTemplateSpecializationDecl>(D); 1665 1666 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1667 : NestedNameSpecifierLoc(), 1668 VarSpec->getTemplateKeywordLoc(), D, 1669 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1670 FoundD, TemplateArgs); 1671 } else { 1672 assert(!TemplateArgs && "No template arguments for non-variable" 1673 " template specialization references"); 1674 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1675 : NestedNameSpecifierLoc(), 1676 SourceLocation(), D, RefersToCapturedVariable, 1677 NameInfo, Ty, VK, FoundD); 1678 } 1679 1680 MarkDeclRefReferenced(E); 1681 1682 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1683 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1684 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1685 getCurFunction()->recordUseOfWeak(E); 1686 1687 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1688 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1689 FD = IFD->getAnonField(); 1690 if (FD) { 1691 UnusedPrivateFields.remove(FD); 1692 // Just in case we're building an illegal pointer-to-member. 1693 if (FD->isBitField()) 1694 E->setObjectKind(OK_BitField); 1695 } 1696 1697 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1698 // designates a bit-field. 1699 if (auto *BD = dyn_cast<BindingDecl>(D)) 1700 if (auto *BE = BD->getBinding()) 1701 E->setObjectKind(BE->getObjectKind()); 1702 1703 return E; 1704 } 1705 1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1707 /// possibly a list of template arguments. 1708 /// 1709 /// If this produces template arguments, it is permitted to call 1710 /// DecomposeTemplateName. 1711 /// 1712 /// This actually loses a lot of source location information for 1713 /// non-standard name kinds; we should consider preserving that in 1714 /// some way. 1715 void 1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1717 TemplateArgumentListInfo &Buffer, 1718 DeclarationNameInfo &NameInfo, 1719 const TemplateArgumentListInfo *&TemplateArgs) { 1720 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1721 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1722 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1723 1724 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1725 Id.TemplateId->NumArgs); 1726 translateTemplateArguments(TemplateArgsPtr, Buffer); 1727 1728 TemplateName TName = Id.TemplateId->Template.get(); 1729 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1730 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1731 TemplateArgs = &Buffer; 1732 } else { 1733 NameInfo = GetNameFromUnqualifiedId(Id); 1734 TemplateArgs = nullptr; 1735 } 1736 } 1737 1738 static void emitEmptyLookupTypoDiagnostic( 1739 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1740 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1741 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1742 DeclContext *Ctx = 1743 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1744 if (!TC) { 1745 // Emit a special diagnostic for failed member lookups. 1746 // FIXME: computing the declaration context might fail here (?) 1747 if (Ctx) 1748 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1749 << SS.getRange(); 1750 else 1751 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1752 return; 1753 } 1754 1755 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1756 bool DroppedSpecifier = 1757 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1758 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1759 ? diag::note_implicit_param_decl 1760 : diag::note_previous_decl; 1761 if (!Ctx) 1762 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1763 SemaRef.PDiag(NoteID)); 1764 else 1765 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1766 << Typo << Ctx << DroppedSpecifier 1767 << SS.getRange(), 1768 SemaRef.PDiag(NoteID)); 1769 } 1770 1771 /// Diagnose an empty lookup. 1772 /// 1773 /// \return false if new lookup candidates were found 1774 bool 1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1776 std::unique_ptr<CorrectionCandidateCallback> CCC, 1777 TemplateArgumentListInfo *ExplicitTemplateArgs, 1778 ArrayRef<Expr *> Args, TypoExpr **Out) { 1779 DeclarationName Name = R.getLookupName(); 1780 1781 unsigned diagnostic = diag::err_undeclared_var_use; 1782 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1783 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1784 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1785 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1786 diagnostic = diag::err_undeclared_use; 1787 diagnostic_suggest = diag::err_undeclared_use_suggest; 1788 } 1789 1790 // If the original lookup was an unqualified lookup, fake an 1791 // unqualified lookup. This is useful when (for example) the 1792 // original lookup would not have found something because it was a 1793 // dependent name. 1794 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1795 while (DC) { 1796 if (isa<CXXRecordDecl>(DC)) { 1797 LookupQualifiedName(R, DC); 1798 1799 if (!R.empty()) { 1800 // Don't give errors about ambiguities in this lookup. 1801 R.suppressDiagnostics(); 1802 1803 // During a default argument instantiation the CurContext points 1804 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1805 // function parameter list, hence add an explicit check. 1806 bool isDefaultArgument = 1807 !CodeSynthesisContexts.empty() && 1808 CodeSynthesisContexts.back().Kind == 1809 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1810 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1811 bool isInstance = CurMethod && 1812 CurMethod->isInstance() && 1813 DC == CurMethod->getParent() && !isDefaultArgument; 1814 1815 // Give a code modification hint to insert 'this->'. 1816 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1817 // Actually quite difficult! 1818 if (getLangOpts().MSVCCompat) 1819 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1820 if (isInstance) { 1821 Diag(R.getNameLoc(), diagnostic) << Name 1822 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1823 CheckCXXThisCapture(R.getNameLoc()); 1824 } else { 1825 Diag(R.getNameLoc(), diagnostic) << Name; 1826 } 1827 1828 // Do we really want to note all of these? 1829 for (NamedDecl *D : R) 1830 Diag(D->getLocation(), diag::note_dependent_var_use); 1831 1832 // Return true if we are inside a default argument instantiation 1833 // and the found name refers to an instance member function, otherwise 1834 // the function calling DiagnoseEmptyLookup will try to create an 1835 // implicit member call and this is wrong for default argument. 1836 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1837 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1838 return true; 1839 } 1840 1841 // Tell the callee to try to recover. 1842 return false; 1843 } 1844 1845 R.clear(); 1846 } 1847 1848 // In Microsoft mode, if we are performing lookup from within a friend 1849 // function definition declared at class scope then we must set 1850 // DC to the lexical parent to be able to search into the parent 1851 // class. 1852 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1853 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1854 DC->getLexicalParent()->isRecord()) 1855 DC = DC->getLexicalParent(); 1856 else 1857 DC = DC->getParent(); 1858 } 1859 1860 // We didn't find anything, so try to correct for a typo. 1861 TypoCorrection Corrected; 1862 if (S && Out) { 1863 SourceLocation TypoLoc = R.getNameLoc(); 1864 assert(!ExplicitTemplateArgs && 1865 "Diagnosing an empty lookup with explicit template args!"); 1866 *Out = CorrectTypoDelayed( 1867 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1868 [=](const TypoCorrection &TC) { 1869 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1870 diagnostic, diagnostic_suggest); 1871 }, 1872 nullptr, CTK_ErrorRecovery); 1873 if (*Out) 1874 return true; 1875 } else if (S && (Corrected = 1876 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1877 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1878 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1879 bool DroppedSpecifier = 1880 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1881 R.setLookupName(Corrected.getCorrection()); 1882 1883 bool AcceptableWithRecovery = false; 1884 bool AcceptableWithoutRecovery = false; 1885 NamedDecl *ND = Corrected.getFoundDecl(); 1886 if (ND) { 1887 if (Corrected.isOverloaded()) { 1888 OverloadCandidateSet OCS(R.getNameLoc(), 1889 OverloadCandidateSet::CSK_Normal); 1890 OverloadCandidateSet::iterator Best; 1891 for (NamedDecl *CD : Corrected) { 1892 if (FunctionTemplateDecl *FTD = 1893 dyn_cast<FunctionTemplateDecl>(CD)) 1894 AddTemplateOverloadCandidate( 1895 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1896 Args, OCS); 1897 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1898 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1899 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1900 Args, OCS); 1901 } 1902 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1903 case OR_Success: 1904 ND = Best->FoundDecl; 1905 Corrected.setCorrectionDecl(ND); 1906 break; 1907 default: 1908 // FIXME: Arbitrarily pick the first declaration for the note. 1909 Corrected.setCorrectionDecl(ND); 1910 break; 1911 } 1912 } 1913 R.addDecl(ND); 1914 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1915 CXXRecordDecl *Record = nullptr; 1916 if (Corrected.getCorrectionSpecifier()) { 1917 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1918 Record = Ty->getAsCXXRecordDecl(); 1919 } 1920 if (!Record) 1921 Record = cast<CXXRecordDecl>( 1922 ND->getDeclContext()->getRedeclContext()); 1923 R.setNamingClass(Record); 1924 } 1925 1926 auto *UnderlyingND = ND->getUnderlyingDecl(); 1927 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1928 isa<FunctionTemplateDecl>(UnderlyingND); 1929 // FIXME: If we ended up with a typo for a type name or 1930 // Objective-C class name, we're in trouble because the parser 1931 // is in the wrong place to recover. Suggest the typo 1932 // correction, but don't make it a fix-it since we're not going 1933 // to recover well anyway. 1934 AcceptableWithoutRecovery = 1935 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1936 } else { 1937 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1938 // because we aren't able to recover. 1939 AcceptableWithoutRecovery = true; 1940 } 1941 1942 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1943 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1944 ? diag::note_implicit_param_decl 1945 : diag::note_previous_decl; 1946 if (SS.isEmpty()) 1947 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1948 PDiag(NoteID), AcceptableWithRecovery); 1949 else 1950 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1951 << Name << computeDeclContext(SS, false) 1952 << DroppedSpecifier << SS.getRange(), 1953 PDiag(NoteID), AcceptableWithRecovery); 1954 1955 // Tell the callee whether to try to recover. 1956 return !AcceptableWithRecovery; 1957 } 1958 } 1959 R.clear(); 1960 1961 // Emit a special diagnostic for failed member lookups. 1962 // FIXME: computing the declaration context might fail here (?) 1963 if (!SS.isEmpty()) { 1964 Diag(R.getNameLoc(), diag::err_no_member) 1965 << Name << computeDeclContext(SS, false) 1966 << SS.getRange(); 1967 return true; 1968 } 1969 1970 // Give up, we can't recover. 1971 Diag(R.getNameLoc(), diagnostic) << Name; 1972 return true; 1973 } 1974 1975 /// In Microsoft mode, if we are inside a template class whose parent class has 1976 /// dependent base classes, and we can't resolve an unqualified identifier, then 1977 /// assume the identifier is a member of a dependent base class. We can only 1978 /// recover successfully in static methods, instance methods, and other contexts 1979 /// where 'this' is available. This doesn't precisely match MSVC's 1980 /// instantiation model, but it's close enough. 1981 static Expr * 1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1983 DeclarationNameInfo &NameInfo, 1984 SourceLocation TemplateKWLoc, 1985 const TemplateArgumentListInfo *TemplateArgs) { 1986 // Only try to recover from lookup into dependent bases in static methods or 1987 // contexts where 'this' is available. 1988 QualType ThisType = S.getCurrentThisType(); 1989 const CXXRecordDecl *RD = nullptr; 1990 if (!ThisType.isNull()) 1991 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1992 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1993 RD = MD->getParent(); 1994 if (!RD || !RD->hasAnyDependentBases()) 1995 return nullptr; 1996 1997 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1998 // is available, suggest inserting 'this->' as a fixit. 1999 SourceLocation Loc = NameInfo.getLoc(); 2000 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2001 DB << NameInfo.getName() << RD; 2002 2003 if (!ThisType.isNull()) { 2004 DB << FixItHint::CreateInsertion(Loc, "this->"); 2005 return CXXDependentScopeMemberExpr::Create( 2006 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2007 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2008 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2009 } 2010 2011 // Synthesize a fake NNS that points to the derived class. This will 2012 // perform name lookup during template instantiation. 2013 CXXScopeSpec SS; 2014 auto *NNS = 2015 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2016 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2017 return DependentScopeDeclRefExpr::Create( 2018 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2019 TemplateArgs); 2020 } 2021 2022 ExprResult 2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2024 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2025 bool HasTrailingLParen, bool IsAddressOfOperand, 2026 std::unique_ptr<CorrectionCandidateCallback> CCC, 2027 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2028 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2029 "cannot be direct & operand and have a trailing lparen"); 2030 if (SS.isInvalid()) 2031 return ExprError(); 2032 2033 TemplateArgumentListInfo TemplateArgsBuffer; 2034 2035 // Decompose the UnqualifiedId into the following data. 2036 DeclarationNameInfo NameInfo; 2037 const TemplateArgumentListInfo *TemplateArgs; 2038 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2039 2040 DeclarationName Name = NameInfo.getName(); 2041 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2042 SourceLocation NameLoc = NameInfo.getLoc(); 2043 2044 if (II && II->isEditorPlaceholder()) { 2045 // FIXME: When typed placeholders are supported we can create a typed 2046 // placeholder expression node. 2047 return ExprError(); 2048 } 2049 2050 // C++ [temp.dep.expr]p3: 2051 // An id-expression is type-dependent if it contains: 2052 // -- an identifier that was declared with a dependent type, 2053 // (note: handled after lookup) 2054 // -- a template-id that is dependent, 2055 // (note: handled in BuildTemplateIdExpr) 2056 // -- a conversion-function-id that specifies a dependent type, 2057 // -- a nested-name-specifier that contains a class-name that 2058 // names a dependent type. 2059 // Determine whether this is a member of an unknown specialization; 2060 // we need to handle these differently. 2061 bool DependentID = false; 2062 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2063 Name.getCXXNameType()->isDependentType()) { 2064 DependentID = true; 2065 } else if (SS.isSet()) { 2066 if (DeclContext *DC = computeDeclContext(SS, false)) { 2067 if (RequireCompleteDeclContext(SS, DC)) 2068 return ExprError(); 2069 } else { 2070 DependentID = true; 2071 } 2072 } 2073 2074 if (DependentID) 2075 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2076 IsAddressOfOperand, TemplateArgs); 2077 2078 // Perform the required lookup. 2079 LookupResult R(*this, NameInfo, 2080 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2081 ? LookupObjCImplicitSelfParam 2082 : LookupOrdinaryName); 2083 if (TemplateArgs) { 2084 // Lookup the template name again to correctly establish the context in 2085 // which it was found. This is really unfortunate as we already did the 2086 // lookup to determine that it was a template name in the first place. If 2087 // this becomes a performance hit, we can work harder to preserve those 2088 // results until we get here but it's likely not worth it. 2089 bool MemberOfUnknownSpecialization; 2090 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2091 MemberOfUnknownSpecialization); 2092 2093 if (MemberOfUnknownSpecialization || 2094 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2095 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2096 IsAddressOfOperand, TemplateArgs); 2097 } else { 2098 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2099 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2100 2101 // If the result might be in a dependent base class, this is a dependent 2102 // id-expression. 2103 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2104 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2105 IsAddressOfOperand, TemplateArgs); 2106 2107 // If this reference is in an Objective-C method, then we need to do 2108 // some special Objective-C lookup, too. 2109 if (IvarLookupFollowUp) { 2110 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2111 if (E.isInvalid()) 2112 return ExprError(); 2113 2114 if (Expr *Ex = E.getAs<Expr>()) 2115 return Ex; 2116 } 2117 } 2118 2119 if (R.isAmbiguous()) 2120 return ExprError(); 2121 2122 // This could be an implicitly declared function reference (legal in C90, 2123 // extension in C99, forbidden in C++). 2124 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2125 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2126 if (D) R.addDecl(D); 2127 } 2128 2129 // Determine whether this name might be a candidate for 2130 // argument-dependent lookup. 2131 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2132 2133 if (R.empty() && !ADL) { 2134 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2135 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2136 TemplateKWLoc, TemplateArgs)) 2137 return E; 2138 } 2139 2140 // Don't diagnose an empty lookup for inline assembly. 2141 if (IsInlineAsmIdentifier) 2142 return ExprError(); 2143 2144 // If this name wasn't predeclared and if this is not a function 2145 // call, diagnose the problem. 2146 TypoExpr *TE = nullptr; 2147 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2148 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2149 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2150 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2151 "Typo correction callback misconfigured"); 2152 if (CCC) { 2153 // Make sure the callback knows what the typo being diagnosed is. 2154 CCC->setTypoName(II); 2155 if (SS.isValid()) 2156 CCC->setTypoNNS(SS.getScopeRep()); 2157 } 2158 if (DiagnoseEmptyLookup(S, SS, R, 2159 CCC ? std::move(CCC) : std::move(DefaultValidator), 2160 nullptr, None, &TE)) { 2161 if (TE && KeywordReplacement) { 2162 auto &State = getTypoExprState(TE); 2163 auto BestTC = State.Consumer->getNextCorrection(); 2164 if (BestTC.isKeyword()) { 2165 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2166 if (State.DiagHandler) 2167 State.DiagHandler(BestTC); 2168 KeywordReplacement->startToken(); 2169 KeywordReplacement->setKind(II->getTokenID()); 2170 KeywordReplacement->setIdentifierInfo(II); 2171 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2172 // Clean up the state associated with the TypoExpr, since it has 2173 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2174 clearDelayedTypo(TE); 2175 // Signal that a correction to a keyword was performed by returning a 2176 // valid-but-null ExprResult. 2177 return (Expr*)nullptr; 2178 } 2179 State.Consumer->resetCorrectionStream(); 2180 } 2181 return TE ? TE : ExprError(); 2182 } 2183 2184 assert(!R.empty() && 2185 "DiagnoseEmptyLookup returned false but added no results"); 2186 2187 // If we found an Objective-C instance variable, let 2188 // LookupInObjCMethod build the appropriate expression to 2189 // reference the ivar. 2190 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2191 R.clear(); 2192 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2193 // In a hopelessly buggy code, Objective-C instance variable 2194 // lookup fails and no expression will be built to reference it. 2195 if (!E.isInvalid() && !E.get()) 2196 return ExprError(); 2197 return E; 2198 } 2199 } 2200 2201 // This is guaranteed from this point on. 2202 assert(!R.empty() || ADL); 2203 2204 // Check whether this might be a C++ implicit instance member access. 2205 // C++ [class.mfct.non-static]p3: 2206 // When an id-expression that is not part of a class member access 2207 // syntax and not used to form a pointer to member is used in the 2208 // body of a non-static member function of class X, if name lookup 2209 // resolves the name in the id-expression to a non-static non-type 2210 // member of some class C, the id-expression is transformed into a 2211 // class member access expression using (*this) as the 2212 // postfix-expression to the left of the . operator. 2213 // 2214 // But we don't actually need to do this for '&' operands if R 2215 // resolved to a function or overloaded function set, because the 2216 // expression is ill-formed if it actually works out to be a 2217 // non-static member function: 2218 // 2219 // C++ [expr.ref]p4: 2220 // Otherwise, if E1.E2 refers to a non-static member function. . . 2221 // [t]he expression can be used only as the left-hand operand of a 2222 // member function call. 2223 // 2224 // There are other safeguards against such uses, but it's important 2225 // to get this right here so that we don't end up making a 2226 // spuriously dependent expression if we're inside a dependent 2227 // instance method. 2228 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2229 bool MightBeImplicitMember; 2230 if (!IsAddressOfOperand) 2231 MightBeImplicitMember = true; 2232 else if (!SS.isEmpty()) 2233 MightBeImplicitMember = false; 2234 else if (R.isOverloadedResult()) 2235 MightBeImplicitMember = false; 2236 else if (R.isUnresolvableResult()) 2237 MightBeImplicitMember = true; 2238 else 2239 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2240 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2241 isa<MSPropertyDecl>(R.getFoundDecl()); 2242 2243 if (MightBeImplicitMember) 2244 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2245 R, TemplateArgs, S); 2246 } 2247 2248 if (TemplateArgs || TemplateKWLoc.isValid()) { 2249 2250 // In C++1y, if this is a variable template id, then check it 2251 // in BuildTemplateIdExpr(). 2252 // The single lookup result must be a variable template declaration. 2253 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2254 Id.TemplateId->Kind == TNK_Var_template) { 2255 assert(R.getAsSingle<VarTemplateDecl>() && 2256 "There should only be one declaration found."); 2257 } 2258 2259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2260 } 2261 2262 return BuildDeclarationNameExpr(SS, R, ADL); 2263 } 2264 2265 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2266 /// declaration name, generally during template instantiation. 2267 /// There's a large number of things which don't need to be done along 2268 /// this path. 2269 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2270 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2271 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2272 DeclContext *DC = computeDeclContext(SS, false); 2273 if (!DC) 2274 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2275 NameInfo, /*TemplateArgs=*/nullptr); 2276 2277 if (RequireCompleteDeclContext(SS, DC)) 2278 return ExprError(); 2279 2280 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2281 LookupQualifiedName(R, DC); 2282 2283 if (R.isAmbiguous()) 2284 return ExprError(); 2285 2286 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2287 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2288 NameInfo, /*TemplateArgs=*/nullptr); 2289 2290 if (R.empty()) { 2291 Diag(NameInfo.getLoc(), diag::err_no_member) 2292 << NameInfo.getName() << DC << SS.getRange(); 2293 return ExprError(); 2294 } 2295 2296 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2297 // Diagnose a missing typename if this resolved unambiguously to a type in 2298 // a dependent context. If we can recover with a type, downgrade this to 2299 // a warning in Microsoft compatibility mode. 2300 unsigned DiagID = diag::err_typename_missing; 2301 if (RecoveryTSI && getLangOpts().MSVCCompat) 2302 DiagID = diag::ext_typename_missing; 2303 SourceLocation Loc = SS.getBeginLoc(); 2304 auto D = Diag(Loc, DiagID); 2305 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2306 << SourceRange(Loc, NameInfo.getEndLoc()); 2307 2308 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2309 // context. 2310 if (!RecoveryTSI) 2311 return ExprError(); 2312 2313 // Only issue the fixit if we're prepared to recover. 2314 D << FixItHint::CreateInsertion(Loc, "typename "); 2315 2316 // Recover by pretending this was an elaborated type. 2317 QualType Ty = Context.getTypeDeclType(TD); 2318 TypeLocBuilder TLB; 2319 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2320 2321 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2322 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2323 QTL.setElaboratedKeywordLoc(SourceLocation()); 2324 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2325 2326 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2327 2328 return ExprEmpty(); 2329 } 2330 2331 // Defend against this resolving to an implicit member access. We usually 2332 // won't get here if this might be a legitimate a class member (we end up in 2333 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2334 // a pointer-to-member or in an unevaluated context in C++11. 2335 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2336 return BuildPossibleImplicitMemberExpr(SS, 2337 /*TemplateKWLoc=*/SourceLocation(), 2338 R, /*TemplateArgs=*/nullptr, S); 2339 2340 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2341 } 2342 2343 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2344 /// detected that we're currently inside an ObjC method. Perform some 2345 /// additional lookup. 2346 /// 2347 /// Ideally, most of this would be done by lookup, but there's 2348 /// actually quite a lot of extra work involved. 2349 /// 2350 /// Returns a null sentinel to indicate trivial success. 2351 ExprResult 2352 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2353 IdentifierInfo *II, bool AllowBuiltinCreation) { 2354 SourceLocation Loc = Lookup.getNameLoc(); 2355 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2356 2357 // Check for error condition which is already reported. 2358 if (!CurMethod) 2359 return ExprError(); 2360 2361 // There are two cases to handle here. 1) scoped lookup could have failed, 2362 // in which case we should look for an ivar. 2) scoped lookup could have 2363 // found a decl, but that decl is outside the current instance method (i.e. 2364 // a global variable). In these two cases, we do a lookup for an ivar with 2365 // this name, if the lookup sucedes, we replace it our current decl. 2366 2367 // If we're in a class method, we don't normally want to look for 2368 // ivars. But if we don't find anything else, and there's an 2369 // ivar, that's an error. 2370 bool IsClassMethod = CurMethod->isClassMethod(); 2371 2372 bool LookForIvars; 2373 if (Lookup.empty()) 2374 LookForIvars = true; 2375 else if (IsClassMethod) 2376 LookForIvars = false; 2377 else 2378 LookForIvars = (Lookup.isSingleResult() && 2379 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2380 ObjCInterfaceDecl *IFace = nullptr; 2381 if (LookForIvars) { 2382 IFace = CurMethod->getClassInterface(); 2383 ObjCInterfaceDecl *ClassDeclared; 2384 ObjCIvarDecl *IV = nullptr; 2385 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2386 // Diagnose using an ivar in a class method. 2387 if (IsClassMethod) 2388 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2389 << IV->getDeclName()); 2390 2391 // If we're referencing an invalid decl, just return this as a silent 2392 // error node. The error diagnostic was already emitted on the decl. 2393 if (IV->isInvalidDecl()) 2394 return ExprError(); 2395 2396 // Check if referencing a field with __attribute__((deprecated)). 2397 if (DiagnoseUseOfDecl(IV, Loc)) 2398 return ExprError(); 2399 2400 // Diagnose the use of an ivar outside of the declaring class. 2401 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2402 !declaresSameEntity(ClassDeclared, IFace) && 2403 !getLangOpts().DebuggerSupport) 2404 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2405 2406 // FIXME: This should use a new expr for a direct reference, don't 2407 // turn this into Self->ivar, just return a BareIVarExpr or something. 2408 IdentifierInfo &II = Context.Idents.get("self"); 2409 UnqualifiedId SelfName; 2410 SelfName.setIdentifier(&II, SourceLocation()); 2411 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2412 CXXScopeSpec SelfScopeSpec; 2413 SourceLocation TemplateKWLoc; 2414 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2415 SelfName, false, false); 2416 if (SelfExpr.isInvalid()) 2417 return ExprError(); 2418 2419 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2420 if (SelfExpr.isInvalid()) 2421 return ExprError(); 2422 2423 MarkAnyDeclReferenced(Loc, IV, true); 2424 2425 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2426 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2427 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2428 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2429 2430 ObjCIvarRefExpr *Result = new (Context) 2431 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2432 IV->getLocation(), SelfExpr.get(), true, true); 2433 2434 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2435 if (!isUnevaluatedContext() && 2436 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2437 getCurFunction()->recordUseOfWeak(Result); 2438 } 2439 if (getLangOpts().ObjCAutoRefCount) { 2440 if (CurContext->isClosure()) 2441 Diag(Loc, diag::warn_implicitly_retains_self) 2442 << FixItHint::CreateInsertion(Loc, "self->"); 2443 } 2444 2445 return Result; 2446 } 2447 } else if (CurMethod->isInstanceMethod()) { 2448 // We should warn if a local variable hides an ivar. 2449 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2450 ObjCInterfaceDecl *ClassDeclared; 2451 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2452 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2453 declaresSameEntity(IFace, ClassDeclared)) 2454 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2455 } 2456 } 2457 } else if (Lookup.isSingleResult() && 2458 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2459 // If accessing a stand-alone ivar in a class method, this is an error. 2460 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2461 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2462 << IV->getDeclName()); 2463 } 2464 2465 if (Lookup.empty() && II && AllowBuiltinCreation) { 2466 // FIXME. Consolidate this with similar code in LookupName. 2467 if (unsigned BuiltinID = II->getBuiltinID()) { 2468 if (!(getLangOpts().CPlusPlus && 2469 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2470 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2471 S, Lookup.isForRedeclaration(), 2472 Lookup.getNameLoc()); 2473 if (D) Lookup.addDecl(D); 2474 } 2475 } 2476 } 2477 // Sentinel value saying that we didn't do anything special. 2478 return ExprResult((Expr *)nullptr); 2479 } 2480 2481 /// \brief Cast a base object to a member's actual type. 2482 /// 2483 /// Logically this happens in three phases: 2484 /// 2485 /// * First we cast from the base type to the naming class. 2486 /// The naming class is the class into which we were looking 2487 /// when we found the member; it's the qualifier type if a 2488 /// qualifier was provided, and otherwise it's the base type. 2489 /// 2490 /// * Next we cast from the naming class to the declaring class. 2491 /// If the member we found was brought into a class's scope by 2492 /// a using declaration, this is that class; otherwise it's 2493 /// the class declaring the member. 2494 /// 2495 /// * Finally we cast from the declaring class to the "true" 2496 /// declaring class of the member. This conversion does not 2497 /// obey access control. 2498 ExprResult 2499 Sema::PerformObjectMemberConversion(Expr *From, 2500 NestedNameSpecifier *Qualifier, 2501 NamedDecl *FoundDecl, 2502 NamedDecl *Member) { 2503 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2504 if (!RD) 2505 return From; 2506 2507 QualType DestRecordType; 2508 QualType DestType; 2509 QualType FromRecordType; 2510 QualType FromType = From->getType(); 2511 bool PointerConversions = false; 2512 if (isa<FieldDecl>(Member)) { 2513 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2514 2515 if (FromType->getAs<PointerType>()) { 2516 DestType = Context.getPointerType(DestRecordType); 2517 FromRecordType = FromType->getPointeeType(); 2518 PointerConversions = true; 2519 } else { 2520 DestType = DestRecordType; 2521 FromRecordType = FromType; 2522 } 2523 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2524 if (Method->isStatic()) 2525 return From; 2526 2527 DestType = Method->getThisType(Context); 2528 DestRecordType = DestType->getPointeeType(); 2529 2530 if (FromType->getAs<PointerType>()) { 2531 FromRecordType = FromType->getPointeeType(); 2532 PointerConversions = true; 2533 } else { 2534 FromRecordType = FromType; 2535 DestType = DestRecordType; 2536 } 2537 } else { 2538 // No conversion necessary. 2539 return From; 2540 } 2541 2542 if (DestType->isDependentType() || FromType->isDependentType()) 2543 return From; 2544 2545 // If the unqualified types are the same, no conversion is necessary. 2546 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2547 return From; 2548 2549 SourceRange FromRange = From->getSourceRange(); 2550 SourceLocation FromLoc = FromRange.getBegin(); 2551 2552 ExprValueKind VK = From->getValueKind(); 2553 2554 // C++ [class.member.lookup]p8: 2555 // [...] Ambiguities can often be resolved by qualifying a name with its 2556 // class name. 2557 // 2558 // If the member was a qualified name and the qualified referred to a 2559 // specific base subobject type, we'll cast to that intermediate type 2560 // first and then to the object in which the member is declared. That allows 2561 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2562 // 2563 // class Base { public: int x; }; 2564 // class Derived1 : public Base { }; 2565 // class Derived2 : public Base { }; 2566 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2567 // 2568 // void VeryDerived::f() { 2569 // x = 17; // error: ambiguous base subobjects 2570 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2571 // } 2572 if (Qualifier && Qualifier->getAsType()) { 2573 QualType QType = QualType(Qualifier->getAsType(), 0); 2574 assert(QType->isRecordType() && "lookup done with non-record type"); 2575 2576 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2577 2578 // In C++98, the qualifier type doesn't actually have to be a base 2579 // type of the object type, in which case we just ignore it. 2580 // Otherwise build the appropriate casts. 2581 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2582 CXXCastPath BasePath; 2583 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2584 FromLoc, FromRange, &BasePath)) 2585 return ExprError(); 2586 2587 if (PointerConversions) 2588 QType = Context.getPointerType(QType); 2589 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2590 VK, &BasePath).get(); 2591 2592 FromType = QType; 2593 FromRecordType = QRecordType; 2594 2595 // If the qualifier type was the same as the destination type, 2596 // we're done. 2597 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2598 return From; 2599 } 2600 } 2601 2602 bool IgnoreAccess = false; 2603 2604 // If we actually found the member through a using declaration, cast 2605 // down to the using declaration's type. 2606 // 2607 // Pointer equality is fine here because only one declaration of a 2608 // class ever has member declarations. 2609 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2610 assert(isa<UsingShadowDecl>(FoundDecl)); 2611 QualType URecordType = Context.getTypeDeclType( 2612 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2613 2614 // We only need to do this if the naming-class to declaring-class 2615 // conversion is non-trivial. 2616 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2617 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2618 CXXCastPath BasePath; 2619 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2620 FromLoc, FromRange, &BasePath)) 2621 return ExprError(); 2622 2623 QualType UType = URecordType; 2624 if (PointerConversions) 2625 UType = Context.getPointerType(UType); 2626 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2627 VK, &BasePath).get(); 2628 FromType = UType; 2629 FromRecordType = URecordType; 2630 } 2631 2632 // We don't do access control for the conversion from the 2633 // declaring class to the true declaring class. 2634 IgnoreAccess = true; 2635 } 2636 2637 CXXCastPath BasePath; 2638 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2639 FromLoc, FromRange, &BasePath, 2640 IgnoreAccess)) 2641 return ExprError(); 2642 2643 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2644 VK, &BasePath); 2645 } 2646 2647 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2648 const LookupResult &R, 2649 bool HasTrailingLParen) { 2650 // Only when used directly as the postfix-expression of a call. 2651 if (!HasTrailingLParen) 2652 return false; 2653 2654 // Never if a scope specifier was provided. 2655 if (SS.isSet()) 2656 return false; 2657 2658 // Only in C++ or ObjC++. 2659 if (!getLangOpts().CPlusPlus) 2660 return false; 2661 2662 // Turn off ADL when we find certain kinds of declarations during 2663 // normal lookup: 2664 for (NamedDecl *D : R) { 2665 // C++0x [basic.lookup.argdep]p3: 2666 // -- a declaration of a class member 2667 // Since using decls preserve this property, we check this on the 2668 // original decl. 2669 if (D->isCXXClassMember()) 2670 return false; 2671 2672 // C++0x [basic.lookup.argdep]p3: 2673 // -- a block-scope function declaration that is not a 2674 // using-declaration 2675 // NOTE: we also trigger this for function templates (in fact, we 2676 // don't check the decl type at all, since all other decl types 2677 // turn off ADL anyway). 2678 if (isa<UsingShadowDecl>(D)) 2679 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2680 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2681 return false; 2682 2683 // C++0x [basic.lookup.argdep]p3: 2684 // -- a declaration that is neither a function or a function 2685 // template 2686 // And also for builtin functions. 2687 if (isa<FunctionDecl>(D)) { 2688 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2689 2690 // But also builtin functions. 2691 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2692 return false; 2693 } else if (!isa<FunctionTemplateDecl>(D)) 2694 return false; 2695 } 2696 2697 return true; 2698 } 2699 2700 2701 /// Diagnoses obvious problems with the use of the given declaration 2702 /// as an expression. This is only actually called for lookups that 2703 /// were not overloaded, and it doesn't promise that the declaration 2704 /// will in fact be used. 2705 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2706 if (D->isInvalidDecl()) 2707 return true; 2708 2709 if (isa<TypedefNameDecl>(D)) { 2710 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2711 return true; 2712 } 2713 2714 if (isa<ObjCInterfaceDecl>(D)) { 2715 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2716 return true; 2717 } 2718 2719 if (isa<NamespaceDecl>(D)) { 2720 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2721 return true; 2722 } 2723 2724 return false; 2725 } 2726 2727 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2728 LookupResult &R, bool NeedsADL, 2729 bool AcceptInvalidDecl) { 2730 // If this is a single, fully-resolved result and we don't need ADL, 2731 // just build an ordinary singleton decl ref. 2732 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2733 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2734 R.getRepresentativeDecl(), nullptr, 2735 AcceptInvalidDecl); 2736 2737 // We only need to check the declaration if there's exactly one 2738 // result, because in the overloaded case the results can only be 2739 // functions and function templates. 2740 if (R.isSingleResult() && 2741 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2742 return ExprError(); 2743 2744 // Otherwise, just build an unresolved lookup expression. Suppress 2745 // any lookup-related diagnostics; we'll hash these out later, when 2746 // we've picked a target. 2747 R.suppressDiagnostics(); 2748 2749 UnresolvedLookupExpr *ULE 2750 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2751 SS.getWithLocInContext(Context), 2752 R.getLookupNameInfo(), 2753 NeedsADL, R.isOverloadedResult(), 2754 R.begin(), R.end()); 2755 2756 return ULE; 2757 } 2758 2759 static void 2760 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2761 ValueDecl *var, DeclContext *DC); 2762 2763 /// \brief Complete semantic analysis for a reference to the given declaration. 2764 ExprResult Sema::BuildDeclarationNameExpr( 2765 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2766 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2767 bool AcceptInvalidDecl) { 2768 assert(D && "Cannot refer to a NULL declaration"); 2769 assert(!isa<FunctionTemplateDecl>(D) && 2770 "Cannot refer unambiguously to a function template"); 2771 2772 SourceLocation Loc = NameInfo.getLoc(); 2773 if (CheckDeclInExpr(*this, Loc, D)) 2774 return ExprError(); 2775 2776 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2777 // Specifically diagnose references to class templates that are missing 2778 // a template argument list. 2779 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2780 << Template << SS.getRange(); 2781 Diag(Template->getLocation(), diag::note_template_decl_here); 2782 return ExprError(); 2783 } 2784 2785 // Make sure that we're referring to a value. 2786 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2787 if (!VD) { 2788 Diag(Loc, diag::err_ref_non_value) 2789 << D << SS.getRange(); 2790 Diag(D->getLocation(), diag::note_declared_at); 2791 return ExprError(); 2792 } 2793 2794 // Check whether this declaration can be used. Note that we suppress 2795 // this check when we're going to perform argument-dependent lookup 2796 // on this function name, because this might not be the function 2797 // that overload resolution actually selects. 2798 if (DiagnoseUseOfDecl(VD, Loc)) 2799 return ExprError(); 2800 2801 // Only create DeclRefExpr's for valid Decl's. 2802 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2803 return ExprError(); 2804 2805 // Handle members of anonymous structs and unions. If we got here, 2806 // and the reference is to a class member indirect field, then this 2807 // must be the subject of a pointer-to-member expression. 2808 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2809 if (!indirectField->isCXXClassMember()) 2810 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2811 indirectField); 2812 2813 { 2814 QualType type = VD->getType(); 2815 if (type.isNull()) 2816 return ExprError(); 2817 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2818 // C++ [except.spec]p17: 2819 // An exception-specification is considered to be needed when: 2820 // - in an expression, the function is the unique lookup result or 2821 // the selected member of a set of overloaded functions. 2822 ResolveExceptionSpec(Loc, FPT); 2823 type = VD->getType(); 2824 } 2825 ExprValueKind valueKind = VK_RValue; 2826 2827 switch (D->getKind()) { 2828 // Ignore all the non-ValueDecl kinds. 2829 #define ABSTRACT_DECL(kind) 2830 #define VALUE(type, base) 2831 #define DECL(type, base) \ 2832 case Decl::type: 2833 #include "clang/AST/DeclNodes.inc" 2834 llvm_unreachable("invalid value decl kind"); 2835 2836 // These shouldn't make it here. 2837 case Decl::ObjCAtDefsField: 2838 case Decl::ObjCIvar: 2839 llvm_unreachable("forming non-member reference to ivar?"); 2840 2841 // Enum constants are always r-values and never references. 2842 // Unresolved using declarations are dependent. 2843 case Decl::EnumConstant: 2844 case Decl::UnresolvedUsingValue: 2845 case Decl::OMPDeclareReduction: 2846 valueKind = VK_RValue; 2847 break; 2848 2849 // Fields and indirect fields that got here must be for 2850 // pointer-to-member expressions; we just call them l-values for 2851 // internal consistency, because this subexpression doesn't really 2852 // exist in the high-level semantics. 2853 case Decl::Field: 2854 case Decl::IndirectField: 2855 assert(getLangOpts().CPlusPlus && 2856 "building reference to field in C?"); 2857 2858 // These can't have reference type in well-formed programs, but 2859 // for internal consistency we do this anyway. 2860 type = type.getNonReferenceType(); 2861 valueKind = VK_LValue; 2862 break; 2863 2864 // Non-type template parameters are either l-values or r-values 2865 // depending on the type. 2866 case Decl::NonTypeTemplateParm: { 2867 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2868 type = reftype->getPointeeType(); 2869 valueKind = VK_LValue; // even if the parameter is an r-value reference 2870 break; 2871 } 2872 2873 // For non-references, we need to strip qualifiers just in case 2874 // the template parameter was declared as 'const int' or whatever. 2875 valueKind = VK_RValue; 2876 type = type.getUnqualifiedType(); 2877 break; 2878 } 2879 2880 case Decl::Var: 2881 case Decl::VarTemplateSpecialization: 2882 case Decl::VarTemplatePartialSpecialization: 2883 case Decl::Decomposition: 2884 case Decl::OMPCapturedExpr: 2885 // In C, "extern void blah;" is valid and is an r-value. 2886 if (!getLangOpts().CPlusPlus && 2887 !type.hasQualifiers() && 2888 type->isVoidType()) { 2889 valueKind = VK_RValue; 2890 break; 2891 } 2892 LLVM_FALLTHROUGH; 2893 2894 case Decl::ImplicitParam: 2895 case Decl::ParmVar: { 2896 // These are always l-values. 2897 valueKind = VK_LValue; 2898 type = type.getNonReferenceType(); 2899 2900 // FIXME: Does the addition of const really only apply in 2901 // potentially-evaluated contexts? Since the variable isn't actually 2902 // captured in an unevaluated context, it seems that the answer is no. 2903 if (!isUnevaluatedContext()) { 2904 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2905 if (!CapturedType.isNull()) 2906 type = CapturedType; 2907 } 2908 2909 break; 2910 } 2911 2912 case Decl::Binding: { 2913 // These are always lvalues. 2914 valueKind = VK_LValue; 2915 type = type.getNonReferenceType(); 2916 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2917 // decides how that's supposed to work. 2918 auto *BD = cast<BindingDecl>(VD); 2919 if (BD->getDeclContext()->isFunctionOrMethod() && 2920 BD->getDeclContext() != CurContext) 2921 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2922 break; 2923 } 2924 2925 case Decl::Function: { 2926 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2927 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2928 type = Context.BuiltinFnTy; 2929 valueKind = VK_RValue; 2930 break; 2931 } 2932 } 2933 2934 const FunctionType *fty = type->castAs<FunctionType>(); 2935 2936 // If we're referring to a function with an __unknown_anytype 2937 // result type, make the entire expression __unknown_anytype. 2938 if (fty->getReturnType() == Context.UnknownAnyTy) { 2939 type = Context.UnknownAnyTy; 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 2944 // Functions are l-values in C++. 2945 if (getLangOpts().CPlusPlus) { 2946 valueKind = VK_LValue; 2947 break; 2948 } 2949 2950 // C99 DR 316 says that, if a function type comes from a 2951 // function definition (without a prototype), that type is only 2952 // used for checking compatibility. Therefore, when referencing 2953 // the function, we pretend that we don't have the full function 2954 // type. 2955 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2956 isa<FunctionProtoType>(fty)) 2957 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2958 fty->getExtInfo()); 2959 2960 // Functions are r-values in C. 2961 valueKind = VK_RValue; 2962 break; 2963 } 2964 2965 case Decl::CXXDeductionGuide: 2966 llvm_unreachable("building reference to deduction guide"); 2967 2968 case Decl::MSProperty: 2969 valueKind = VK_LValue; 2970 break; 2971 2972 case Decl::CXXMethod: 2973 // If we're referring to a method with an __unknown_anytype 2974 // result type, make the entire expression __unknown_anytype. 2975 // This should only be possible with a type written directly. 2976 if (const FunctionProtoType *proto 2977 = dyn_cast<FunctionProtoType>(VD->getType())) 2978 if (proto->getReturnType() == Context.UnknownAnyTy) { 2979 type = Context.UnknownAnyTy; 2980 valueKind = VK_RValue; 2981 break; 2982 } 2983 2984 // C++ methods are l-values if static, r-values if non-static. 2985 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2986 valueKind = VK_LValue; 2987 break; 2988 } 2989 LLVM_FALLTHROUGH; 2990 2991 case Decl::CXXConversion: 2992 case Decl::CXXDestructor: 2993 case Decl::CXXConstructor: 2994 valueKind = VK_RValue; 2995 break; 2996 } 2997 2998 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2999 TemplateArgs); 3000 } 3001 } 3002 3003 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3004 SmallString<32> &Target) { 3005 Target.resize(CharByteWidth * (Source.size() + 1)); 3006 char *ResultPtr = &Target[0]; 3007 const llvm::UTF8 *ErrorPtr; 3008 bool success = 3009 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3010 (void)success; 3011 assert(success); 3012 Target.resize(ResultPtr - &Target[0]); 3013 } 3014 3015 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3016 PredefinedExpr::IdentType IT) { 3017 // Pick the current block, lambda, captured statement or function. 3018 Decl *currentDecl = nullptr; 3019 if (const BlockScopeInfo *BSI = getCurBlock()) 3020 currentDecl = BSI->TheDecl; 3021 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3022 currentDecl = LSI->CallOperator; 3023 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3024 currentDecl = CSI->TheCapturedDecl; 3025 else 3026 currentDecl = getCurFunctionOrMethodDecl(); 3027 3028 if (!currentDecl) { 3029 Diag(Loc, diag::ext_predef_outside_function); 3030 currentDecl = Context.getTranslationUnitDecl(); 3031 } 3032 3033 QualType ResTy; 3034 StringLiteral *SL = nullptr; 3035 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3036 ResTy = Context.DependentTy; 3037 else { 3038 // Pre-defined identifiers are of type char[x], where x is the length of 3039 // the string. 3040 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3041 unsigned Length = Str.length(); 3042 3043 llvm::APInt LengthI(32, Length + 1); 3044 if (IT == PredefinedExpr::LFunction) { 3045 ResTy = Context.WideCharTy.withConst(); 3046 SmallString<32> RawChars; 3047 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3048 Str, RawChars); 3049 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3050 /*IndexTypeQuals*/ 0); 3051 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3052 /*Pascal*/ false, ResTy, Loc); 3053 } else { 3054 ResTy = Context.CharTy.withConst(); 3055 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3056 /*IndexTypeQuals*/ 0); 3057 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3058 /*Pascal*/ false, ResTy, Loc); 3059 } 3060 } 3061 3062 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3063 } 3064 3065 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3066 PredefinedExpr::IdentType IT; 3067 3068 switch (Kind) { 3069 default: llvm_unreachable("Unknown simple primary expr!"); 3070 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3071 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3072 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3073 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3074 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3075 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3076 } 3077 3078 return BuildPredefinedExpr(Loc, IT); 3079 } 3080 3081 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3082 SmallString<16> CharBuffer; 3083 bool Invalid = false; 3084 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3085 if (Invalid) 3086 return ExprError(); 3087 3088 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3089 PP, Tok.getKind()); 3090 if (Literal.hadError()) 3091 return ExprError(); 3092 3093 QualType Ty; 3094 if (Literal.isWide()) 3095 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3096 else if (Literal.isUTF16()) 3097 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3098 else if (Literal.isUTF32()) 3099 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3100 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3101 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3102 else 3103 Ty = Context.CharTy; // 'x' -> char in C++ 3104 3105 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3106 if (Literal.isWide()) 3107 Kind = CharacterLiteral::Wide; 3108 else if (Literal.isUTF16()) 3109 Kind = CharacterLiteral::UTF16; 3110 else if (Literal.isUTF32()) 3111 Kind = CharacterLiteral::UTF32; 3112 else if (Literal.isUTF8()) 3113 Kind = CharacterLiteral::UTF8; 3114 3115 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3116 Tok.getLocation()); 3117 3118 if (Literal.getUDSuffix().empty()) 3119 return Lit; 3120 3121 // We're building a user-defined literal. 3122 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3123 SourceLocation UDSuffixLoc = 3124 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3125 3126 // Make sure we're allowed user-defined literals here. 3127 if (!UDLScope) 3128 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3129 3130 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3131 // operator "" X (ch) 3132 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3133 Lit, Tok.getLocation()); 3134 } 3135 3136 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3137 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3138 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3139 Context.IntTy, Loc); 3140 } 3141 3142 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3143 QualType Ty, SourceLocation Loc) { 3144 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3145 3146 using llvm::APFloat; 3147 APFloat Val(Format); 3148 3149 APFloat::opStatus result = Literal.GetFloatValue(Val); 3150 3151 // Overflow is always an error, but underflow is only an error if 3152 // we underflowed to zero (APFloat reports denormals as underflow). 3153 if ((result & APFloat::opOverflow) || 3154 ((result & APFloat::opUnderflow) && Val.isZero())) { 3155 unsigned diagnostic; 3156 SmallString<20> buffer; 3157 if (result & APFloat::opOverflow) { 3158 diagnostic = diag::warn_float_overflow; 3159 APFloat::getLargest(Format).toString(buffer); 3160 } else { 3161 diagnostic = diag::warn_float_underflow; 3162 APFloat::getSmallest(Format).toString(buffer); 3163 } 3164 3165 S.Diag(Loc, diagnostic) 3166 << Ty 3167 << StringRef(buffer.data(), buffer.size()); 3168 } 3169 3170 bool isExact = (result == APFloat::opOK); 3171 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3172 } 3173 3174 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3175 assert(E && "Invalid expression"); 3176 3177 if (E->isValueDependent()) 3178 return false; 3179 3180 QualType QT = E->getType(); 3181 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3182 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3183 return true; 3184 } 3185 3186 llvm::APSInt ValueAPS; 3187 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3188 3189 if (R.isInvalid()) 3190 return true; 3191 3192 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3193 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3194 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3195 << ValueAPS.toString(10) << ValueIsPositive; 3196 return true; 3197 } 3198 3199 return false; 3200 } 3201 3202 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3203 // Fast path for a single digit (which is quite common). A single digit 3204 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3205 if (Tok.getLength() == 1) { 3206 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3207 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3208 } 3209 3210 SmallString<128> SpellingBuffer; 3211 // NumericLiteralParser wants to overread by one character. Add padding to 3212 // the buffer in case the token is copied to the buffer. If getSpelling() 3213 // returns a StringRef to the memory buffer, it should have a null char at 3214 // the EOF, so it is also safe. 3215 SpellingBuffer.resize(Tok.getLength() + 1); 3216 3217 // Get the spelling of the token, which eliminates trigraphs, etc. 3218 bool Invalid = false; 3219 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3220 if (Invalid) 3221 return ExprError(); 3222 3223 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3224 if (Literal.hadError) 3225 return ExprError(); 3226 3227 if (Literal.hasUDSuffix()) { 3228 // We're building a user-defined literal. 3229 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3230 SourceLocation UDSuffixLoc = 3231 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3232 3233 // Make sure we're allowed user-defined literals here. 3234 if (!UDLScope) 3235 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3236 3237 QualType CookedTy; 3238 if (Literal.isFloatingLiteral()) { 3239 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3240 // long double, the literal is treated as a call of the form 3241 // operator "" X (f L) 3242 CookedTy = Context.LongDoubleTy; 3243 } else { 3244 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3245 // unsigned long long, the literal is treated as a call of the form 3246 // operator "" X (n ULL) 3247 CookedTy = Context.UnsignedLongLongTy; 3248 } 3249 3250 DeclarationName OpName = 3251 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3252 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3253 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3254 3255 SourceLocation TokLoc = Tok.getLocation(); 3256 3257 // Perform literal operator lookup to determine if we're building a raw 3258 // literal or a cooked one. 3259 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3260 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3261 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3262 /*AllowStringTemplate*/ false, 3263 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3264 case LOLR_ErrorNoDiagnostic: 3265 // Lookup failure for imaginary constants isn't fatal, there's still the 3266 // GNU extension producing _Complex types. 3267 break; 3268 case LOLR_Error: 3269 return ExprError(); 3270 case LOLR_Cooked: { 3271 Expr *Lit; 3272 if (Literal.isFloatingLiteral()) { 3273 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3274 } else { 3275 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3276 if (Literal.GetIntegerValue(ResultVal)) 3277 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3278 << /* Unsigned */ 1; 3279 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3280 Tok.getLocation()); 3281 } 3282 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3283 } 3284 3285 case LOLR_Raw: { 3286 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3287 // literal is treated as a call of the form 3288 // operator "" X ("n") 3289 unsigned Length = Literal.getUDSuffixOffset(); 3290 QualType StrTy = Context.getConstantArrayType( 3291 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3292 ArrayType::Normal, 0); 3293 Expr *Lit = StringLiteral::Create( 3294 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3295 /*Pascal*/false, StrTy, &TokLoc, 1); 3296 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3297 } 3298 3299 case LOLR_Template: { 3300 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3301 // template), L is treated as a call fo the form 3302 // operator "" X <'c1', 'c2', ... 'ck'>() 3303 // where n is the source character sequence c1 c2 ... ck. 3304 TemplateArgumentListInfo ExplicitArgs; 3305 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3306 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3307 llvm::APSInt Value(CharBits, CharIsUnsigned); 3308 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3309 Value = TokSpelling[I]; 3310 TemplateArgument Arg(Context, Value, Context.CharTy); 3311 TemplateArgumentLocInfo ArgInfo; 3312 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3313 } 3314 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3315 &ExplicitArgs); 3316 } 3317 case LOLR_StringTemplate: 3318 llvm_unreachable("unexpected literal operator lookup result"); 3319 } 3320 } 3321 3322 Expr *Res; 3323 3324 if (Literal.isFloatingLiteral()) { 3325 QualType Ty; 3326 if (Literal.isHalf){ 3327 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3328 Ty = Context.HalfTy; 3329 else { 3330 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3331 return ExprError(); 3332 } 3333 } else if (Literal.isFloat) 3334 Ty = Context.FloatTy; 3335 else if (Literal.isLong) 3336 Ty = Context.LongDoubleTy; 3337 else if (Literal.isFloat16) 3338 Ty = Context.Float16Ty; 3339 else if (Literal.isFloat128) 3340 Ty = Context.Float128Ty; 3341 else 3342 Ty = Context.DoubleTy; 3343 3344 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3345 3346 if (Ty == Context.DoubleTy) { 3347 if (getLangOpts().SinglePrecisionConstants) { 3348 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3349 if (BTy->getKind() != BuiltinType::Float) { 3350 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3351 } 3352 } else if (getLangOpts().OpenCL && 3353 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3354 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3355 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3356 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3357 } 3358 } 3359 } else if (!Literal.isIntegerLiteral()) { 3360 return ExprError(); 3361 } else { 3362 QualType Ty; 3363 3364 // 'long long' is a C99 or C++11 feature. 3365 if (!getLangOpts().C99 && Literal.isLongLong) { 3366 if (getLangOpts().CPlusPlus) 3367 Diag(Tok.getLocation(), 3368 getLangOpts().CPlusPlus11 ? 3369 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3370 else 3371 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3372 } 3373 3374 // Get the value in the widest-possible width. 3375 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3376 llvm::APInt ResultVal(MaxWidth, 0); 3377 3378 if (Literal.GetIntegerValue(ResultVal)) { 3379 // If this value didn't fit into uintmax_t, error and force to ull. 3380 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3381 << /* Unsigned */ 1; 3382 Ty = Context.UnsignedLongLongTy; 3383 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3384 "long long is not intmax_t?"); 3385 } else { 3386 // If this value fits into a ULL, try to figure out what else it fits into 3387 // according to the rules of C99 6.4.4.1p5. 3388 3389 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3390 // be an unsigned int. 3391 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3392 3393 // Check from smallest to largest, picking the smallest type we can. 3394 unsigned Width = 0; 3395 3396 // Microsoft specific integer suffixes are explicitly sized. 3397 if (Literal.MicrosoftInteger) { 3398 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3399 Width = 8; 3400 Ty = Context.CharTy; 3401 } else { 3402 Width = Literal.MicrosoftInteger; 3403 Ty = Context.getIntTypeForBitwidth(Width, 3404 /*Signed=*/!Literal.isUnsigned); 3405 } 3406 } 3407 3408 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3409 // Are int/unsigned possibilities? 3410 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3411 3412 // Does it fit in a unsigned int? 3413 if (ResultVal.isIntN(IntSize)) { 3414 // Does it fit in a signed int? 3415 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3416 Ty = Context.IntTy; 3417 else if (AllowUnsigned) 3418 Ty = Context.UnsignedIntTy; 3419 Width = IntSize; 3420 } 3421 } 3422 3423 // Are long/unsigned long possibilities? 3424 if (Ty.isNull() && !Literal.isLongLong) { 3425 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3426 3427 // Does it fit in a unsigned long? 3428 if (ResultVal.isIntN(LongSize)) { 3429 // Does it fit in a signed long? 3430 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3431 Ty = Context.LongTy; 3432 else if (AllowUnsigned) 3433 Ty = Context.UnsignedLongTy; 3434 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3435 // is compatible. 3436 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3437 const unsigned LongLongSize = 3438 Context.getTargetInfo().getLongLongWidth(); 3439 Diag(Tok.getLocation(), 3440 getLangOpts().CPlusPlus 3441 ? Literal.isLong 3442 ? diag::warn_old_implicitly_unsigned_long_cxx 3443 : /*C++98 UB*/ diag:: 3444 ext_old_implicitly_unsigned_long_cxx 3445 : diag::warn_old_implicitly_unsigned_long) 3446 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3447 : /*will be ill-formed*/ 1); 3448 Ty = Context.UnsignedLongTy; 3449 } 3450 Width = LongSize; 3451 } 3452 } 3453 3454 // Check long long if needed. 3455 if (Ty.isNull()) { 3456 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3457 3458 // Does it fit in a unsigned long long? 3459 if (ResultVal.isIntN(LongLongSize)) { 3460 // Does it fit in a signed long long? 3461 // To be compatible with MSVC, hex integer literals ending with the 3462 // LL or i64 suffix are always signed in Microsoft mode. 3463 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3464 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3465 Ty = Context.LongLongTy; 3466 else if (AllowUnsigned) 3467 Ty = Context.UnsignedLongLongTy; 3468 Width = LongLongSize; 3469 } 3470 } 3471 3472 // If we still couldn't decide a type, we probably have something that 3473 // does not fit in a signed long long, but has no U suffix. 3474 if (Ty.isNull()) { 3475 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3476 Ty = Context.UnsignedLongLongTy; 3477 Width = Context.getTargetInfo().getLongLongWidth(); 3478 } 3479 3480 if (ResultVal.getBitWidth() != Width) 3481 ResultVal = ResultVal.trunc(Width); 3482 } 3483 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3484 } 3485 3486 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3487 if (Literal.isImaginary) { 3488 Res = new (Context) ImaginaryLiteral(Res, 3489 Context.getComplexType(Res->getType())); 3490 3491 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3492 } 3493 return Res; 3494 } 3495 3496 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3497 assert(E && "ActOnParenExpr() missing expr"); 3498 return new (Context) ParenExpr(L, R, E); 3499 } 3500 3501 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3502 SourceLocation Loc, 3503 SourceRange ArgRange) { 3504 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3505 // scalar or vector data type argument..." 3506 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3507 // type (C99 6.2.5p18) or void. 3508 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3509 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3510 << T << ArgRange; 3511 return true; 3512 } 3513 3514 assert((T->isVoidType() || !T->isIncompleteType()) && 3515 "Scalar types should always be complete"); 3516 return false; 3517 } 3518 3519 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3520 SourceLocation Loc, 3521 SourceRange ArgRange, 3522 UnaryExprOrTypeTrait TraitKind) { 3523 // Invalid types must be hard errors for SFINAE in C++. 3524 if (S.LangOpts.CPlusPlus) 3525 return true; 3526 3527 // C99 6.5.3.4p1: 3528 if (T->isFunctionType() && 3529 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3530 // sizeof(function)/alignof(function) is allowed as an extension. 3531 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3532 << TraitKind << ArgRange; 3533 return false; 3534 } 3535 3536 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3537 // this is an error (OpenCL v1.1 s6.3.k) 3538 if (T->isVoidType()) { 3539 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3540 : diag::ext_sizeof_alignof_void_type; 3541 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3542 return false; 3543 } 3544 3545 return true; 3546 } 3547 3548 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3549 SourceLocation Loc, 3550 SourceRange ArgRange, 3551 UnaryExprOrTypeTrait TraitKind) { 3552 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3553 // runtime doesn't allow it. 3554 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3555 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3556 << T << (TraitKind == UETT_SizeOf) 3557 << ArgRange; 3558 return true; 3559 } 3560 3561 return false; 3562 } 3563 3564 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3565 /// pointer type is equal to T) and emit a warning if it is. 3566 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3567 Expr *E) { 3568 // Don't warn if the operation changed the type. 3569 if (T != E->getType()) 3570 return; 3571 3572 // Now look for array decays. 3573 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3574 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3575 return; 3576 3577 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3578 << ICE->getType() 3579 << ICE->getSubExpr()->getType(); 3580 } 3581 3582 /// \brief Check the constraints on expression operands to unary type expression 3583 /// and type traits. 3584 /// 3585 /// Completes any types necessary and validates the constraints on the operand 3586 /// expression. The logic mostly mirrors the type-based overload, but may modify 3587 /// the expression as it completes the type for that expression through template 3588 /// instantiation, etc. 3589 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3590 UnaryExprOrTypeTrait ExprKind) { 3591 QualType ExprTy = E->getType(); 3592 assert(!ExprTy->isReferenceType()); 3593 3594 if (ExprKind == UETT_VecStep) 3595 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3596 E->getSourceRange()); 3597 3598 // Whitelist some types as extensions 3599 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3600 E->getSourceRange(), ExprKind)) 3601 return false; 3602 3603 // 'alignof' applied to an expression only requires the base element type of 3604 // the expression to be complete. 'sizeof' requires the expression's type to 3605 // be complete (and will attempt to complete it if it's an array of unknown 3606 // bound). 3607 if (ExprKind == UETT_AlignOf) { 3608 if (RequireCompleteType(E->getExprLoc(), 3609 Context.getBaseElementType(E->getType()), 3610 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3611 E->getSourceRange())) 3612 return true; 3613 } else { 3614 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3615 ExprKind, E->getSourceRange())) 3616 return true; 3617 } 3618 3619 // Completing the expression's type may have changed it. 3620 ExprTy = E->getType(); 3621 assert(!ExprTy->isReferenceType()); 3622 3623 if (ExprTy->isFunctionType()) { 3624 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3625 << ExprKind << E->getSourceRange(); 3626 return true; 3627 } 3628 3629 // The operand for sizeof and alignof is in an unevaluated expression context, 3630 // so side effects could result in unintended consequences. 3631 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3632 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3633 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3634 3635 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3636 E->getSourceRange(), ExprKind)) 3637 return true; 3638 3639 if (ExprKind == UETT_SizeOf) { 3640 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3641 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3642 QualType OType = PVD->getOriginalType(); 3643 QualType Type = PVD->getType(); 3644 if (Type->isPointerType() && OType->isArrayType()) { 3645 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3646 << Type << OType; 3647 Diag(PVD->getLocation(), diag::note_declared_at); 3648 } 3649 } 3650 } 3651 3652 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3653 // decays into a pointer and returns an unintended result. This is most 3654 // likely a typo for "sizeof(array) op x". 3655 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3656 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3657 BO->getLHS()); 3658 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3659 BO->getRHS()); 3660 } 3661 } 3662 3663 return false; 3664 } 3665 3666 /// \brief Check the constraints on operands to unary expression and type 3667 /// traits. 3668 /// 3669 /// This will complete any types necessary, and validate the various constraints 3670 /// on those operands. 3671 /// 3672 /// The UsualUnaryConversions() function is *not* called by this routine. 3673 /// C99 6.3.2.1p[2-4] all state: 3674 /// Except when it is the operand of the sizeof operator ... 3675 /// 3676 /// C++ [expr.sizeof]p4 3677 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3678 /// standard conversions are not applied to the operand of sizeof. 3679 /// 3680 /// This policy is followed for all of the unary trait expressions. 3681 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3682 SourceLocation OpLoc, 3683 SourceRange ExprRange, 3684 UnaryExprOrTypeTrait ExprKind) { 3685 if (ExprType->isDependentType()) 3686 return false; 3687 3688 // C++ [expr.sizeof]p2: 3689 // When applied to a reference or a reference type, the result 3690 // is the size of the referenced type. 3691 // C++11 [expr.alignof]p3: 3692 // When alignof is applied to a reference type, the result 3693 // shall be the alignment of the referenced type. 3694 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3695 ExprType = Ref->getPointeeType(); 3696 3697 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3698 // When alignof or _Alignof is applied to an array type, the result 3699 // is the alignment of the element type. 3700 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3701 ExprType = Context.getBaseElementType(ExprType); 3702 3703 if (ExprKind == UETT_VecStep) 3704 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3705 3706 // Whitelist some types as extensions 3707 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3708 ExprKind)) 3709 return false; 3710 3711 if (RequireCompleteType(OpLoc, ExprType, 3712 diag::err_sizeof_alignof_incomplete_type, 3713 ExprKind, ExprRange)) 3714 return true; 3715 3716 if (ExprType->isFunctionType()) { 3717 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3718 << ExprKind << ExprRange; 3719 return true; 3720 } 3721 3722 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3723 ExprKind)) 3724 return true; 3725 3726 return false; 3727 } 3728 3729 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3730 E = E->IgnoreParens(); 3731 3732 // Cannot know anything else if the expression is dependent. 3733 if (E->isTypeDependent()) 3734 return false; 3735 3736 if (E->getObjectKind() == OK_BitField) { 3737 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3738 << 1 << E->getSourceRange(); 3739 return true; 3740 } 3741 3742 ValueDecl *D = nullptr; 3743 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3744 D = DRE->getDecl(); 3745 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3746 D = ME->getMemberDecl(); 3747 } 3748 3749 // If it's a field, require the containing struct to have a 3750 // complete definition so that we can compute the layout. 3751 // 3752 // This can happen in C++11 onwards, either by naming the member 3753 // in a way that is not transformed into a member access expression 3754 // (in an unevaluated operand, for instance), or by naming the member 3755 // in a trailing-return-type. 3756 // 3757 // For the record, since __alignof__ on expressions is a GCC 3758 // extension, GCC seems to permit this but always gives the 3759 // nonsensical answer 0. 3760 // 3761 // We don't really need the layout here --- we could instead just 3762 // directly check for all the appropriate alignment-lowing 3763 // attributes --- but that would require duplicating a lot of 3764 // logic that just isn't worth duplicating for such a marginal 3765 // use-case. 3766 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3767 // Fast path this check, since we at least know the record has a 3768 // definition if we can find a member of it. 3769 if (!FD->getParent()->isCompleteDefinition()) { 3770 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3771 << E->getSourceRange(); 3772 return true; 3773 } 3774 3775 // Otherwise, if it's a field, and the field doesn't have 3776 // reference type, then it must have a complete type (or be a 3777 // flexible array member, which we explicitly want to 3778 // white-list anyway), which makes the following checks trivial. 3779 if (!FD->getType()->isReferenceType()) 3780 return false; 3781 } 3782 3783 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3784 } 3785 3786 bool Sema::CheckVecStepExpr(Expr *E) { 3787 E = E->IgnoreParens(); 3788 3789 // Cannot know anything else if the expression is dependent. 3790 if (E->isTypeDependent()) 3791 return false; 3792 3793 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3794 } 3795 3796 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3797 CapturingScopeInfo *CSI) { 3798 assert(T->isVariablyModifiedType()); 3799 assert(CSI != nullptr); 3800 3801 // We're going to walk down into the type and look for VLA expressions. 3802 do { 3803 const Type *Ty = T.getTypePtr(); 3804 switch (Ty->getTypeClass()) { 3805 #define TYPE(Class, Base) 3806 #define ABSTRACT_TYPE(Class, Base) 3807 #define NON_CANONICAL_TYPE(Class, Base) 3808 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3809 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3810 #include "clang/AST/TypeNodes.def" 3811 T = QualType(); 3812 break; 3813 // These types are never variably-modified. 3814 case Type::Builtin: 3815 case Type::Complex: 3816 case Type::Vector: 3817 case Type::ExtVector: 3818 case Type::Record: 3819 case Type::Enum: 3820 case Type::Elaborated: 3821 case Type::TemplateSpecialization: 3822 case Type::ObjCObject: 3823 case Type::ObjCInterface: 3824 case Type::ObjCObjectPointer: 3825 case Type::ObjCTypeParam: 3826 case Type::Pipe: 3827 llvm_unreachable("type class is never variably-modified!"); 3828 case Type::Adjusted: 3829 T = cast<AdjustedType>(Ty)->getOriginalType(); 3830 break; 3831 case Type::Decayed: 3832 T = cast<DecayedType>(Ty)->getPointeeType(); 3833 break; 3834 case Type::Pointer: 3835 T = cast<PointerType>(Ty)->getPointeeType(); 3836 break; 3837 case Type::BlockPointer: 3838 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3839 break; 3840 case Type::LValueReference: 3841 case Type::RValueReference: 3842 T = cast<ReferenceType>(Ty)->getPointeeType(); 3843 break; 3844 case Type::MemberPointer: 3845 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3846 break; 3847 case Type::ConstantArray: 3848 case Type::IncompleteArray: 3849 // Losing element qualification here is fine. 3850 T = cast<ArrayType>(Ty)->getElementType(); 3851 break; 3852 case Type::VariableArray: { 3853 // Losing element qualification here is fine. 3854 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3855 3856 // Unknown size indication requires no size computation. 3857 // Otherwise, evaluate and record it. 3858 if (auto Size = VAT->getSizeExpr()) { 3859 if (!CSI->isVLATypeCaptured(VAT)) { 3860 RecordDecl *CapRecord = nullptr; 3861 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3862 CapRecord = LSI->Lambda; 3863 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3864 CapRecord = CRSI->TheRecordDecl; 3865 } 3866 if (CapRecord) { 3867 auto ExprLoc = Size->getExprLoc(); 3868 auto SizeType = Context.getSizeType(); 3869 // Build the non-static data member. 3870 auto Field = 3871 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3872 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3873 /*BW*/ nullptr, /*Mutable*/ false, 3874 /*InitStyle*/ ICIS_NoInit); 3875 Field->setImplicit(true); 3876 Field->setAccess(AS_private); 3877 Field->setCapturedVLAType(VAT); 3878 CapRecord->addDecl(Field); 3879 3880 CSI->addVLATypeCapture(ExprLoc, SizeType); 3881 } 3882 } 3883 } 3884 T = VAT->getElementType(); 3885 break; 3886 } 3887 case Type::FunctionProto: 3888 case Type::FunctionNoProto: 3889 T = cast<FunctionType>(Ty)->getReturnType(); 3890 break; 3891 case Type::Paren: 3892 case Type::TypeOf: 3893 case Type::UnaryTransform: 3894 case Type::Attributed: 3895 case Type::SubstTemplateTypeParm: 3896 case Type::PackExpansion: 3897 // Keep walking after single level desugaring. 3898 T = T.getSingleStepDesugaredType(Context); 3899 break; 3900 case Type::Typedef: 3901 T = cast<TypedefType>(Ty)->desugar(); 3902 break; 3903 case Type::Decltype: 3904 T = cast<DecltypeType>(Ty)->desugar(); 3905 break; 3906 case Type::Auto: 3907 case Type::DeducedTemplateSpecialization: 3908 T = cast<DeducedType>(Ty)->getDeducedType(); 3909 break; 3910 case Type::TypeOfExpr: 3911 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3912 break; 3913 case Type::Atomic: 3914 T = cast<AtomicType>(Ty)->getValueType(); 3915 break; 3916 } 3917 } while (!T.isNull() && T->isVariablyModifiedType()); 3918 } 3919 3920 /// \brief Build a sizeof or alignof expression given a type operand. 3921 ExprResult 3922 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3923 SourceLocation OpLoc, 3924 UnaryExprOrTypeTrait ExprKind, 3925 SourceRange R) { 3926 if (!TInfo) 3927 return ExprError(); 3928 3929 QualType T = TInfo->getType(); 3930 3931 if (!T->isDependentType() && 3932 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3933 return ExprError(); 3934 3935 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3936 if (auto *TT = T->getAs<TypedefType>()) { 3937 for (auto I = FunctionScopes.rbegin(), 3938 E = std::prev(FunctionScopes.rend()); 3939 I != E; ++I) { 3940 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3941 if (CSI == nullptr) 3942 break; 3943 DeclContext *DC = nullptr; 3944 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3945 DC = LSI->CallOperator; 3946 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3947 DC = CRSI->TheCapturedDecl; 3948 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3949 DC = BSI->TheDecl; 3950 if (DC) { 3951 if (DC->containsDecl(TT->getDecl())) 3952 break; 3953 captureVariablyModifiedType(Context, T, CSI); 3954 } 3955 } 3956 } 3957 } 3958 3959 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3960 return new (Context) UnaryExprOrTypeTraitExpr( 3961 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3962 } 3963 3964 /// \brief Build a sizeof or alignof expression given an expression 3965 /// operand. 3966 ExprResult 3967 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3968 UnaryExprOrTypeTrait ExprKind) { 3969 ExprResult PE = CheckPlaceholderExpr(E); 3970 if (PE.isInvalid()) 3971 return ExprError(); 3972 3973 E = PE.get(); 3974 3975 // Verify that the operand is valid. 3976 bool isInvalid = false; 3977 if (E->isTypeDependent()) { 3978 // Delay type-checking for type-dependent expressions. 3979 } else if (ExprKind == UETT_AlignOf) { 3980 isInvalid = CheckAlignOfExpr(*this, E); 3981 } else if (ExprKind == UETT_VecStep) { 3982 isInvalid = CheckVecStepExpr(E); 3983 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3984 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3985 isInvalid = true; 3986 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3987 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3988 isInvalid = true; 3989 } else { 3990 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3991 } 3992 3993 if (isInvalid) 3994 return ExprError(); 3995 3996 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3997 PE = TransformToPotentiallyEvaluated(E); 3998 if (PE.isInvalid()) return ExprError(); 3999 E = PE.get(); 4000 } 4001 4002 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4003 return new (Context) UnaryExprOrTypeTraitExpr( 4004 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4005 } 4006 4007 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4008 /// expr and the same for @c alignof and @c __alignof 4009 /// Note that the ArgRange is invalid if isType is false. 4010 ExprResult 4011 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4012 UnaryExprOrTypeTrait ExprKind, bool IsType, 4013 void *TyOrEx, SourceRange ArgRange) { 4014 // If error parsing type, ignore. 4015 if (!TyOrEx) return ExprError(); 4016 4017 if (IsType) { 4018 TypeSourceInfo *TInfo; 4019 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4020 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4021 } 4022 4023 Expr *ArgEx = (Expr *)TyOrEx; 4024 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4025 return Result; 4026 } 4027 4028 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4029 bool IsReal) { 4030 if (V.get()->isTypeDependent()) 4031 return S.Context.DependentTy; 4032 4033 // _Real and _Imag are only l-values for normal l-values. 4034 if (V.get()->getObjectKind() != OK_Ordinary) { 4035 V = S.DefaultLvalueConversion(V.get()); 4036 if (V.isInvalid()) 4037 return QualType(); 4038 } 4039 4040 // These operators return the element type of a complex type. 4041 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4042 return CT->getElementType(); 4043 4044 // Otherwise they pass through real integer and floating point types here. 4045 if (V.get()->getType()->isArithmeticType()) 4046 return V.get()->getType(); 4047 4048 // Test for placeholders. 4049 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4050 if (PR.isInvalid()) return QualType(); 4051 if (PR.get() != V.get()) { 4052 V = PR; 4053 return CheckRealImagOperand(S, V, Loc, IsReal); 4054 } 4055 4056 // Reject anything else. 4057 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4058 << (IsReal ? "__real" : "__imag"); 4059 return QualType(); 4060 } 4061 4062 4063 4064 ExprResult 4065 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4066 tok::TokenKind Kind, Expr *Input) { 4067 UnaryOperatorKind Opc; 4068 switch (Kind) { 4069 default: llvm_unreachable("Unknown unary op!"); 4070 case tok::plusplus: Opc = UO_PostInc; break; 4071 case tok::minusminus: Opc = UO_PostDec; break; 4072 } 4073 4074 // Since this might is a postfix expression, get rid of ParenListExprs. 4075 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4076 if (Result.isInvalid()) return ExprError(); 4077 Input = Result.get(); 4078 4079 return BuildUnaryOp(S, OpLoc, Opc, Input); 4080 } 4081 4082 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4083 /// 4084 /// \return true on error 4085 static bool checkArithmeticOnObjCPointer(Sema &S, 4086 SourceLocation opLoc, 4087 Expr *op) { 4088 assert(op->getType()->isObjCObjectPointerType()); 4089 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4090 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4091 return false; 4092 4093 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4094 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4095 << op->getSourceRange(); 4096 return true; 4097 } 4098 4099 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4100 auto *BaseNoParens = Base->IgnoreParens(); 4101 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4102 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4103 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4104 } 4105 4106 ExprResult 4107 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4108 Expr *idx, SourceLocation rbLoc) { 4109 if (base && !base->getType().isNull() && 4110 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4111 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4112 /*Length=*/nullptr, rbLoc); 4113 4114 // Since this might be a postfix expression, get rid of ParenListExprs. 4115 if (isa<ParenListExpr>(base)) { 4116 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4117 if (result.isInvalid()) return ExprError(); 4118 base = result.get(); 4119 } 4120 4121 // Handle any non-overload placeholder types in the base and index 4122 // expressions. We can't handle overloads here because the other 4123 // operand might be an overloadable type, in which case the overload 4124 // resolution for the operator overload should get the first crack 4125 // at the overload. 4126 bool IsMSPropertySubscript = false; 4127 if (base->getType()->isNonOverloadPlaceholderType()) { 4128 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4129 if (!IsMSPropertySubscript) { 4130 ExprResult result = CheckPlaceholderExpr(base); 4131 if (result.isInvalid()) 4132 return ExprError(); 4133 base = result.get(); 4134 } 4135 } 4136 if (idx->getType()->isNonOverloadPlaceholderType()) { 4137 ExprResult result = CheckPlaceholderExpr(idx); 4138 if (result.isInvalid()) return ExprError(); 4139 idx = result.get(); 4140 } 4141 4142 // Build an unanalyzed expression if either operand is type-dependent. 4143 if (getLangOpts().CPlusPlus && 4144 (base->isTypeDependent() || idx->isTypeDependent())) { 4145 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4146 VK_LValue, OK_Ordinary, rbLoc); 4147 } 4148 4149 // MSDN, property (C++) 4150 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4151 // This attribute can also be used in the declaration of an empty array in a 4152 // class or structure definition. For example: 4153 // __declspec(property(get=GetX, put=PutX)) int x[]; 4154 // The above statement indicates that x[] can be used with one or more array 4155 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4156 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4157 if (IsMSPropertySubscript) { 4158 // Build MS property subscript expression if base is MS property reference 4159 // or MS property subscript. 4160 return new (Context) MSPropertySubscriptExpr( 4161 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4162 } 4163 4164 // Use C++ overloaded-operator rules if either operand has record 4165 // type. The spec says to do this if either type is *overloadable*, 4166 // but enum types can't declare subscript operators or conversion 4167 // operators, so there's nothing interesting for overload resolution 4168 // to do if there aren't any record types involved. 4169 // 4170 // ObjC pointers have their own subscripting logic that is not tied 4171 // to overload resolution and so should not take this path. 4172 if (getLangOpts().CPlusPlus && 4173 (base->getType()->isRecordType() || 4174 (!base->getType()->isObjCObjectPointerType() && 4175 idx->getType()->isRecordType()))) { 4176 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4177 } 4178 4179 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4180 } 4181 4182 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4183 Expr *LowerBound, 4184 SourceLocation ColonLoc, Expr *Length, 4185 SourceLocation RBLoc) { 4186 if (Base->getType()->isPlaceholderType() && 4187 !Base->getType()->isSpecificPlaceholderType( 4188 BuiltinType::OMPArraySection)) { 4189 ExprResult Result = CheckPlaceholderExpr(Base); 4190 if (Result.isInvalid()) 4191 return ExprError(); 4192 Base = Result.get(); 4193 } 4194 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4195 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4196 if (Result.isInvalid()) 4197 return ExprError(); 4198 Result = DefaultLvalueConversion(Result.get()); 4199 if (Result.isInvalid()) 4200 return ExprError(); 4201 LowerBound = Result.get(); 4202 } 4203 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4204 ExprResult Result = CheckPlaceholderExpr(Length); 4205 if (Result.isInvalid()) 4206 return ExprError(); 4207 Result = DefaultLvalueConversion(Result.get()); 4208 if (Result.isInvalid()) 4209 return ExprError(); 4210 Length = Result.get(); 4211 } 4212 4213 // Build an unanalyzed expression if either operand is type-dependent. 4214 if (Base->isTypeDependent() || 4215 (LowerBound && 4216 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4217 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4218 return new (Context) 4219 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4220 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4221 } 4222 4223 // Perform default conversions. 4224 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4225 QualType ResultTy; 4226 if (OriginalTy->isAnyPointerType()) { 4227 ResultTy = OriginalTy->getPointeeType(); 4228 } else if (OriginalTy->isArrayType()) { 4229 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4230 } else { 4231 return ExprError( 4232 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4233 << Base->getSourceRange()); 4234 } 4235 // C99 6.5.2.1p1 4236 if (LowerBound) { 4237 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4238 LowerBound); 4239 if (Res.isInvalid()) 4240 return ExprError(Diag(LowerBound->getExprLoc(), 4241 diag::err_omp_typecheck_section_not_integer) 4242 << 0 << LowerBound->getSourceRange()); 4243 LowerBound = Res.get(); 4244 4245 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4246 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4247 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4248 << 0 << LowerBound->getSourceRange(); 4249 } 4250 if (Length) { 4251 auto Res = 4252 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4253 if (Res.isInvalid()) 4254 return ExprError(Diag(Length->getExprLoc(), 4255 diag::err_omp_typecheck_section_not_integer) 4256 << 1 << Length->getSourceRange()); 4257 Length = Res.get(); 4258 4259 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4260 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4261 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4262 << 1 << Length->getSourceRange(); 4263 } 4264 4265 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4266 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4267 // type. Note that functions are not objects, and that (in C99 parlance) 4268 // incomplete types are not object types. 4269 if (ResultTy->isFunctionType()) { 4270 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4271 << ResultTy << Base->getSourceRange(); 4272 return ExprError(); 4273 } 4274 4275 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4276 diag::err_omp_section_incomplete_type, Base)) 4277 return ExprError(); 4278 4279 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4280 llvm::APSInt LowerBoundValue; 4281 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4282 // OpenMP 4.5, [2.4 Array Sections] 4283 // The array section must be a subset of the original array. 4284 if (LowerBoundValue.isNegative()) { 4285 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4286 << LowerBound->getSourceRange(); 4287 return ExprError(); 4288 } 4289 } 4290 } 4291 4292 if (Length) { 4293 llvm::APSInt LengthValue; 4294 if (Length->EvaluateAsInt(LengthValue, Context)) { 4295 // OpenMP 4.5, [2.4 Array Sections] 4296 // The length must evaluate to non-negative integers. 4297 if (LengthValue.isNegative()) { 4298 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4299 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4300 << Length->getSourceRange(); 4301 return ExprError(); 4302 } 4303 } 4304 } else if (ColonLoc.isValid() && 4305 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4306 !OriginalTy->isVariableArrayType()))) { 4307 // OpenMP 4.5, [2.4 Array Sections] 4308 // When the size of the array dimension is not known, the length must be 4309 // specified explicitly. 4310 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4311 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4312 return ExprError(); 4313 } 4314 4315 if (!Base->getType()->isSpecificPlaceholderType( 4316 BuiltinType::OMPArraySection)) { 4317 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4318 if (Result.isInvalid()) 4319 return ExprError(); 4320 Base = Result.get(); 4321 } 4322 return new (Context) 4323 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4324 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4325 } 4326 4327 ExprResult 4328 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4329 Expr *Idx, SourceLocation RLoc) { 4330 Expr *LHSExp = Base; 4331 Expr *RHSExp = Idx; 4332 4333 ExprValueKind VK = VK_LValue; 4334 ExprObjectKind OK = OK_Ordinary; 4335 4336 // Per C++ core issue 1213, the result is an xvalue if either operand is 4337 // a non-lvalue array, and an lvalue otherwise. 4338 if (getLangOpts().CPlusPlus11 && 4339 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) || 4340 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue()))) 4341 VK = VK_XValue; 4342 4343 // Perform default conversions. 4344 if (!LHSExp->getType()->getAs<VectorType>()) { 4345 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4346 if (Result.isInvalid()) 4347 return ExprError(); 4348 LHSExp = Result.get(); 4349 } 4350 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4351 if (Result.isInvalid()) 4352 return ExprError(); 4353 RHSExp = Result.get(); 4354 4355 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4356 4357 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4358 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4359 // in the subscript position. As a result, we need to derive the array base 4360 // and index from the expression types. 4361 Expr *BaseExpr, *IndexExpr; 4362 QualType ResultType; 4363 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4364 BaseExpr = LHSExp; 4365 IndexExpr = RHSExp; 4366 ResultType = Context.DependentTy; 4367 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4368 BaseExpr = LHSExp; 4369 IndexExpr = RHSExp; 4370 ResultType = PTy->getPointeeType(); 4371 } else if (const ObjCObjectPointerType *PTy = 4372 LHSTy->getAs<ObjCObjectPointerType>()) { 4373 BaseExpr = LHSExp; 4374 IndexExpr = RHSExp; 4375 4376 // Use custom logic if this should be the pseudo-object subscript 4377 // expression. 4378 if (!LangOpts.isSubscriptPointerArithmetic()) 4379 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4380 nullptr); 4381 4382 ResultType = PTy->getPointeeType(); 4383 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4384 // Handle the uncommon case of "123[Ptr]". 4385 BaseExpr = RHSExp; 4386 IndexExpr = LHSExp; 4387 ResultType = PTy->getPointeeType(); 4388 } else if (const ObjCObjectPointerType *PTy = 4389 RHSTy->getAs<ObjCObjectPointerType>()) { 4390 // Handle the uncommon case of "123[Ptr]". 4391 BaseExpr = RHSExp; 4392 IndexExpr = LHSExp; 4393 ResultType = PTy->getPointeeType(); 4394 if (!LangOpts.isSubscriptPointerArithmetic()) { 4395 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4396 << ResultType << BaseExpr->getSourceRange(); 4397 return ExprError(); 4398 } 4399 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4400 BaseExpr = LHSExp; // vectors: V[123] 4401 IndexExpr = RHSExp; 4402 VK = LHSExp->getValueKind(); 4403 if (VK != VK_RValue) 4404 OK = OK_VectorComponent; 4405 4406 ResultType = VTy->getElementType(); 4407 QualType BaseType = BaseExpr->getType(); 4408 Qualifiers BaseQuals = BaseType.getQualifiers(); 4409 Qualifiers MemberQuals = ResultType.getQualifiers(); 4410 Qualifiers Combined = BaseQuals + MemberQuals; 4411 if (Combined != MemberQuals) 4412 ResultType = Context.getQualifiedType(ResultType, Combined); 4413 } else if (LHSTy->isArrayType()) { 4414 // If we see an array that wasn't promoted by 4415 // DefaultFunctionArrayLvalueConversion, it must be an array that 4416 // wasn't promoted because of the C90 rule that doesn't 4417 // allow promoting non-lvalue arrays. Warn, then 4418 // force the promotion here. 4419 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4420 LHSExp->getSourceRange(); 4421 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4422 CK_ArrayToPointerDecay).get(); 4423 LHSTy = LHSExp->getType(); 4424 4425 BaseExpr = LHSExp; 4426 IndexExpr = RHSExp; 4427 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4428 } else if (RHSTy->isArrayType()) { 4429 // Same as previous, except for 123[f().a] case 4430 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4431 RHSExp->getSourceRange(); 4432 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4433 CK_ArrayToPointerDecay).get(); 4434 RHSTy = RHSExp->getType(); 4435 4436 BaseExpr = RHSExp; 4437 IndexExpr = LHSExp; 4438 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4439 } else { 4440 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4441 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4442 } 4443 // C99 6.5.2.1p1 4444 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4445 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4446 << IndexExpr->getSourceRange()); 4447 4448 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4449 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4450 && !IndexExpr->isTypeDependent()) 4451 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4452 4453 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4454 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4455 // type. Note that Functions are not objects, and that (in C99 parlance) 4456 // incomplete types are not object types. 4457 if (ResultType->isFunctionType()) { 4458 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4459 << ResultType << BaseExpr->getSourceRange(); 4460 return ExprError(); 4461 } 4462 4463 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4464 // GNU extension: subscripting on pointer to void 4465 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4466 << BaseExpr->getSourceRange(); 4467 4468 // C forbids expressions of unqualified void type from being l-values. 4469 // See IsCForbiddenLValueType. 4470 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4471 } else if (!ResultType->isDependentType() && 4472 RequireCompleteType(LLoc, ResultType, 4473 diag::err_subscript_incomplete_type, BaseExpr)) 4474 return ExprError(); 4475 4476 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4477 !ResultType.isCForbiddenLValueType()); 4478 4479 return new (Context) 4480 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4481 } 4482 4483 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4484 ParmVarDecl *Param) { 4485 if (Param->hasUnparsedDefaultArg()) { 4486 Diag(CallLoc, 4487 diag::err_use_of_default_argument_to_function_declared_later) << 4488 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4489 Diag(UnparsedDefaultArgLocs[Param], 4490 diag::note_default_argument_declared_here); 4491 return true; 4492 } 4493 4494 if (Param->hasUninstantiatedDefaultArg()) { 4495 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4496 4497 EnterExpressionEvaluationContext EvalContext( 4498 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4499 4500 // Instantiate the expression. 4501 // 4502 // FIXME: Pass in a correct Pattern argument, otherwise 4503 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4504 // 4505 // template<typename T> 4506 // struct A { 4507 // static int FooImpl(); 4508 // 4509 // template<typename Tp> 4510 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4511 // // template argument list [[T], [Tp]], should be [[Tp]]. 4512 // friend A<Tp> Foo(int a); 4513 // }; 4514 // 4515 // template<typename T> 4516 // A<T> Foo(int a = A<T>::FooImpl()); 4517 MultiLevelTemplateArgumentList MutiLevelArgList 4518 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4519 4520 InstantiatingTemplate Inst(*this, CallLoc, Param, 4521 MutiLevelArgList.getInnermost()); 4522 if (Inst.isInvalid()) 4523 return true; 4524 if (Inst.isAlreadyInstantiating()) { 4525 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4526 Param->setInvalidDecl(); 4527 return true; 4528 } 4529 4530 ExprResult Result; 4531 { 4532 // C++ [dcl.fct.default]p5: 4533 // The names in the [default argument] expression are bound, and 4534 // the semantic constraints are checked, at the point where the 4535 // default argument expression appears. 4536 ContextRAII SavedContext(*this, FD); 4537 LocalInstantiationScope Local(*this); 4538 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4539 /*DirectInit*/false); 4540 } 4541 if (Result.isInvalid()) 4542 return true; 4543 4544 // Check the expression as an initializer for the parameter. 4545 InitializedEntity Entity 4546 = InitializedEntity::InitializeParameter(Context, Param); 4547 InitializationKind Kind 4548 = InitializationKind::CreateCopy(Param->getLocation(), 4549 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4550 Expr *ResultE = Result.getAs<Expr>(); 4551 4552 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4553 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4554 if (Result.isInvalid()) 4555 return true; 4556 4557 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4558 Param->getOuterLocStart()); 4559 if (Result.isInvalid()) 4560 return true; 4561 4562 // Remember the instantiated default argument. 4563 Param->setDefaultArg(Result.getAs<Expr>()); 4564 if (ASTMutationListener *L = getASTMutationListener()) { 4565 L->DefaultArgumentInstantiated(Param); 4566 } 4567 } 4568 4569 // If the default argument expression is not set yet, we are building it now. 4570 if (!Param->hasInit()) { 4571 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD; 4572 Param->setInvalidDecl(); 4573 return true; 4574 } 4575 4576 // If the default expression creates temporaries, we need to 4577 // push them to the current stack of expression temporaries so they'll 4578 // be properly destroyed. 4579 // FIXME: We should really be rebuilding the default argument with new 4580 // bound temporaries; see the comment in PR5810. 4581 // We don't need to do that with block decls, though, because 4582 // blocks in default argument expression can never capture anything. 4583 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4584 // Set the "needs cleanups" bit regardless of whether there are 4585 // any explicit objects. 4586 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4587 4588 // Append all the objects to the cleanup list. Right now, this 4589 // should always be a no-op, because blocks in default argument 4590 // expressions should never be able to capture anything. 4591 assert(!Init->getNumObjects() && 4592 "default argument expression has capturing blocks?"); 4593 } 4594 4595 // We already type-checked the argument, so we know it works. 4596 // Just mark all of the declarations in this potentially-evaluated expression 4597 // as being "referenced". 4598 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4599 /*SkipLocalVariables=*/true); 4600 return false; 4601 } 4602 4603 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4604 FunctionDecl *FD, ParmVarDecl *Param) { 4605 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4606 return ExprError(); 4607 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4608 } 4609 4610 Sema::VariadicCallType 4611 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4612 Expr *Fn) { 4613 if (Proto && Proto->isVariadic()) { 4614 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4615 return VariadicConstructor; 4616 else if (Fn && Fn->getType()->isBlockPointerType()) 4617 return VariadicBlock; 4618 else if (FDecl) { 4619 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4620 if (Method->isInstance()) 4621 return VariadicMethod; 4622 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4623 return VariadicMethod; 4624 return VariadicFunction; 4625 } 4626 return VariadicDoesNotApply; 4627 } 4628 4629 namespace { 4630 class FunctionCallCCC : public FunctionCallFilterCCC { 4631 public: 4632 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4633 unsigned NumArgs, MemberExpr *ME) 4634 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4635 FunctionName(FuncName) {} 4636 4637 bool ValidateCandidate(const TypoCorrection &candidate) override { 4638 if (!candidate.getCorrectionSpecifier() || 4639 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4640 return false; 4641 } 4642 4643 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4644 } 4645 4646 private: 4647 const IdentifierInfo *const FunctionName; 4648 }; 4649 } 4650 4651 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4652 FunctionDecl *FDecl, 4653 ArrayRef<Expr *> Args) { 4654 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4655 DeclarationName FuncName = FDecl->getDeclName(); 4656 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4657 4658 if (TypoCorrection Corrected = S.CorrectTypo( 4659 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4660 S.getScopeForContext(S.CurContext), nullptr, 4661 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4662 Args.size(), ME), 4663 Sema::CTK_ErrorRecovery)) { 4664 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4665 if (Corrected.isOverloaded()) { 4666 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4667 OverloadCandidateSet::iterator Best; 4668 for (NamedDecl *CD : Corrected) { 4669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4670 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4671 OCS); 4672 } 4673 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4674 case OR_Success: 4675 ND = Best->FoundDecl; 4676 Corrected.setCorrectionDecl(ND); 4677 break; 4678 default: 4679 break; 4680 } 4681 } 4682 ND = ND->getUnderlyingDecl(); 4683 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4684 return Corrected; 4685 } 4686 } 4687 return TypoCorrection(); 4688 } 4689 4690 /// ConvertArgumentsForCall - Converts the arguments specified in 4691 /// Args/NumArgs to the parameter types of the function FDecl with 4692 /// function prototype Proto. Call is the call expression itself, and 4693 /// Fn is the function expression. For a C++ member function, this 4694 /// routine does not attempt to convert the object argument. Returns 4695 /// true if the call is ill-formed. 4696 bool 4697 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4698 FunctionDecl *FDecl, 4699 const FunctionProtoType *Proto, 4700 ArrayRef<Expr *> Args, 4701 SourceLocation RParenLoc, 4702 bool IsExecConfig) { 4703 // Bail out early if calling a builtin with custom typechecking. 4704 if (FDecl) 4705 if (unsigned ID = FDecl->getBuiltinID()) 4706 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4707 return false; 4708 4709 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4710 // assignment, to the types of the corresponding parameter, ... 4711 unsigned NumParams = Proto->getNumParams(); 4712 bool Invalid = false; 4713 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4714 unsigned FnKind = Fn->getType()->isBlockPointerType() 4715 ? 1 /* block */ 4716 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4717 : 0 /* function */); 4718 4719 // If too few arguments are available (and we don't have default 4720 // arguments for the remaining parameters), don't make the call. 4721 if (Args.size() < NumParams) { 4722 if (Args.size() < MinArgs) { 4723 TypoCorrection TC; 4724 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4725 unsigned diag_id = 4726 MinArgs == NumParams && !Proto->isVariadic() 4727 ? diag::err_typecheck_call_too_few_args_suggest 4728 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4729 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4730 << static_cast<unsigned>(Args.size()) 4731 << TC.getCorrectionRange()); 4732 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4733 Diag(RParenLoc, 4734 MinArgs == NumParams && !Proto->isVariadic() 4735 ? diag::err_typecheck_call_too_few_args_one 4736 : diag::err_typecheck_call_too_few_args_at_least_one) 4737 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4738 else 4739 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4740 ? diag::err_typecheck_call_too_few_args 4741 : diag::err_typecheck_call_too_few_args_at_least) 4742 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4743 << Fn->getSourceRange(); 4744 4745 // Emit the location of the prototype. 4746 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4747 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4748 << FDecl; 4749 4750 return true; 4751 } 4752 Call->setNumArgs(Context, NumParams); 4753 } 4754 4755 // If too many are passed and not variadic, error on the extras and drop 4756 // them. 4757 if (Args.size() > NumParams) { 4758 if (!Proto->isVariadic()) { 4759 TypoCorrection TC; 4760 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4761 unsigned diag_id = 4762 MinArgs == NumParams && !Proto->isVariadic() 4763 ? diag::err_typecheck_call_too_many_args_suggest 4764 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4765 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4766 << static_cast<unsigned>(Args.size()) 4767 << TC.getCorrectionRange()); 4768 } else if (NumParams == 1 && FDecl && 4769 FDecl->getParamDecl(0)->getDeclName()) 4770 Diag(Args[NumParams]->getLocStart(), 4771 MinArgs == NumParams 4772 ? diag::err_typecheck_call_too_many_args_one 4773 : diag::err_typecheck_call_too_many_args_at_most_one) 4774 << FnKind << FDecl->getParamDecl(0) 4775 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4776 << SourceRange(Args[NumParams]->getLocStart(), 4777 Args.back()->getLocEnd()); 4778 else 4779 Diag(Args[NumParams]->getLocStart(), 4780 MinArgs == NumParams 4781 ? diag::err_typecheck_call_too_many_args 4782 : diag::err_typecheck_call_too_many_args_at_most) 4783 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4784 << Fn->getSourceRange() 4785 << SourceRange(Args[NumParams]->getLocStart(), 4786 Args.back()->getLocEnd()); 4787 4788 // Emit the location of the prototype. 4789 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4790 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4791 << FDecl; 4792 4793 // This deletes the extra arguments. 4794 Call->setNumArgs(Context, NumParams); 4795 return true; 4796 } 4797 } 4798 SmallVector<Expr *, 8> AllArgs; 4799 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4800 4801 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4802 Proto, 0, Args, AllArgs, CallType); 4803 if (Invalid) 4804 return true; 4805 unsigned TotalNumArgs = AllArgs.size(); 4806 for (unsigned i = 0; i < TotalNumArgs; ++i) 4807 Call->setArg(i, AllArgs[i]); 4808 4809 return false; 4810 } 4811 4812 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4813 const FunctionProtoType *Proto, 4814 unsigned FirstParam, ArrayRef<Expr *> Args, 4815 SmallVectorImpl<Expr *> &AllArgs, 4816 VariadicCallType CallType, bool AllowExplicit, 4817 bool IsListInitialization) { 4818 unsigned NumParams = Proto->getNumParams(); 4819 bool Invalid = false; 4820 size_t ArgIx = 0; 4821 // Continue to check argument types (even if we have too few/many args). 4822 for (unsigned i = FirstParam; i < NumParams; i++) { 4823 QualType ProtoArgType = Proto->getParamType(i); 4824 4825 Expr *Arg; 4826 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4827 if (ArgIx < Args.size()) { 4828 Arg = Args[ArgIx++]; 4829 4830 if (RequireCompleteType(Arg->getLocStart(), 4831 ProtoArgType, 4832 diag::err_call_incomplete_argument, Arg)) 4833 return true; 4834 4835 // Strip the unbridged-cast placeholder expression off, if applicable. 4836 bool CFAudited = false; 4837 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4838 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4839 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4840 Arg = stripARCUnbridgedCast(Arg); 4841 else if (getLangOpts().ObjCAutoRefCount && 4842 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4843 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4844 CFAudited = true; 4845 4846 if (Proto->getExtParameterInfo(i).isNoEscape()) 4847 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4848 BE->getBlockDecl()->setDoesNotEscape(); 4849 4850 InitializedEntity Entity = 4851 Param ? InitializedEntity::InitializeParameter(Context, Param, 4852 ProtoArgType) 4853 : InitializedEntity::InitializeParameter( 4854 Context, ProtoArgType, Proto->isParamConsumed(i)); 4855 4856 // Remember that parameter belongs to a CF audited API. 4857 if (CFAudited) 4858 Entity.setParameterCFAudited(); 4859 4860 ExprResult ArgE = PerformCopyInitialization( 4861 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4862 if (ArgE.isInvalid()) 4863 return true; 4864 4865 Arg = ArgE.getAs<Expr>(); 4866 } else { 4867 assert(Param && "can't use default arguments without a known callee"); 4868 4869 ExprResult ArgExpr = 4870 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4871 if (ArgExpr.isInvalid()) 4872 return true; 4873 4874 Arg = ArgExpr.getAs<Expr>(); 4875 } 4876 4877 // Check for array bounds violations for each argument to the call. This 4878 // check only triggers warnings when the argument isn't a more complex Expr 4879 // with its own checking, such as a BinaryOperator. 4880 CheckArrayAccess(Arg); 4881 4882 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4883 CheckStaticArrayArgument(CallLoc, Param, Arg); 4884 4885 AllArgs.push_back(Arg); 4886 } 4887 4888 // If this is a variadic call, handle args passed through "...". 4889 if (CallType != VariadicDoesNotApply) { 4890 // Assume that extern "C" functions with variadic arguments that 4891 // return __unknown_anytype aren't *really* variadic. 4892 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4893 FDecl->isExternC()) { 4894 for (Expr *A : Args.slice(ArgIx)) { 4895 QualType paramType; // ignored 4896 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4897 Invalid |= arg.isInvalid(); 4898 AllArgs.push_back(arg.get()); 4899 } 4900 4901 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4902 } else { 4903 for (Expr *A : Args.slice(ArgIx)) { 4904 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4905 Invalid |= Arg.isInvalid(); 4906 AllArgs.push_back(Arg.get()); 4907 } 4908 } 4909 4910 // Check for array bounds violations. 4911 for (Expr *A : Args.slice(ArgIx)) 4912 CheckArrayAccess(A); 4913 } 4914 return Invalid; 4915 } 4916 4917 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4918 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4919 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4920 TL = DTL.getOriginalLoc(); 4921 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4922 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4923 << ATL.getLocalSourceRange(); 4924 } 4925 4926 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4927 /// array parameter, check that it is non-null, and that if it is formed by 4928 /// array-to-pointer decay, the underlying array is sufficiently large. 4929 /// 4930 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4931 /// array type derivation, then for each call to the function, the value of the 4932 /// corresponding actual argument shall provide access to the first element of 4933 /// an array with at least as many elements as specified by the size expression. 4934 void 4935 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4936 ParmVarDecl *Param, 4937 const Expr *ArgExpr) { 4938 // Static array parameters are not supported in C++. 4939 if (!Param || getLangOpts().CPlusPlus) 4940 return; 4941 4942 QualType OrigTy = Param->getOriginalType(); 4943 4944 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4945 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4946 return; 4947 4948 if (ArgExpr->isNullPointerConstant(Context, 4949 Expr::NPC_NeverValueDependent)) { 4950 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4951 DiagnoseCalleeStaticArrayParam(*this, Param); 4952 return; 4953 } 4954 4955 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4956 if (!CAT) 4957 return; 4958 4959 const ConstantArrayType *ArgCAT = 4960 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4961 if (!ArgCAT) 4962 return; 4963 4964 if (ArgCAT->getSize().ult(CAT->getSize())) { 4965 Diag(CallLoc, diag::warn_static_array_too_small) 4966 << ArgExpr->getSourceRange() 4967 << (unsigned) ArgCAT->getSize().getZExtValue() 4968 << (unsigned) CAT->getSize().getZExtValue(); 4969 DiagnoseCalleeStaticArrayParam(*this, Param); 4970 } 4971 } 4972 4973 /// Given a function expression of unknown-any type, try to rebuild it 4974 /// to have a function type. 4975 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4976 4977 /// Is the given type a placeholder that we need to lower out 4978 /// immediately during argument processing? 4979 static bool isPlaceholderToRemoveAsArg(QualType type) { 4980 // Placeholders are never sugared. 4981 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4982 if (!placeholder) return false; 4983 4984 switch (placeholder->getKind()) { 4985 // Ignore all the non-placeholder types. 4986 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4987 case BuiltinType::Id: 4988 #include "clang/Basic/OpenCLImageTypes.def" 4989 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4990 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4991 #include "clang/AST/BuiltinTypes.def" 4992 return false; 4993 4994 // We cannot lower out overload sets; they might validly be resolved 4995 // by the call machinery. 4996 case BuiltinType::Overload: 4997 return false; 4998 4999 // Unbridged casts in ARC can be handled in some call positions and 5000 // should be left in place. 5001 case BuiltinType::ARCUnbridgedCast: 5002 return false; 5003 5004 // Pseudo-objects should be converted as soon as possible. 5005 case BuiltinType::PseudoObject: 5006 return true; 5007 5008 // The debugger mode could theoretically but currently does not try 5009 // to resolve unknown-typed arguments based on known parameter types. 5010 case BuiltinType::UnknownAny: 5011 return true; 5012 5013 // These are always invalid as call arguments and should be reported. 5014 case BuiltinType::BoundMember: 5015 case BuiltinType::BuiltinFn: 5016 case BuiltinType::OMPArraySection: 5017 return true; 5018 5019 } 5020 llvm_unreachable("bad builtin type kind"); 5021 } 5022 5023 /// Check an argument list for placeholders that we won't try to 5024 /// handle later. 5025 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5026 // Apply this processing to all the arguments at once instead of 5027 // dying at the first failure. 5028 bool hasInvalid = false; 5029 for (size_t i = 0, e = args.size(); i != e; i++) { 5030 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5031 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5032 if (result.isInvalid()) hasInvalid = true; 5033 else args[i] = result.get(); 5034 } else if (hasInvalid) { 5035 (void)S.CorrectDelayedTyposInExpr(args[i]); 5036 } 5037 } 5038 return hasInvalid; 5039 } 5040 5041 /// If a builtin function has a pointer argument with no explicit address 5042 /// space, then it should be able to accept a pointer to any address 5043 /// space as input. In order to do this, we need to replace the 5044 /// standard builtin declaration with one that uses the same address space 5045 /// as the call. 5046 /// 5047 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5048 /// it does not contain any pointer arguments without 5049 /// an address space qualifer. Otherwise the rewritten 5050 /// FunctionDecl is returned. 5051 /// TODO: Handle pointer return types. 5052 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5053 const FunctionDecl *FDecl, 5054 MultiExprArg ArgExprs) { 5055 5056 QualType DeclType = FDecl->getType(); 5057 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5058 5059 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5060 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5061 return nullptr; 5062 5063 bool NeedsNewDecl = false; 5064 unsigned i = 0; 5065 SmallVector<QualType, 8> OverloadParams; 5066 5067 for (QualType ParamType : FT->param_types()) { 5068 5069 // Convert array arguments to pointer to simplify type lookup. 5070 ExprResult ArgRes = 5071 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5072 if (ArgRes.isInvalid()) 5073 return nullptr; 5074 Expr *Arg = ArgRes.get(); 5075 QualType ArgType = Arg->getType(); 5076 if (!ParamType->isPointerType() || 5077 ParamType.getQualifiers().hasAddressSpace() || 5078 !ArgType->isPointerType() || 5079 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5080 OverloadParams.push_back(ParamType); 5081 continue; 5082 } 5083 5084 NeedsNewDecl = true; 5085 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5086 5087 QualType PointeeType = ParamType->getPointeeType(); 5088 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5089 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5090 } 5091 5092 if (!NeedsNewDecl) 5093 return nullptr; 5094 5095 FunctionProtoType::ExtProtoInfo EPI; 5096 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5097 OverloadParams, EPI); 5098 DeclContext *Parent = Context.getTranslationUnitDecl(); 5099 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5100 FDecl->getLocation(), 5101 FDecl->getLocation(), 5102 FDecl->getIdentifier(), 5103 OverloadTy, 5104 /*TInfo=*/nullptr, 5105 SC_Extern, false, 5106 /*hasPrototype=*/true); 5107 SmallVector<ParmVarDecl*, 16> Params; 5108 FT = cast<FunctionProtoType>(OverloadTy); 5109 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5110 QualType ParamType = FT->getParamType(i); 5111 ParmVarDecl *Parm = 5112 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5113 SourceLocation(), nullptr, ParamType, 5114 /*TInfo=*/nullptr, SC_None, nullptr); 5115 Parm->setScopeInfo(0, i); 5116 Params.push_back(Parm); 5117 } 5118 OverloadDecl->setParams(Params); 5119 return OverloadDecl; 5120 } 5121 5122 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5123 FunctionDecl *Callee, 5124 MultiExprArg ArgExprs) { 5125 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5126 // similar attributes) really don't like it when functions are called with an 5127 // invalid number of args. 5128 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5129 /*PartialOverloading=*/false) && 5130 !Callee->isVariadic()) 5131 return; 5132 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5133 return; 5134 5135 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5136 S.Diag(Fn->getLocStart(), 5137 isa<CXXMethodDecl>(Callee) 5138 ? diag::err_ovl_no_viable_member_function_in_call 5139 : diag::err_ovl_no_viable_function_in_call) 5140 << Callee << Callee->getSourceRange(); 5141 S.Diag(Callee->getLocation(), 5142 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5143 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5144 return; 5145 } 5146 } 5147 5148 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5149 const UnresolvedMemberExpr *const UME, Sema &S) { 5150 5151 const auto GetFunctionLevelDCIfCXXClass = 5152 [](Sema &S) -> const CXXRecordDecl * { 5153 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5154 if (!DC || !DC->getParent()) 5155 return nullptr; 5156 5157 // If the call to some member function was made from within a member 5158 // function body 'M' return return 'M's parent. 5159 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5160 return MD->getParent()->getCanonicalDecl(); 5161 // else the call was made from within a default member initializer of a 5162 // class, so return the class. 5163 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5164 return RD->getCanonicalDecl(); 5165 return nullptr; 5166 }; 5167 // If our DeclContext is neither a member function nor a class (in the 5168 // case of a lambda in a default member initializer), we can't have an 5169 // enclosing 'this'. 5170 5171 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5172 if (!CurParentClass) 5173 return false; 5174 5175 // The naming class for implicit member functions call is the class in which 5176 // name lookup starts. 5177 const CXXRecordDecl *const NamingClass = 5178 UME->getNamingClass()->getCanonicalDecl(); 5179 assert(NamingClass && "Must have naming class even for implicit access"); 5180 5181 // If the unresolved member functions were found in a 'naming class' that is 5182 // related (either the same or derived from) to the class that contains the 5183 // member function that itself contained the implicit member access. 5184 5185 return CurParentClass == NamingClass || 5186 CurParentClass->isDerivedFrom(NamingClass); 5187 } 5188 5189 static void 5190 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5191 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5192 5193 if (!UME) 5194 return; 5195 5196 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5197 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5198 // already been captured, or if this is an implicit member function call (if 5199 // it isn't, an attempt to capture 'this' should already have been made). 5200 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5201 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5202 return; 5203 5204 // Check if the naming class in which the unresolved members were found is 5205 // related (same as or is a base of) to the enclosing class. 5206 5207 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5208 return; 5209 5210 5211 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5212 // If the enclosing function is not dependent, then this lambda is 5213 // capture ready, so if we can capture this, do so. 5214 if (!EnclosingFunctionCtx->isDependentContext()) { 5215 // If the current lambda and all enclosing lambdas can capture 'this' - 5216 // then go ahead and capture 'this' (since our unresolved overload set 5217 // contains at least one non-static member function). 5218 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5219 S.CheckCXXThisCapture(CallLoc); 5220 } else if (S.CurContext->isDependentContext()) { 5221 // ... since this is an implicit member reference, that might potentially 5222 // involve a 'this' capture, mark 'this' for potential capture in 5223 // enclosing lambdas. 5224 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5225 CurLSI->addPotentialThisCapture(CallLoc); 5226 } 5227 } 5228 5229 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5230 /// This provides the location of the left/right parens and a list of comma 5231 /// locations. 5232 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5233 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5234 Expr *ExecConfig, bool IsExecConfig) { 5235 // Since this might be a postfix expression, get rid of ParenListExprs. 5236 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5237 if (Result.isInvalid()) return ExprError(); 5238 Fn = Result.get(); 5239 5240 if (checkArgsForPlaceholders(*this, ArgExprs)) 5241 return ExprError(); 5242 5243 if (getLangOpts().CPlusPlus) { 5244 // If this is a pseudo-destructor expression, build the call immediately. 5245 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5246 if (!ArgExprs.empty()) { 5247 // Pseudo-destructor calls should not have any arguments. 5248 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5249 << FixItHint::CreateRemoval( 5250 SourceRange(ArgExprs.front()->getLocStart(), 5251 ArgExprs.back()->getLocEnd())); 5252 } 5253 5254 return new (Context) 5255 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5256 } 5257 if (Fn->getType() == Context.PseudoObjectTy) { 5258 ExprResult result = CheckPlaceholderExpr(Fn); 5259 if (result.isInvalid()) return ExprError(); 5260 Fn = result.get(); 5261 } 5262 5263 // Determine whether this is a dependent call inside a C++ template, 5264 // in which case we won't do any semantic analysis now. 5265 bool Dependent = false; 5266 if (Fn->isTypeDependent()) 5267 Dependent = true; 5268 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5269 Dependent = true; 5270 5271 if (Dependent) { 5272 if (ExecConfig) { 5273 return new (Context) CUDAKernelCallExpr( 5274 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5275 Context.DependentTy, VK_RValue, RParenLoc); 5276 } else { 5277 5278 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5279 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5280 Fn->getLocStart()); 5281 5282 return new (Context) CallExpr( 5283 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5284 } 5285 } 5286 5287 // Determine whether this is a call to an object (C++ [over.call.object]). 5288 if (Fn->getType()->isRecordType()) 5289 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5290 RParenLoc); 5291 5292 if (Fn->getType() == Context.UnknownAnyTy) { 5293 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5294 if (result.isInvalid()) return ExprError(); 5295 Fn = result.get(); 5296 } 5297 5298 if (Fn->getType() == Context.BoundMemberTy) { 5299 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5300 RParenLoc); 5301 } 5302 } 5303 5304 // Check for overloaded calls. This can happen even in C due to extensions. 5305 if (Fn->getType() == Context.OverloadTy) { 5306 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5307 5308 // We aren't supposed to apply this logic if there's an '&' involved. 5309 if (!find.HasFormOfMemberPointer) { 5310 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5311 return new (Context) CallExpr( 5312 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5313 OverloadExpr *ovl = find.Expression; 5314 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5315 return BuildOverloadedCallExpr( 5316 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5317 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5318 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5319 RParenLoc); 5320 } 5321 } 5322 5323 // If we're directly calling a function, get the appropriate declaration. 5324 if (Fn->getType() == Context.UnknownAnyTy) { 5325 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5326 if (result.isInvalid()) return ExprError(); 5327 Fn = result.get(); 5328 } 5329 5330 Expr *NakedFn = Fn->IgnoreParens(); 5331 5332 bool CallingNDeclIndirectly = false; 5333 NamedDecl *NDecl = nullptr; 5334 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5335 if (UnOp->getOpcode() == UO_AddrOf) { 5336 CallingNDeclIndirectly = true; 5337 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5338 } 5339 } 5340 5341 if (isa<DeclRefExpr>(NakedFn)) { 5342 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5343 5344 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5345 if (FDecl && FDecl->getBuiltinID()) { 5346 // Rewrite the function decl for this builtin by replacing parameters 5347 // with no explicit address space with the address space of the arguments 5348 // in ArgExprs. 5349 if ((FDecl = 5350 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5351 NDecl = FDecl; 5352 Fn = DeclRefExpr::Create( 5353 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5354 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5355 } 5356 } 5357 } else if (isa<MemberExpr>(NakedFn)) 5358 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5359 5360 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5361 if (CallingNDeclIndirectly && 5362 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5363 Fn->getLocStart())) 5364 return ExprError(); 5365 5366 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5367 return ExprError(); 5368 5369 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5370 } 5371 5372 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5373 ExecConfig, IsExecConfig); 5374 } 5375 5376 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5377 /// 5378 /// __builtin_astype( value, dst type ) 5379 /// 5380 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5381 SourceLocation BuiltinLoc, 5382 SourceLocation RParenLoc) { 5383 ExprValueKind VK = VK_RValue; 5384 ExprObjectKind OK = OK_Ordinary; 5385 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5386 QualType SrcTy = E->getType(); 5387 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5388 return ExprError(Diag(BuiltinLoc, 5389 diag::err_invalid_astype_of_different_size) 5390 << DstTy 5391 << SrcTy 5392 << E->getSourceRange()); 5393 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5394 } 5395 5396 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5397 /// provided arguments. 5398 /// 5399 /// __builtin_convertvector( value, dst type ) 5400 /// 5401 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5402 SourceLocation BuiltinLoc, 5403 SourceLocation RParenLoc) { 5404 TypeSourceInfo *TInfo; 5405 GetTypeFromParser(ParsedDestTy, &TInfo); 5406 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5407 } 5408 5409 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5410 /// i.e. an expression not of \p OverloadTy. The expression should 5411 /// unary-convert to an expression of function-pointer or 5412 /// block-pointer type. 5413 /// 5414 /// \param NDecl the declaration being called, if available 5415 ExprResult 5416 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5417 SourceLocation LParenLoc, 5418 ArrayRef<Expr *> Args, 5419 SourceLocation RParenLoc, 5420 Expr *Config, bool IsExecConfig) { 5421 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5422 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5423 5424 // Functions with 'interrupt' attribute cannot be called directly. 5425 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5426 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5427 return ExprError(); 5428 } 5429 5430 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5431 // so there's some risk when calling out to non-interrupt handler functions 5432 // that the callee might not preserve them. This is easy to diagnose here, 5433 // but can be very challenging to debug. 5434 if (auto *Caller = getCurFunctionDecl()) 5435 if (Caller->hasAttr<ARMInterruptAttr>()) { 5436 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5437 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5438 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5439 } 5440 5441 // Promote the function operand. 5442 // We special-case function promotion here because we only allow promoting 5443 // builtin functions to function pointers in the callee of a call. 5444 ExprResult Result; 5445 if (BuiltinID && 5446 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5447 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5448 CK_BuiltinFnToFnPtr).get(); 5449 } else { 5450 Result = CallExprUnaryConversions(Fn); 5451 } 5452 if (Result.isInvalid()) 5453 return ExprError(); 5454 Fn = Result.get(); 5455 5456 // Make the call expr early, before semantic checks. This guarantees cleanup 5457 // of arguments and function on error. 5458 CallExpr *TheCall; 5459 if (Config) 5460 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5461 cast<CallExpr>(Config), Args, 5462 Context.BoolTy, VK_RValue, 5463 RParenLoc); 5464 else 5465 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5466 VK_RValue, RParenLoc); 5467 5468 if (!getLangOpts().CPlusPlus) { 5469 // C cannot always handle TypoExpr nodes in builtin calls and direct 5470 // function calls as their argument checking don't necessarily handle 5471 // dependent types properly, so make sure any TypoExprs have been 5472 // dealt with. 5473 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5474 if (!Result.isUsable()) return ExprError(); 5475 TheCall = dyn_cast<CallExpr>(Result.get()); 5476 if (!TheCall) return Result; 5477 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5478 } 5479 5480 // Bail out early if calling a builtin with custom typechecking. 5481 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5482 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5483 5484 retry: 5485 const FunctionType *FuncT; 5486 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5487 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5488 // have type pointer to function". 5489 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5490 if (!FuncT) 5491 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5492 << Fn->getType() << Fn->getSourceRange()); 5493 } else if (const BlockPointerType *BPT = 5494 Fn->getType()->getAs<BlockPointerType>()) { 5495 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5496 } else { 5497 // Handle calls to expressions of unknown-any type. 5498 if (Fn->getType() == Context.UnknownAnyTy) { 5499 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5500 if (rewrite.isInvalid()) return ExprError(); 5501 Fn = rewrite.get(); 5502 TheCall->setCallee(Fn); 5503 goto retry; 5504 } 5505 5506 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5507 << Fn->getType() << Fn->getSourceRange()); 5508 } 5509 5510 if (getLangOpts().CUDA) { 5511 if (Config) { 5512 // CUDA: Kernel calls must be to global functions 5513 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5514 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5515 << FDecl << Fn->getSourceRange()); 5516 5517 // CUDA: Kernel function must have 'void' return type 5518 if (!FuncT->getReturnType()->isVoidType()) 5519 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5520 << Fn->getType() << Fn->getSourceRange()); 5521 } else { 5522 // CUDA: Calls to global functions must be configured 5523 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5524 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5525 << FDecl << Fn->getSourceRange()); 5526 } 5527 } 5528 5529 // Check for a valid return type 5530 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5531 FDecl)) 5532 return ExprError(); 5533 5534 // We know the result type of the call, set it. 5535 TheCall->setType(FuncT->getCallResultType(Context)); 5536 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5537 5538 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5539 if (Proto) { 5540 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5541 IsExecConfig)) 5542 return ExprError(); 5543 } else { 5544 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5545 5546 if (FDecl) { 5547 // Check if we have too few/too many template arguments, based 5548 // on our knowledge of the function definition. 5549 const FunctionDecl *Def = nullptr; 5550 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5551 Proto = Def->getType()->getAs<FunctionProtoType>(); 5552 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5553 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5554 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5555 } 5556 5557 // If the function we're calling isn't a function prototype, but we have 5558 // a function prototype from a prior declaratiom, use that prototype. 5559 if (!FDecl->hasPrototype()) 5560 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5561 } 5562 5563 // Promote the arguments (C99 6.5.2.2p6). 5564 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5565 Expr *Arg = Args[i]; 5566 5567 if (Proto && i < Proto->getNumParams()) { 5568 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5569 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5570 ExprResult ArgE = 5571 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5572 if (ArgE.isInvalid()) 5573 return true; 5574 5575 Arg = ArgE.getAs<Expr>(); 5576 5577 } else { 5578 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5579 5580 if (ArgE.isInvalid()) 5581 return true; 5582 5583 Arg = ArgE.getAs<Expr>(); 5584 } 5585 5586 if (RequireCompleteType(Arg->getLocStart(), 5587 Arg->getType(), 5588 diag::err_call_incomplete_argument, Arg)) 5589 return ExprError(); 5590 5591 TheCall->setArg(i, Arg); 5592 } 5593 } 5594 5595 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5596 if (!Method->isStatic()) 5597 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5598 << Fn->getSourceRange()); 5599 5600 // Check for sentinels 5601 if (NDecl) 5602 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5603 5604 // Do special checking on direct calls to functions. 5605 if (FDecl) { 5606 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5607 return ExprError(); 5608 5609 if (BuiltinID) 5610 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5611 } else if (NDecl) { 5612 if (CheckPointerCall(NDecl, TheCall, Proto)) 5613 return ExprError(); 5614 } else { 5615 if (CheckOtherCall(TheCall, Proto)) 5616 return ExprError(); 5617 } 5618 5619 return MaybeBindToTemporary(TheCall); 5620 } 5621 5622 ExprResult 5623 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5624 SourceLocation RParenLoc, Expr *InitExpr) { 5625 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5626 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5627 5628 TypeSourceInfo *TInfo; 5629 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5630 if (!TInfo) 5631 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5632 5633 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5634 } 5635 5636 ExprResult 5637 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5638 SourceLocation RParenLoc, Expr *LiteralExpr) { 5639 QualType literalType = TInfo->getType(); 5640 5641 if (literalType->isArrayType()) { 5642 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5643 diag::err_illegal_decl_array_incomplete_type, 5644 SourceRange(LParenLoc, 5645 LiteralExpr->getSourceRange().getEnd()))) 5646 return ExprError(); 5647 if (literalType->isVariableArrayType()) 5648 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5649 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5650 } else if (!literalType->isDependentType() && 5651 RequireCompleteType(LParenLoc, literalType, 5652 diag::err_typecheck_decl_incomplete_type, 5653 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5654 return ExprError(); 5655 5656 InitializedEntity Entity 5657 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5658 InitializationKind Kind 5659 = InitializationKind::CreateCStyleCast(LParenLoc, 5660 SourceRange(LParenLoc, RParenLoc), 5661 /*InitList=*/true); 5662 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5663 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5664 &literalType); 5665 if (Result.isInvalid()) 5666 return ExprError(); 5667 LiteralExpr = Result.get(); 5668 5669 bool isFileScope = !CurContext->isFunctionOrMethod(); 5670 if (isFileScope && 5671 !LiteralExpr->isTypeDependent() && 5672 !LiteralExpr->isValueDependent() && 5673 !literalType->isDependentType()) { // 6.5.2.5p3 5674 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5675 return ExprError(); 5676 } 5677 5678 // In C, compound literals are l-values for some reason. 5679 // For GCC compatibility, in C++, file-scope array compound literals with 5680 // constant initializers are also l-values, and compound literals are 5681 // otherwise prvalues. 5682 // 5683 // (GCC also treats C++ list-initialized file-scope array prvalues with 5684 // constant initializers as l-values, but that's non-conforming, so we don't 5685 // follow it there.) 5686 // 5687 // FIXME: It would be better to handle the lvalue cases as materializing and 5688 // lifetime-extending a temporary object, but our materialized temporaries 5689 // representation only supports lifetime extension from a variable, not "out 5690 // of thin air". 5691 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5692 // is bound to the result of applying array-to-pointer decay to the compound 5693 // literal. 5694 // FIXME: GCC supports compound literals of reference type, which should 5695 // obviously have a value kind derived from the kind of reference involved. 5696 ExprValueKind VK = 5697 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5698 ? VK_RValue 5699 : VK_LValue; 5700 5701 return MaybeBindToTemporary( 5702 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5703 VK, LiteralExpr, isFileScope)); 5704 } 5705 5706 ExprResult 5707 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5708 SourceLocation RBraceLoc) { 5709 // Immediately handle non-overload placeholders. Overloads can be 5710 // resolved contextually, but everything else here can't. 5711 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5712 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5713 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5714 5715 // Ignore failures; dropping the entire initializer list because 5716 // of one failure would be terrible for indexing/etc. 5717 if (result.isInvalid()) continue; 5718 5719 InitArgList[I] = result.get(); 5720 } 5721 } 5722 5723 // Semantic analysis for initializers is done by ActOnDeclarator() and 5724 // CheckInitializer() - it requires knowledge of the object being intialized. 5725 5726 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5727 RBraceLoc); 5728 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5729 return E; 5730 } 5731 5732 /// Do an explicit extend of the given block pointer if we're in ARC. 5733 void Sema::maybeExtendBlockObject(ExprResult &E) { 5734 assert(E.get()->getType()->isBlockPointerType()); 5735 assert(E.get()->isRValue()); 5736 5737 // Only do this in an r-value context. 5738 if (!getLangOpts().ObjCAutoRefCount) return; 5739 5740 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5741 CK_ARCExtendBlockObject, E.get(), 5742 /*base path*/ nullptr, VK_RValue); 5743 Cleanup.setExprNeedsCleanups(true); 5744 } 5745 5746 /// Prepare a conversion of the given expression to an ObjC object 5747 /// pointer type. 5748 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5749 QualType type = E.get()->getType(); 5750 if (type->isObjCObjectPointerType()) { 5751 return CK_BitCast; 5752 } else if (type->isBlockPointerType()) { 5753 maybeExtendBlockObject(E); 5754 return CK_BlockPointerToObjCPointerCast; 5755 } else { 5756 assert(type->isPointerType()); 5757 return CK_CPointerToObjCPointerCast; 5758 } 5759 } 5760 5761 /// Prepares for a scalar cast, performing all the necessary stages 5762 /// except the final cast and returning the kind required. 5763 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5764 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5765 // Also, callers should have filtered out the invalid cases with 5766 // pointers. Everything else should be possible. 5767 5768 QualType SrcTy = Src.get()->getType(); 5769 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5770 return CK_NoOp; 5771 5772 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5773 case Type::STK_MemberPointer: 5774 llvm_unreachable("member pointer type in C"); 5775 5776 case Type::STK_CPointer: 5777 case Type::STK_BlockPointer: 5778 case Type::STK_ObjCObjectPointer: 5779 switch (DestTy->getScalarTypeKind()) { 5780 case Type::STK_CPointer: { 5781 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5782 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5783 if (SrcAS != DestAS) 5784 return CK_AddressSpaceConversion; 5785 return CK_BitCast; 5786 } 5787 case Type::STK_BlockPointer: 5788 return (SrcKind == Type::STK_BlockPointer 5789 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5790 case Type::STK_ObjCObjectPointer: 5791 if (SrcKind == Type::STK_ObjCObjectPointer) 5792 return CK_BitCast; 5793 if (SrcKind == Type::STK_CPointer) 5794 return CK_CPointerToObjCPointerCast; 5795 maybeExtendBlockObject(Src); 5796 return CK_BlockPointerToObjCPointerCast; 5797 case Type::STK_Bool: 5798 return CK_PointerToBoolean; 5799 case Type::STK_Integral: 5800 return CK_PointerToIntegral; 5801 case Type::STK_Floating: 5802 case Type::STK_FloatingComplex: 5803 case Type::STK_IntegralComplex: 5804 case Type::STK_MemberPointer: 5805 llvm_unreachable("illegal cast from pointer"); 5806 } 5807 llvm_unreachable("Should have returned before this"); 5808 5809 case Type::STK_Bool: // casting from bool is like casting from an integer 5810 case Type::STK_Integral: 5811 switch (DestTy->getScalarTypeKind()) { 5812 case Type::STK_CPointer: 5813 case Type::STK_ObjCObjectPointer: 5814 case Type::STK_BlockPointer: 5815 if (Src.get()->isNullPointerConstant(Context, 5816 Expr::NPC_ValueDependentIsNull)) 5817 return CK_NullToPointer; 5818 return CK_IntegralToPointer; 5819 case Type::STK_Bool: 5820 return CK_IntegralToBoolean; 5821 case Type::STK_Integral: 5822 return CK_IntegralCast; 5823 case Type::STK_Floating: 5824 return CK_IntegralToFloating; 5825 case Type::STK_IntegralComplex: 5826 Src = ImpCastExprToType(Src.get(), 5827 DestTy->castAs<ComplexType>()->getElementType(), 5828 CK_IntegralCast); 5829 return CK_IntegralRealToComplex; 5830 case Type::STK_FloatingComplex: 5831 Src = ImpCastExprToType(Src.get(), 5832 DestTy->castAs<ComplexType>()->getElementType(), 5833 CK_IntegralToFloating); 5834 return CK_FloatingRealToComplex; 5835 case Type::STK_MemberPointer: 5836 llvm_unreachable("member pointer type in C"); 5837 } 5838 llvm_unreachable("Should have returned before this"); 5839 5840 case Type::STK_Floating: 5841 switch (DestTy->getScalarTypeKind()) { 5842 case Type::STK_Floating: 5843 return CK_FloatingCast; 5844 case Type::STK_Bool: 5845 return CK_FloatingToBoolean; 5846 case Type::STK_Integral: 5847 return CK_FloatingToIntegral; 5848 case Type::STK_FloatingComplex: 5849 Src = ImpCastExprToType(Src.get(), 5850 DestTy->castAs<ComplexType>()->getElementType(), 5851 CK_FloatingCast); 5852 return CK_FloatingRealToComplex; 5853 case Type::STK_IntegralComplex: 5854 Src = ImpCastExprToType(Src.get(), 5855 DestTy->castAs<ComplexType>()->getElementType(), 5856 CK_FloatingToIntegral); 5857 return CK_IntegralRealToComplex; 5858 case Type::STK_CPointer: 5859 case Type::STK_ObjCObjectPointer: 5860 case Type::STK_BlockPointer: 5861 llvm_unreachable("valid float->pointer cast?"); 5862 case Type::STK_MemberPointer: 5863 llvm_unreachable("member pointer type in C"); 5864 } 5865 llvm_unreachable("Should have returned before this"); 5866 5867 case Type::STK_FloatingComplex: 5868 switch (DestTy->getScalarTypeKind()) { 5869 case Type::STK_FloatingComplex: 5870 return CK_FloatingComplexCast; 5871 case Type::STK_IntegralComplex: 5872 return CK_FloatingComplexToIntegralComplex; 5873 case Type::STK_Floating: { 5874 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5875 if (Context.hasSameType(ET, DestTy)) 5876 return CK_FloatingComplexToReal; 5877 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5878 return CK_FloatingCast; 5879 } 5880 case Type::STK_Bool: 5881 return CK_FloatingComplexToBoolean; 5882 case Type::STK_Integral: 5883 Src = ImpCastExprToType(Src.get(), 5884 SrcTy->castAs<ComplexType>()->getElementType(), 5885 CK_FloatingComplexToReal); 5886 return CK_FloatingToIntegral; 5887 case Type::STK_CPointer: 5888 case Type::STK_ObjCObjectPointer: 5889 case Type::STK_BlockPointer: 5890 llvm_unreachable("valid complex float->pointer cast?"); 5891 case Type::STK_MemberPointer: 5892 llvm_unreachable("member pointer type in C"); 5893 } 5894 llvm_unreachable("Should have returned before this"); 5895 5896 case Type::STK_IntegralComplex: 5897 switch (DestTy->getScalarTypeKind()) { 5898 case Type::STK_FloatingComplex: 5899 return CK_IntegralComplexToFloatingComplex; 5900 case Type::STK_IntegralComplex: 5901 return CK_IntegralComplexCast; 5902 case Type::STK_Integral: { 5903 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5904 if (Context.hasSameType(ET, DestTy)) 5905 return CK_IntegralComplexToReal; 5906 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5907 return CK_IntegralCast; 5908 } 5909 case Type::STK_Bool: 5910 return CK_IntegralComplexToBoolean; 5911 case Type::STK_Floating: 5912 Src = ImpCastExprToType(Src.get(), 5913 SrcTy->castAs<ComplexType>()->getElementType(), 5914 CK_IntegralComplexToReal); 5915 return CK_IntegralToFloating; 5916 case Type::STK_CPointer: 5917 case Type::STK_ObjCObjectPointer: 5918 case Type::STK_BlockPointer: 5919 llvm_unreachable("valid complex int->pointer cast?"); 5920 case Type::STK_MemberPointer: 5921 llvm_unreachable("member pointer type in C"); 5922 } 5923 llvm_unreachable("Should have returned before this"); 5924 } 5925 5926 llvm_unreachable("Unhandled scalar cast"); 5927 } 5928 5929 static bool breakDownVectorType(QualType type, uint64_t &len, 5930 QualType &eltType) { 5931 // Vectors are simple. 5932 if (const VectorType *vecType = type->getAs<VectorType>()) { 5933 len = vecType->getNumElements(); 5934 eltType = vecType->getElementType(); 5935 assert(eltType->isScalarType()); 5936 return true; 5937 } 5938 5939 // We allow lax conversion to and from non-vector types, but only if 5940 // they're real types (i.e. non-complex, non-pointer scalar types). 5941 if (!type->isRealType()) return false; 5942 5943 len = 1; 5944 eltType = type; 5945 return true; 5946 } 5947 5948 /// Are the two types lax-compatible vector types? That is, given 5949 /// that one of them is a vector, do they have equal storage sizes, 5950 /// where the storage size is the number of elements times the element 5951 /// size? 5952 /// 5953 /// This will also return false if either of the types is neither a 5954 /// vector nor a real type. 5955 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5956 assert(destTy->isVectorType() || srcTy->isVectorType()); 5957 5958 // Disallow lax conversions between scalars and ExtVectors (these 5959 // conversions are allowed for other vector types because common headers 5960 // depend on them). Most scalar OP ExtVector cases are handled by the 5961 // splat path anyway, which does what we want (convert, not bitcast). 5962 // What this rules out for ExtVectors is crazy things like char4*float. 5963 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5964 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5965 5966 uint64_t srcLen, destLen; 5967 QualType srcEltTy, destEltTy; 5968 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5969 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5970 5971 // ASTContext::getTypeSize will return the size rounded up to a 5972 // power of 2, so instead of using that, we need to use the raw 5973 // element size multiplied by the element count. 5974 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5975 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5976 5977 return (srcLen * srcEltSize == destLen * destEltSize); 5978 } 5979 5980 /// Is this a legal conversion between two types, one of which is 5981 /// known to be a vector type? 5982 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5983 assert(destTy->isVectorType() || srcTy->isVectorType()); 5984 5985 if (!Context.getLangOpts().LaxVectorConversions) 5986 return false; 5987 return areLaxCompatibleVectorTypes(srcTy, destTy); 5988 } 5989 5990 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5991 CastKind &Kind) { 5992 assert(VectorTy->isVectorType() && "Not a vector type!"); 5993 5994 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5995 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5996 return Diag(R.getBegin(), 5997 Ty->isVectorType() ? 5998 diag::err_invalid_conversion_between_vectors : 5999 diag::err_invalid_conversion_between_vector_and_integer) 6000 << VectorTy << Ty << R; 6001 } else 6002 return Diag(R.getBegin(), 6003 diag::err_invalid_conversion_between_vector_and_scalar) 6004 << VectorTy << Ty << R; 6005 6006 Kind = CK_BitCast; 6007 return false; 6008 } 6009 6010 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6011 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6012 6013 if (DestElemTy == SplattedExpr->getType()) 6014 return SplattedExpr; 6015 6016 assert(DestElemTy->isFloatingType() || 6017 DestElemTy->isIntegralOrEnumerationType()); 6018 6019 CastKind CK; 6020 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6021 // OpenCL requires that we convert `true` boolean expressions to -1, but 6022 // only when splatting vectors. 6023 if (DestElemTy->isFloatingType()) { 6024 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6025 // in two steps: boolean to signed integral, then to floating. 6026 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6027 CK_BooleanToSignedIntegral); 6028 SplattedExpr = CastExprRes.get(); 6029 CK = CK_IntegralToFloating; 6030 } else { 6031 CK = CK_BooleanToSignedIntegral; 6032 } 6033 } else { 6034 ExprResult CastExprRes = SplattedExpr; 6035 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6036 if (CastExprRes.isInvalid()) 6037 return ExprError(); 6038 SplattedExpr = CastExprRes.get(); 6039 } 6040 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6041 } 6042 6043 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6044 Expr *CastExpr, CastKind &Kind) { 6045 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6046 6047 QualType SrcTy = CastExpr->getType(); 6048 6049 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6050 // an ExtVectorType. 6051 // In OpenCL, casts between vectors of different types are not allowed. 6052 // (See OpenCL 6.2). 6053 if (SrcTy->isVectorType()) { 6054 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6055 (getLangOpts().OpenCL && 6056 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6057 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6058 << DestTy << SrcTy << R; 6059 return ExprError(); 6060 } 6061 Kind = CK_BitCast; 6062 return CastExpr; 6063 } 6064 6065 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6066 // conversion will take place first from scalar to elt type, and then 6067 // splat from elt type to vector. 6068 if (SrcTy->isPointerType()) 6069 return Diag(R.getBegin(), 6070 diag::err_invalid_conversion_between_vector_and_scalar) 6071 << DestTy << SrcTy << R; 6072 6073 Kind = CK_VectorSplat; 6074 return prepareVectorSplat(DestTy, CastExpr); 6075 } 6076 6077 ExprResult 6078 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6079 Declarator &D, ParsedType &Ty, 6080 SourceLocation RParenLoc, Expr *CastExpr) { 6081 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6082 "ActOnCastExpr(): missing type or expr"); 6083 6084 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6085 if (D.isInvalidType()) 6086 return ExprError(); 6087 6088 if (getLangOpts().CPlusPlus) { 6089 // Check that there are no default arguments (C++ only). 6090 CheckExtraCXXDefaultArguments(D); 6091 } else { 6092 // Make sure any TypoExprs have been dealt with. 6093 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6094 if (!Res.isUsable()) 6095 return ExprError(); 6096 CastExpr = Res.get(); 6097 } 6098 6099 checkUnusedDeclAttributes(D); 6100 6101 QualType castType = castTInfo->getType(); 6102 Ty = CreateParsedType(castType, castTInfo); 6103 6104 bool isVectorLiteral = false; 6105 6106 // Check for an altivec or OpenCL literal, 6107 // i.e. all the elements are integer constants. 6108 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6109 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6110 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6111 && castType->isVectorType() && (PE || PLE)) { 6112 if (PLE && PLE->getNumExprs() == 0) { 6113 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6114 return ExprError(); 6115 } 6116 if (PE || PLE->getNumExprs() == 1) { 6117 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6118 if (!E->getType()->isVectorType()) 6119 isVectorLiteral = true; 6120 } 6121 else 6122 isVectorLiteral = true; 6123 } 6124 6125 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6126 // then handle it as such. 6127 if (isVectorLiteral) 6128 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6129 6130 // If the Expr being casted is a ParenListExpr, handle it specially. 6131 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6132 // sequence of BinOp comma operators. 6133 if (isa<ParenListExpr>(CastExpr)) { 6134 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6135 if (Result.isInvalid()) return ExprError(); 6136 CastExpr = Result.get(); 6137 } 6138 6139 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6140 !getSourceManager().isInSystemMacro(LParenLoc)) 6141 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6142 6143 CheckTollFreeBridgeCast(castType, CastExpr); 6144 6145 CheckObjCBridgeRelatedCast(castType, CastExpr); 6146 6147 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6148 6149 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6150 } 6151 6152 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6153 SourceLocation RParenLoc, Expr *E, 6154 TypeSourceInfo *TInfo) { 6155 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6156 "Expected paren or paren list expression"); 6157 6158 Expr **exprs; 6159 unsigned numExprs; 6160 Expr *subExpr; 6161 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6162 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6163 LiteralLParenLoc = PE->getLParenLoc(); 6164 LiteralRParenLoc = PE->getRParenLoc(); 6165 exprs = PE->getExprs(); 6166 numExprs = PE->getNumExprs(); 6167 } else { // isa<ParenExpr> by assertion at function entrance 6168 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6169 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6170 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6171 exprs = &subExpr; 6172 numExprs = 1; 6173 } 6174 6175 QualType Ty = TInfo->getType(); 6176 assert(Ty->isVectorType() && "Expected vector type"); 6177 6178 SmallVector<Expr *, 8> initExprs; 6179 const VectorType *VTy = Ty->getAs<VectorType>(); 6180 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6181 6182 // '(...)' form of vector initialization in AltiVec: the number of 6183 // initializers must be one or must match the size of the vector. 6184 // If a single value is specified in the initializer then it will be 6185 // replicated to all the components of the vector 6186 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6187 // The number of initializers must be one or must match the size of the 6188 // vector. If a single value is specified in the initializer then it will 6189 // be replicated to all the components of the vector 6190 if (numExprs == 1) { 6191 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6192 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6193 if (Literal.isInvalid()) 6194 return ExprError(); 6195 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6196 PrepareScalarCast(Literal, ElemTy)); 6197 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6198 } 6199 else if (numExprs < numElems) { 6200 Diag(E->getExprLoc(), 6201 diag::err_incorrect_number_of_vector_initializers); 6202 return ExprError(); 6203 } 6204 else 6205 initExprs.append(exprs, exprs + numExprs); 6206 } 6207 else { 6208 // For OpenCL, when the number of initializers is a single value, 6209 // it will be replicated to all components of the vector. 6210 if (getLangOpts().OpenCL && 6211 VTy->getVectorKind() == VectorType::GenericVector && 6212 numExprs == 1) { 6213 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6214 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6215 if (Literal.isInvalid()) 6216 return ExprError(); 6217 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6218 PrepareScalarCast(Literal, ElemTy)); 6219 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6220 } 6221 6222 initExprs.append(exprs, exprs + numExprs); 6223 } 6224 // FIXME: This means that pretty-printing the final AST will produce curly 6225 // braces instead of the original commas. 6226 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6227 initExprs, LiteralRParenLoc); 6228 initE->setType(Ty); 6229 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6230 } 6231 6232 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6233 /// the ParenListExpr into a sequence of comma binary operators. 6234 ExprResult 6235 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6236 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6237 if (!E) 6238 return OrigExpr; 6239 6240 ExprResult Result(E->getExpr(0)); 6241 6242 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6243 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6244 E->getExpr(i)); 6245 6246 if (Result.isInvalid()) return ExprError(); 6247 6248 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6249 } 6250 6251 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6252 SourceLocation R, 6253 MultiExprArg Val) { 6254 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6255 return expr; 6256 } 6257 6258 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6259 /// constant and the other is not a pointer. Returns true if a diagnostic is 6260 /// emitted. 6261 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6262 SourceLocation QuestionLoc) { 6263 Expr *NullExpr = LHSExpr; 6264 Expr *NonPointerExpr = RHSExpr; 6265 Expr::NullPointerConstantKind NullKind = 6266 NullExpr->isNullPointerConstant(Context, 6267 Expr::NPC_ValueDependentIsNotNull); 6268 6269 if (NullKind == Expr::NPCK_NotNull) { 6270 NullExpr = RHSExpr; 6271 NonPointerExpr = LHSExpr; 6272 NullKind = 6273 NullExpr->isNullPointerConstant(Context, 6274 Expr::NPC_ValueDependentIsNotNull); 6275 } 6276 6277 if (NullKind == Expr::NPCK_NotNull) 6278 return false; 6279 6280 if (NullKind == Expr::NPCK_ZeroExpression) 6281 return false; 6282 6283 if (NullKind == Expr::NPCK_ZeroLiteral) { 6284 // In this case, check to make sure that we got here from a "NULL" 6285 // string in the source code. 6286 NullExpr = NullExpr->IgnoreParenImpCasts(); 6287 SourceLocation loc = NullExpr->getExprLoc(); 6288 if (!findMacroSpelling(loc, "NULL")) 6289 return false; 6290 } 6291 6292 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6293 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6294 << NonPointerExpr->getType() << DiagType 6295 << NonPointerExpr->getSourceRange(); 6296 return true; 6297 } 6298 6299 /// \brief Return false if the condition expression is valid, true otherwise. 6300 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6301 QualType CondTy = Cond->getType(); 6302 6303 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6304 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6305 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6306 << CondTy << Cond->getSourceRange(); 6307 return true; 6308 } 6309 6310 // C99 6.5.15p2 6311 if (CondTy->isScalarType()) return false; 6312 6313 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6314 << CondTy << Cond->getSourceRange(); 6315 return true; 6316 } 6317 6318 /// \brief Handle when one or both operands are void type. 6319 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6320 ExprResult &RHS) { 6321 Expr *LHSExpr = LHS.get(); 6322 Expr *RHSExpr = RHS.get(); 6323 6324 if (!LHSExpr->getType()->isVoidType()) 6325 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6326 << RHSExpr->getSourceRange(); 6327 if (!RHSExpr->getType()->isVoidType()) 6328 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6329 << LHSExpr->getSourceRange(); 6330 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6331 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6332 return S.Context.VoidTy; 6333 } 6334 6335 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6336 /// true otherwise. 6337 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6338 QualType PointerTy) { 6339 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6340 !NullExpr.get()->isNullPointerConstant(S.Context, 6341 Expr::NPC_ValueDependentIsNull)) 6342 return true; 6343 6344 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6345 return false; 6346 } 6347 6348 /// \brief Checks compatibility between two pointers and return the resulting 6349 /// type. 6350 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6351 ExprResult &RHS, 6352 SourceLocation Loc) { 6353 QualType LHSTy = LHS.get()->getType(); 6354 QualType RHSTy = RHS.get()->getType(); 6355 6356 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6357 // Two identical pointers types are always compatible. 6358 return LHSTy; 6359 } 6360 6361 QualType lhptee, rhptee; 6362 6363 // Get the pointee types. 6364 bool IsBlockPointer = false; 6365 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6366 lhptee = LHSBTy->getPointeeType(); 6367 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6368 IsBlockPointer = true; 6369 } else { 6370 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6371 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6372 } 6373 6374 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6375 // differently qualified versions of compatible types, the result type is 6376 // a pointer to an appropriately qualified version of the composite 6377 // type. 6378 6379 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6380 // clause doesn't make sense for our extensions. E.g. address space 2 should 6381 // be incompatible with address space 3: they may live on different devices or 6382 // anything. 6383 Qualifiers lhQual = lhptee.getQualifiers(); 6384 Qualifiers rhQual = rhptee.getQualifiers(); 6385 6386 LangAS ResultAddrSpace = LangAS::Default; 6387 LangAS LAddrSpace = lhQual.getAddressSpace(); 6388 LangAS RAddrSpace = rhQual.getAddressSpace(); 6389 if (S.getLangOpts().OpenCL) { 6390 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6391 // spaces is disallowed. 6392 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6393 ResultAddrSpace = LAddrSpace; 6394 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6395 ResultAddrSpace = RAddrSpace; 6396 else { 6397 S.Diag(Loc, 6398 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6399 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6400 << RHS.get()->getSourceRange(); 6401 return QualType(); 6402 } 6403 } 6404 6405 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6406 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6407 lhQual.removeCVRQualifiers(); 6408 rhQual.removeCVRQualifiers(); 6409 6410 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6411 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6412 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6413 // qual types are compatible iff 6414 // * corresponded types are compatible 6415 // * CVR qualifiers are equal 6416 // * address spaces are equal 6417 // Thus for conditional operator we merge CVR and address space unqualified 6418 // pointees and if there is a composite type we return a pointer to it with 6419 // merged qualifiers. 6420 if (S.getLangOpts().OpenCL) { 6421 LHSCastKind = LAddrSpace == ResultAddrSpace 6422 ? CK_BitCast 6423 : CK_AddressSpaceConversion; 6424 RHSCastKind = RAddrSpace == ResultAddrSpace 6425 ? CK_BitCast 6426 : CK_AddressSpaceConversion; 6427 lhQual.removeAddressSpace(); 6428 rhQual.removeAddressSpace(); 6429 } 6430 6431 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6432 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6433 6434 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6435 6436 if (CompositeTy.isNull()) { 6437 // In this situation, we assume void* type. No especially good 6438 // reason, but this is what gcc does, and we do have to pick 6439 // to get a consistent AST. 6440 QualType incompatTy; 6441 incompatTy = S.Context.getPointerType( 6442 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6443 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6444 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6445 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6446 // for casts between types with incompatible address space qualifiers. 6447 // For the following code the compiler produces casts between global and 6448 // local address spaces of the corresponded innermost pointees: 6449 // local int *global *a; 6450 // global int *global *b; 6451 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6452 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6453 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6454 << RHS.get()->getSourceRange(); 6455 return incompatTy; 6456 } 6457 6458 // The pointer types are compatible. 6459 // In case of OpenCL ResultTy should have the address space qualifier 6460 // which is a superset of address spaces of both the 2nd and the 3rd 6461 // operands of the conditional operator. 6462 QualType ResultTy = [&, ResultAddrSpace]() { 6463 if (S.getLangOpts().OpenCL) { 6464 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6465 CompositeQuals.setAddressSpace(ResultAddrSpace); 6466 return S.Context 6467 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6468 .withCVRQualifiers(MergedCVRQual); 6469 } 6470 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6471 }(); 6472 if (IsBlockPointer) 6473 ResultTy = S.Context.getBlockPointerType(ResultTy); 6474 else 6475 ResultTy = S.Context.getPointerType(ResultTy); 6476 6477 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6478 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6479 return ResultTy; 6480 } 6481 6482 /// \brief Return the resulting type when the operands are both block pointers. 6483 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6484 ExprResult &LHS, 6485 ExprResult &RHS, 6486 SourceLocation Loc) { 6487 QualType LHSTy = LHS.get()->getType(); 6488 QualType RHSTy = RHS.get()->getType(); 6489 6490 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6491 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6492 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6493 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6494 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6495 return destType; 6496 } 6497 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6498 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6499 << RHS.get()->getSourceRange(); 6500 return QualType(); 6501 } 6502 6503 // We have 2 block pointer types. 6504 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6505 } 6506 6507 /// \brief Return the resulting type when the operands are both pointers. 6508 static QualType 6509 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6510 ExprResult &RHS, 6511 SourceLocation Loc) { 6512 // get the pointer types 6513 QualType LHSTy = LHS.get()->getType(); 6514 QualType RHSTy = RHS.get()->getType(); 6515 6516 // get the "pointed to" types 6517 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6518 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6519 6520 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6521 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6522 // Figure out necessary qualifiers (C99 6.5.15p6) 6523 QualType destPointee 6524 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6525 QualType destType = S.Context.getPointerType(destPointee); 6526 // Add qualifiers if necessary. 6527 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6528 // Promote to void*. 6529 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6530 return destType; 6531 } 6532 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6533 QualType destPointee 6534 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6535 QualType destType = S.Context.getPointerType(destPointee); 6536 // Add qualifiers if necessary. 6537 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6538 // Promote to void*. 6539 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6540 return destType; 6541 } 6542 6543 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6544 } 6545 6546 /// \brief Return false if the first expression is not an integer and the second 6547 /// expression is not a pointer, true otherwise. 6548 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6549 Expr* PointerExpr, SourceLocation Loc, 6550 bool IsIntFirstExpr) { 6551 if (!PointerExpr->getType()->isPointerType() || 6552 !Int.get()->getType()->isIntegerType()) 6553 return false; 6554 6555 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6556 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6557 6558 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6559 << Expr1->getType() << Expr2->getType() 6560 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6561 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6562 CK_IntegralToPointer); 6563 return true; 6564 } 6565 6566 /// \brief Simple conversion between integer and floating point types. 6567 /// 6568 /// Used when handling the OpenCL conditional operator where the 6569 /// condition is a vector while the other operands are scalar. 6570 /// 6571 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6572 /// types are either integer or floating type. Between the two 6573 /// operands, the type with the higher rank is defined as the "result 6574 /// type". The other operand needs to be promoted to the same type. No 6575 /// other type promotion is allowed. We cannot use 6576 /// UsualArithmeticConversions() for this purpose, since it always 6577 /// promotes promotable types. 6578 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6579 ExprResult &RHS, 6580 SourceLocation QuestionLoc) { 6581 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6582 if (LHS.isInvalid()) 6583 return QualType(); 6584 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6585 if (RHS.isInvalid()) 6586 return QualType(); 6587 6588 // For conversion purposes, we ignore any qualifiers. 6589 // For example, "const float" and "float" are equivalent. 6590 QualType LHSType = 6591 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6592 QualType RHSType = 6593 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6594 6595 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6596 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6597 << LHSType << LHS.get()->getSourceRange(); 6598 return QualType(); 6599 } 6600 6601 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6602 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6603 << RHSType << RHS.get()->getSourceRange(); 6604 return QualType(); 6605 } 6606 6607 // If both types are identical, no conversion is needed. 6608 if (LHSType == RHSType) 6609 return LHSType; 6610 6611 // Now handle "real" floating types (i.e. float, double, long double). 6612 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6613 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6614 /*IsCompAssign = */ false); 6615 6616 // Finally, we have two differing integer types. 6617 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6618 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6619 } 6620 6621 /// \brief Convert scalar operands to a vector that matches the 6622 /// condition in length. 6623 /// 6624 /// Used when handling the OpenCL conditional operator where the 6625 /// condition is a vector while the other operands are scalar. 6626 /// 6627 /// We first compute the "result type" for the scalar operands 6628 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6629 /// into a vector of that type where the length matches the condition 6630 /// vector type. s6.11.6 requires that the element types of the result 6631 /// and the condition must have the same number of bits. 6632 static QualType 6633 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6634 QualType CondTy, SourceLocation QuestionLoc) { 6635 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6636 if (ResTy.isNull()) return QualType(); 6637 6638 const VectorType *CV = CondTy->getAs<VectorType>(); 6639 assert(CV); 6640 6641 // Determine the vector result type 6642 unsigned NumElements = CV->getNumElements(); 6643 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6644 6645 // Ensure that all types have the same number of bits 6646 if (S.Context.getTypeSize(CV->getElementType()) 6647 != S.Context.getTypeSize(ResTy)) { 6648 // Since VectorTy is created internally, it does not pretty print 6649 // with an OpenCL name. Instead, we just print a description. 6650 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6651 SmallString<64> Str; 6652 llvm::raw_svector_ostream OS(Str); 6653 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6654 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6655 << CondTy << OS.str(); 6656 return QualType(); 6657 } 6658 6659 // Convert operands to the vector result type 6660 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6661 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6662 6663 return VectorTy; 6664 } 6665 6666 /// \brief Return false if this is a valid OpenCL condition vector 6667 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6668 SourceLocation QuestionLoc) { 6669 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6670 // integral type. 6671 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6672 assert(CondTy); 6673 QualType EleTy = CondTy->getElementType(); 6674 if (EleTy->isIntegerType()) return false; 6675 6676 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6677 << Cond->getType() << Cond->getSourceRange(); 6678 return true; 6679 } 6680 6681 /// \brief Return false if the vector condition type and the vector 6682 /// result type are compatible. 6683 /// 6684 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6685 /// number of elements, and their element types have the same number 6686 /// of bits. 6687 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6688 SourceLocation QuestionLoc) { 6689 const VectorType *CV = CondTy->getAs<VectorType>(); 6690 const VectorType *RV = VecResTy->getAs<VectorType>(); 6691 assert(CV && RV); 6692 6693 if (CV->getNumElements() != RV->getNumElements()) { 6694 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6695 << CondTy << VecResTy; 6696 return true; 6697 } 6698 6699 QualType CVE = CV->getElementType(); 6700 QualType RVE = RV->getElementType(); 6701 6702 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6703 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6704 << CondTy << VecResTy; 6705 return true; 6706 } 6707 6708 return false; 6709 } 6710 6711 /// \brief Return the resulting type for the conditional operator in 6712 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6713 /// s6.3.i) when the condition is a vector type. 6714 static QualType 6715 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6716 ExprResult &LHS, ExprResult &RHS, 6717 SourceLocation QuestionLoc) { 6718 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6719 if (Cond.isInvalid()) 6720 return QualType(); 6721 QualType CondTy = Cond.get()->getType(); 6722 6723 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6724 return QualType(); 6725 6726 // If either operand is a vector then find the vector type of the 6727 // result as specified in OpenCL v1.1 s6.3.i. 6728 if (LHS.get()->getType()->isVectorType() || 6729 RHS.get()->getType()->isVectorType()) { 6730 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6731 /*isCompAssign*/false, 6732 /*AllowBothBool*/true, 6733 /*AllowBoolConversions*/false); 6734 if (VecResTy.isNull()) return QualType(); 6735 // The result type must match the condition type as specified in 6736 // OpenCL v1.1 s6.11.6. 6737 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6738 return QualType(); 6739 return VecResTy; 6740 } 6741 6742 // Both operands are scalar. 6743 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6744 } 6745 6746 /// \brief Return true if the Expr is block type 6747 static bool checkBlockType(Sema &S, const Expr *E) { 6748 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6749 QualType Ty = CE->getCallee()->getType(); 6750 if (Ty->isBlockPointerType()) { 6751 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6752 return true; 6753 } 6754 } 6755 return false; 6756 } 6757 6758 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6759 /// In that case, LHS = cond. 6760 /// C99 6.5.15 6761 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6762 ExprResult &RHS, ExprValueKind &VK, 6763 ExprObjectKind &OK, 6764 SourceLocation QuestionLoc) { 6765 6766 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6767 if (!LHSResult.isUsable()) return QualType(); 6768 LHS = LHSResult; 6769 6770 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6771 if (!RHSResult.isUsable()) return QualType(); 6772 RHS = RHSResult; 6773 6774 // C++ is sufficiently different to merit its own checker. 6775 if (getLangOpts().CPlusPlus) 6776 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6777 6778 VK = VK_RValue; 6779 OK = OK_Ordinary; 6780 6781 // The OpenCL operator with a vector condition is sufficiently 6782 // different to merit its own checker. 6783 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6784 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6785 6786 // First, check the condition. 6787 Cond = UsualUnaryConversions(Cond.get()); 6788 if (Cond.isInvalid()) 6789 return QualType(); 6790 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6791 return QualType(); 6792 6793 // Now check the two expressions. 6794 if (LHS.get()->getType()->isVectorType() || 6795 RHS.get()->getType()->isVectorType()) 6796 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6797 /*AllowBothBool*/true, 6798 /*AllowBoolConversions*/false); 6799 6800 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6801 if (LHS.isInvalid() || RHS.isInvalid()) 6802 return QualType(); 6803 6804 QualType LHSTy = LHS.get()->getType(); 6805 QualType RHSTy = RHS.get()->getType(); 6806 6807 // Diagnose attempts to convert between __float128 and long double where 6808 // such conversions currently can't be handled. 6809 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6810 Diag(QuestionLoc, 6811 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6812 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6813 return QualType(); 6814 } 6815 6816 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6817 // selection operator (?:). 6818 if (getLangOpts().OpenCL && 6819 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6820 return QualType(); 6821 } 6822 6823 // If both operands have arithmetic type, do the usual arithmetic conversions 6824 // to find a common type: C99 6.5.15p3,5. 6825 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6826 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6827 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6828 6829 return ResTy; 6830 } 6831 6832 // If both operands are the same structure or union type, the result is that 6833 // type. 6834 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6835 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6836 if (LHSRT->getDecl() == RHSRT->getDecl()) 6837 // "If both the operands have structure or union type, the result has 6838 // that type." This implies that CV qualifiers are dropped. 6839 return LHSTy.getUnqualifiedType(); 6840 // FIXME: Type of conditional expression must be complete in C mode. 6841 } 6842 6843 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6844 // The following || allows only one side to be void (a GCC-ism). 6845 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6846 return checkConditionalVoidType(*this, LHS, RHS); 6847 } 6848 6849 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6850 // the type of the other operand." 6851 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6852 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6853 6854 // All objective-c pointer type analysis is done here. 6855 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6856 QuestionLoc); 6857 if (LHS.isInvalid() || RHS.isInvalid()) 6858 return QualType(); 6859 if (!compositeType.isNull()) 6860 return compositeType; 6861 6862 6863 // Handle block pointer types. 6864 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6865 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6866 QuestionLoc); 6867 6868 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6869 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6870 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6871 QuestionLoc); 6872 6873 // GCC compatibility: soften pointer/integer mismatch. Note that 6874 // null pointers have been filtered out by this point. 6875 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6876 /*isIntFirstExpr=*/true)) 6877 return RHSTy; 6878 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6879 /*isIntFirstExpr=*/false)) 6880 return LHSTy; 6881 6882 // Emit a better diagnostic if one of the expressions is a null pointer 6883 // constant and the other is not a pointer type. In this case, the user most 6884 // likely forgot to take the address of the other expression. 6885 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6886 return QualType(); 6887 6888 // Otherwise, the operands are not compatible. 6889 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6890 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6891 << RHS.get()->getSourceRange(); 6892 return QualType(); 6893 } 6894 6895 /// FindCompositeObjCPointerType - Helper method to find composite type of 6896 /// two objective-c pointer types of the two input expressions. 6897 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6898 SourceLocation QuestionLoc) { 6899 QualType LHSTy = LHS.get()->getType(); 6900 QualType RHSTy = RHS.get()->getType(); 6901 6902 // Handle things like Class and struct objc_class*. Here we case the result 6903 // to the pseudo-builtin, because that will be implicitly cast back to the 6904 // redefinition type if an attempt is made to access its fields. 6905 if (LHSTy->isObjCClassType() && 6906 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6907 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6908 return LHSTy; 6909 } 6910 if (RHSTy->isObjCClassType() && 6911 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6912 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6913 return RHSTy; 6914 } 6915 // And the same for struct objc_object* / id 6916 if (LHSTy->isObjCIdType() && 6917 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6918 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6919 return LHSTy; 6920 } 6921 if (RHSTy->isObjCIdType() && 6922 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6923 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6924 return RHSTy; 6925 } 6926 // And the same for struct objc_selector* / SEL 6927 if (Context.isObjCSelType(LHSTy) && 6928 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6929 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6930 return LHSTy; 6931 } 6932 if (Context.isObjCSelType(RHSTy) && 6933 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6934 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6935 return RHSTy; 6936 } 6937 // Check constraints for Objective-C object pointers types. 6938 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6939 6940 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6941 // Two identical object pointer types are always compatible. 6942 return LHSTy; 6943 } 6944 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6945 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6946 QualType compositeType = LHSTy; 6947 6948 // If both operands are interfaces and either operand can be 6949 // assigned to the other, use that type as the composite 6950 // type. This allows 6951 // xxx ? (A*) a : (B*) b 6952 // where B is a subclass of A. 6953 // 6954 // Additionally, as for assignment, if either type is 'id' 6955 // allow silent coercion. Finally, if the types are 6956 // incompatible then make sure to use 'id' as the composite 6957 // type so the result is acceptable for sending messages to. 6958 6959 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6960 // It could return the composite type. 6961 if (!(compositeType = 6962 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6963 // Nothing more to do. 6964 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6965 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6966 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6967 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6968 } else if ((LHSTy->isObjCQualifiedIdType() || 6969 RHSTy->isObjCQualifiedIdType()) && 6970 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6971 // Need to handle "id<xx>" explicitly. 6972 // GCC allows qualified id and any Objective-C type to devolve to 6973 // id. Currently localizing to here until clear this should be 6974 // part of ObjCQualifiedIdTypesAreCompatible. 6975 compositeType = Context.getObjCIdType(); 6976 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6977 compositeType = Context.getObjCIdType(); 6978 } else { 6979 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6980 << LHSTy << RHSTy 6981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6982 QualType incompatTy = Context.getObjCIdType(); 6983 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6984 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6985 return incompatTy; 6986 } 6987 // The object pointer types are compatible. 6988 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6989 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6990 return compositeType; 6991 } 6992 // Check Objective-C object pointer types and 'void *' 6993 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6994 if (getLangOpts().ObjCAutoRefCount) { 6995 // ARC forbids the implicit conversion of object pointers to 'void *', 6996 // so these types are not compatible. 6997 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6998 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6999 LHS = RHS = true; 7000 return QualType(); 7001 } 7002 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7003 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7004 QualType destPointee 7005 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7006 QualType destType = Context.getPointerType(destPointee); 7007 // Add qualifiers if necessary. 7008 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7009 // Promote to void*. 7010 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7011 return destType; 7012 } 7013 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7014 if (getLangOpts().ObjCAutoRefCount) { 7015 // ARC forbids the implicit conversion of object pointers to 'void *', 7016 // so these types are not compatible. 7017 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7018 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7019 LHS = RHS = true; 7020 return QualType(); 7021 } 7022 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7023 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7024 QualType destPointee 7025 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7026 QualType destType = Context.getPointerType(destPointee); 7027 // Add qualifiers if necessary. 7028 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7029 // Promote to void*. 7030 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7031 return destType; 7032 } 7033 return QualType(); 7034 } 7035 7036 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7037 /// ParenRange in parentheses. 7038 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7039 const PartialDiagnostic &Note, 7040 SourceRange ParenRange) { 7041 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7042 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7043 EndLoc.isValid()) { 7044 Self.Diag(Loc, Note) 7045 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7046 << FixItHint::CreateInsertion(EndLoc, ")"); 7047 } else { 7048 // We can't display the parentheses, so just show the bare note. 7049 Self.Diag(Loc, Note) << ParenRange; 7050 } 7051 } 7052 7053 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7054 return BinaryOperator::isAdditiveOp(Opc) || 7055 BinaryOperator::isMultiplicativeOp(Opc) || 7056 BinaryOperator::isShiftOp(Opc); 7057 } 7058 7059 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7060 /// expression, either using a built-in or overloaded operator, 7061 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7062 /// expression. 7063 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7064 Expr **RHSExprs) { 7065 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7066 E = E->IgnoreImpCasts(); 7067 E = E->IgnoreConversionOperator(); 7068 E = E->IgnoreImpCasts(); 7069 7070 // Built-in binary operator. 7071 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7072 if (IsArithmeticOp(OP->getOpcode())) { 7073 *Opcode = OP->getOpcode(); 7074 *RHSExprs = OP->getRHS(); 7075 return true; 7076 } 7077 } 7078 7079 // Overloaded operator. 7080 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7081 if (Call->getNumArgs() != 2) 7082 return false; 7083 7084 // Make sure this is really a binary operator that is safe to pass into 7085 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7086 OverloadedOperatorKind OO = Call->getOperator(); 7087 if (OO < OO_Plus || OO > OO_Arrow || 7088 OO == OO_PlusPlus || OO == OO_MinusMinus) 7089 return false; 7090 7091 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7092 if (IsArithmeticOp(OpKind)) { 7093 *Opcode = OpKind; 7094 *RHSExprs = Call->getArg(1); 7095 return true; 7096 } 7097 } 7098 7099 return false; 7100 } 7101 7102 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7103 /// or is a logical expression such as (x==y) which has int type, but is 7104 /// commonly interpreted as boolean. 7105 static bool ExprLooksBoolean(Expr *E) { 7106 E = E->IgnoreParenImpCasts(); 7107 7108 if (E->getType()->isBooleanType()) 7109 return true; 7110 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7111 return OP->isComparisonOp() || OP->isLogicalOp(); 7112 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7113 return OP->getOpcode() == UO_LNot; 7114 if (E->getType()->isPointerType()) 7115 return true; 7116 7117 return false; 7118 } 7119 7120 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7121 /// and binary operator are mixed in a way that suggests the programmer assumed 7122 /// the conditional operator has higher precedence, for example: 7123 /// "int x = a + someBinaryCondition ? 1 : 2". 7124 static void DiagnoseConditionalPrecedence(Sema &Self, 7125 SourceLocation OpLoc, 7126 Expr *Condition, 7127 Expr *LHSExpr, 7128 Expr *RHSExpr) { 7129 BinaryOperatorKind CondOpcode; 7130 Expr *CondRHS; 7131 7132 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7133 return; 7134 if (!ExprLooksBoolean(CondRHS)) 7135 return; 7136 7137 // The condition is an arithmetic binary expression, with a right- 7138 // hand side that looks boolean, so warn. 7139 7140 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7141 << Condition->getSourceRange() 7142 << BinaryOperator::getOpcodeStr(CondOpcode); 7143 7144 SuggestParentheses(Self, OpLoc, 7145 Self.PDiag(diag::note_precedence_silence) 7146 << BinaryOperator::getOpcodeStr(CondOpcode), 7147 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 7148 7149 SuggestParentheses(Self, OpLoc, 7150 Self.PDiag(diag::note_precedence_conditional_first), 7151 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 7152 } 7153 7154 /// Compute the nullability of a conditional expression. 7155 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7156 QualType LHSTy, QualType RHSTy, 7157 ASTContext &Ctx) { 7158 if (!ResTy->isAnyPointerType()) 7159 return ResTy; 7160 7161 auto GetNullability = [&Ctx](QualType Ty) { 7162 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7163 if (Kind) 7164 return *Kind; 7165 return NullabilityKind::Unspecified; 7166 }; 7167 7168 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7169 NullabilityKind MergedKind; 7170 7171 // Compute nullability of a binary conditional expression. 7172 if (IsBin) { 7173 if (LHSKind == NullabilityKind::NonNull) 7174 MergedKind = NullabilityKind::NonNull; 7175 else 7176 MergedKind = RHSKind; 7177 // Compute nullability of a normal conditional expression. 7178 } else { 7179 if (LHSKind == NullabilityKind::Nullable || 7180 RHSKind == NullabilityKind::Nullable) 7181 MergedKind = NullabilityKind::Nullable; 7182 else if (LHSKind == NullabilityKind::NonNull) 7183 MergedKind = RHSKind; 7184 else if (RHSKind == NullabilityKind::NonNull) 7185 MergedKind = LHSKind; 7186 else 7187 MergedKind = NullabilityKind::Unspecified; 7188 } 7189 7190 // Return if ResTy already has the correct nullability. 7191 if (GetNullability(ResTy) == MergedKind) 7192 return ResTy; 7193 7194 // Strip all nullability from ResTy. 7195 while (ResTy->getNullability(Ctx)) 7196 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7197 7198 // Create a new AttributedType with the new nullability kind. 7199 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7200 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7201 } 7202 7203 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7204 /// in the case of a the GNU conditional expr extension. 7205 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7206 SourceLocation ColonLoc, 7207 Expr *CondExpr, Expr *LHSExpr, 7208 Expr *RHSExpr) { 7209 if (!getLangOpts().CPlusPlus) { 7210 // C cannot handle TypoExpr nodes in the condition because it 7211 // doesn't handle dependent types properly, so make sure any TypoExprs have 7212 // been dealt with before checking the operands. 7213 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7214 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7215 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7216 7217 if (!CondResult.isUsable()) 7218 return ExprError(); 7219 7220 if (LHSExpr) { 7221 if (!LHSResult.isUsable()) 7222 return ExprError(); 7223 } 7224 7225 if (!RHSResult.isUsable()) 7226 return ExprError(); 7227 7228 CondExpr = CondResult.get(); 7229 LHSExpr = LHSResult.get(); 7230 RHSExpr = RHSResult.get(); 7231 } 7232 7233 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7234 // was the condition. 7235 OpaqueValueExpr *opaqueValue = nullptr; 7236 Expr *commonExpr = nullptr; 7237 if (!LHSExpr) { 7238 commonExpr = CondExpr; 7239 // Lower out placeholder types first. This is important so that we don't 7240 // try to capture a placeholder. This happens in few cases in C++; such 7241 // as Objective-C++'s dictionary subscripting syntax. 7242 if (commonExpr->hasPlaceholderType()) { 7243 ExprResult result = CheckPlaceholderExpr(commonExpr); 7244 if (!result.isUsable()) return ExprError(); 7245 commonExpr = result.get(); 7246 } 7247 // We usually want to apply unary conversions *before* saving, except 7248 // in the special case of a C++ l-value conditional. 7249 if (!(getLangOpts().CPlusPlus 7250 && !commonExpr->isTypeDependent() 7251 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7252 && commonExpr->isGLValue() 7253 && commonExpr->isOrdinaryOrBitFieldObject() 7254 && RHSExpr->isOrdinaryOrBitFieldObject() 7255 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7256 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7257 if (commonRes.isInvalid()) 7258 return ExprError(); 7259 commonExpr = commonRes.get(); 7260 } 7261 7262 // If the common expression is a class or array prvalue, materialize it 7263 // so that we can safely refer to it multiple times. 7264 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7265 commonExpr->getType()->isArrayType())) { 7266 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7267 if (MatExpr.isInvalid()) 7268 return ExprError(); 7269 commonExpr = MatExpr.get(); 7270 } 7271 7272 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7273 commonExpr->getType(), 7274 commonExpr->getValueKind(), 7275 commonExpr->getObjectKind(), 7276 commonExpr); 7277 LHSExpr = CondExpr = opaqueValue; 7278 } 7279 7280 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7281 ExprValueKind VK = VK_RValue; 7282 ExprObjectKind OK = OK_Ordinary; 7283 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7284 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7285 VK, OK, QuestionLoc); 7286 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7287 RHS.isInvalid()) 7288 return ExprError(); 7289 7290 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7291 RHS.get()); 7292 7293 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7294 7295 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7296 Context); 7297 7298 if (!commonExpr) 7299 return new (Context) 7300 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7301 RHS.get(), result, VK, OK); 7302 7303 return new (Context) BinaryConditionalOperator( 7304 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7305 ColonLoc, result, VK, OK); 7306 } 7307 7308 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7309 // being closely modeled after the C99 spec:-). The odd characteristic of this 7310 // routine is it effectively iqnores the qualifiers on the top level pointee. 7311 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7312 // FIXME: add a couple examples in this comment. 7313 static Sema::AssignConvertType 7314 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7315 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7316 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7317 7318 // get the "pointed to" type (ignoring qualifiers at the top level) 7319 const Type *lhptee, *rhptee; 7320 Qualifiers lhq, rhq; 7321 std::tie(lhptee, lhq) = 7322 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7323 std::tie(rhptee, rhq) = 7324 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7325 7326 Sema::AssignConvertType ConvTy = Sema::Compatible; 7327 7328 // C99 6.5.16.1p1: This following citation is common to constraints 7329 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7330 // qualifiers of the type *pointed to* by the right; 7331 7332 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7333 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7334 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7335 // Ignore lifetime for further calculation. 7336 lhq.removeObjCLifetime(); 7337 rhq.removeObjCLifetime(); 7338 } 7339 7340 if (!lhq.compatiblyIncludes(rhq)) { 7341 // Treat address-space mismatches as fatal. TODO: address subspaces 7342 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7343 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7344 7345 // It's okay to add or remove GC or lifetime qualifiers when converting to 7346 // and from void*. 7347 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7348 .compatiblyIncludes( 7349 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7350 && (lhptee->isVoidType() || rhptee->isVoidType())) 7351 ; // keep old 7352 7353 // Treat lifetime mismatches as fatal. 7354 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7355 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7356 7357 // For GCC/MS compatibility, other qualifier mismatches are treated 7358 // as still compatible in C. 7359 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7360 } 7361 7362 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7363 // incomplete type and the other is a pointer to a qualified or unqualified 7364 // version of void... 7365 if (lhptee->isVoidType()) { 7366 if (rhptee->isIncompleteOrObjectType()) 7367 return ConvTy; 7368 7369 // As an extension, we allow cast to/from void* to function pointer. 7370 assert(rhptee->isFunctionType()); 7371 return Sema::FunctionVoidPointer; 7372 } 7373 7374 if (rhptee->isVoidType()) { 7375 if (lhptee->isIncompleteOrObjectType()) 7376 return ConvTy; 7377 7378 // As an extension, we allow cast to/from void* to function pointer. 7379 assert(lhptee->isFunctionType()); 7380 return Sema::FunctionVoidPointer; 7381 } 7382 7383 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7384 // unqualified versions of compatible types, ... 7385 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7386 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7387 // Check if the pointee types are compatible ignoring the sign. 7388 // We explicitly check for char so that we catch "char" vs 7389 // "unsigned char" on systems where "char" is unsigned. 7390 if (lhptee->isCharType()) 7391 ltrans = S.Context.UnsignedCharTy; 7392 else if (lhptee->hasSignedIntegerRepresentation()) 7393 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7394 7395 if (rhptee->isCharType()) 7396 rtrans = S.Context.UnsignedCharTy; 7397 else if (rhptee->hasSignedIntegerRepresentation()) 7398 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7399 7400 if (ltrans == rtrans) { 7401 // Types are compatible ignoring the sign. Qualifier incompatibility 7402 // takes priority over sign incompatibility because the sign 7403 // warning can be disabled. 7404 if (ConvTy != Sema::Compatible) 7405 return ConvTy; 7406 7407 return Sema::IncompatiblePointerSign; 7408 } 7409 7410 // If we are a multi-level pointer, it's possible that our issue is simply 7411 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7412 // the eventual target type is the same and the pointers have the same 7413 // level of indirection, this must be the issue. 7414 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7415 do { 7416 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7417 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7418 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7419 7420 if (lhptee == rhptee) 7421 return Sema::IncompatibleNestedPointerQualifiers; 7422 } 7423 7424 // General pointer incompatibility takes priority over qualifiers. 7425 return Sema::IncompatiblePointer; 7426 } 7427 if (!S.getLangOpts().CPlusPlus && 7428 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7429 return Sema::IncompatiblePointer; 7430 return ConvTy; 7431 } 7432 7433 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7434 /// block pointer types are compatible or whether a block and normal pointer 7435 /// are compatible. It is more restrict than comparing two function pointer 7436 // types. 7437 static Sema::AssignConvertType 7438 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7439 QualType RHSType) { 7440 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7441 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7442 7443 QualType lhptee, rhptee; 7444 7445 // get the "pointed to" type (ignoring qualifiers at the top level) 7446 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7447 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7448 7449 // In C++, the types have to match exactly. 7450 if (S.getLangOpts().CPlusPlus) 7451 return Sema::IncompatibleBlockPointer; 7452 7453 Sema::AssignConvertType ConvTy = Sema::Compatible; 7454 7455 // For blocks we enforce that qualifiers are identical. 7456 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7457 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7458 if (S.getLangOpts().OpenCL) { 7459 LQuals.removeAddressSpace(); 7460 RQuals.removeAddressSpace(); 7461 } 7462 if (LQuals != RQuals) 7463 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7464 7465 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7466 // assignment. 7467 // The current behavior is similar to C++ lambdas. A block might be 7468 // assigned to a variable iff its return type and parameters are compatible 7469 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7470 // an assignment. Presumably it should behave in way that a function pointer 7471 // assignment does in C, so for each parameter and return type: 7472 // * CVR and address space of LHS should be a superset of CVR and address 7473 // space of RHS. 7474 // * unqualified types should be compatible. 7475 if (S.getLangOpts().OpenCL) { 7476 if (!S.Context.typesAreBlockPointerCompatible( 7477 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7478 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7479 return Sema::IncompatibleBlockPointer; 7480 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7481 return Sema::IncompatibleBlockPointer; 7482 7483 return ConvTy; 7484 } 7485 7486 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7487 /// for assignment compatibility. 7488 static Sema::AssignConvertType 7489 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7490 QualType RHSType) { 7491 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7492 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7493 7494 if (LHSType->isObjCBuiltinType()) { 7495 // Class is not compatible with ObjC object pointers. 7496 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7497 !RHSType->isObjCQualifiedClassType()) 7498 return Sema::IncompatiblePointer; 7499 return Sema::Compatible; 7500 } 7501 if (RHSType->isObjCBuiltinType()) { 7502 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7503 !LHSType->isObjCQualifiedClassType()) 7504 return Sema::IncompatiblePointer; 7505 return Sema::Compatible; 7506 } 7507 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7508 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7509 7510 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7511 // make an exception for id<P> 7512 !LHSType->isObjCQualifiedIdType()) 7513 return Sema::CompatiblePointerDiscardsQualifiers; 7514 7515 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7516 return Sema::Compatible; 7517 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7518 return Sema::IncompatibleObjCQualifiedId; 7519 return Sema::IncompatiblePointer; 7520 } 7521 7522 Sema::AssignConvertType 7523 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7524 QualType LHSType, QualType RHSType) { 7525 // Fake up an opaque expression. We don't actually care about what 7526 // cast operations are required, so if CheckAssignmentConstraints 7527 // adds casts to this they'll be wasted, but fortunately that doesn't 7528 // usually happen on valid code. 7529 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7530 ExprResult RHSPtr = &RHSExpr; 7531 CastKind K; 7532 7533 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7534 } 7535 7536 /// This helper function returns true if QT is a vector type that has element 7537 /// type ElementType. 7538 static bool isVector(QualType QT, QualType ElementType) { 7539 if (const VectorType *VT = QT->getAs<VectorType>()) 7540 return VT->getElementType() == ElementType; 7541 return false; 7542 } 7543 7544 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7545 /// has code to accommodate several GCC extensions when type checking 7546 /// pointers. Here are some objectionable examples that GCC considers warnings: 7547 /// 7548 /// int a, *pint; 7549 /// short *pshort; 7550 /// struct foo *pfoo; 7551 /// 7552 /// pint = pshort; // warning: assignment from incompatible pointer type 7553 /// a = pint; // warning: assignment makes integer from pointer without a cast 7554 /// pint = a; // warning: assignment makes pointer from integer without a cast 7555 /// pint = pfoo; // warning: assignment from incompatible pointer type 7556 /// 7557 /// As a result, the code for dealing with pointers is more complex than the 7558 /// C99 spec dictates. 7559 /// 7560 /// Sets 'Kind' for any result kind except Incompatible. 7561 Sema::AssignConvertType 7562 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7563 CastKind &Kind, bool ConvertRHS) { 7564 QualType RHSType = RHS.get()->getType(); 7565 QualType OrigLHSType = LHSType; 7566 7567 // Get canonical types. We're not formatting these types, just comparing 7568 // them. 7569 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7570 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7571 7572 // Common case: no conversion required. 7573 if (LHSType == RHSType) { 7574 Kind = CK_NoOp; 7575 return Compatible; 7576 } 7577 7578 // If we have an atomic type, try a non-atomic assignment, then just add an 7579 // atomic qualification step. 7580 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7581 Sema::AssignConvertType result = 7582 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7583 if (result != Compatible) 7584 return result; 7585 if (Kind != CK_NoOp && ConvertRHS) 7586 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7587 Kind = CK_NonAtomicToAtomic; 7588 return Compatible; 7589 } 7590 7591 // If the left-hand side is a reference type, then we are in a 7592 // (rare!) case where we've allowed the use of references in C, 7593 // e.g., as a parameter type in a built-in function. In this case, 7594 // just make sure that the type referenced is compatible with the 7595 // right-hand side type. The caller is responsible for adjusting 7596 // LHSType so that the resulting expression does not have reference 7597 // type. 7598 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7599 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7600 Kind = CK_LValueBitCast; 7601 return Compatible; 7602 } 7603 return Incompatible; 7604 } 7605 7606 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7607 // to the same ExtVector type. 7608 if (LHSType->isExtVectorType()) { 7609 if (RHSType->isExtVectorType()) 7610 return Incompatible; 7611 if (RHSType->isArithmeticType()) { 7612 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7613 if (ConvertRHS) 7614 RHS = prepareVectorSplat(LHSType, RHS.get()); 7615 Kind = CK_VectorSplat; 7616 return Compatible; 7617 } 7618 } 7619 7620 // Conversions to or from vector type. 7621 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7622 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7623 // Allow assignments of an AltiVec vector type to an equivalent GCC 7624 // vector type and vice versa 7625 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7626 Kind = CK_BitCast; 7627 return Compatible; 7628 } 7629 7630 // If we are allowing lax vector conversions, and LHS and RHS are both 7631 // vectors, the total size only needs to be the same. This is a bitcast; 7632 // no bits are changed but the result type is different. 7633 if (isLaxVectorConversion(RHSType, LHSType)) { 7634 Kind = CK_BitCast; 7635 return IncompatibleVectors; 7636 } 7637 } 7638 7639 // When the RHS comes from another lax conversion (e.g. binops between 7640 // scalars and vectors) the result is canonicalized as a vector. When the 7641 // LHS is also a vector, the lax is allowed by the condition above. Handle 7642 // the case where LHS is a scalar. 7643 if (LHSType->isScalarType()) { 7644 const VectorType *VecType = RHSType->getAs<VectorType>(); 7645 if (VecType && VecType->getNumElements() == 1 && 7646 isLaxVectorConversion(RHSType, LHSType)) { 7647 ExprResult *VecExpr = &RHS; 7648 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7649 Kind = CK_BitCast; 7650 return Compatible; 7651 } 7652 } 7653 7654 return Incompatible; 7655 } 7656 7657 // Diagnose attempts to convert between __float128 and long double where 7658 // such conversions currently can't be handled. 7659 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7660 return Incompatible; 7661 7662 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7663 // discards the imaginary part. 7664 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7665 !LHSType->getAs<ComplexType>()) 7666 return Incompatible; 7667 7668 // Arithmetic conversions. 7669 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7670 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7671 if (ConvertRHS) 7672 Kind = PrepareScalarCast(RHS, LHSType); 7673 return Compatible; 7674 } 7675 7676 // Conversions to normal pointers. 7677 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7678 // U* -> T* 7679 if (isa<PointerType>(RHSType)) { 7680 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7681 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7682 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7683 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7684 } 7685 7686 // int -> T* 7687 if (RHSType->isIntegerType()) { 7688 Kind = CK_IntegralToPointer; // FIXME: null? 7689 return IntToPointer; 7690 } 7691 7692 // C pointers are not compatible with ObjC object pointers, 7693 // with two exceptions: 7694 if (isa<ObjCObjectPointerType>(RHSType)) { 7695 // - conversions to void* 7696 if (LHSPointer->getPointeeType()->isVoidType()) { 7697 Kind = CK_BitCast; 7698 return Compatible; 7699 } 7700 7701 // - conversions from 'Class' to the redefinition type 7702 if (RHSType->isObjCClassType() && 7703 Context.hasSameType(LHSType, 7704 Context.getObjCClassRedefinitionType())) { 7705 Kind = CK_BitCast; 7706 return Compatible; 7707 } 7708 7709 Kind = CK_BitCast; 7710 return IncompatiblePointer; 7711 } 7712 7713 // U^ -> void* 7714 if (RHSType->getAs<BlockPointerType>()) { 7715 if (LHSPointer->getPointeeType()->isVoidType()) { 7716 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7717 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7718 ->getPointeeType() 7719 .getAddressSpace(); 7720 Kind = 7721 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7722 return Compatible; 7723 } 7724 } 7725 7726 return Incompatible; 7727 } 7728 7729 // Conversions to block pointers. 7730 if (isa<BlockPointerType>(LHSType)) { 7731 // U^ -> T^ 7732 if (RHSType->isBlockPointerType()) { 7733 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7734 ->getPointeeType() 7735 .getAddressSpace(); 7736 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7737 ->getPointeeType() 7738 .getAddressSpace(); 7739 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7740 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7741 } 7742 7743 // int or null -> T^ 7744 if (RHSType->isIntegerType()) { 7745 Kind = CK_IntegralToPointer; // FIXME: null 7746 return IntToBlockPointer; 7747 } 7748 7749 // id -> T^ 7750 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7751 Kind = CK_AnyPointerToBlockPointerCast; 7752 return Compatible; 7753 } 7754 7755 // void* -> T^ 7756 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7757 if (RHSPT->getPointeeType()->isVoidType()) { 7758 Kind = CK_AnyPointerToBlockPointerCast; 7759 return Compatible; 7760 } 7761 7762 return Incompatible; 7763 } 7764 7765 // Conversions to Objective-C pointers. 7766 if (isa<ObjCObjectPointerType>(LHSType)) { 7767 // A* -> B* 7768 if (RHSType->isObjCObjectPointerType()) { 7769 Kind = CK_BitCast; 7770 Sema::AssignConvertType result = 7771 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7772 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7773 result == Compatible && 7774 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7775 result = IncompatibleObjCWeakRef; 7776 return result; 7777 } 7778 7779 // int or null -> A* 7780 if (RHSType->isIntegerType()) { 7781 Kind = CK_IntegralToPointer; // FIXME: null 7782 return IntToPointer; 7783 } 7784 7785 // In general, C pointers are not compatible with ObjC object pointers, 7786 // with two exceptions: 7787 if (isa<PointerType>(RHSType)) { 7788 Kind = CK_CPointerToObjCPointerCast; 7789 7790 // - conversions from 'void*' 7791 if (RHSType->isVoidPointerType()) { 7792 return Compatible; 7793 } 7794 7795 // - conversions to 'Class' from its redefinition type 7796 if (LHSType->isObjCClassType() && 7797 Context.hasSameType(RHSType, 7798 Context.getObjCClassRedefinitionType())) { 7799 return Compatible; 7800 } 7801 7802 return IncompatiblePointer; 7803 } 7804 7805 // Only under strict condition T^ is compatible with an Objective-C pointer. 7806 if (RHSType->isBlockPointerType() && 7807 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7808 if (ConvertRHS) 7809 maybeExtendBlockObject(RHS); 7810 Kind = CK_BlockPointerToObjCPointerCast; 7811 return Compatible; 7812 } 7813 7814 return Incompatible; 7815 } 7816 7817 // Conversions from pointers that are not covered by the above. 7818 if (isa<PointerType>(RHSType)) { 7819 // T* -> _Bool 7820 if (LHSType == Context.BoolTy) { 7821 Kind = CK_PointerToBoolean; 7822 return Compatible; 7823 } 7824 7825 // T* -> int 7826 if (LHSType->isIntegerType()) { 7827 Kind = CK_PointerToIntegral; 7828 return PointerToInt; 7829 } 7830 7831 return Incompatible; 7832 } 7833 7834 // Conversions from Objective-C pointers that are not covered by the above. 7835 if (isa<ObjCObjectPointerType>(RHSType)) { 7836 // T* -> _Bool 7837 if (LHSType == Context.BoolTy) { 7838 Kind = CK_PointerToBoolean; 7839 return Compatible; 7840 } 7841 7842 // T* -> int 7843 if (LHSType->isIntegerType()) { 7844 Kind = CK_PointerToIntegral; 7845 return PointerToInt; 7846 } 7847 7848 return Incompatible; 7849 } 7850 7851 // struct A -> struct B 7852 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7853 if (Context.typesAreCompatible(LHSType, RHSType)) { 7854 Kind = CK_NoOp; 7855 return Compatible; 7856 } 7857 } 7858 7859 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7860 Kind = CK_IntToOCLSampler; 7861 return Compatible; 7862 } 7863 7864 return Incompatible; 7865 } 7866 7867 /// \brief Constructs a transparent union from an expression that is 7868 /// used to initialize the transparent union. 7869 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7870 ExprResult &EResult, QualType UnionType, 7871 FieldDecl *Field) { 7872 // Build an initializer list that designates the appropriate member 7873 // of the transparent union. 7874 Expr *E = EResult.get(); 7875 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7876 E, SourceLocation()); 7877 Initializer->setType(UnionType); 7878 Initializer->setInitializedFieldInUnion(Field); 7879 7880 // Build a compound literal constructing a value of the transparent 7881 // union type from this initializer list. 7882 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7883 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7884 VK_RValue, Initializer, false); 7885 } 7886 7887 Sema::AssignConvertType 7888 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7889 ExprResult &RHS) { 7890 QualType RHSType = RHS.get()->getType(); 7891 7892 // If the ArgType is a Union type, we want to handle a potential 7893 // transparent_union GCC extension. 7894 const RecordType *UT = ArgType->getAsUnionType(); 7895 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7896 return Incompatible; 7897 7898 // The field to initialize within the transparent union. 7899 RecordDecl *UD = UT->getDecl(); 7900 FieldDecl *InitField = nullptr; 7901 // It's compatible if the expression matches any of the fields. 7902 for (auto *it : UD->fields()) { 7903 if (it->getType()->isPointerType()) { 7904 // If the transparent union contains a pointer type, we allow: 7905 // 1) void pointer 7906 // 2) null pointer constant 7907 if (RHSType->isPointerType()) 7908 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7909 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7910 InitField = it; 7911 break; 7912 } 7913 7914 if (RHS.get()->isNullPointerConstant(Context, 7915 Expr::NPC_ValueDependentIsNull)) { 7916 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7917 CK_NullToPointer); 7918 InitField = it; 7919 break; 7920 } 7921 } 7922 7923 CastKind Kind; 7924 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7925 == Compatible) { 7926 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7927 InitField = it; 7928 break; 7929 } 7930 } 7931 7932 if (!InitField) 7933 return Incompatible; 7934 7935 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7936 return Compatible; 7937 } 7938 7939 Sema::AssignConvertType 7940 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7941 bool Diagnose, 7942 bool DiagnoseCFAudited, 7943 bool ConvertRHS) { 7944 // We need to be able to tell the caller whether we diagnosed a problem, if 7945 // they ask us to issue diagnostics. 7946 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 7947 7948 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7949 // we can't avoid *all* modifications at the moment, so we need some somewhere 7950 // to put the updated value. 7951 ExprResult LocalRHS = CallerRHS; 7952 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7953 7954 if (getLangOpts().CPlusPlus) { 7955 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7956 // C++ 5.17p3: If the left operand is not of class type, the 7957 // expression is implicitly converted (C++ 4) to the 7958 // cv-unqualified type of the left operand. 7959 QualType RHSType = RHS.get()->getType(); 7960 if (Diagnose) { 7961 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7962 AA_Assigning); 7963 } else { 7964 ImplicitConversionSequence ICS = 7965 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7966 /*SuppressUserConversions=*/false, 7967 /*AllowExplicit=*/false, 7968 /*InOverloadResolution=*/false, 7969 /*CStyle=*/false, 7970 /*AllowObjCWritebackConversion=*/false); 7971 if (ICS.isFailure()) 7972 return Incompatible; 7973 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7974 ICS, AA_Assigning); 7975 } 7976 if (RHS.isInvalid()) 7977 return Incompatible; 7978 Sema::AssignConvertType result = Compatible; 7979 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7980 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 7981 result = IncompatibleObjCWeakRef; 7982 return result; 7983 } 7984 7985 // FIXME: Currently, we fall through and treat C++ classes like C 7986 // structures. 7987 // FIXME: We also fall through for atomics; not sure what should 7988 // happen there, though. 7989 } else if (RHS.get()->getType() == Context.OverloadTy) { 7990 // As a set of extensions to C, we support overloading on functions. These 7991 // functions need to be resolved here. 7992 DeclAccessPair DAP; 7993 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7994 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7995 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7996 else 7997 return Incompatible; 7998 } 7999 8000 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8001 // a null pointer constant. 8002 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8003 LHSType->isBlockPointerType()) && 8004 RHS.get()->isNullPointerConstant(Context, 8005 Expr::NPC_ValueDependentIsNull)) { 8006 if (Diagnose || ConvertRHS) { 8007 CastKind Kind; 8008 CXXCastPath Path; 8009 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8010 /*IgnoreBaseAccess=*/false, Diagnose); 8011 if (ConvertRHS) 8012 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8013 } 8014 return Compatible; 8015 } 8016 8017 // This check seems unnatural, however it is necessary to ensure the proper 8018 // conversion of functions/arrays. If the conversion were done for all 8019 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8020 // expressions that suppress this implicit conversion (&, sizeof). 8021 // 8022 // Suppress this for references: C++ 8.5.3p5. 8023 if (!LHSType->isReferenceType()) { 8024 // FIXME: We potentially allocate here even if ConvertRHS is false. 8025 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8026 if (RHS.isInvalid()) 8027 return Incompatible; 8028 } 8029 8030 Expr *PRE = RHS.get()->IgnoreParenCasts(); 8031 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 8032 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 8033 if (PDecl && !PDecl->hasDefinition()) { 8034 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl; 8035 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 8036 } 8037 } 8038 8039 CastKind Kind; 8040 Sema::AssignConvertType result = 8041 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8042 8043 // C99 6.5.16.1p2: The value of the right operand is converted to the 8044 // type of the assignment expression. 8045 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8046 // so that we can use references in built-in functions even in C. 8047 // The getNonReferenceType() call makes sure that the resulting expression 8048 // does not have reference type. 8049 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8050 QualType Ty = LHSType.getNonLValueExprType(Context); 8051 Expr *E = RHS.get(); 8052 8053 // Check for various Objective-C errors. If we are not reporting 8054 // diagnostics and just checking for errors, e.g., during overload 8055 // resolution, return Incompatible to indicate the failure. 8056 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8057 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8058 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8059 if (!Diagnose) 8060 return Incompatible; 8061 } 8062 if (getLangOpts().ObjC1 && 8063 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 8064 E->getType(), E, Diagnose) || 8065 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8066 if (!Diagnose) 8067 return Incompatible; 8068 // Replace the expression with a corrected version and continue so we 8069 // can find further errors. 8070 RHS = E; 8071 return Compatible; 8072 } 8073 8074 if (ConvertRHS) 8075 RHS = ImpCastExprToType(E, Ty, Kind); 8076 } 8077 return result; 8078 } 8079 8080 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8081 ExprResult &RHS) { 8082 Diag(Loc, diag::err_typecheck_invalid_operands) 8083 << LHS.get()->getType() << RHS.get()->getType() 8084 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8085 return QualType(); 8086 } 8087 8088 // Diagnose cases where a scalar was implicitly converted to a vector and 8089 // diagnose the underlying types. Otherwise, diagnose the error 8090 // as invalid vector logical operands for non-C++ cases. 8091 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8092 ExprResult &RHS) { 8093 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8094 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8095 8096 bool LHSNatVec = LHSType->isVectorType(); 8097 bool RHSNatVec = RHSType->isVectorType(); 8098 8099 if (!(LHSNatVec && RHSNatVec)) { 8100 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8101 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8102 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8103 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8104 << Vector->getSourceRange(); 8105 return QualType(); 8106 } 8107 8108 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8109 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8110 << RHS.get()->getSourceRange(); 8111 8112 return QualType(); 8113 } 8114 8115 /// Try to convert a value of non-vector type to a vector type by converting 8116 /// the type to the element type of the vector and then performing a splat. 8117 /// If the language is OpenCL, we only use conversions that promote scalar 8118 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8119 /// for float->int. 8120 /// 8121 /// OpenCL V2.0 6.2.6.p2: 8122 /// An error shall occur if any scalar operand type has greater rank 8123 /// than the type of the vector element. 8124 /// 8125 /// \param scalar - if non-null, actually perform the conversions 8126 /// \return true if the operation fails (but without diagnosing the failure) 8127 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8128 QualType scalarTy, 8129 QualType vectorEltTy, 8130 QualType vectorTy, 8131 unsigned &DiagID) { 8132 // The conversion to apply to the scalar before splatting it, 8133 // if necessary. 8134 CastKind scalarCast = CK_NoOp; 8135 8136 if (vectorEltTy->isIntegralType(S.Context)) { 8137 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8138 (scalarTy->isIntegerType() && 8139 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8140 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8141 return true; 8142 } 8143 if (!scalarTy->isIntegralType(S.Context)) 8144 return true; 8145 scalarCast = CK_IntegralCast; 8146 } else if (vectorEltTy->isRealFloatingType()) { 8147 if (scalarTy->isRealFloatingType()) { 8148 if (S.getLangOpts().OpenCL && 8149 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8150 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8151 return true; 8152 } 8153 scalarCast = CK_FloatingCast; 8154 } 8155 else if (scalarTy->isIntegralType(S.Context)) 8156 scalarCast = CK_IntegralToFloating; 8157 else 8158 return true; 8159 } else { 8160 return true; 8161 } 8162 8163 // Adjust scalar if desired. 8164 if (scalar) { 8165 if (scalarCast != CK_NoOp) 8166 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8167 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8168 } 8169 return false; 8170 } 8171 8172 /// Convert vector E to a vector with the same number of elements but different 8173 /// element type. 8174 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8175 const auto *VecTy = E->getType()->getAs<VectorType>(); 8176 assert(VecTy && "Expression E must be a vector"); 8177 QualType NewVecTy = S.Context.getVectorType(ElementType, 8178 VecTy->getNumElements(), 8179 VecTy->getVectorKind()); 8180 8181 // Look through the implicit cast. Return the subexpression if its type is 8182 // NewVecTy. 8183 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8184 if (ICE->getSubExpr()->getType() == NewVecTy) 8185 return ICE->getSubExpr(); 8186 8187 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8188 return S.ImpCastExprToType(E, NewVecTy, Cast); 8189 } 8190 8191 /// Test if a (constant) integer Int can be casted to another integer type 8192 /// IntTy without losing precision. 8193 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8194 QualType OtherIntTy) { 8195 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8196 8197 // Reject cases where the value of the Int is unknown as that would 8198 // possibly cause truncation, but accept cases where the scalar can be 8199 // demoted without loss of precision. 8200 llvm::APSInt Result; 8201 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8202 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8203 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8204 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8205 8206 if (CstInt) { 8207 // If the scalar is constant and is of a higher order and has more active 8208 // bits that the vector element type, reject it. 8209 unsigned NumBits = IntSigned 8210 ? (Result.isNegative() ? Result.getMinSignedBits() 8211 : Result.getActiveBits()) 8212 : Result.getActiveBits(); 8213 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8214 return true; 8215 8216 // If the signedness of the scalar type and the vector element type 8217 // differs and the number of bits is greater than that of the vector 8218 // element reject it. 8219 return (IntSigned != OtherIntSigned && 8220 NumBits > S.Context.getIntWidth(OtherIntTy)); 8221 } 8222 8223 // Reject cases where the value of the scalar is not constant and it's 8224 // order is greater than that of the vector element type. 8225 return (Order < 0); 8226 } 8227 8228 /// Test if a (constant) integer Int can be casted to floating point type 8229 /// FloatTy without losing precision. 8230 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8231 QualType FloatTy) { 8232 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8233 8234 // Determine if the integer constant can be expressed as a floating point 8235 // number of the appropiate type. 8236 llvm::APSInt Result; 8237 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8238 uint64_t Bits = 0; 8239 if (CstInt) { 8240 // Reject constants that would be truncated if they were converted to 8241 // the floating point type. Test by simple to/from conversion. 8242 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8243 // could be avoided if there was a convertFromAPInt method 8244 // which could signal back if implicit truncation occurred. 8245 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8246 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8247 llvm::APFloat::rmTowardZero); 8248 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8249 !IntTy->hasSignedIntegerRepresentation()); 8250 bool Ignored = false; 8251 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8252 &Ignored); 8253 if (Result != ConvertBack) 8254 return true; 8255 } else { 8256 // Reject types that cannot be fully encoded into the mantissa of 8257 // the float. 8258 Bits = S.Context.getTypeSize(IntTy); 8259 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8260 S.Context.getFloatTypeSemantics(FloatTy)); 8261 if (Bits > FloatPrec) 8262 return true; 8263 } 8264 8265 return false; 8266 } 8267 8268 /// Attempt to convert and splat Scalar into a vector whose types matches 8269 /// Vector following GCC conversion rules. The rule is that implicit 8270 /// conversion can occur when Scalar can be casted to match Vector's element 8271 /// type without causing truncation of Scalar. 8272 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8273 ExprResult *Vector) { 8274 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8275 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8276 const VectorType *VT = VectorTy->getAs<VectorType>(); 8277 8278 assert(!isa<ExtVectorType>(VT) && 8279 "ExtVectorTypes should not be handled here!"); 8280 8281 QualType VectorEltTy = VT->getElementType(); 8282 8283 // Reject cases where the vector element type or the scalar element type are 8284 // not integral or floating point types. 8285 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8286 return true; 8287 8288 // The conversion to apply to the scalar before splatting it, 8289 // if necessary. 8290 CastKind ScalarCast = CK_NoOp; 8291 8292 // Accept cases where the vector elements are integers and the scalar is 8293 // an integer. 8294 // FIXME: Notionally if the scalar was a floating point value with a precise 8295 // integral representation, we could cast it to an appropriate integer 8296 // type and then perform the rest of the checks here. GCC will perform 8297 // this conversion in some cases as determined by the input language. 8298 // We should accept it on a language independent basis. 8299 if (VectorEltTy->isIntegralType(S.Context) && 8300 ScalarTy->isIntegralType(S.Context) && 8301 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8302 8303 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8304 return true; 8305 8306 ScalarCast = CK_IntegralCast; 8307 } else if (VectorEltTy->isRealFloatingType()) { 8308 if (ScalarTy->isRealFloatingType()) { 8309 8310 // Reject cases where the scalar type is not a constant and has a higher 8311 // Order than the vector element type. 8312 llvm::APFloat Result(0.0); 8313 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8314 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8315 if (!CstScalar && Order < 0) 8316 return true; 8317 8318 // If the scalar cannot be safely casted to the vector element type, 8319 // reject it. 8320 if (CstScalar) { 8321 bool Truncated = false; 8322 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8323 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8324 if (Truncated) 8325 return true; 8326 } 8327 8328 ScalarCast = CK_FloatingCast; 8329 } else if (ScalarTy->isIntegralType(S.Context)) { 8330 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8331 return true; 8332 8333 ScalarCast = CK_IntegralToFloating; 8334 } else 8335 return true; 8336 } 8337 8338 // Adjust scalar if desired. 8339 if (Scalar) { 8340 if (ScalarCast != CK_NoOp) 8341 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8342 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8343 } 8344 return false; 8345 } 8346 8347 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8348 SourceLocation Loc, bool IsCompAssign, 8349 bool AllowBothBool, 8350 bool AllowBoolConversions) { 8351 if (!IsCompAssign) { 8352 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8353 if (LHS.isInvalid()) 8354 return QualType(); 8355 } 8356 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8357 if (RHS.isInvalid()) 8358 return QualType(); 8359 8360 // For conversion purposes, we ignore any qualifiers. 8361 // For example, "const float" and "float" are equivalent. 8362 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8363 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8364 8365 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8366 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8367 assert(LHSVecType || RHSVecType); 8368 8369 // AltiVec-style "vector bool op vector bool" combinations are allowed 8370 // for some operators but not others. 8371 if (!AllowBothBool && 8372 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8373 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8374 return InvalidOperands(Loc, LHS, RHS); 8375 8376 // If the vector types are identical, return. 8377 if (Context.hasSameType(LHSType, RHSType)) 8378 return LHSType; 8379 8380 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8381 if (LHSVecType && RHSVecType && 8382 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8383 if (isa<ExtVectorType>(LHSVecType)) { 8384 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8385 return LHSType; 8386 } 8387 8388 if (!IsCompAssign) 8389 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8390 return RHSType; 8391 } 8392 8393 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8394 // can be mixed, with the result being the non-bool type. The non-bool 8395 // operand must have integer element type. 8396 if (AllowBoolConversions && LHSVecType && RHSVecType && 8397 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8398 (Context.getTypeSize(LHSVecType->getElementType()) == 8399 Context.getTypeSize(RHSVecType->getElementType()))) { 8400 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8401 LHSVecType->getElementType()->isIntegerType() && 8402 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8403 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8404 return LHSType; 8405 } 8406 if (!IsCompAssign && 8407 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8408 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8409 RHSVecType->getElementType()->isIntegerType()) { 8410 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8411 return RHSType; 8412 } 8413 } 8414 8415 // If there's a vector type and a scalar, try to convert the scalar to 8416 // the vector element type and splat. 8417 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8418 if (!RHSVecType) { 8419 if (isa<ExtVectorType>(LHSVecType)) { 8420 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8421 LHSVecType->getElementType(), LHSType, 8422 DiagID)) 8423 return LHSType; 8424 } else { 8425 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8426 return LHSType; 8427 } 8428 } 8429 if (!LHSVecType) { 8430 if (isa<ExtVectorType>(RHSVecType)) { 8431 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8432 LHSType, RHSVecType->getElementType(), 8433 RHSType, DiagID)) 8434 return RHSType; 8435 } else { 8436 if (LHS.get()->getValueKind() == VK_LValue || 8437 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8438 return RHSType; 8439 } 8440 } 8441 8442 // FIXME: The code below also handles conversion between vectors and 8443 // non-scalars, we should break this down into fine grained specific checks 8444 // and emit proper diagnostics. 8445 QualType VecType = LHSVecType ? LHSType : RHSType; 8446 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8447 QualType OtherType = LHSVecType ? RHSType : LHSType; 8448 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8449 if (isLaxVectorConversion(OtherType, VecType)) { 8450 // If we're allowing lax vector conversions, only the total (data) size 8451 // needs to be the same. For non compound assignment, if one of the types is 8452 // scalar, the result is always the vector type. 8453 if (!IsCompAssign) { 8454 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8455 return VecType; 8456 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8457 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8458 // type. Note that this is already done by non-compound assignments in 8459 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8460 // <1 x T> -> T. The result is also a vector type. 8461 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8462 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8463 ExprResult *RHSExpr = &RHS; 8464 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8465 return VecType; 8466 } 8467 } 8468 8469 // Okay, the expression is invalid. 8470 8471 // If there's a non-vector, non-real operand, diagnose that. 8472 if ((!RHSVecType && !RHSType->isRealType()) || 8473 (!LHSVecType && !LHSType->isRealType())) { 8474 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8475 << LHSType << RHSType 8476 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8477 return QualType(); 8478 } 8479 8480 // OpenCL V1.1 6.2.6.p1: 8481 // If the operands are of more than one vector type, then an error shall 8482 // occur. Implicit conversions between vector types are not permitted, per 8483 // section 6.2.1. 8484 if (getLangOpts().OpenCL && 8485 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8486 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8487 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8488 << RHSType; 8489 return QualType(); 8490 } 8491 8492 8493 // If there is a vector type that is not a ExtVector and a scalar, we reach 8494 // this point if scalar could not be converted to the vector's element type 8495 // without truncation. 8496 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8497 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8498 QualType Scalar = LHSVecType ? RHSType : LHSType; 8499 QualType Vector = LHSVecType ? LHSType : RHSType; 8500 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8501 Diag(Loc, 8502 diag::err_typecheck_vector_not_convertable_implict_truncation) 8503 << ScalarOrVector << Scalar << Vector; 8504 8505 return QualType(); 8506 } 8507 8508 // Otherwise, use the generic diagnostic. 8509 Diag(Loc, DiagID) 8510 << LHSType << RHSType 8511 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8512 return QualType(); 8513 } 8514 8515 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8516 // expression. These are mainly cases where the null pointer is used as an 8517 // integer instead of a pointer. 8518 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8519 SourceLocation Loc, bool IsCompare) { 8520 // The canonical way to check for a GNU null is with isNullPointerConstant, 8521 // but we use a bit of a hack here for speed; this is a relatively 8522 // hot path, and isNullPointerConstant is slow. 8523 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8524 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8525 8526 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8527 8528 // Avoid analyzing cases where the result will either be invalid (and 8529 // diagnosed as such) or entirely valid and not something to warn about. 8530 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8531 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8532 return; 8533 8534 // Comparison operations would not make sense with a null pointer no matter 8535 // what the other expression is. 8536 if (!IsCompare) { 8537 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8538 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8539 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8540 return; 8541 } 8542 8543 // The rest of the operations only make sense with a null pointer 8544 // if the other expression is a pointer. 8545 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8546 NonNullType->canDecayToPointerType()) 8547 return; 8548 8549 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8550 << LHSNull /* LHS is NULL */ << NonNullType 8551 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8552 } 8553 8554 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8555 ExprResult &RHS, 8556 SourceLocation Loc, bool IsDiv) { 8557 // Check for division/remainder by zero. 8558 llvm::APSInt RHSValue; 8559 if (!RHS.get()->isValueDependent() && 8560 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8561 S.DiagRuntimeBehavior(Loc, RHS.get(), 8562 S.PDiag(diag::warn_remainder_division_by_zero) 8563 << IsDiv << RHS.get()->getSourceRange()); 8564 } 8565 8566 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8567 SourceLocation Loc, 8568 bool IsCompAssign, bool IsDiv) { 8569 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8570 8571 if (LHS.get()->getType()->isVectorType() || 8572 RHS.get()->getType()->isVectorType()) 8573 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8574 /*AllowBothBool*/getLangOpts().AltiVec, 8575 /*AllowBoolConversions*/false); 8576 8577 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8578 if (LHS.isInvalid() || RHS.isInvalid()) 8579 return QualType(); 8580 8581 8582 if (compType.isNull() || !compType->isArithmeticType()) 8583 return InvalidOperands(Loc, LHS, RHS); 8584 if (IsDiv) 8585 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8586 return compType; 8587 } 8588 8589 QualType Sema::CheckRemainderOperands( 8590 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8591 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8592 8593 if (LHS.get()->getType()->isVectorType() || 8594 RHS.get()->getType()->isVectorType()) { 8595 if (LHS.get()->getType()->hasIntegerRepresentation() && 8596 RHS.get()->getType()->hasIntegerRepresentation()) 8597 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8598 /*AllowBothBool*/getLangOpts().AltiVec, 8599 /*AllowBoolConversions*/false); 8600 return InvalidOperands(Loc, LHS, RHS); 8601 } 8602 8603 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8604 if (LHS.isInvalid() || RHS.isInvalid()) 8605 return QualType(); 8606 8607 if (compType.isNull() || !compType->isIntegerType()) 8608 return InvalidOperands(Loc, LHS, RHS); 8609 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8610 return compType; 8611 } 8612 8613 /// \brief Diagnose invalid arithmetic on two void pointers. 8614 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8615 Expr *LHSExpr, Expr *RHSExpr) { 8616 S.Diag(Loc, S.getLangOpts().CPlusPlus 8617 ? diag::err_typecheck_pointer_arith_void_type 8618 : diag::ext_gnu_void_ptr) 8619 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8620 << RHSExpr->getSourceRange(); 8621 } 8622 8623 /// \brief Diagnose invalid arithmetic on a void pointer. 8624 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8625 Expr *Pointer) { 8626 S.Diag(Loc, S.getLangOpts().CPlusPlus 8627 ? diag::err_typecheck_pointer_arith_void_type 8628 : diag::ext_gnu_void_ptr) 8629 << 0 /* one pointer */ << Pointer->getSourceRange(); 8630 } 8631 8632 /// \brief Diagnose invalid arithmetic on a null pointer. 8633 /// 8634 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8635 /// idiom, which we recognize as a GNU extension. 8636 /// 8637 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8638 Expr *Pointer, bool IsGNUIdiom) { 8639 if (IsGNUIdiom) 8640 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8641 << Pointer->getSourceRange(); 8642 else 8643 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8644 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8645 } 8646 8647 /// \brief Diagnose invalid arithmetic on two function pointers. 8648 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8649 Expr *LHS, Expr *RHS) { 8650 assert(LHS->getType()->isAnyPointerType()); 8651 assert(RHS->getType()->isAnyPointerType()); 8652 S.Diag(Loc, S.getLangOpts().CPlusPlus 8653 ? diag::err_typecheck_pointer_arith_function_type 8654 : diag::ext_gnu_ptr_func_arith) 8655 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8656 // We only show the second type if it differs from the first. 8657 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8658 RHS->getType()) 8659 << RHS->getType()->getPointeeType() 8660 << LHS->getSourceRange() << RHS->getSourceRange(); 8661 } 8662 8663 /// \brief Diagnose invalid arithmetic on a function pointer. 8664 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8665 Expr *Pointer) { 8666 assert(Pointer->getType()->isAnyPointerType()); 8667 S.Diag(Loc, S.getLangOpts().CPlusPlus 8668 ? diag::err_typecheck_pointer_arith_function_type 8669 : diag::ext_gnu_ptr_func_arith) 8670 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8671 << 0 /* one pointer, so only one type */ 8672 << Pointer->getSourceRange(); 8673 } 8674 8675 /// \brief Emit error if Operand is incomplete pointer type 8676 /// 8677 /// \returns True if pointer has incomplete type 8678 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8679 Expr *Operand) { 8680 QualType ResType = Operand->getType(); 8681 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8682 ResType = ResAtomicType->getValueType(); 8683 8684 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8685 QualType PointeeTy = ResType->getPointeeType(); 8686 return S.RequireCompleteType(Loc, PointeeTy, 8687 diag::err_typecheck_arithmetic_incomplete_type, 8688 PointeeTy, Operand->getSourceRange()); 8689 } 8690 8691 /// \brief Check the validity of an arithmetic pointer operand. 8692 /// 8693 /// If the operand has pointer type, this code will check for pointer types 8694 /// which are invalid in arithmetic operations. These will be diagnosed 8695 /// appropriately, including whether or not the use is supported as an 8696 /// extension. 8697 /// 8698 /// \returns True when the operand is valid to use (even if as an extension). 8699 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8700 Expr *Operand) { 8701 QualType ResType = Operand->getType(); 8702 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8703 ResType = ResAtomicType->getValueType(); 8704 8705 if (!ResType->isAnyPointerType()) return true; 8706 8707 QualType PointeeTy = ResType->getPointeeType(); 8708 if (PointeeTy->isVoidType()) { 8709 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8710 return !S.getLangOpts().CPlusPlus; 8711 } 8712 if (PointeeTy->isFunctionType()) { 8713 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8714 return !S.getLangOpts().CPlusPlus; 8715 } 8716 8717 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8718 8719 return true; 8720 } 8721 8722 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 8723 /// operands. 8724 /// 8725 /// This routine will diagnose any invalid arithmetic on pointer operands much 8726 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8727 /// for emitting a single diagnostic even for operations where both LHS and RHS 8728 /// are (potentially problematic) pointers. 8729 /// 8730 /// \returns True when the operand is valid to use (even if as an extension). 8731 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8732 Expr *LHSExpr, Expr *RHSExpr) { 8733 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8734 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8735 if (!isLHSPointer && !isRHSPointer) return true; 8736 8737 QualType LHSPointeeTy, RHSPointeeTy; 8738 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8739 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8740 8741 // if both are pointers check if operation is valid wrt address spaces 8742 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8743 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8744 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8745 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8746 S.Diag(Loc, 8747 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8748 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8749 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8750 return false; 8751 } 8752 } 8753 8754 // Check for arithmetic on pointers to incomplete types. 8755 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8756 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8757 if (isLHSVoidPtr || isRHSVoidPtr) { 8758 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8759 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8760 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8761 8762 return !S.getLangOpts().CPlusPlus; 8763 } 8764 8765 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8766 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8767 if (isLHSFuncPtr || isRHSFuncPtr) { 8768 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8769 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8770 RHSExpr); 8771 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8772 8773 return !S.getLangOpts().CPlusPlus; 8774 } 8775 8776 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8777 return false; 8778 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8779 return false; 8780 8781 return true; 8782 } 8783 8784 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8785 /// literal. 8786 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8787 Expr *LHSExpr, Expr *RHSExpr) { 8788 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8789 Expr* IndexExpr = RHSExpr; 8790 if (!StrExpr) { 8791 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8792 IndexExpr = LHSExpr; 8793 } 8794 8795 bool IsStringPlusInt = StrExpr && 8796 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8797 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8798 return; 8799 8800 llvm::APSInt index; 8801 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8802 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8803 if (index.isNonNegative() && 8804 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8805 index.isUnsigned())) 8806 return; 8807 } 8808 8809 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8810 Self.Diag(OpLoc, diag::warn_string_plus_int) 8811 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8812 8813 // Only print a fixit for "str" + int, not for int + "str". 8814 if (IndexExpr == RHSExpr) { 8815 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8816 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8817 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8818 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8819 << FixItHint::CreateInsertion(EndLoc, "]"); 8820 } else 8821 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8822 } 8823 8824 /// \brief Emit a warning when adding a char literal to a string. 8825 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8826 Expr *LHSExpr, Expr *RHSExpr) { 8827 const Expr *StringRefExpr = LHSExpr; 8828 const CharacterLiteral *CharExpr = 8829 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8830 8831 if (!CharExpr) { 8832 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8833 StringRefExpr = RHSExpr; 8834 } 8835 8836 if (!CharExpr || !StringRefExpr) 8837 return; 8838 8839 const QualType StringType = StringRefExpr->getType(); 8840 8841 // Return if not a PointerType. 8842 if (!StringType->isAnyPointerType()) 8843 return; 8844 8845 // Return if not a CharacterType. 8846 if (!StringType->getPointeeType()->isAnyCharacterType()) 8847 return; 8848 8849 ASTContext &Ctx = Self.getASTContext(); 8850 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8851 8852 const QualType CharType = CharExpr->getType(); 8853 if (!CharType->isAnyCharacterType() && 8854 CharType->isIntegerType() && 8855 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8856 Self.Diag(OpLoc, diag::warn_string_plus_char) 8857 << DiagRange << Ctx.CharTy; 8858 } else { 8859 Self.Diag(OpLoc, diag::warn_string_plus_char) 8860 << DiagRange << CharExpr->getType(); 8861 } 8862 8863 // Only print a fixit for str + char, not for char + str. 8864 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8865 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8866 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8867 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8868 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8869 << FixItHint::CreateInsertion(EndLoc, "]"); 8870 } else { 8871 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8872 } 8873 } 8874 8875 /// \brief Emit error when two pointers are incompatible. 8876 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8877 Expr *LHSExpr, Expr *RHSExpr) { 8878 assert(LHSExpr->getType()->isAnyPointerType()); 8879 assert(RHSExpr->getType()->isAnyPointerType()); 8880 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8881 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8882 << RHSExpr->getSourceRange(); 8883 } 8884 8885 // C99 6.5.6 8886 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8887 SourceLocation Loc, BinaryOperatorKind Opc, 8888 QualType* CompLHSTy) { 8889 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8890 8891 if (LHS.get()->getType()->isVectorType() || 8892 RHS.get()->getType()->isVectorType()) { 8893 QualType compType = CheckVectorOperands( 8894 LHS, RHS, Loc, CompLHSTy, 8895 /*AllowBothBool*/getLangOpts().AltiVec, 8896 /*AllowBoolConversions*/getLangOpts().ZVector); 8897 if (CompLHSTy) *CompLHSTy = compType; 8898 return compType; 8899 } 8900 8901 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8902 if (LHS.isInvalid() || RHS.isInvalid()) 8903 return QualType(); 8904 8905 // Diagnose "string literal" '+' int and string '+' "char literal". 8906 if (Opc == BO_Add) { 8907 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8908 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8909 } 8910 8911 // handle the common case first (both operands are arithmetic). 8912 if (!compType.isNull() && compType->isArithmeticType()) { 8913 if (CompLHSTy) *CompLHSTy = compType; 8914 return compType; 8915 } 8916 8917 // Type-checking. Ultimately the pointer's going to be in PExp; 8918 // note that we bias towards the LHS being the pointer. 8919 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8920 8921 bool isObjCPointer; 8922 if (PExp->getType()->isPointerType()) { 8923 isObjCPointer = false; 8924 } else if (PExp->getType()->isObjCObjectPointerType()) { 8925 isObjCPointer = true; 8926 } else { 8927 std::swap(PExp, IExp); 8928 if (PExp->getType()->isPointerType()) { 8929 isObjCPointer = false; 8930 } else if (PExp->getType()->isObjCObjectPointerType()) { 8931 isObjCPointer = true; 8932 } else { 8933 return InvalidOperands(Loc, LHS, RHS); 8934 } 8935 } 8936 assert(PExp->getType()->isAnyPointerType()); 8937 8938 if (!IExp->getType()->isIntegerType()) 8939 return InvalidOperands(Loc, LHS, RHS); 8940 8941 // Adding to a null pointer results in undefined behavior. 8942 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 8943 Context, Expr::NPC_ValueDependentIsNotNull)) { 8944 // In C++ adding zero to a null pointer is defined. 8945 llvm::APSInt KnownVal; 8946 if (!getLangOpts().CPlusPlus || 8947 (!IExp->isValueDependent() && 8948 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 8949 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 8950 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 8951 Context, BO_Add, PExp, IExp); 8952 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 8953 } 8954 } 8955 8956 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8957 return QualType(); 8958 8959 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8960 return QualType(); 8961 8962 // Check array bounds for pointer arithemtic 8963 CheckArrayAccess(PExp, IExp); 8964 8965 if (CompLHSTy) { 8966 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8967 if (LHSTy.isNull()) { 8968 LHSTy = LHS.get()->getType(); 8969 if (LHSTy->isPromotableIntegerType()) 8970 LHSTy = Context.getPromotedIntegerType(LHSTy); 8971 } 8972 *CompLHSTy = LHSTy; 8973 } 8974 8975 return PExp->getType(); 8976 } 8977 8978 // C99 6.5.6 8979 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8980 SourceLocation Loc, 8981 QualType* CompLHSTy) { 8982 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8983 8984 if (LHS.get()->getType()->isVectorType() || 8985 RHS.get()->getType()->isVectorType()) { 8986 QualType compType = CheckVectorOperands( 8987 LHS, RHS, Loc, CompLHSTy, 8988 /*AllowBothBool*/getLangOpts().AltiVec, 8989 /*AllowBoolConversions*/getLangOpts().ZVector); 8990 if (CompLHSTy) *CompLHSTy = compType; 8991 return compType; 8992 } 8993 8994 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8995 if (LHS.isInvalid() || RHS.isInvalid()) 8996 return QualType(); 8997 8998 // Enforce type constraints: C99 6.5.6p3. 8999 9000 // Handle the common case first (both operands are arithmetic). 9001 if (!compType.isNull() && compType->isArithmeticType()) { 9002 if (CompLHSTy) *CompLHSTy = compType; 9003 return compType; 9004 } 9005 9006 // Either ptr - int or ptr - ptr. 9007 if (LHS.get()->getType()->isAnyPointerType()) { 9008 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9009 9010 // Diagnose bad cases where we step over interface counts. 9011 if (LHS.get()->getType()->isObjCObjectPointerType() && 9012 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9013 return QualType(); 9014 9015 // The result type of a pointer-int computation is the pointer type. 9016 if (RHS.get()->getType()->isIntegerType()) { 9017 // Subtracting from a null pointer should produce a warning. 9018 // The last argument to the diagnose call says this doesn't match the 9019 // GNU int-to-pointer idiom. 9020 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9021 Expr::NPC_ValueDependentIsNotNull)) { 9022 // In C++ adding zero to a null pointer is defined. 9023 llvm::APSInt KnownVal; 9024 if (!getLangOpts().CPlusPlus || 9025 (!RHS.get()->isValueDependent() && 9026 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9027 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9028 } 9029 } 9030 9031 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9032 return QualType(); 9033 9034 // Check array bounds for pointer arithemtic 9035 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9036 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9037 9038 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9039 return LHS.get()->getType(); 9040 } 9041 9042 // Handle pointer-pointer subtractions. 9043 if (const PointerType *RHSPTy 9044 = RHS.get()->getType()->getAs<PointerType>()) { 9045 QualType rpointee = RHSPTy->getPointeeType(); 9046 9047 if (getLangOpts().CPlusPlus) { 9048 // Pointee types must be the same: C++ [expr.add] 9049 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9050 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9051 } 9052 } else { 9053 // Pointee types must be compatible C99 6.5.6p3 9054 if (!Context.typesAreCompatible( 9055 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9056 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9057 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9058 return QualType(); 9059 } 9060 } 9061 9062 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9063 LHS.get(), RHS.get())) 9064 return QualType(); 9065 9066 // FIXME: Add warnings for nullptr - ptr. 9067 9068 // The pointee type may have zero size. As an extension, a structure or 9069 // union may have zero size or an array may have zero length. In this 9070 // case subtraction does not make sense. 9071 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9072 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9073 if (ElementSize.isZero()) { 9074 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9075 << rpointee.getUnqualifiedType() 9076 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9077 } 9078 } 9079 9080 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9081 return Context.getPointerDiffType(); 9082 } 9083 } 9084 9085 return InvalidOperands(Loc, LHS, RHS); 9086 } 9087 9088 static bool isScopedEnumerationType(QualType T) { 9089 if (const EnumType *ET = T->getAs<EnumType>()) 9090 return ET->getDecl()->isScoped(); 9091 return false; 9092 } 9093 9094 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9095 SourceLocation Loc, BinaryOperatorKind Opc, 9096 QualType LHSType) { 9097 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9098 // so skip remaining warnings as we don't want to modify values within Sema. 9099 if (S.getLangOpts().OpenCL) 9100 return; 9101 9102 llvm::APSInt Right; 9103 // Check right/shifter operand 9104 if (RHS.get()->isValueDependent() || 9105 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9106 return; 9107 9108 if (Right.isNegative()) { 9109 S.DiagRuntimeBehavior(Loc, RHS.get(), 9110 S.PDiag(diag::warn_shift_negative) 9111 << RHS.get()->getSourceRange()); 9112 return; 9113 } 9114 llvm::APInt LeftBits(Right.getBitWidth(), 9115 S.Context.getTypeSize(LHS.get()->getType())); 9116 if (Right.uge(LeftBits)) { 9117 S.DiagRuntimeBehavior(Loc, RHS.get(), 9118 S.PDiag(diag::warn_shift_gt_typewidth) 9119 << RHS.get()->getSourceRange()); 9120 return; 9121 } 9122 if (Opc != BO_Shl) 9123 return; 9124 9125 // When left shifting an ICE which is signed, we can check for overflow which 9126 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9127 // integers have defined behavior modulo one more than the maximum value 9128 // representable in the result type, so never warn for those. 9129 llvm::APSInt Left; 9130 if (LHS.get()->isValueDependent() || 9131 LHSType->hasUnsignedIntegerRepresentation() || 9132 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9133 return; 9134 9135 // If LHS does not have a signed type and non-negative value 9136 // then, the behavior is undefined. Warn about it. 9137 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9138 S.DiagRuntimeBehavior(Loc, LHS.get(), 9139 S.PDiag(diag::warn_shift_lhs_negative) 9140 << LHS.get()->getSourceRange()); 9141 return; 9142 } 9143 9144 llvm::APInt ResultBits = 9145 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9146 if (LeftBits.uge(ResultBits)) 9147 return; 9148 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9149 Result = Result.shl(Right); 9150 9151 // Print the bit representation of the signed integer as an unsigned 9152 // hexadecimal number. 9153 SmallString<40> HexResult; 9154 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9155 9156 // If we are only missing a sign bit, this is less likely to result in actual 9157 // bugs -- if the result is cast back to an unsigned type, it will have the 9158 // expected value. Thus we place this behind a different warning that can be 9159 // turned off separately if needed. 9160 if (LeftBits == ResultBits - 1) { 9161 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9162 << HexResult << LHSType 9163 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9164 return; 9165 } 9166 9167 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9168 << HexResult.str() << Result.getMinSignedBits() << LHSType 9169 << Left.getBitWidth() << LHS.get()->getSourceRange() 9170 << RHS.get()->getSourceRange(); 9171 } 9172 9173 /// \brief Return the resulting type when a vector is shifted 9174 /// by a scalar or vector shift amount. 9175 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9176 SourceLocation Loc, bool IsCompAssign) { 9177 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9178 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9179 !LHS.get()->getType()->isVectorType()) { 9180 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9181 << RHS.get()->getType() << LHS.get()->getType() 9182 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9183 return QualType(); 9184 } 9185 9186 if (!IsCompAssign) { 9187 LHS = S.UsualUnaryConversions(LHS.get()); 9188 if (LHS.isInvalid()) return QualType(); 9189 } 9190 9191 RHS = S.UsualUnaryConversions(RHS.get()); 9192 if (RHS.isInvalid()) return QualType(); 9193 9194 QualType LHSType = LHS.get()->getType(); 9195 // Note that LHS might be a scalar because the routine calls not only in 9196 // OpenCL case. 9197 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9198 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9199 9200 // Note that RHS might not be a vector. 9201 QualType RHSType = RHS.get()->getType(); 9202 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9203 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9204 9205 // The operands need to be integers. 9206 if (!LHSEleType->isIntegerType()) { 9207 S.Diag(Loc, diag::err_typecheck_expect_int) 9208 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9209 return QualType(); 9210 } 9211 9212 if (!RHSEleType->isIntegerType()) { 9213 S.Diag(Loc, diag::err_typecheck_expect_int) 9214 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9215 return QualType(); 9216 } 9217 9218 if (!LHSVecTy) { 9219 assert(RHSVecTy); 9220 if (IsCompAssign) 9221 return RHSType; 9222 if (LHSEleType != RHSEleType) { 9223 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9224 LHSEleType = RHSEleType; 9225 } 9226 QualType VecTy = 9227 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9228 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9229 LHSType = VecTy; 9230 } else if (RHSVecTy) { 9231 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9232 // are applied component-wise. So if RHS is a vector, then ensure 9233 // that the number of elements is the same as LHS... 9234 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9235 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9236 << LHS.get()->getType() << RHS.get()->getType() 9237 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9238 return QualType(); 9239 } 9240 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9241 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9242 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9243 if (LHSBT != RHSBT && 9244 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9245 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9246 << LHS.get()->getType() << RHS.get()->getType() 9247 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9248 } 9249 } 9250 } else { 9251 // ...else expand RHS to match the number of elements in LHS. 9252 QualType VecTy = 9253 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9254 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9255 } 9256 9257 return LHSType; 9258 } 9259 9260 // C99 6.5.7 9261 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9262 SourceLocation Loc, BinaryOperatorKind Opc, 9263 bool IsCompAssign) { 9264 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9265 9266 // Vector shifts promote their scalar inputs to vector type. 9267 if (LHS.get()->getType()->isVectorType() || 9268 RHS.get()->getType()->isVectorType()) { 9269 if (LangOpts.ZVector) { 9270 // The shift operators for the z vector extensions work basically 9271 // like general shifts, except that neither the LHS nor the RHS is 9272 // allowed to be a "vector bool". 9273 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9274 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9275 return InvalidOperands(Loc, LHS, RHS); 9276 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9277 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9278 return InvalidOperands(Loc, LHS, RHS); 9279 } 9280 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9281 } 9282 9283 // Shifts don't perform usual arithmetic conversions, they just do integer 9284 // promotions on each operand. C99 6.5.7p3 9285 9286 // For the LHS, do usual unary conversions, but then reset them away 9287 // if this is a compound assignment. 9288 ExprResult OldLHS = LHS; 9289 LHS = UsualUnaryConversions(LHS.get()); 9290 if (LHS.isInvalid()) 9291 return QualType(); 9292 QualType LHSType = LHS.get()->getType(); 9293 if (IsCompAssign) LHS = OldLHS; 9294 9295 // The RHS is simpler. 9296 RHS = UsualUnaryConversions(RHS.get()); 9297 if (RHS.isInvalid()) 9298 return QualType(); 9299 QualType RHSType = RHS.get()->getType(); 9300 9301 // C99 6.5.7p2: Each of the operands shall have integer type. 9302 if (!LHSType->hasIntegerRepresentation() || 9303 !RHSType->hasIntegerRepresentation()) 9304 return InvalidOperands(Loc, LHS, RHS); 9305 9306 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9307 // hasIntegerRepresentation() above instead of this. 9308 if (isScopedEnumerationType(LHSType) || 9309 isScopedEnumerationType(RHSType)) { 9310 return InvalidOperands(Loc, LHS, RHS); 9311 } 9312 // Sanity-check shift operands 9313 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9314 9315 // "The type of the result is that of the promoted left operand." 9316 return LHSType; 9317 } 9318 9319 /// If two different enums are compared, raise a warning. 9320 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9321 Expr *RHS) { 9322 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9323 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9324 9325 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9326 if (!LHSEnumType) 9327 return; 9328 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9329 if (!RHSEnumType) 9330 return; 9331 9332 // Ignore anonymous enums. 9333 if (!LHSEnumType->getDecl()->getIdentifier() && 9334 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9335 return; 9336 if (!RHSEnumType->getDecl()->getIdentifier() && 9337 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9338 return; 9339 9340 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9341 return; 9342 9343 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9344 << LHSStrippedType << RHSStrippedType 9345 << LHS->getSourceRange() << RHS->getSourceRange(); 9346 } 9347 9348 /// \brief Diagnose bad pointer comparisons. 9349 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9350 ExprResult &LHS, ExprResult &RHS, 9351 bool IsError) { 9352 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9353 : diag::ext_typecheck_comparison_of_distinct_pointers) 9354 << LHS.get()->getType() << RHS.get()->getType() 9355 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9356 } 9357 9358 /// \brief Returns false if the pointers are converted to a composite type, 9359 /// true otherwise. 9360 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9361 ExprResult &LHS, ExprResult &RHS) { 9362 // C++ [expr.rel]p2: 9363 // [...] Pointer conversions (4.10) and qualification 9364 // conversions (4.4) are performed on pointer operands (or on 9365 // a pointer operand and a null pointer constant) to bring 9366 // them to their composite pointer type. [...] 9367 // 9368 // C++ [expr.eq]p1 uses the same notion for (in)equality 9369 // comparisons of pointers. 9370 9371 QualType LHSType = LHS.get()->getType(); 9372 QualType RHSType = RHS.get()->getType(); 9373 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9374 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9375 9376 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9377 if (T.isNull()) { 9378 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9379 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9380 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9381 else 9382 S.InvalidOperands(Loc, LHS, RHS); 9383 return true; 9384 } 9385 9386 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9387 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9388 return false; 9389 } 9390 9391 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9392 ExprResult &LHS, 9393 ExprResult &RHS, 9394 bool IsError) { 9395 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9396 : diag::ext_typecheck_comparison_of_fptr_to_void) 9397 << LHS.get()->getType() << RHS.get()->getType() 9398 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9399 } 9400 9401 static bool isObjCObjectLiteral(ExprResult &E) { 9402 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9403 case Stmt::ObjCArrayLiteralClass: 9404 case Stmt::ObjCDictionaryLiteralClass: 9405 case Stmt::ObjCStringLiteralClass: 9406 case Stmt::ObjCBoxedExprClass: 9407 return true; 9408 default: 9409 // Note that ObjCBoolLiteral is NOT an object literal! 9410 return false; 9411 } 9412 } 9413 9414 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9415 const ObjCObjectPointerType *Type = 9416 LHS->getType()->getAs<ObjCObjectPointerType>(); 9417 9418 // If this is not actually an Objective-C object, bail out. 9419 if (!Type) 9420 return false; 9421 9422 // Get the LHS object's interface type. 9423 QualType InterfaceType = Type->getPointeeType(); 9424 9425 // If the RHS isn't an Objective-C object, bail out. 9426 if (!RHS->getType()->isObjCObjectPointerType()) 9427 return false; 9428 9429 // Try to find the -isEqual: method. 9430 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9431 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9432 InterfaceType, 9433 /*instance=*/true); 9434 if (!Method) { 9435 if (Type->isObjCIdType()) { 9436 // For 'id', just check the global pool. 9437 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9438 /*receiverId=*/true); 9439 } else { 9440 // Check protocols. 9441 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9442 /*instance=*/true); 9443 } 9444 } 9445 9446 if (!Method) 9447 return false; 9448 9449 QualType T = Method->parameters()[0]->getType(); 9450 if (!T->isObjCObjectPointerType()) 9451 return false; 9452 9453 QualType R = Method->getReturnType(); 9454 if (!R->isScalarType()) 9455 return false; 9456 9457 return true; 9458 } 9459 9460 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9461 FromE = FromE->IgnoreParenImpCasts(); 9462 switch (FromE->getStmtClass()) { 9463 default: 9464 break; 9465 case Stmt::ObjCStringLiteralClass: 9466 // "string literal" 9467 return LK_String; 9468 case Stmt::ObjCArrayLiteralClass: 9469 // "array literal" 9470 return LK_Array; 9471 case Stmt::ObjCDictionaryLiteralClass: 9472 // "dictionary literal" 9473 return LK_Dictionary; 9474 case Stmt::BlockExprClass: 9475 return LK_Block; 9476 case Stmt::ObjCBoxedExprClass: { 9477 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9478 switch (Inner->getStmtClass()) { 9479 case Stmt::IntegerLiteralClass: 9480 case Stmt::FloatingLiteralClass: 9481 case Stmt::CharacterLiteralClass: 9482 case Stmt::ObjCBoolLiteralExprClass: 9483 case Stmt::CXXBoolLiteralExprClass: 9484 // "numeric literal" 9485 return LK_Numeric; 9486 case Stmt::ImplicitCastExprClass: { 9487 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9488 // Boolean literals can be represented by implicit casts. 9489 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9490 return LK_Numeric; 9491 break; 9492 } 9493 default: 9494 break; 9495 } 9496 return LK_Boxed; 9497 } 9498 } 9499 return LK_None; 9500 } 9501 9502 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9503 ExprResult &LHS, ExprResult &RHS, 9504 BinaryOperator::Opcode Opc){ 9505 Expr *Literal; 9506 Expr *Other; 9507 if (isObjCObjectLiteral(LHS)) { 9508 Literal = LHS.get(); 9509 Other = RHS.get(); 9510 } else { 9511 Literal = RHS.get(); 9512 Other = LHS.get(); 9513 } 9514 9515 // Don't warn on comparisons against nil. 9516 Other = Other->IgnoreParenCasts(); 9517 if (Other->isNullPointerConstant(S.getASTContext(), 9518 Expr::NPC_ValueDependentIsNotNull)) 9519 return; 9520 9521 // This should be kept in sync with warn_objc_literal_comparison. 9522 // LK_String should always be after the other literals, since it has its own 9523 // warning flag. 9524 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9525 assert(LiteralKind != Sema::LK_Block); 9526 if (LiteralKind == Sema::LK_None) { 9527 llvm_unreachable("Unknown Objective-C object literal kind"); 9528 } 9529 9530 if (LiteralKind == Sema::LK_String) 9531 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9532 << Literal->getSourceRange(); 9533 else 9534 S.Diag(Loc, diag::warn_objc_literal_comparison) 9535 << LiteralKind << Literal->getSourceRange(); 9536 9537 if (BinaryOperator::isEqualityOp(Opc) && 9538 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9539 SourceLocation Start = LHS.get()->getLocStart(); 9540 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 9541 CharSourceRange OpRange = 9542 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9543 9544 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9545 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9546 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9547 << FixItHint::CreateInsertion(End, "]"); 9548 } 9549 } 9550 9551 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9552 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9553 ExprResult &RHS, SourceLocation Loc, 9554 BinaryOperatorKind Opc) { 9555 // Check that left hand side is !something. 9556 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9557 if (!UO || UO->getOpcode() != UO_LNot) return; 9558 9559 // Only check if the right hand side is non-bool arithmetic type. 9560 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9561 9562 // Make sure that the something in !something is not bool. 9563 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9564 if (SubExpr->isKnownToHaveBooleanValue()) return; 9565 9566 // Emit warning. 9567 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9568 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9569 << Loc << IsBitwiseOp; 9570 9571 // First note suggest !(x < y) 9572 SourceLocation FirstOpen = SubExpr->getLocStart(); 9573 SourceLocation FirstClose = RHS.get()->getLocEnd(); 9574 FirstClose = S.getLocForEndOfToken(FirstClose); 9575 if (FirstClose.isInvalid()) 9576 FirstOpen = SourceLocation(); 9577 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9578 << IsBitwiseOp 9579 << FixItHint::CreateInsertion(FirstOpen, "(") 9580 << FixItHint::CreateInsertion(FirstClose, ")"); 9581 9582 // Second note suggests (!x) < y 9583 SourceLocation SecondOpen = LHS.get()->getLocStart(); 9584 SourceLocation SecondClose = LHS.get()->getLocEnd(); 9585 SecondClose = S.getLocForEndOfToken(SecondClose); 9586 if (SecondClose.isInvalid()) 9587 SecondOpen = SourceLocation(); 9588 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9589 << FixItHint::CreateInsertion(SecondOpen, "(") 9590 << FixItHint::CreateInsertion(SecondClose, ")"); 9591 } 9592 9593 // Get the decl for a simple expression: a reference to a variable, 9594 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9595 static ValueDecl *getCompareDecl(Expr *E) { 9596 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9597 return DR->getDecl(); 9598 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9599 if (Ivar->isFreeIvar()) 9600 return Ivar->getDecl(); 9601 } 9602 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9603 if (Mem->isImplicitAccess()) 9604 return Mem->getMemberDecl(); 9605 } 9606 return nullptr; 9607 } 9608 9609 /// Diagnose some forms of syntactically-obvious tautological comparison. 9610 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9611 Expr *LHS, Expr *RHS, 9612 BinaryOperatorKind Opc) { 9613 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9614 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9615 9616 QualType LHSType = LHS->getType(); 9617 if (LHSType->hasFloatingRepresentation() || 9618 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9619 LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() || 9620 S.inTemplateInstantiation()) 9621 return; 9622 9623 // For non-floating point types, check for self-comparisons of the form 9624 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9625 // often indicate logic errors in the program. 9626 // 9627 // NOTE: Don't warn about comparison expressions resulting from macro 9628 // expansion. Also don't warn about comparisons which are only self 9629 // comparisons within a template instantiation. The warnings should catch 9630 // obvious cases in the definition of the template anyways. The idea is to 9631 // warn when the typed comparison operator will always evaluate to the same 9632 // result. 9633 ValueDecl *DL = getCompareDecl(LHSStripped); 9634 ValueDecl *DR = getCompareDecl(RHSStripped); 9635 if (DL && DR && declaresSameEntity(DL, DR)) { 9636 StringRef Result; 9637 switch (Opc) { 9638 case BO_EQ: case BO_LE: case BO_GE: 9639 Result = "true"; 9640 break; 9641 case BO_NE: case BO_LT: case BO_GT: 9642 Result = "false"; 9643 break; 9644 case BO_Cmp: 9645 Result = "'std::strong_ordering::equal'"; 9646 break; 9647 default: 9648 break; 9649 } 9650 S.DiagRuntimeBehavior(Loc, nullptr, 9651 S.PDiag(diag::warn_comparison_always) 9652 << 0 /*self-comparison*/ << !Result.empty() 9653 << Result); 9654 } else if (DL && DR && 9655 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9656 !DL->isWeak() && !DR->isWeak()) { 9657 // What is it always going to evaluate to? 9658 StringRef Result; 9659 switch(Opc) { 9660 case BO_EQ: // e.g. array1 == array2 9661 Result = "false"; 9662 break; 9663 case BO_NE: // e.g. array1 != array2 9664 Result = "true"; 9665 break; 9666 default: // e.g. array1 <= array2 9667 // The best we can say is 'a constant' 9668 break; 9669 } 9670 S.DiagRuntimeBehavior(Loc, nullptr, 9671 S.PDiag(diag::warn_comparison_always) 9672 << 1 /*array comparison*/ 9673 << !Result.empty() << Result); 9674 } 9675 9676 if (isa<CastExpr>(LHSStripped)) 9677 LHSStripped = LHSStripped->IgnoreParenCasts(); 9678 if (isa<CastExpr>(RHSStripped)) 9679 RHSStripped = RHSStripped->IgnoreParenCasts(); 9680 9681 // Warn about comparisons against a string constant (unless the other 9682 // operand is null); the user probably wants strcmp. 9683 Expr *LiteralString = nullptr; 9684 Expr *LiteralStringStripped = nullptr; 9685 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9686 !RHSStripped->isNullPointerConstant(S.Context, 9687 Expr::NPC_ValueDependentIsNull)) { 9688 LiteralString = LHS; 9689 LiteralStringStripped = LHSStripped; 9690 } else if ((isa<StringLiteral>(RHSStripped) || 9691 isa<ObjCEncodeExpr>(RHSStripped)) && 9692 !LHSStripped->isNullPointerConstant(S.Context, 9693 Expr::NPC_ValueDependentIsNull)) { 9694 LiteralString = RHS; 9695 LiteralStringStripped = RHSStripped; 9696 } 9697 9698 if (LiteralString) { 9699 S.DiagRuntimeBehavior(Loc, nullptr, 9700 S.PDiag(diag::warn_stringcompare) 9701 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9702 << LiteralString->getSourceRange()); 9703 } 9704 } 9705 9706 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9707 ExprResult &RHS, 9708 SourceLocation Loc, 9709 BinaryOperatorKind Opc) { 9710 // C99 6.5.8p3 / C99 6.5.9p4 9711 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9712 if (LHS.isInvalid() || RHS.isInvalid()) 9713 return QualType(); 9714 if (Type.isNull()) 9715 return S.InvalidOperands(Loc, LHS, RHS); 9716 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9717 9718 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9719 9720 enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering; 9721 if (Type->isAnyComplexType()) 9722 Ordering = StrongEquality; 9723 else if (Type->isFloatingType()) 9724 Ordering = PartialOrdering; 9725 else 9726 Ordering = StrongOrdering; 9727 9728 if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc)) 9729 return S.InvalidOperands(Loc, LHS, RHS); 9730 9731 // Check for comparisons of floating point operands using != and ==. 9732 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 9733 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9734 9735 // The result of comparisons is 'bool' in C++, 'int' in C. 9736 // FIXME: For BO_Cmp, return the relevant comparison category type. 9737 return S.Context.getLogicalOperationType(); 9738 } 9739 9740 // C99 6.5.8, C++ [expr.rel] 9741 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 9742 SourceLocation Loc, BinaryOperatorKind Opc, 9743 bool IsRelational) { 9744 // Comparisons expect an rvalue, so convert to rvalue before any 9745 // type-related checks. 9746 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9747 if (LHS.isInvalid()) 9748 return QualType(); 9749 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9750 if (RHS.isInvalid()) 9751 return QualType(); 9752 9753 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 9754 9755 // Handle vector comparisons separately. 9756 if (LHS.get()->getType()->isVectorType() || 9757 RHS.get()->getType()->isVectorType()) 9758 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 9759 9760 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 9761 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 9762 9763 QualType LHSType = LHS.get()->getType(); 9764 QualType RHSType = RHS.get()->getType(); 9765 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 9766 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 9767 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 9768 9769 QualType ResultTy = Context.getLogicalOperationType(); 9770 9771 const Expr::NullPointerConstantKind LHSNullKind = 9772 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9773 const Expr::NullPointerConstantKind RHSNullKind = 9774 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 9775 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 9776 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 9777 9778 if (!IsRelational && LHSIsNull != RHSIsNull) { 9779 bool IsEquality = Opc == BO_EQ; 9780 if (RHSIsNull) 9781 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 9782 RHS.get()->getSourceRange()); 9783 else 9784 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 9785 LHS.get()->getSourceRange()); 9786 } 9787 9788 if ((LHSType->isIntegerType() && !LHSIsNull) || 9789 (RHSType->isIntegerType() && !RHSIsNull)) { 9790 // Skip normal pointer conversion checks in this case; we have better 9791 // diagnostics for this below. 9792 } else if (getLangOpts().CPlusPlus) { 9793 // Equality comparison of a function pointer to a void pointer is invalid, 9794 // but we allow it as an extension. 9795 // FIXME: If we really want to allow this, should it be part of composite 9796 // pointer type computation so it works in conditionals too? 9797 if (!IsRelational && 9798 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 9799 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 9800 // This is a gcc extension compatibility comparison. 9801 // In a SFINAE context, we treat this as a hard error to maintain 9802 // conformance with the C++ standard. 9803 diagnoseFunctionPointerToVoidComparison( 9804 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 9805 9806 if (isSFINAEContext()) 9807 return QualType(); 9808 9809 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9810 return ResultTy; 9811 } 9812 9813 // C++ [expr.eq]p2: 9814 // If at least one operand is a pointer [...] bring them to their 9815 // composite pointer type. 9816 // C++ [expr.rel]p2: 9817 // If both operands are pointers, [...] bring them to their composite 9818 // pointer type. 9819 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 9820 (IsRelational ? 2 : 1) && 9821 (!LangOpts.ObjCAutoRefCount || 9822 !(LHSType->isObjCObjectPointerType() || 9823 RHSType->isObjCObjectPointerType()))) { 9824 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9825 return QualType(); 9826 else 9827 return ResultTy; 9828 } 9829 } else if (LHSType->isPointerType() && 9830 RHSType->isPointerType()) { // C99 6.5.8p2 9831 // All of the following pointer-related warnings are GCC extensions, except 9832 // when handling null pointer constants. 9833 QualType LCanPointeeTy = 9834 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9835 QualType RCanPointeeTy = 9836 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 9837 9838 // C99 6.5.9p2 and C99 6.5.8p2 9839 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 9840 RCanPointeeTy.getUnqualifiedType())) { 9841 // Valid unless a relational comparison of function pointers 9842 if (IsRelational && LCanPointeeTy->isFunctionType()) { 9843 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 9844 << LHSType << RHSType << LHS.get()->getSourceRange() 9845 << RHS.get()->getSourceRange(); 9846 } 9847 } else if (!IsRelational && 9848 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 9849 // Valid unless comparison between non-null pointer and function pointer 9850 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 9851 && !LHSIsNull && !RHSIsNull) 9852 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 9853 /*isError*/false); 9854 } else { 9855 // Invalid 9856 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 9857 } 9858 if (LCanPointeeTy != RCanPointeeTy) { 9859 // Treat NULL constant as a special case in OpenCL. 9860 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 9861 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 9862 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 9863 Diag(Loc, 9864 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9865 << LHSType << RHSType << 0 /* comparison */ 9866 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9867 } 9868 } 9869 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9870 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9871 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9872 : CK_BitCast; 9873 if (LHSIsNull && !RHSIsNull) 9874 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9875 else 9876 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9877 } 9878 return ResultTy; 9879 } 9880 9881 if (getLangOpts().CPlusPlus) { 9882 // C++ [expr.eq]p4: 9883 // Two operands of type std::nullptr_t or one operand of type 9884 // std::nullptr_t and the other a null pointer constant compare equal. 9885 if (!IsRelational && LHSIsNull && RHSIsNull) { 9886 if (LHSType->isNullPtrType()) { 9887 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9888 return ResultTy; 9889 } 9890 if (RHSType->isNullPtrType()) { 9891 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9892 return ResultTy; 9893 } 9894 } 9895 9896 // Comparison of Objective-C pointers and block pointers against nullptr_t. 9897 // These aren't covered by the composite pointer type rules. 9898 if (!IsRelational && RHSType->isNullPtrType() && 9899 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 9900 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9901 return ResultTy; 9902 } 9903 if (!IsRelational && LHSType->isNullPtrType() && 9904 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 9905 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9906 return ResultTy; 9907 } 9908 9909 if (IsRelational && 9910 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 9911 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 9912 // HACK: Relational comparison of nullptr_t against a pointer type is 9913 // invalid per DR583, but we allow it within std::less<> and friends, 9914 // since otherwise common uses of it break. 9915 // FIXME: Consider removing this hack once LWG fixes std::less<> and 9916 // friends to have std::nullptr_t overload candidates. 9917 DeclContext *DC = CurContext; 9918 if (isa<FunctionDecl>(DC)) 9919 DC = DC->getParent(); 9920 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 9921 if (CTSD->isInStdNamespace() && 9922 llvm::StringSwitch<bool>(CTSD->getName()) 9923 .Cases("less", "less_equal", "greater", "greater_equal", true) 9924 .Default(false)) { 9925 if (RHSType->isNullPtrType()) 9926 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9927 else 9928 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9929 return ResultTy; 9930 } 9931 } 9932 } 9933 9934 // C++ [expr.eq]p2: 9935 // If at least one operand is a pointer to member, [...] bring them to 9936 // their composite pointer type. 9937 if (!IsRelational && 9938 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 9939 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9940 return QualType(); 9941 else 9942 return ResultTy; 9943 } 9944 } 9945 9946 // Handle block pointer types. 9947 if (!IsRelational && LHSType->isBlockPointerType() && 9948 RHSType->isBlockPointerType()) { 9949 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9950 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9951 9952 if (!LHSIsNull && !RHSIsNull && 9953 !Context.typesAreCompatible(lpointee, rpointee)) { 9954 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9955 << LHSType << RHSType << LHS.get()->getSourceRange() 9956 << RHS.get()->getSourceRange(); 9957 } 9958 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9959 return ResultTy; 9960 } 9961 9962 // Allow block pointers to be compared with null pointer constants. 9963 if (!IsRelational 9964 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9965 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9966 if (!LHSIsNull && !RHSIsNull) { 9967 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9968 ->getPointeeType()->isVoidType()) 9969 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9970 ->getPointeeType()->isVoidType()))) 9971 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9972 << LHSType << RHSType << LHS.get()->getSourceRange() 9973 << RHS.get()->getSourceRange(); 9974 } 9975 if (LHSIsNull && !RHSIsNull) 9976 LHS = ImpCastExprToType(LHS.get(), RHSType, 9977 RHSType->isPointerType() ? CK_BitCast 9978 : CK_AnyPointerToBlockPointerCast); 9979 else 9980 RHS = ImpCastExprToType(RHS.get(), LHSType, 9981 LHSType->isPointerType() ? CK_BitCast 9982 : CK_AnyPointerToBlockPointerCast); 9983 return ResultTy; 9984 } 9985 9986 if (LHSType->isObjCObjectPointerType() || 9987 RHSType->isObjCObjectPointerType()) { 9988 const PointerType *LPT = LHSType->getAs<PointerType>(); 9989 const PointerType *RPT = RHSType->getAs<PointerType>(); 9990 if (LPT || RPT) { 9991 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9992 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9993 9994 if (!LPtrToVoid && !RPtrToVoid && 9995 !Context.typesAreCompatible(LHSType, RHSType)) { 9996 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9997 /*isError*/false); 9998 } 9999 if (LHSIsNull && !RHSIsNull) { 10000 Expr *E = LHS.get(); 10001 if (getLangOpts().ObjCAutoRefCount) 10002 CheckObjCConversion(SourceRange(), RHSType, E, 10003 CCK_ImplicitConversion); 10004 LHS = ImpCastExprToType(E, RHSType, 10005 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10006 } 10007 else { 10008 Expr *E = RHS.get(); 10009 if (getLangOpts().ObjCAutoRefCount) 10010 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10011 /*Diagnose=*/true, 10012 /*DiagnoseCFAudited=*/false, Opc); 10013 RHS = ImpCastExprToType(E, LHSType, 10014 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10015 } 10016 return ResultTy; 10017 } 10018 if (LHSType->isObjCObjectPointerType() && 10019 RHSType->isObjCObjectPointerType()) { 10020 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10021 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10022 /*isError*/false); 10023 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10024 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10025 10026 if (LHSIsNull && !RHSIsNull) 10027 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10028 else 10029 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10030 return ResultTy; 10031 } 10032 } 10033 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10034 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10035 unsigned DiagID = 0; 10036 bool isError = false; 10037 if (LangOpts.DebuggerSupport) { 10038 // Under a debugger, allow the comparison of pointers to integers, 10039 // since users tend to want to compare addresses. 10040 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10041 (RHSIsNull && RHSType->isIntegerType())) { 10042 if (IsRelational) { 10043 isError = getLangOpts().CPlusPlus; 10044 DiagID = 10045 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10046 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10047 } 10048 } else if (getLangOpts().CPlusPlus) { 10049 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10050 isError = true; 10051 } else if (IsRelational) 10052 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10053 else 10054 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10055 10056 if (DiagID) { 10057 Diag(Loc, DiagID) 10058 << LHSType << RHSType << LHS.get()->getSourceRange() 10059 << RHS.get()->getSourceRange(); 10060 if (isError) 10061 return QualType(); 10062 } 10063 10064 if (LHSType->isIntegerType()) 10065 LHS = ImpCastExprToType(LHS.get(), RHSType, 10066 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10067 else 10068 RHS = ImpCastExprToType(RHS.get(), LHSType, 10069 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10070 return ResultTy; 10071 } 10072 10073 // Handle block pointers. 10074 if (!IsRelational && RHSIsNull 10075 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10076 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10077 return ResultTy; 10078 } 10079 if (!IsRelational && LHSIsNull 10080 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10081 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10082 return ResultTy; 10083 } 10084 10085 if (getLangOpts().OpenCLVersion >= 200) { 10086 if (LHSIsNull && RHSType->isQueueT()) { 10087 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10088 return ResultTy; 10089 } 10090 10091 if (LHSType->isQueueT() && RHSIsNull) { 10092 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10093 return ResultTy; 10094 } 10095 } 10096 10097 return InvalidOperands(Loc, LHS, RHS); 10098 } 10099 10100 // Return a signed ext_vector_type that is of identical size and number of 10101 // elements. For floating point vectors, return an integer type of identical 10102 // size and number of elements. In the non ext_vector_type case, search from 10103 // the largest type to the smallest type to avoid cases where long long == long, 10104 // where long gets picked over long long. 10105 QualType Sema::GetSignedVectorType(QualType V) { 10106 const VectorType *VTy = V->getAs<VectorType>(); 10107 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10108 10109 if (isa<ExtVectorType>(VTy)) { 10110 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10111 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10112 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10113 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10114 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10115 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10116 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10117 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10118 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10119 "Unhandled vector element size in vector compare"); 10120 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10121 } 10122 10123 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10124 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10125 VectorType::GenericVector); 10126 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10127 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10128 VectorType::GenericVector); 10129 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10130 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10131 VectorType::GenericVector); 10132 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10133 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10134 VectorType::GenericVector); 10135 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10136 "Unhandled vector element size in vector compare"); 10137 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10138 VectorType::GenericVector); 10139 } 10140 10141 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10142 /// operates on extended vector types. Instead of producing an IntTy result, 10143 /// like a scalar comparison, a vector comparison produces a vector of integer 10144 /// types. 10145 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10146 SourceLocation Loc, 10147 BinaryOperatorKind Opc) { 10148 // Check to make sure we're operating on vectors of the same type and width, 10149 // Allowing one side to be a scalar of element type. 10150 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10151 /*AllowBothBool*/true, 10152 /*AllowBoolConversions*/getLangOpts().ZVector); 10153 if (vType.isNull()) 10154 return vType; 10155 10156 QualType LHSType = LHS.get()->getType(); 10157 10158 // If AltiVec, the comparison results in a numeric type, i.e. 10159 // bool for C++, int for C 10160 if (getLangOpts().AltiVec && 10161 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10162 return Context.getLogicalOperationType(); 10163 10164 // For non-floating point types, check for self-comparisons of the form 10165 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10166 // often indicate logic errors in the program. 10167 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10168 10169 // Check for comparisons of floating point operands using != and ==. 10170 if (BinaryOperator::isEqualityOp(Opc) && 10171 LHSType->hasFloatingRepresentation()) { 10172 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10173 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10174 } 10175 10176 // Return a signed type for the vector. 10177 return GetSignedVectorType(vType); 10178 } 10179 10180 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10181 SourceLocation Loc) { 10182 // Ensure that either both operands are of the same vector type, or 10183 // one operand is of a vector type and the other is of its element type. 10184 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10185 /*AllowBothBool*/true, 10186 /*AllowBoolConversions*/false); 10187 if (vType.isNull()) 10188 return InvalidOperands(Loc, LHS, RHS); 10189 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10190 vType->hasFloatingRepresentation()) 10191 return InvalidOperands(Loc, LHS, RHS); 10192 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10193 // usage of the logical operators && and || with vectors in C. This 10194 // check could be notionally dropped. 10195 if (!getLangOpts().CPlusPlus && 10196 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10197 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10198 10199 return GetSignedVectorType(LHS.get()->getType()); 10200 } 10201 10202 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10203 SourceLocation Loc, 10204 BinaryOperatorKind Opc) { 10205 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10206 10207 bool IsCompAssign = 10208 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10209 10210 if (LHS.get()->getType()->isVectorType() || 10211 RHS.get()->getType()->isVectorType()) { 10212 if (LHS.get()->getType()->hasIntegerRepresentation() && 10213 RHS.get()->getType()->hasIntegerRepresentation()) 10214 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10215 /*AllowBothBool*/true, 10216 /*AllowBoolConversions*/getLangOpts().ZVector); 10217 return InvalidOperands(Loc, LHS, RHS); 10218 } 10219 10220 if (Opc == BO_And) 10221 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10222 10223 ExprResult LHSResult = LHS, RHSResult = RHS; 10224 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10225 IsCompAssign); 10226 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10227 return QualType(); 10228 LHS = LHSResult.get(); 10229 RHS = RHSResult.get(); 10230 10231 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10232 return compType; 10233 return InvalidOperands(Loc, LHS, RHS); 10234 } 10235 10236 // C99 6.5.[13,14] 10237 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10238 SourceLocation Loc, 10239 BinaryOperatorKind Opc) { 10240 // Check vector operands differently. 10241 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10242 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10243 10244 // Diagnose cases where the user write a logical and/or but probably meant a 10245 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10246 // is a constant. 10247 if (LHS.get()->getType()->isIntegerType() && 10248 !LHS.get()->getType()->isBooleanType() && 10249 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10250 // Don't warn in macros or template instantiations. 10251 !Loc.isMacroID() && !inTemplateInstantiation()) { 10252 // If the RHS can be constant folded, and if it constant folds to something 10253 // that isn't 0 or 1 (which indicate a potential logical operation that 10254 // happened to fold to true/false) then warn. 10255 // Parens on the RHS are ignored. 10256 llvm::APSInt Result; 10257 if (RHS.get()->EvaluateAsInt(Result, Context)) 10258 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10259 !RHS.get()->getExprLoc().isMacroID()) || 10260 (Result != 0 && Result != 1)) { 10261 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10262 << RHS.get()->getSourceRange() 10263 << (Opc == BO_LAnd ? "&&" : "||"); 10264 // Suggest replacing the logical operator with the bitwise version 10265 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10266 << (Opc == BO_LAnd ? "&" : "|") 10267 << FixItHint::CreateReplacement(SourceRange( 10268 Loc, getLocForEndOfToken(Loc)), 10269 Opc == BO_LAnd ? "&" : "|"); 10270 if (Opc == BO_LAnd) 10271 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10272 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10273 << FixItHint::CreateRemoval( 10274 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 10275 RHS.get()->getLocEnd())); 10276 } 10277 } 10278 10279 if (!Context.getLangOpts().CPlusPlus) { 10280 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10281 // not operate on the built-in scalar and vector float types. 10282 if (Context.getLangOpts().OpenCL && 10283 Context.getLangOpts().OpenCLVersion < 120) { 10284 if (LHS.get()->getType()->isFloatingType() || 10285 RHS.get()->getType()->isFloatingType()) 10286 return InvalidOperands(Loc, LHS, RHS); 10287 } 10288 10289 LHS = UsualUnaryConversions(LHS.get()); 10290 if (LHS.isInvalid()) 10291 return QualType(); 10292 10293 RHS = UsualUnaryConversions(RHS.get()); 10294 if (RHS.isInvalid()) 10295 return QualType(); 10296 10297 if (!LHS.get()->getType()->isScalarType() || 10298 !RHS.get()->getType()->isScalarType()) 10299 return InvalidOperands(Loc, LHS, RHS); 10300 10301 return Context.IntTy; 10302 } 10303 10304 // The following is safe because we only use this method for 10305 // non-overloadable operands. 10306 10307 // C++ [expr.log.and]p1 10308 // C++ [expr.log.or]p1 10309 // The operands are both contextually converted to type bool. 10310 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10311 if (LHSRes.isInvalid()) 10312 return InvalidOperands(Loc, LHS, RHS); 10313 LHS = LHSRes; 10314 10315 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10316 if (RHSRes.isInvalid()) 10317 return InvalidOperands(Loc, LHS, RHS); 10318 RHS = RHSRes; 10319 10320 // C++ [expr.log.and]p2 10321 // C++ [expr.log.or]p2 10322 // The result is a bool. 10323 return Context.BoolTy; 10324 } 10325 10326 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10327 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10328 if (!ME) return false; 10329 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10330 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10331 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10332 if (!Base) return false; 10333 return Base->getMethodDecl() != nullptr; 10334 } 10335 10336 /// Is the given expression (which must be 'const') a reference to a 10337 /// variable which was originally non-const, but which has become 10338 /// 'const' due to being captured within a block? 10339 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10340 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10341 assert(E->isLValue() && E->getType().isConstQualified()); 10342 E = E->IgnoreParens(); 10343 10344 // Must be a reference to a declaration from an enclosing scope. 10345 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10346 if (!DRE) return NCCK_None; 10347 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10348 10349 // The declaration must be a variable which is not declared 'const'. 10350 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10351 if (!var) return NCCK_None; 10352 if (var->getType().isConstQualified()) return NCCK_None; 10353 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10354 10355 // Decide whether the first capture was for a block or a lambda. 10356 DeclContext *DC = S.CurContext, *Prev = nullptr; 10357 // Decide whether the first capture was for a block or a lambda. 10358 while (DC) { 10359 // For init-capture, it is possible that the variable belongs to the 10360 // template pattern of the current context. 10361 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10362 if (var->isInitCapture() && 10363 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10364 break; 10365 if (DC == var->getDeclContext()) 10366 break; 10367 Prev = DC; 10368 DC = DC->getParent(); 10369 } 10370 // Unless we have an init-capture, we've gone one step too far. 10371 if (!var->isInitCapture()) 10372 DC = Prev; 10373 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10374 } 10375 10376 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10377 Ty = Ty.getNonReferenceType(); 10378 if (IsDereference && Ty->isPointerType()) 10379 Ty = Ty->getPointeeType(); 10380 return !Ty.isConstQualified(); 10381 } 10382 10383 // Update err_typecheck_assign_const and note_typecheck_assign_const 10384 // when this enum is changed. 10385 enum { 10386 ConstFunction, 10387 ConstVariable, 10388 ConstMember, 10389 ConstMethod, 10390 NestedConstMember, 10391 ConstUnknown, // Keep as last element 10392 }; 10393 10394 /// Emit the "read-only variable not assignable" error and print notes to give 10395 /// more information about why the variable is not assignable, such as pointing 10396 /// to the declaration of a const variable, showing that a method is const, or 10397 /// that the function is returning a const reference. 10398 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10399 SourceLocation Loc) { 10400 SourceRange ExprRange = E->getSourceRange(); 10401 10402 // Only emit one error on the first const found. All other consts will emit 10403 // a note to the error. 10404 bool DiagnosticEmitted = false; 10405 10406 // Track if the current expression is the result of a dereference, and if the 10407 // next checked expression is the result of a dereference. 10408 bool IsDereference = false; 10409 bool NextIsDereference = false; 10410 10411 // Loop to process MemberExpr chains. 10412 while (true) { 10413 IsDereference = NextIsDereference; 10414 10415 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10416 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10417 NextIsDereference = ME->isArrow(); 10418 const ValueDecl *VD = ME->getMemberDecl(); 10419 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10420 // Mutable fields can be modified even if the class is const. 10421 if (Field->isMutable()) { 10422 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10423 break; 10424 } 10425 10426 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10427 if (!DiagnosticEmitted) { 10428 S.Diag(Loc, diag::err_typecheck_assign_const) 10429 << ExprRange << ConstMember << false /*static*/ << Field 10430 << Field->getType(); 10431 DiagnosticEmitted = true; 10432 } 10433 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10434 << ConstMember << false /*static*/ << Field << Field->getType() 10435 << Field->getSourceRange(); 10436 } 10437 E = ME->getBase(); 10438 continue; 10439 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10440 if (VDecl->getType().isConstQualified()) { 10441 if (!DiagnosticEmitted) { 10442 S.Diag(Loc, diag::err_typecheck_assign_const) 10443 << ExprRange << ConstMember << true /*static*/ << VDecl 10444 << VDecl->getType(); 10445 DiagnosticEmitted = true; 10446 } 10447 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10448 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10449 << VDecl->getSourceRange(); 10450 } 10451 // Static fields do not inherit constness from parents. 10452 break; 10453 } 10454 break; // End MemberExpr 10455 } else if (const ArraySubscriptExpr *ASE = 10456 dyn_cast<ArraySubscriptExpr>(E)) { 10457 E = ASE->getBase()->IgnoreParenImpCasts(); 10458 continue; 10459 } else if (const ExtVectorElementExpr *EVE = 10460 dyn_cast<ExtVectorElementExpr>(E)) { 10461 E = EVE->getBase()->IgnoreParenImpCasts(); 10462 continue; 10463 } 10464 break; 10465 } 10466 10467 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10468 // Function calls 10469 const FunctionDecl *FD = CE->getDirectCallee(); 10470 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10471 if (!DiagnosticEmitted) { 10472 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10473 << ConstFunction << FD; 10474 DiagnosticEmitted = true; 10475 } 10476 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10477 diag::note_typecheck_assign_const) 10478 << ConstFunction << FD << FD->getReturnType() 10479 << FD->getReturnTypeSourceRange(); 10480 } 10481 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10482 // Point to variable declaration. 10483 if (const ValueDecl *VD = DRE->getDecl()) { 10484 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10485 if (!DiagnosticEmitted) { 10486 S.Diag(Loc, diag::err_typecheck_assign_const) 10487 << ExprRange << ConstVariable << VD << VD->getType(); 10488 DiagnosticEmitted = true; 10489 } 10490 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10491 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10492 } 10493 } 10494 } else if (isa<CXXThisExpr>(E)) { 10495 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10496 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10497 if (MD->isConst()) { 10498 if (!DiagnosticEmitted) { 10499 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10500 << ConstMethod << MD; 10501 DiagnosticEmitted = true; 10502 } 10503 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10504 << ConstMethod << MD << MD->getSourceRange(); 10505 } 10506 } 10507 } 10508 } 10509 10510 if (DiagnosticEmitted) 10511 return; 10512 10513 // Can't determine a more specific message, so display the generic error. 10514 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10515 } 10516 10517 enum OriginalExprKind { 10518 OEK_Variable, 10519 OEK_Member, 10520 OEK_LValue 10521 }; 10522 10523 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10524 const RecordType *Ty, 10525 SourceLocation Loc, SourceRange Range, 10526 OriginalExprKind OEK, 10527 bool &DiagnosticEmitted, 10528 bool IsNested = false) { 10529 // We walk the record hierarchy breadth-first to ensure that we print 10530 // diagnostics in field nesting order. 10531 // First, check every field for constness. 10532 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10533 if (Field->getType().isConstQualified()) { 10534 if (!DiagnosticEmitted) { 10535 S.Diag(Loc, diag::err_typecheck_assign_const) 10536 << Range << NestedConstMember << OEK << VD 10537 << IsNested << Field; 10538 DiagnosticEmitted = true; 10539 } 10540 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10541 << NestedConstMember << IsNested << Field 10542 << Field->getType() << Field->getSourceRange(); 10543 } 10544 } 10545 // Then, recurse. 10546 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10547 QualType FTy = Field->getType(); 10548 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10549 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10550 OEK, DiagnosticEmitted, true); 10551 } 10552 } 10553 10554 /// Emit an error for the case where a record we are trying to assign to has a 10555 /// const-qualified field somewhere in its hierarchy. 10556 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10557 SourceLocation Loc) { 10558 QualType Ty = E->getType(); 10559 assert(Ty->isRecordType() && "lvalue was not record?"); 10560 SourceRange Range = E->getSourceRange(); 10561 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10562 bool DiagEmitted = false; 10563 10564 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10565 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10566 Range, OEK_Member, DiagEmitted); 10567 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10568 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10569 Range, OEK_Variable, DiagEmitted); 10570 else 10571 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10572 Range, OEK_LValue, DiagEmitted); 10573 if (!DiagEmitted) 10574 DiagnoseConstAssignment(S, E, Loc); 10575 } 10576 10577 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10578 /// emit an error and return true. If so, return false. 10579 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10580 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10581 10582 S.CheckShadowingDeclModification(E, Loc); 10583 10584 SourceLocation OrigLoc = Loc; 10585 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10586 &Loc); 10587 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10588 IsLV = Expr::MLV_InvalidMessageExpression; 10589 if (IsLV == Expr::MLV_Valid) 10590 return false; 10591 10592 unsigned DiagID = 0; 10593 bool NeedType = false; 10594 switch (IsLV) { // C99 6.5.16p2 10595 case Expr::MLV_ConstQualified: 10596 // Use a specialized diagnostic when we're assigning to an object 10597 // from an enclosing function or block. 10598 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10599 if (NCCK == NCCK_Block) 10600 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10601 else 10602 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10603 break; 10604 } 10605 10606 // In ARC, use some specialized diagnostics for occasions where we 10607 // infer 'const'. These are always pseudo-strong variables. 10608 if (S.getLangOpts().ObjCAutoRefCount) { 10609 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10610 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10611 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10612 10613 // Use the normal diagnostic if it's pseudo-__strong but the 10614 // user actually wrote 'const'. 10615 if (var->isARCPseudoStrong() && 10616 (!var->getTypeSourceInfo() || 10617 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10618 // There are two pseudo-strong cases: 10619 // - self 10620 ObjCMethodDecl *method = S.getCurMethodDecl(); 10621 if (method && var == method->getSelfDecl()) 10622 DiagID = method->isClassMethod() 10623 ? diag::err_typecheck_arc_assign_self_class_method 10624 : diag::err_typecheck_arc_assign_self; 10625 10626 // - fast enumeration variables 10627 else 10628 DiagID = diag::err_typecheck_arr_assign_enumeration; 10629 10630 SourceRange Assign; 10631 if (Loc != OrigLoc) 10632 Assign = SourceRange(OrigLoc, OrigLoc); 10633 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10634 // We need to preserve the AST regardless, so migration tool 10635 // can do its job. 10636 return false; 10637 } 10638 } 10639 } 10640 10641 // If none of the special cases above are triggered, then this is a 10642 // simple const assignment. 10643 if (DiagID == 0) { 10644 DiagnoseConstAssignment(S, E, Loc); 10645 return true; 10646 } 10647 10648 break; 10649 case Expr::MLV_ConstAddrSpace: 10650 DiagnoseConstAssignment(S, E, Loc); 10651 return true; 10652 case Expr::MLV_ConstQualifiedField: 10653 DiagnoseRecursiveConstFields(S, E, Loc); 10654 return true; 10655 case Expr::MLV_ArrayType: 10656 case Expr::MLV_ArrayTemporary: 10657 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10658 NeedType = true; 10659 break; 10660 case Expr::MLV_NotObjectType: 10661 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 10662 NeedType = true; 10663 break; 10664 case Expr::MLV_LValueCast: 10665 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 10666 break; 10667 case Expr::MLV_Valid: 10668 llvm_unreachable("did not take early return for MLV_Valid"); 10669 case Expr::MLV_InvalidExpression: 10670 case Expr::MLV_MemberFunction: 10671 case Expr::MLV_ClassTemporary: 10672 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 10673 break; 10674 case Expr::MLV_IncompleteType: 10675 case Expr::MLV_IncompleteVoidType: 10676 return S.RequireCompleteType(Loc, E->getType(), 10677 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 10678 case Expr::MLV_DuplicateVectorComponents: 10679 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 10680 break; 10681 case Expr::MLV_NoSetterProperty: 10682 llvm_unreachable("readonly properties should be processed differently"); 10683 case Expr::MLV_InvalidMessageExpression: 10684 DiagID = diag::err_readonly_message_assignment; 10685 break; 10686 case Expr::MLV_SubObjCPropertySetting: 10687 DiagID = diag::err_no_subobject_property_setting; 10688 break; 10689 } 10690 10691 SourceRange Assign; 10692 if (Loc != OrigLoc) 10693 Assign = SourceRange(OrigLoc, OrigLoc); 10694 if (NeedType) 10695 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 10696 else 10697 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10698 return true; 10699 } 10700 10701 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 10702 SourceLocation Loc, 10703 Sema &Sema) { 10704 // C / C++ fields 10705 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 10706 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 10707 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 10708 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 10709 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 10710 } 10711 10712 // Objective-C instance variables 10713 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 10714 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 10715 if (OL && OR && OL->getDecl() == OR->getDecl()) { 10716 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 10717 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 10718 if (RL && RR && RL->getDecl() == RR->getDecl()) 10719 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 10720 } 10721 } 10722 10723 // C99 6.5.16.1 10724 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 10725 SourceLocation Loc, 10726 QualType CompoundType) { 10727 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 10728 10729 // Verify that LHS is a modifiable lvalue, and emit error if not. 10730 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 10731 return QualType(); 10732 10733 QualType LHSType = LHSExpr->getType(); 10734 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 10735 CompoundType; 10736 // OpenCL v1.2 s6.1.1.1 p2: 10737 // The half data type can only be used to declare a pointer to a buffer that 10738 // contains half values 10739 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 10740 LHSType->isHalfType()) { 10741 Diag(Loc, diag::err_opencl_half_load_store) << 1 10742 << LHSType.getUnqualifiedType(); 10743 return QualType(); 10744 } 10745 10746 AssignConvertType ConvTy; 10747 if (CompoundType.isNull()) { 10748 Expr *RHSCheck = RHS.get(); 10749 10750 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 10751 10752 QualType LHSTy(LHSType); 10753 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 10754 if (RHS.isInvalid()) 10755 return QualType(); 10756 // Special case of NSObject attributes on c-style pointer types. 10757 if (ConvTy == IncompatiblePointer && 10758 ((Context.isObjCNSObjectType(LHSType) && 10759 RHSType->isObjCObjectPointerType()) || 10760 (Context.isObjCNSObjectType(RHSType) && 10761 LHSType->isObjCObjectPointerType()))) 10762 ConvTy = Compatible; 10763 10764 if (ConvTy == Compatible && 10765 LHSType->isObjCObjectType()) 10766 Diag(Loc, diag::err_objc_object_assignment) 10767 << LHSType; 10768 10769 // If the RHS is a unary plus or minus, check to see if they = and + are 10770 // right next to each other. If so, the user may have typo'd "x =+ 4" 10771 // instead of "x += 4". 10772 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 10773 RHSCheck = ICE->getSubExpr(); 10774 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 10775 if ((UO->getOpcode() == UO_Plus || 10776 UO->getOpcode() == UO_Minus) && 10777 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 10778 // Only if the two operators are exactly adjacent. 10779 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 10780 // And there is a space or other character before the subexpr of the 10781 // unary +/-. We don't want to warn on "x=-1". 10782 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 10783 UO->getSubExpr()->getLocStart().isFileID()) { 10784 Diag(Loc, diag::warn_not_compound_assign) 10785 << (UO->getOpcode() == UO_Plus ? "+" : "-") 10786 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 10787 } 10788 } 10789 10790 if (ConvTy == Compatible) { 10791 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 10792 // Warn about retain cycles where a block captures the LHS, but 10793 // not if the LHS is a simple variable into which the block is 10794 // being stored...unless that variable can be captured by reference! 10795 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 10796 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 10797 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 10798 checkRetainCycles(LHSExpr, RHS.get()); 10799 } 10800 10801 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 10802 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 10803 // It is safe to assign a weak reference into a strong variable. 10804 // Although this code can still have problems: 10805 // id x = self.weakProp; 10806 // id y = self.weakProp; 10807 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10808 // paths through the function. This should be revisited if 10809 // -Wrepeated-use-of-weak is made flow-sensitive. 10810 // For ObjCWeak only, we do not warn if the assign is to a non-weak 10811 // variable, which will be valid for the current autorelease scope. 10812 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10813 RHS.get()->getLocStart())) 10814 getCurFunction()->markSafeWeakUse(RHS.get()); 10815 10816 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 10817 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 10818 } 10819 } 10820 } else { 10821 // Compound assignment "x += y" 10822 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 10823 } 10824 10825 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 10826 RHS.get(), AA_Assigning)) 10827 return QualType(); 10828 10829 CheckForNullPointerDereference(*this, LHSExpr); 10830 10831 // C99 6.5.16p3: The type of an assignment expression is the type of the 10832 // left operand unless the left operand has qualified type, in which case 10833 // it is the unqualified version of the type of the left operand. 10834 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 10835 // is converted to the type of the assignment expression (above). 10836 // C++ 5.17p1: the type of the assignment expression is that of its left 10837 // operand. 10838 return (getLangOpts().CPlusPlus 10839 ? LHSType : LHSType.getUnqualifiedType()); 10840 } 10841 10842 // Only ignore explicit casts to void. 10843 static bool IgnoreCommaOperand(const Expr *E) { 10844 E = E->IgnoreParens(); 10845 10846 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 10847 if (CE->getCastKind() == CK_ToVoid) { 10848 return true; 10849 } 10850 } 10851 10852 return false; 10853 } 10854 10855 // Look for instances where it is likely the comma operator is confused with 10856 // another operator. There is a whitelist of acceptable expressions for the 10857 // left hand side of the comma operator, otherwise emit a warning. 10858 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 10859 // No warnings in macros 10860 if (Loc.isMacroID()) 10861 return; 10862 10863 // Don't warn in template instantiations. 10864 if (inTemplateInstantiation()) 10865 return; 10866 10867 // Scope isn't fine-grained enough to whitelist the specific cases, so 10868 // instead, skip more than needed, then call back into here with the 10869 // CommaVisitor in SemaStmt.cpp. 10870 // The whitelisted locations are the initialization and increment portions 10871 // of a for loop. The additional checks are on the condition of 10872 // if statements, do/while loops, and for loops. 10873 const unsigned ForIncrementFlags = 10874 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 10875 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 10876 const unsigned ScopeFlags = getCurScope()->getFlags(); 10877 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 10878 (ScopeFlags & ForInitFlags) == ForInitFlags) 10879 return; 10880 10881 // If there are multiple comma operators used together, get the RHS of the 10882 // of the comma operator as the LHS. 10883 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 10884 if (BO->getOpcode() != BO_Comma) 10885 break; 10886 LHS = BO->getRHS(); 10887 } 10888 10889 // Only allow some expressions on LHS to not warn. 10890 if (IgnoreCommaOperand(LHS)) 10891 return; 10892 10893 Diag(Loc, diag::warn_comma_operator); 10894 Diag(LHS->getLocStart(), diag::note_cast_to_void) 10895 << LHS->getSourceRange() 10896 << FixItHint::CreateInsertion(LHS->getLocStart(), 10897 LangOpts.CPlusPlus ? "static_cast<void>(" 10898 : "(void)(") 10899 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()), 10900 ")"); 10901 } 10902 10903 // C99 6.5.17 10904 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 10905 SourceLocation Loc) { 10906 LHS = S.CheckPlaceholderExpr(LHS.get()); 10907 RHS = S.CheckPlaceholderExpr(RHS.get()); 10908 if (LHS.isInvalid() || RHS.isInvalid()) 10909 return QualType(); 10910 10911 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 10912 // operands, but not unary promotions. 10913 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 10914 10915 // So we treat the LHS as a ignored value, and in C++ we allow the 10916 // containing site to determine what should be done with the RHS. 10917 LHS = S.IgnoredValueConversions(LHS.get()); 10918 if (LHS.isInvalid()) 10919 return QualType(); 10920 10921 S.DiagnoseUnusedExprResult(LHS.get()); 10922 10923 if (!S.getLangOpts().CPlusPlus) { 10924 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 10925 if (RHS.isInvalid()) 10926 return QualType(); 10927 if (!RHS.get()->getType()->isVoidType()) 10928 S.RequireCompleteType(Loc, RHS.get()->getType(), 10929 diag::err_incomplete_type); 10930 } 10931 10932 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 10933 S.DiagnoseCommaOperator(LHS.get(), Loc); 10934 10935 return RHS.get()->getType(); 10936 } 10937 10938 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 10939 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 10940 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 10941 ExprValueKind &VK, 10942 ExprObjectKind &OK, 10943 SourceLocation OpLoc, 10944 bool IsInc, bool IsPrefix) { 10945 if (Op->isTypeDependent()) 10946 return S.Context.DependentTy; 10947 10948 QualType ResType = Op->getType(); 10949 // Atomic types can be used for increment / decrement where the non-atomic 10950 // versions can, so ignore the _Atomic() specifier for the purpose of 10951 // checking. 10952 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10953 ResType = ResAtomicType->getValueType(); 10954 10955 assert(!ResType.isNull() && "no type for increment/decrement expression"); 10956 10957 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 10958 // Decrement of bool is not allowed. 10959 if (!IsInc) { 10960 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 10961 return QualType(); 10962 } 10963 // Increment of bool sets it to true, but is deprecated. 10964 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 10965 : diag::warn_increment_bool) 10966 << Op->getSourceRange(); 10967 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 10968 // Error on enum increments and decrements in C++ mode 10969 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 10970 return QualType(); 10971 } else if (ResType->isRealType()) { 10972 // OK! 10973 } else if (ResType->isPointerType()) { 10974 // C99 6.5.2.4p2, 6.5.6p2 10975 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 10976 return QualType(); 10977 } else if (ResType->isObjCObjectPointerType()) { 10978 // On modern runtimes, ObjC pointer arithmetic is forbidden. 10979 // Otherwise, we just need a complete type. 10980 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 10981 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 10982 return QualType(); 10983 } else if (ResType->isAnyComplexType()) { 10984 // C99 does not support ++/-- on complex types, we allow as an extension. 10985 S.Diag(OpLoc, diag::ext_integer_increment_complex) 10986 << ResType << Op->getSourceRange(); 10987 } else if (ResType->isPlaceholderType()) { 10988 ExprResult PR = S.CheckPlaceholderExpr(Op); 10989 if (PR.isInvalid()) return QualType(); 10990 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 10991 IsInc, IsPrefix); 10992 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 10993 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 10994 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 10995 (ResType->getAs<VectorType>()->getVectorKind() != 10996 VectorType::AltiVecBool)) { 10997 // The z vector extensions allow ++ and -- for non-bool vectors. 10998 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 10999 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11000 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11001 } else { 11002 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11003 << ResType << int(IsInc) << Op->getSourceRange(); 11004 return QualType(); 11005 } 11006 // At this point, we know we have a real, complex or pointer type. 11007 // Now make sure the operand is a modifiable lvalue. 11008 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11009 return QualType(); 11010 // In C++, a prefix increment is the same type as the operand. Otherwise 11011 // (in C or with postfix), the increment is the unqualified type of the 11012 // operand. 11013 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11014 VK = VK_LValue; 11015 OK = Op->getObjectKind(); 11016 return ResType; 11017 } else { 11018 VK = VK_RValue; 11019 return ResType.getUnqualifiedType(); 11020 } 11021 } 11022 11023 11024 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11025 /// This routine allows us to typecheck complex/recursive expressions 11026 /// where the declaration is needed for type checking. We only need to 11027 /// handle cases when the expression references a function designator 11028 /// or is an lvalue. Here are some examples: 11029 /// - &(x) => x 11030 /// - &*****f => f for f a function designator. 11031 /// - &s.xx => s 11032 /// - &s.zz[1].yy -> s, if zz is an array 11033 /// - *(x + 1) -> x, if x is an array 11034 /// - &"123"[2] -> 0 11035 /// - & __real__ x -> x 11036 static ValueDecl *getPrimaryDecl(Expr *E) { 11037 switch (E->getStmtClass()) { 11038 case Stmt::DeclRefExprClass: 11039 return cast<DeclRefExpr>(E)->getDecl(); 11040 case Stmt::MemberExprClass: 11041 // If this is an arrow operator, the address is an offset from 11042 // the base's value, so the object the base refers to is 11043 // irrelevant. 11044 if (cast<MemberExpr>(E)->isArrow()) 11045 return nullptr; 11046 // Otherwise, the expression refers to a part of the base 11047 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11048 case Stmt::ArraySubscriptExprClass: { 11049 // FIXME: This code shouldn't be necessary! We should catch the implicit 11050 // promotion of register arrays earlier. 11051 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11052 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11053 if (ICE->getSubExpr()->getType()->isArrayType()) 11054 return getPrimaryDecl(ICE->getSubExpr()); 11055 } 11056 return nullptr; 11057 } 11058 case Stmt::UnaryOperatorClass: { 11059 UnaryOperator *UO = cast<UnaryOperator>(E); 11060 11061 switch(UO->getOpcode()) { 11062 case UO_Real: 11063 case UO_Imag: 11064 case UO_Extension: 11065 return getPrimaryDecl(UO->getSubExpr()); 11066 default: 11067 return nullptr; 11068 } 11069 } 11070 case Stmt::ParenExprClass: 11071 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11072 case Stmt::ImplicitCastExprClass: 11073 // If the result of an implicit cast is an l-value, we care about 11074 // the sub-expression; otherwise, the result here doesn't matter. 11075 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11076 default: 11077 return nullptr; 11078 } 11079 } 11080 11081 namespace { 11082 enum { 11083 AO_Bit_Field = 0, 11084 AO_Vector_Element = 1, 11085 AO_Property_Expansion = 2, 11086 AO_Register_Variable = 3, 11087 AO_No_Error = 4 11088 }; 11089 } 11090 /// \brief Diagnose invalid operand for address of operations. 11091 /// 11092 /// \param Type The type of operand which cannot have its address taken. 11093 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11094 Expr *E, unsigned Type) { 11095 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11096 } 11097 11098 /// CheckAddressOfOperand - The operand of & must be either a function 11099 /// designator or an lvalue designating an object. If it is an lvalue, the 11100 /// object cannot be declared with storage class register or be a bit field. 11101 /// Note: The usual conversions are *not* applied to the operand of the & 11102 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11103 /// In C++, the operand might be an overloaded function name, in which case 11104 /// we allow the '&' but retain the overloaded-function type. 11105 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11106 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11107 if (PTy->getKind() == BuiltinType::Overload) { 11108 Expr *E = OrigOp.get()->IgnoreParens(); 11109 if (!isa<OverloadExpr>(E)) { 11110 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11111 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11112 << OrigOp.get()->getSourceRange(); 11113 return QualType(); 11114 } 11115 11116 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11117 if (isa<UnresolvedMemberExpr>(Ovl)) 11118 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11119 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11120 << OrigOp.get()->getSourceRange(); 11121 return QualType(); 11122 } 11123 11124 return Context.OverloadTy; 11125 } 11126 11127 if (PTy->getKind() == BuiltinType::UnknownAny) 11128 return Context.UnknownAnyTy; 11129 11130 if (PTy->getKind() == BuiltinType::BoundMember) { 11131 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11132 << OrigOp.get()->getSourceRange(); 11133 return QualType(); 11134 } 11135 11136 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11137 if (OrigOp.isInvalid()) return QualType(); 11138 } 11139 11140 if (OrigOp.get()->isTypeDependent()) 11141 return Context.DependentTy; 11142 11143 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11144 11145 // Make sure to ignore parentheses in subsequent checks 11146 Expr *op = OrigOp.get()->IgnoreParens(); 11147 11148 // In OpenCL captures for blocks called as lambda functions 11149 // are located in the private address space. Blocks used in 11150 // enqueue_kernel can be located in a different address space 11151 // depending on a vendor implementation. Thus preventing 11152 // taking an address of the capture to avoid invalid AS casts. 11153 if (LangOpts.OpenCL) { 11154 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11155 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11156 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11157 return QualType(); 11158 } 11159 } 11160 11161 if (getLangOpts().C99) { 11162 // Implement C99-only parts of addressof rules. 11163 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11164 if (uOp->getOpcode() == UO_Deref) 11165 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11166 // (assuming the deref expression is valid). 11167 return uOp->getSubExpr()->getType(); 11168 } 11169 // Technically, there should be a check for array subscript 11170 // expressions here, but the result of one is always an lvalue anyway. 11171 } 11172 ValueDecl *dcl = getPrimaryDecl(op); 11173 11174 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11175 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11176 op->getLocStart())) 11177 return QualType(); 11178 11179 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11180 unsigned AddressOfError = AO_No_Error; 11181 11182 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11183 bool sfinae = (bool)isSFINAEContext(); 11184 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11185 : diag::ext_typecheck_addrof_temporary) 11186 << op->getType() << op->getSourceRange(); 11187 if (sfinae) 11188 return QualType(); 11189 // Materialize the temporary as an lvalue so that we can take its address. 11190 OrigOp = op = 11191 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11192 } else if (isa<ObjCSelectorExpr>(op)) { 11193 return Context.getPointerType(op->getType()); 11194 } else if (lval == Expr::LV_MemberFunction) { 11195 // If it's an instance method, make a member pointer. 11196 // The expression must have exactly the form &A::foo. 11197 11198 // If the underlying expression isn't a decl ref, give up. 11199 if (!isa<DeclRefExpr>(op)) { 11200 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11201 << OrigOp.get()->getSourceRange(); 11202 return QualType(); 11203 } 11204 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11205 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11206 11207 // The id-expression was parenthesized. 11208 if (OrigOp.get() != DRE) { 11209 Diag(OpLoc, diag::err_parens_pointer_member_function) 11210 << OrigOp.get()->getSourceRange(); 11211 11212 // The method was named without a qualifier. 11213 } else if (!DRE->getQualifier()) { 11214 if (MD->getParent()->getName().empty()) 11215 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11216 << op->getSourceRange(); 11217 else { 11218 SmallString<32> Str; 11219 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11220 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11221 << op->getSourceRange() 11222 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11223 } 11224 } 11225 11226 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11227 if (isa<CXXDestructorDecl>(MD)) 11228 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11229 11230 QualType MPTy = Context.getMemberPointerType( 11231 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11232 // Under the MS ABI, lock down the inheritance model now. 11233 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11234 (void)isCompleteType(OpLoc, MPTy); 11235 return MPTy; 11236 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11237 // C99 6.5.3.2p1 11238 // The operand must be either an l-value or a function designator 11239 if (!op->getType()->isFunctionType()) { 11240 // Use a special diagnostic for loads from property references. 11241 if (isa<PseudoObjectExpr>(op)) { 11242 AddressOfError = AO_Property_Expansion; 11243 } else { 11244 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11245 << op->getType() << op->getSourceRange(); 11246 return QualType(); 11247 } 11248 } 11249 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11250 // The operand cannot be a bit-field 11251 AddressOfError = AO_Bit_Field; 11252 } else if (op->getObjectKind() == OK_VectorComponent) { 11253 // The operand cannot be an element of a vector 11254 AddressOfError = AO_Vector_Element; 11255 } else if (dcl) { // C99 6.5.3.2p1 11256 // We have an lvalue with a decl. Make sure the decl is not declared 11257 // with the register storage-class specifier. 11258 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11259 // in C++ it is not error to take address of a register 11260 // variable (c++03 7.1.1P3) 11261 if (vd->getStorageClass() == SC_Register && 11262 !getLangOpts().CPlusPlus) { 11263 AddressOfError = AO_Register_Variable; 11264 } 11265 } else if (isa<MSPropertyDecl>(dcl)) { 11266 AddressOfError = AO_Property_Expansion; 11267 } else if (isa<FunctionTemplateDecl>(dcl)) { 11268 return Context.OverloadTy; 11269 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11270 // Okay: we can take the address of a field. 11271 // Could be a pointer to member, though, if there is an explicit 11272 // scope qualifier for the class. 11273 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11274 DeclContext *Ctx = dcl->getDeclContext(); 11275 if (Ctx && Ctx->isRecord()) { 11276 if (dcl->getType()->isReferenceType()) { 11277 Diag(OpLoc, 11278 diag::err_cannot_form_pointer_to_member_of_reference_type) 11279 << dcl->getDeclName() << dcl->getType(); 11280 return QualType(); 11281 } 11282 11283 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11284 Ctx = Ctx->getParent(); 11285 11286 QualType MPTy = Context.getMemberPointerType( 11287 op->getType(), 11288 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11289 // Under the MS ABI, lock down the inheritance model now. 11290 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11291 (void)isCompleteType(OpLoc, MPTy); 11292 return MPTy; 11293 } 11294 } 11295 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11296 !isa<BindingDecl>(dcl)) 11297 llvm_unreachable("Unknown/unexpected decl type"); 11298 } 11299 11300 if (AddressOfError != AO_No_Error) { 11301 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11302 return QualType(); 11303 } 11304 11305 if (lval == Expr::LV_IncompleteVoidType) { 11306 // Taking the address of a void variable is technically illegal, but we 11307 // allow it in cases which are otherwise valid. 11308 // Example: "extern void x; void* y = &x;". 11309 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11310 } 11311 11312 // If the operand has type "type", the result has type "pointer to type". 11313 if (op->getType()->isObjCObjectType()) 11314 return Context.getObjCObjectPointerType(op->getType()); 11315 11316 CheckAddressOfPackedMember(op); 11317 11318 return Context.getPointerType(op->getType()); 11319 } 11320 11321 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11322 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11323 if (!DRE) 11324 return; 11325 const Decl *D = DRE->getDecl(); 11326 if (!D) 11327 return; 11328 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11329 if (!Param) 11330 return; 11331 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11332 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11333 return; 11334 if (FunctionScopeInfo *FD = S.getCurFunction()) 11335 if (!FD->ModifiedNonNullParams.count(Param)) 11336 FD->ModifiedNonNullParams.insert(Param); 11337 } 11338 11339 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11340 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11341 SourceLocation OpLoc) { 11342 if (Op->isTypeDependent()) 11343 return S.Context.DependentTy; 11344 11345 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11346 if (ConvResult.isInvalid()) 11347 return QualType(); 11348 Op = ConvResult.get(); 11349 QualType OpTy = Op->getType(); 11350 QualType Result; 11351 11352 if (isa<CXXReinterpretCastExpr>(Op)) { 11353 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11354 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11355 Op->getSourceRange()); 11356 } 11357 11358 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11359 { 11360 Result = PT->getPointeeType(); 11361 } 11362 else if (const ObjCObjectPointerType *OPT = 11363 OpTy->getAs<ObjCObjectPointerType>()) 11364 Result = OPT->getPointeeType(); 11365 else { 11366 ExprResult PR = S.CheckPlaceholderExpr(Op); 11367 if (PR.isInvalid()) return QualType(); 11368 if (PR.get() != Op) 11369 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11370 } 11371 11372 if (Result.isNull()) { 11373 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11374 << OpTy << Op->getSourceRange(); 11375 return QualType(); 11376 } 11377 11378 // Note that per both C89 and C99, indirection is always legal, even if Result 11379 // is an incomplete type or void. It would be possible to warn about 11380 // dereferencing a void pointer, but it's completely well-defined, and such a 11381 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11382 // for pointers to 'void' but is fine for any other pointer type: 11383 // 11384 // C++ [expr.unary.op]p1: 11385 // [...] the expression to which [the unary * operator] is applied shall 11386 // be a pointer to an object type, or a pointer to a function type 11387 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11388 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11389 << OpTy << Op->getSourceRange(); 11390 11391 // Dereferences are usually l-values... 11392 VK = VK_LValue; 11393 11394 // ...except that certain expressions are never l-values in C. 11395 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11396 VK = VK_RValue; 11397 11398 return Result; 11399 } 11400 11401 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11402 BinaryOperatorKind Opc; 11403 switch (Kind) { 11404 default: llvm_unreachable("Unknown binop!"); 11405 case tok::periodstar: Opc = BO_PtrMemD; break; 11406 case tok::arrowstar: Opc = BO_PtrMemI; break; 11407 case tok::star: Opc = BO_Mul; break; 11408 case tok::slash: Opc = BO_Div; break; 11409 case tok::percent: Opc = BO_Rem; break; 11410 case tok::plus: Opc = BO_Add; break; 11411 case tok::minus: Opc = BO_Sub; break; 11412 case tok::lessless: Opc = BO_Shl; break; 11413 case tok::greatergreater: Opc = BO_Shr; break; 11414 case tok::lessequal: Opc = BO_LE; break; 11415 case tok::less: Opc = BO_LT; break; 11416 case tok::greaterequal: Opc = BO_GE; break; 11417 case tok::greater: Opc = BO_GT; break; 11418 case tok::exclaimequal: Opc = BO_NE; break; 11419 case tok::equalequal: Opc = BO_EQ; break; 11420 case tok::spaceship: Opc = BO_Cmp; break; 11421 case tok::amp: Opc = BO_And; break; 11422 case tok::caret: Opc = BO_Xor; break; 11423 case tok::pipe: Opc = BO_Or; break; 11424 case tok::ampamp: Opc = BO_LAnd; break; 11425 case tok::pipepipe: Opc = BO_LOr; break; 11426 case tok::equal: Opc = BO_Assign; break; 11427 case tok::starequal: Opc = BO_MulAssign; break; 11428 case tok::slashequal: Opc = BO_DivAssign; break; 11429 case tok::percentequal: Opc = BO_RemAssign; break; 11430 case tok::plusequal: Opc = BO_AddAssign; break; 11431 case tok::minusequal: Opc = BO_SubAssign; break; 11432 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11433 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11434 case tok::ampequal: Opc = BO_AndAssign; break; 11435 case tok::caretequal: Opc = BO_XorAssign; break; 11436 case tok::pipeequal: Opc = BO_OrAssign; break; 11437 case tok::comma: Opc = BO_Comma; break; 11438 } 11439 return Opc; 11440 } 11441 11442 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11443 tok::TokenKind Kind) { 11444 UnaryOperatorKind Opc; 11445 switch (Kind) { 11446 default: llvm_unreachable("Unknown unary op!"); 11447 case tok::plusplus: Opc = UO_PreInc; break; 11448 case tok::minusminus: Opc = UO_PreDec; break; 11449 case tok::amp: Opc = UO_AddrOf; break; 11450 case tok::star: Opc = UO_Deref; break; 11451 case tok::plus: Opc = UO_Plus; break; 11452 case tok::minus: Opc = UO_Minus; break; 11453 case tok::tilde: Opc = UO_Not; break; 11454 case tok::exclaim: Opc = UO_LNot; break; 11455 case tok::kw___real: Opc = UO_Real; break; 11456 case tok::kw___imag: Opc = UO_Imag; break; 11457 case tok::kw___extension__: Opc = UO_Extension; break; 11458 } 11459 return Opc; 11460 } 11461 11462 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11463 /// This warning is only emitted for builtin assignment operations. It is also 11464 /// suppressed in the event of macro expansions. 11465 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11466 SourceLocation OpLoc) { 11467 if (S.inTemplateInstantiation()) 11468 return; 11469 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11470 return; 11471 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11472 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11473 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11474 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11475 if (!LHSDeclRef || !RHSDeclRef || 11476 LHSDeclRef->getLocation().isMacroID() || 11477 RHSDeclRef->getLocation().isMacroID()) 11478 return; 11479 const ValueDecl *LHSDecl = 11480 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11481 const ValueDecl *RHSDecl = 11482 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11483 if (LHSDecl != RHSDecl) 11484 return; 11485 if (LHSDecl->getType().isVolatileQualified()) 11486 return; 11487 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11488 if (RefTy->getPointeeType().isVolatileQualified()) 11489 return; 11490 11491 S.Diag(OpLoc, diag::warn_self_assignment) 11492 << LHSDeclRef->getType() 11493 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11494 } 11495 11496 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11497 /// is usually indicative of introspection within the Objective-C pointer. 11498 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11499 SourceLocation OpLoc) { 11500 if (!S.getLangOpts().ObjC1) 11501 return; 11502 11503 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11504 const Expr *LHS = L.get(); 11505 const Expr *RHS = R.get(); 11506 11507 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11508 ObjCPointerExpr = LHS; 11509 OtherExpr = RHS; 11510 } 11511 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11512 ObjCPointerExpr = RHS; 11513 OtherExpr = LHS; 11514 } 11515 11516 // This warning is deliberately made very specific to reduce false 11517 // positives with logic that uses '&' for hashing. This logic mainly 11518 // looks for code trying to introspect into tagged pointers, which 11519 // code should generally never do. 11520 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11521 unsigned Diag = diag::warn_objc_pointer_masking; 11522 // Determine if we are introspecting the result of performSelectorXXX. 11523 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11524 // Special case messages to -performSelector and friends, which 11525 // can return non-pointer values boxed in a pointer value. 11526 // Some clients may wish to silence warnings in this subcase. 11527 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11528 Selector S = ME->getSelector(); 11529 StringRef SelArg0 = S.getNameForSlot(0); 11530 if (SelArg0.startswith("performSelector")) 11531 Diag = diag::warn_objc_pointer_masking_performSelector; 11532 } 11533 11534 S.Diag(OpLoc, Diag) 11535 << ObjCPointerExpr->getSourceRange(); 11536 } 11537 } 11538 11539 static NamedDecl *getDeclFromExpr(Expr *E) { 11540 if (!E) 11541 return nullptr; 11542 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11543 return DRE->getDecl(); 11544 if (auto *ME = dyn_cast<MemberExpr>(E)) 11545 return ME->getMemberDecl(); 11546 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11547 return IRE->getDecl(); 11548 return nullptr; 11549 } 11550 11551 // This helper function promotes a binary operator's operands (which are of a 11552 // half vector type) to a vector of floats and then truncates the result to 11553 // a vector of either half or short. 11554 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11555 BinaryOperatorKind Opc, QualType ResultTy, 11556 ExprValueKind VK, ExprObjectKind OK, 11557 bool IsCompAssign, SourceLocation OpLoc, 11558 FPOptions FPFeatures) { 11559 auto &Context = S.getASTContext(); 11560 assert((isVector(ResultTy, Context.HalfTy) || 11561 isVector(ResultTy, Context.ShortTy)) && 11562 "Result must be a vector of half or short"); 11563 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11564 isVector(RHS.get()->getType(), Context.HalfTy) && 11565 "both operands expected to be a half vector"); 11566 11567 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11568 QualType BinOpResTy = RHS.get()->getType(); 11569 11570 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11571 // change BinOpResTy to a vector of ints. 11572 if (isVector(ResultTy, Context.ShortTy)) 11573 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11574 11575 if (IsCompAssign) 11576 return new (Context) CompoundAssignOperator( 11577 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11578 OpLoc, FPFeatures); 11579 11580 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11581 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11582 VK, OK, OpLoc, FPFeatures); 11583 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11584 } 11585 11586 static std::pair<ExprResult, ExprResult> 11587 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11588 Expr *RHSExpr) { 11589 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11590 if (!S.getLangOpts().CPlusPlus) { 11591 // C cannot handle TypoExpr nodes on either side of a binop because it 11592 // doesn't handle dependent types properly, so make sure any TypoExprs have 11593 // been dealt with before checking the operands. 11594 LHS = S.CorrectDelayedTyposInExpr(LHS); 11595 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11596 if (Opc != BO_Assign) 11597 return ExprResult(E); 11598 // Avoid correcting the RHS to the same Expr as the LHS. 11599 Decl *D = getDeclFromExpr(E); 11600 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11601 }); 11602 } 11603 return std::make_pair(LHS, RHS); 11604 } 11605 11606 /// Returns true if conversion between vectors of halfs and vectors of floats 11607 /// is needed. 11608 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11609 QualType SrcType) { 11610 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11611 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11612 isVector(SrcType, Ctx.HalfTy); 11613 } 11614 11615 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11616 /// operator @p Opc at location @c TokLoc. This routine only supports 11617 /// built-in operations; ActOnBinOp handles overloaded operators. 11618 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11619 BinaryOperatorKind Opc, 11620 Expr *LHSExpr, Expr *RHSExpr) { 11621 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11622 // The syntax only allows initializer lists on the RHS of assignment, 11623 // so we don't need to worry about accepting invalid code for 11624 // non-assignment operators. 11625 // C++11 5.17p9: 11626 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11627 // of x = {} is x = T(). 11628 InitializationKind Kind = InitializationKind::CreateDirectList( 11629 RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11630 InitializedEntity Entity = 11631 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11632 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11633 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11634 if (Init.isInvalid()) 11635 return Init; 11636 RHSExpr = Init.get(); 11637 } 11638 11639 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11640 QualType ResultTy; // Result type of the binary operator. 11641 // The following two variables are used for compound assignment operators 11642 QualType CompLHSTy; // Type of LHS after promotions for computation 11643 QualType CompResultTy; // Type of computation result 11644 ExprValueKind VK = VK_RValue; 11645 ExprObjectKind OK = OK_Ordinary; 11646 bool ConvertHalfVec = false; 11647 11648 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 11649 if (!LHS.isUsable() || !RHS.isUsable()) 11650 return ExprError(); 11651 11652 if (getLangOpts().OpenCL) { 11653 QualType LHSTy = LHSExpr->getType(); 11654 QualType RHSTy = RHSExpr->getType(); 11655 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 11656 // the ATOMIC_VAR_INIT macro. 11657 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 11658 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 11659 if (BO_Assign == Opc) 11660 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 11661 else 11662 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11663 return ExprError(); 11664 } 11665 11666 // OpenCL special types - image, sampler, pipe, and blocks are to be used 11667 // only with a builtin functions and therefore should be disallowed here. 11668 if (LHSTy->isImageType() || RHSTy->isImageType() || 11669 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 11670 LHSTy->isPipeType() || RHSTy->isPipeType() || 11671 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 11672 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 11673 return ExprError(); 11674 } 11675 } 11676 11677 switch (Opc) { 11678 case BO_Assign: 11679 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 11680 if (getLangOpts().CPlusPlus && 11681 LHS.get()->getObjectKind() != OK_ObjCProperty) { 11682 VK = LHS.get()->getValueKind(); 11683 OK = LHS.get()->getObjectKind(); 11684 } 11685 if (!ResultTy.isNull()) { 11686 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11687 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 11688 } 11689 RecordModifiableNonNullParam(*this, LHS.get()); 11690 break; 11691 case BO_PtrMemD: 11692 case BO_PtrMemI: 11693 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 11694 Opc == BO_PtrMemI); 11695 break; 11696 case BO_Mul: 11697 case BO_Div: 11698 ConvertHalfVec = true; 11699 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 11700 Opc == BO_Div); 11701 break; 11702 case BO_Rem: 11703 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 11704 break; 11705 case BO_Add: 11706 ConvertHalfVec = true; 11707 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 11708 break; 11709 case BO_Sub: 11710 ConvertHalfVec = true; 11711 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 11712 break; 11713 case BO_Shl: 11714 case BO_Shr: 11715 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 11716 break; 11717 case BO_LE: 11718 case BO_LT: 11719 case BO_GE: 11720 case BO_GT: 11721 ConvertHalfVec = true; 11722 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11723 break; 11724 case BO_EQ: 11725 case BO_NE: 11726 ConvertHalfVec = true; 11727 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 11728 break; 11729 case BO_Cmp: 11730 // FIXME: Implement proper semantic checking of '<=>'. 11731 ConvertHalfVec = true; 11732 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 11733 if (!ResultTy.isNull()) 11734 ResultTy = Context.VoidTy; 11735 break; 11736 case BO_And: 11737 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 11738 LLVM_FALLTHROUGH; 11739 case BO_Xor: 11740 case BO_Or: 11741 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11742 break; 11743 case BO_LAnd: 11744 case BO_LOr: 11745 ConvertHalfVec = true; 11746 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 11747 break; 11748 case BO_MulAssign: 11749 case BO_DivAssign: 11750 ConvertHalfVec = true; 11751 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 11752 Opc == BO_DivAssign); 11753 CompLHSTy = CompResultTy; 11754 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11755 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11756 break; 11757 case BO_RemAssign: 11758 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 11759 CompLHSTy = CompResultTy; 11760 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11761 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11762 break; 11763 case BO_AddAssign: 11764 ConvertHalfVec = true; 11765 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 11766 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11767 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11768 break; 11769 case BO_SubAssign: 11770 ConvertHalfVec = true; 11771 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 11772 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11773 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11774 break; 11775 case BO_ShlAssign: 11776 case BO_ShrAssign: 11777 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 11778 CompLHSTy = CompResultTy; 11779 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11780 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11781 break; 11782 case BO_AndAssign: 11783 case BO_OrAssign: // fallthrough 11784 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 11785 LLVM_FALLTHROUGH; 11786 case BO_XorAssign: 11787 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 11788 CompLHSTy = CompResultTy; 11789 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 11790 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 11791 break; 11792 case BO_Comma: 11793 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 11794 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 11795 VK = RHS.get()->getValueKind(); 11796 OK = RHS.get()->getObjectKind(); 11797 } 11798 break; 11799 } 11800 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 11801 return ExprError(); 11802 11803 // Some of the binary operations require promoting operands of half vector to 11804 // float vectors and truncating the result back to half vector. For now, we do 11805 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 11806 // arm64). 11807 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 11808 isVector(LHS.get()->getType(), Context.HalfTy) && 11809 "both sides are half vectors or neither sides are"); 11810 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 11811 LHS.get()->getType()); 11812 11813 // Check for array bounds violations for both sides of the BinaryOperator 11814 CheckArrayAccess(LHS.get()); 11815 CheckArrayAccess(RHS.get()); 11816 11817 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 11818 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 11819 &Context.Idents.get("object_setClass"), 11820 SourceLocation(), LookupOrdinaryName); 11821 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 11822 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 11823 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 11824 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 11825 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 11826 FixItHint::CreateInsertion(RHSLocEnd, ")"); 11827 } 11828 else 11829 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 11830 } 11831 else if (const ObjCIvarRefExpr *OIRE = 11832 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 11833 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 11834 11835 // Opc is not a compound assignment if CompResultTy is null. 11836 if (CompResultTy.isNull()) { 11837 if (ConvertHalfVec) 11838 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 11839 OpLoc, FPFeatures); 11840 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 11841 OK, OpLoc, FPFeatures); 11842 } 11843 11844 // Handle compound assignments. 11845 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 11846 OK_ObjCProperty) { 11847 VK = VK_LValue; 11848 OK = LHS.get()->getObjectKind(); 11849 } 11850 11851 if (ConvertHalfVec) 11852 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 11853 OpLoc, FPFeatures); 11854 11855 return new (Context) CompoundAssignOperator( 11856 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 11857 OpLoc, FPFeatures); 11858 } 11859 11860 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 11861 /// operators are mixed in a way that suggests that the programmer forgot that 11862 /// comparison operators have higher precedence. The most typical example of 11863 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 11864 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 11865 SourceLocation OpLoc, Expr *LHSExpr, 11866 Expr *RHSExpr) { 11867 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 11868 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 11869 11870 // Check that one of the sides is a comparison operator and the other isn't. 11871 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 11872 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 11873 if (isLeftComp == isRightComp) 11874 return; 11875 11876 // Bitwise operations are sometimes used as eager logical ops. 11877 // Don't diagnose this. 11878 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 11879 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 11880 if (isLeftBitwise || isRightBitwise) 11881 return; 11882 11883 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 11884 OpLoc) 11885 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 11886 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 11887 SourceRange ParensRange = isLeftComp ? 11888 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 11889 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 11890 11891 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 11892 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 11893 SuggestParentheses(Self, OpLoc, 11894 Self.PDiag(diag::note_precedence_silence) << OpStr, 11895 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 11896 SuggestParentheses(Self, OpLoc, 11897 Self.PDiag(diag::note_precedence_bitwise_first) 11898 << BinaryOperator::getOpcodeStr(Opc), 11899 ParensRange); 11900 } 11901 11902 /// \brief It accepts a '&&' expr that is inside a '||' one. 11903 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 11904 /// in parentheses. 11905 static void 11906 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 11907 BinaryOperator *Bop) { 11908 assert(Bop->getOpcode() == BO_LAnd); 11909 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 11910 << Bop->getSourceRange() << OpLoc; 11911 SuggestParentheses(Self, Bop->getOperatorLoc(), 11912 Self.PDiag(diag::note_precedence_silence) 11913 << Bop->getOpcodeStr(), 11914 Bop->getSourceRange()); 11915 } 11916 11917 /// \brief Returns true if the given expression can be evaluated as a constant 11918 /// 'true'. 11919 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 11920 bool Res; 11921 return !E->isValueDependent() && 11922 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 11923 } 11924 11925 /// \brief Returns true if the given expression can be evaluated as a constant 11926 /// 'false'. 11927 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 11928 bool Res; 11929 return !E->isValueDependent() && 11930 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 11931 } 11932 11933 /// \brief Look for '&&' in the left hand of a '||' expr. 11934 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 11935 Expr *LHSExpr, Expr *RHSExpr) { 11936 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 11937 if (Bop->getOpcode() == BO_LAnd) { 11938 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 11939 if (EvaluatesAsFalse(S, RHSExpr)) 11940 return; 11941 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 11942 if (!EvaluatesAsTrue(S, Bop->getLHS())) 11943 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11944 } else if (Bop->getOpcode() == BO_LOr) { 11945 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 11946 // If it's "a || b && 1 || c" we didn't warn earlier for 11947 // "a || b && 1", but warn now. 11948 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 11949 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 11950 } 11951 } 11952 } 11953 } 11954 11955 /// \brief Look for '&&' in the right hand of a '||' expr. 11956 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 11957 Expr *LHSExpr, Expr *RHSExpr) { 11958 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 11959 if (Bop->getOpcode() == BO_LAnd) { 11960 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 11961 if (EvaluatesAsFalse(S, LHSExpr)) 11962 return; 11963 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 11964 if (!EvaluatesAsTrue(S, Bop->getRHS())) 11965 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 11966 } 11967 } 11968 } 11969 11970 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 11971 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 11972 /// the '&' expression in parentheses. 11973 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 11974 SourceLocation OpLoc, Expr *SubExpr) { 11975 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11976 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 11977 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 11978 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 11979 << Bop->getSourceRange() << OpLoc; 11980 SuggestParentheses(S, Bop->getOperatorLoc(), 11981 S.PDiag(diag::note_precedence_silence) 11982 << Bop->getOpcodeStr(), 11983 Bop->getSourceRange()); 11984 } 11985 } 11986 } 11987 11988 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 11989 Expr *SubExpr, StringRef Shift) { 11990 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 11991 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 11992 StringRef Op = Bop->getOpcodeStr(); 11993 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 11994 << Bop->getSourceRange() << OpLoc << Shift << Op; 11995 SuggestParentheses(S, Bop->getOperatorLoc(), 11996 S.PDiag(diag::note_precedence_silence) << Op, 11997 Bop->getSourceRange()); 11998 } 11999 } 12000 } 12001 12002 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12003 Expr *LHSExpr, Expr *RHSExpr) { 12004 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12005 if (!OCE) 12006 return; 12007 12008 FunctionDecl *FD = OCE->getDirectCallee(); 12009 if (!FD || !FD->isOverloadedOperator()) 12010 return; 12011 12012 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12013 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12014 return; 12015 12016 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12017 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12018 << (Kind == OO_LessLess); 12019 SuggestParentheses(S, OCE->getOperatorLoc(), 12020 S.PDiag(diag::note_precedence_silence) 12021 << (Kind == OO_LessLess ? "<<" : ">>"), 12022 OCE->getSourceRange()); 12023 SuggestParentheses(S, OpLoc, 12024 S.PDiag(diag::note_evaluate_comparison_first), 12025 SourceRange(OCE->getArg(1)->getLocStart(), 12026 RHSExpr->getLocEnd())); 12027 } 12028 12029 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12030 /// precedence. 12031 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12032 SourceLocation OpLoc, Expr *LHSExpr, 12033 Expr *RHSExpr){ 12034 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12035 if (BinaryOperator::isBitwiseOp(Opc)) 12036 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12037 12038 // Diagnose "arg1 & arg2 | arg3" 12039 if ((Opc == BO_Or || Opc == BO_Xor) && 12040 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12041 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12042 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12043 } 12044 12045 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12046 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12047 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12048 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12049 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12050 } 12051 12052 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12053 || Opc == BO_Shr) { 12054 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12055 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12056 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12057 } 12058 12059 // Warn on overloaded shift operators and comparisons, such as: 12060 // cout << 5 == 4; 12061 if (BinaryOperator::isComparisonOp(Opc)) 12062 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12063 } 12064 12065 // Binary Operators. 'Tok' is the token for the operator. 12066 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12067 tok::TokenKind Kind, 12068 Expr *LHSExpr, Expr *RHSExpr) { 12069 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12070 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12071 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12072 12073 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12074 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12075 12076 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12077 } 12078 12079 /// Build an overloaded binary operator expression in the given scope. 12080 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12081 BinaryOperatorKind Opc, 12082 Expr *LHS, Expr *RHS) { 12083 // Find all of the overloaded operators visible from this 12084 // point. We perform both an operator-name lookup from the local 12085 // scope and an argument-dependent lookup based on the types of 12086 // the arguments. 12087 UnresolvedSet<16> Functions; 12088 OverloadedOperatorKind OverOp 12089 = BinaryOperator::getOverloadedOperator(Opc); 12090 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12091 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12092 RHS->getType(), Functions); 12093 12094 // Build the (potentially-overloaded, potentially-dependent) 12095 // binary operation. 12096 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12097 } 12098 12099 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12100 BinaryOperatorKind Opc, 12101 Expr *LHSExpr, Expr *RHSExpr) { 12102 ExprResult LHS, RHS; 12103 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12104 if (!LHS.isUsable() || !RHS.isUsable()) 12105 return ExprError(); 12106 LHSExpr = LHS.get(); 12107 RHSExpr = RHS.get(); 12108 12109 // We want to end up calling one of checkPseudoObjectAssignment 12110 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12111 // both expressions are overloadable or either is type-dependent), 12112 // or CreateBuiltinBinOp (in any other case). We also want to get 12113 // any placeholder types out of the way. 12114 12115 // Handle pseudo-objects in the LHS. 12116 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12117 // Assignments with a pseudo-object l-value need special analysis. 12118 if (pty->getKind() == BuiltinType::PseudoObject && 12119 BinaryOperator::isAssignmentOp(Opc)) 12120 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12121 12122 // Don't resolve overloads if the other type is overloadable. 12123 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12124 // We can't actually test that if we still have a placeholder, 12125 // though. Fortunately, none of the exceptions we see in that 12126 // code below are valid when the LHS is an overload set. Note 12127 // that an overload set can be dependently-typed, but it never 12128 // instantiates to having an overloadable type. 12129 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12130 if (resolvedRHS.isInvalid()) return ExprError(); 12131 RHSExpr = resolvedRHS.get(); 12132 12133 if (RHSExpr->isTypeDependent() || 12134 RHSExpr->getType()->isOverloadableType()) 12135 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12136 } 12137 12138 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12139 // template, diagnose the missing 'template' keyword instead of diagnosing 12140 // an invalid use of a bound member function. 12141 // 12142 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12143 // to C++1z [over.over]/1.4, but we already checked for that case above. 12144 if (Opc == BO_LT && inTemplateInstantiation() && 12145 (pty->getKind() == BuiltinType::BoundMember || 12146 pty->getKind() == BuiltinType::Overload)) { 12147 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12148 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12149 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12150 return isa<FunctionTemplateDecl>(ND); 12151 })) { 12152 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12153 : OE->getNameLoc(), 12154 diag::err_template_kw_missing) 12155 << OE->getName().getAsString() << ""; 12156 return ExprError(); 12157 } 12158 } 12159 12160 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12161 if (LHS.isInvalid()) return ExprError(); 12162 LHSExpr = LHS.get(); 12163 } 12164 12165 // Handle pseudo-objects in the RHS. 12166 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12167 // An overload in the RHS can potentially be resolved by the type 12168 // being assigned to. 12169 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12170 if (getLangOpts().CPlusPlus && 12171 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12172 LHSExpr->getType()->isOverloadableType())) 12173 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12174 12175 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12176 } 12177 12178 // Don't resolve overloads if the other type is overloadable. 12179 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12180 LHSExpr->getType()->isOverloadableType()) 12181 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12182 12183 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12184 if (!resolvedRHS.isUsable()) return ExprError(); 12185 RHSExpr = resolvedRHS.get(); 12186 } 12187 12188 if (getLangOpts().CPlusPlus) { 12189 // If either expression is type-dependent, always build an 12190 // overloaded op. 12191 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12192 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12193 12194 // Otherwise, build an overloaded op if either expression has an 12195 // overloadable type. 12196 if (LHSExpr->getType()->isOverloadableType() || 12197 RHSExpr->getType()->isOverloadableType()) 12198 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12199 } 12200 12201 // Build a built-in binary operation. 12202 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12203 } 12204 12205 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12206 if (T.isNull() || T->isDependentType()) 12207 return false; 12208 12209 if (!T->isPromotableIntegerType()) 12210 return true; 12211 12212 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12213 } 12214 12215 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12216 UnaryOperatorKind Opc, 12217 Expr *InputExpr) { 12218 ExprResult Input = InputExpr; 12219 ExprValueKind VK = VK_RValue; 12220 ExprObjectKind OK = OK_Ordinary; 12221 QualType resultType; 12222 bool CanOverflow = false; 12223 12224 bool ConvertHalfVec = false; 12225 if (getLangOpts().OpenCL) { 12226 QualType Ty = InputExpr->getType(); 12227 // The only legal unary operation for atomics is '&'. 12228 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12229 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12230 // only with a builtin functions and therefore should be disallowed here. 12231 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12232 || Ty->isBlockPointerType())) { 12233 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12234 << InputExpr->getType() 12235 << Input.get()->getSourceRange()); 12236 } 12237 } 12238 switch (Opc) { 12239 case UO_PreInc: 12240 case UO_PreDec: 12241 case UO_PostInc: 12242 case UO_PostDec: 12243 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12244 OpLoc, 12245 Opc == UO_PreInc || 12246 Opc == UO_PostInc, 12247 Opc == UO_PreInc || 12248 Opc == UO_PreDec); 12249 CanOverflow = isOverflowingIntegerType(Context, resultType); 12250 break; 12251 case UO_AddrOf: 12252 resultType = CheckAddressOfOperand(Input, OpLoc); 12253 RecordModifiableNonNullParam(*this, InputExpr); 12254 break; 12255 case UO_Deref: { 12256 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12257 if (Input.isInvalid()) return ExprError(); 12258 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12259 break; 12260 } 12261 case UO_Plus: 12262 case UO_Minus: 12263 CanOverflow = Opc == UO_Minus && 12264 isOverflowingIntegerType(Context, Input.get()->getType()); 12265 Input = UsualUnaryConversions(Input.get()); 12266 if (Input.isInvalid()) return ExprError(); 12267 // Unary plus and minus require promoting an operand of half vector to a 12268 // float vector and truncating the result back to a half vector. For now, we 12269 // do this only when HalfArgsAndReturns is set (that is, when the target is 12270 // arm or arm64). 12271 ConvertHalfVec = 12272 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12273 12274 // If the operand is a half vector, promote it to a float vector. 12275 if (ConvertHalfVec) 12276 Input = convertVector(Input.get(), Context.FloatTy, *this); 12277 resultType = Input.get()->getType(); 12278 if (resultType->isDependentType()) 12279 break; 12280 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12281 break; 12282 else if (resultType->isVectorType() && 12283 // The z vector extensions don't allow + or - with bool vectors. 12284 (!Context.getLangOpts().ZVector || 12285 resultType->getAs<VectorType>()->getVectorKind() != 12286 VectorType::AltiVecBool)) 12287 break; 12288 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12289 Opc == UO_Plus && 12290 resultType->isPointerType()) 12291 break; 12292 12293 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12294 << resultType << Input.get()->getSourceRange()); 12295 12296 case UO_Not: // bitwise complement 12297 Input = UsualUnaryConversions(Input.get()); 12298 if (Input.isInvalid()) 12299 return ExprError(); 12300 resultType = Input.get()->getType(); 12301 12302 if (resultType->isDependentType()) 12303 break; 12304 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12305 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12306 // C99 does not support '~' for complex conjugation. 12307 Diag(OpLoc, diag::ext_integer_complement_complex) 12308 << resultType << Input.get()->getSourceRange(); 12309 else if (resultType->hasIntegerRepresentation()) 12310 break; 12311 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12312 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12313 // on vector float types. 12314 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12315 if (!T->isIntegerType()) 12316 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12317 << resultType << Input.get()->getSourceRange()); 12318 } else { 12319 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12320 << resultType << Input.get()->getSourceRange()); 12321 } 12322 break; 12323 12324 case UO_LNot: // logical negation 12325 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12326 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12327 if (Input.isInvalid()) return ExprError(); 12328 resultType = Input.get()->getType(); 12329 12330 // Though we still have to promote half FP to float... 12331 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12332 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12333 resultType = Context.FloatTy; 12334 } 12335 12336 if (resultType->isDependentType()) 12337 break; 12338 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12339 // C99 6.5.3.3p1: ok, fallthrough; 12340 if (Context.getLangOpts().CPlusPlus) { 12341 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12342 // operand contextually converted to bool. 12343 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12344 ScalarTypeToBooleanCastKind(resultType)); 12345 } else if (Context.getLangOpts().OpenCL && 12346 Context.getLangOpts().OpenCLVersion < 120) { 12347 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12348 // operate on scalar float types. 12349 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12350 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12351 << resultType << Input.get()->getSourceRange()); 12352 } 12353 } else if (resultType->isExtVectorType()) { 12354 if (Context.getLangOpts().OpenCL && 12355 Context.getLangOpts().OpenCLVersion < 120) { 12356 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12357 // operate on vector float types. 12358 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12359 if (!T->isIntegerType()) 12360 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12361 << resultType << Input.get()->getSourceRange()); 12362 } 12363 // Vector logical not returns the signed variant of the operand type. 12364 resultType = GetSignedVectorType(resultType); 12365 break; 12366 } else { 12367 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12368 // type in C++. We should allow that here too. 12369 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12370 << resultType << Input.get()->getSourceRange()); 12371 } 12372 12373 // LNot always has type int. C99 6.5.3.3p5. 12374 // In C++, it's bool. C++ 5.3.1p8 12375 resultType = Context.getLogicalOperationType(); 12376 break; 12377 case UO_Real: 12378 case UO_Imag: 12379 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12380 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12381 // complex l-values to ordinary l-values and all other values to r-values. 12382 if (Input.isInvalid()) return ExprError(); 12383 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12384 if (Input.get()->getValueKind() != VK_RValue && 12385 Input.get()->getObjectKind() == OK_Ordinary) 12386 VK = Input.get()->getValueKind(); 12387 } else if (!getLangOpts().CPlusPlus) { 12388 // In C, a volatile scalar is read by __imag. In C++, it is not. 12389 Input = DefaultLvalueConversion(Input.get()); 12390 } 12391 break; 12392 case UO_Extension: 12393 resultType = Input.get()->getType(); 12394 VK = Input.get()->getValueKind(); 12395 OK = Input.get()->getObjectKind(); 12396 break; 12397 case UO_Coawait: 12398 // It's unnessesary to represent the pass-through operator co_await in the 12399 // AST; just return the input expression instead. 12400 assert(!Input.get()->getType()->isDependentType() && 12401 "the co_await expression must be non-dependant before " 12402 "building operator co_await"); 12403 return Input; 12404 } 12405 if (resultType.isNull() || Input.isInvalid()) 12406 return ExprError(); 12407 12408 // Check for array bounds violations in the operand of the UnaryOperator, 12409 // except for the '*' and '&' operators that have to be handled specially 12410 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12411 // that are explicitly defined as valid by the standard). 12412 if (Opc != UO_AddrOf && Opc != UO_Deref) 12413 CheckArrayAccess(Input.get()); 12414 12415 auto *UO = new (Context) 12416 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12417 // Convert the result back to a half vector. 12418 if (ConvertHalfVec) 12419 return convertVector(UO, Context.HalfTy, *this); 12420 return UO; 12421 } 12422 12423 /// \brief Determine whether the given expression is a qualified member 12424 /// access expression, of a form that could be turned into a pointer to member 12425 /// with the address-of operator. 12426 static bool isQualifiedMemberAccess(Expr *E) { 12427 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12428 if (!DRE->getQualifier()) 12429 return false; 12430 12431 ValueDecl *VD = DRE->getDecl(); 12432 if (!VD->isCXXClassMember()) 12433 return false; 12434 12435 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12436 return true; 12437 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12438 return Method->isInstance(); 12439 12440 return false; 12441 } 12442 12443 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12444 if (!ULE->getQualifier()) 12445 return false; 12446 12447 for (NamedDecl *D : ULE->decls()) { 12448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12449 if (Method->isInstance()) 12450 return true; 12451 } else { 12452 // Overload set does not contain methods. 12453 break; 12454 } 12455 } 12456 12457 return false; 12458 } 12459 12460 return false; 12461 } 12462 12463 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12464 UnaryOperatorKind Opc, Expr *Input) { 12465 // First things first: handle placeholders so that the 12466 // overloaded-operator check considers the right type. 12467 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12468 // Increment and decrement of pseudo-object references. 12469 if (pty->getKind() == BuiltinType::PseudoObject && 12470 UnaryOperator::isIncrementDecrementOp(Opc)) 12471 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12472 12473 // extension is always a builtin operator. 12474 if (Opc == UO_Extension) 12475 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12476 12477 // & gets special logic for several kinds of placeholder. 12478 // The builtin code knows what to do. 12479 if (Opc == UO_AddrOf && 12480 (pty->getKind() == BuiltinType::Overload || 12481 pty->getKind() == BuiltinType::UnknownAny || 12482 pty->getKind() == BuiltinType::BoundMember)) 12483 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12484 12485 // Anything else needs to be handled now. 12486 ExprResult Result = CheckPlaceholderExpr(Input); 12487 if (Result.isInvalid()) return ExprError(); 12488 Input = Result.get(); 12489 } 12490 12491 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12492 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12493 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12494 // Find all of the overloaded operators visible from this 12495 // point. We perform both an operator-name lookup from the local 12496 // scope and an argument-dependent lookup based on the types of 12497 // the arguments. 12498 UnresolvedSet<16> Functions; 12499 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12500 if (S && OverOp != OO_None) 12501 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12502 Functions); 12503 12504 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12505 } 12506 12507 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12508 } 12509 12510 // Unary Operators. 'Tok' is the token for the operator. 12511 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12512 tok::TokenKind Op, Expr *Input) { 12513 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12514 } 12515 12516 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12517 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12518 LabelDecl *TheDecl) { 12519 TheDecl->markUsed(Context); 12520 // Create the AST node. The address of a label always has type 'void*'. 12521 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12522 Context.getPointerType(Context.VoidTy)); 12523 } 12524 12525 /// Given the last statement in a statement-expression, check whether 12526 /// the result is a producing expression (like a call to an 12527 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12528 /// release out of the full-expression. Otherwise, return null. 12529 /// Cannot fail. 12530 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12531 // Should always be wrapped with one of these. 12532 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12533 if (!cleanups) return nullptr; 12534 12535 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12536 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12537 return nullptr; 12538 12539 // Splice out the cast. This shouldn't modify any interesting 12540 // features of the statement. 12541 Expr *producer = cast->getSubExpr(); 12542 assert(producer->getType() == cast->getType()); 12543 assert(producer->getValueKind() == cast->getValueKind()); 12544 cleanups->setSubExpr(producer); 12545 return cleanups; 12546 } 12547 12548 void Sema::ActOnStartStmtExpr() { 12549 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12550 } 12551 12552 void Sema::ActOnStmtExprError() { 12553 // Note that function is also called by TreeTransform when leaving a 12554 // StmtExpr scope without rebuilding anything. 12555 12556 DiscardCleanupsInEvaluationContext(); 12557 PopExpressionEvaluationContext(); 12558 } 12559 12560 ExprResult 12561 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12562 SourceLocation RPLoc) { // "({..})" 12563 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12564 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12565 12566 if (hasAnyUnrecoverableErrorsInThisFunction()) 12567 DiscardCleanupsInEvaluationContext(); 12568 assert(!Cleanup.exprNeedsCleanups() && 12569 "cleanups within StmtExpr not correctly bound!"); 12570 PopExpressionEvaluationContext(); 12571 12572 // FIXME: there are a variety of strange constraints to enforce here, for 12573 // example, it is not possible to goto into a stmt expression apparently. 12574 // More semantic analysis is needed. 12575 12576 // If there are sub-stmts in the compound stmt, take the type of the last one 12577 // as the type of the stmtexpr. 12578 QualType Ty = Context.VoidTy; 12579 bool StmtExprMayBindToTemp = false; 12580 if (!Compound->body_empty()) { 12581 Stmt *LastStmt = Compound->body_back(); 12582 LabelStmt *LastLabelStmt = nullptr; 12583 // If LastStmt is a label, skip down through into the body. 12584 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12585 LastLabelStmt = Label; 12586 LastStmt = Label->getSubStmt(); 12587 } 12588 12589 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12590 // Do function/array conversion on the last expression, but not 12591 // lvalue-to-rvalue. However, initialize an unqualified type. 12592 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12593 if (LastExpr.isInvalid()) 12594 return ExprError(); 12595 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12596 12597 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12598 // In ARC, if the final expression ends in a consume, splice 12599 // the consume out and bind it later. In the alternate case 12600 // (when dealing with a retainable type), the result 12601 // initialization will create a produce. In both cases the 12602 // result will be +1, and we'll need to balance that out with 12603 // a bind. 12604 if (Expr *rebuiltLastStmt 12605 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12606 LastExpr = rebuiltLastStmt; 12607 } else { 12608 LastExpr = PerformCopyInitialization( 12609 InitializedEntity::InitializeResult(LPLoc, 12610 Ty, 12611 false), 12612 SourceLocation(), 12613 LastExpr); 12614 } 12615 12616 if (LastExpr.isInvalid()) 12617 return ExprError(); 12618 if (LastExpr.get() != nullptr) { 12619 if (!LastLabelStmt) 12620 Compound->setLastStmt(LastExpr.get()); 12621 else 12622 LastLabelStmt->setSubStmt(LastExpr.get()); 12623 StmtExprMayBindToTemp = true; 12624 } 12625 } 12626 } 12627 } 12628 12629 // FIXME: Check that expression type is complete/non-abstract; statement 12630 // expressions are not lvalues. 12631 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 12632 if (StmtExprMayBindToTemp) 12633 return MaybeBindToTemporary(ResStmtExpr); 12634 return ResStmtExpr; 12635 } 12636 12637 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 12638 TypeSourceInfo *TInfo, 12639 ArrayRef<OffsetOfComponent> Components, 12640 SourceLocation RParenLoc) { 12641 QualType ArgTy = TInfo->getType(); 12642 bool Dependent = ArgTy->isDependentType(); 12643 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 12644 12645 // We must have at least one component that refers to the type, and the first 12646 // one is known to be a field designator. Verify that the ArgTy represents 12647 // a struct/union/class. 12648 if (!Dependent && !ArgTy->isRecordType()) 12649 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 12650 << ArgTy << TypeRange); 12651 12652 // Type must be complete per C99 7.17p3 because a declaring a variable 12653 // with an incomplete type would be ill-formed. 12654 if (!Dependent 12655 && RequireCompleteType(BuiltinLoc, ArgTy, 12656 diag::err_offsetof_incomplete_type, TypeRange)) 12657 return ExprError(); 12658 12659 bool DidWarnAboutNonPOD = false; 12660 QualType CurrentType = ArgTy; 12661 SmallVector<OffsetOfNode, 4> Comps; 12662 SmallVector<Expr*, 4> Exprs; 12663 for (const OffsetOfComponent &OC : Components) { 12664 if (OC.isBrackets) { 12665 // Offset of an array sub-field. TODO: Should we allow vector elements? 12666 if (!CurrentType->isDependentType()) { 12667 const ArrayType *AT = Context.getAsArrayType(CurrentType); 12668 if(!AT) 12669 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 12670 << CurrentType); 12671 CurrentType = AT->getElementType(); 12672 } else 12673 CurrentType = Context.DependentTy; 12674 12675 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 12676 if (IdxRval.isInvalid()) 12677 return ExprError(); 12678 Expr *Idx = IdxRval.get(); 12679 12680 // The expression must be an integral expression. 12681 // FIXME: An integral constant expression? 12682 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 12683 !Idx->getType()->isIntegerType()) 12684 return ExprError(Diag(Idx->getLocStart(), 12685 diag::err_typecheck_subscript_not_integer) 12686 << Idx->getSourceRange()); 12687 12688 // Record this array index. 12689 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 12690 Exprs.push_back(Idx); 12691 continue; 12692 } 12693 12694 // Offset of a field. 12695 if (CurrentType->isDependentType()) { 12696 // We have the offset of a field, but we can't look into the dependent 12697 // type. Just record the identifier of the field. 12698 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 12699 CurrentType = Context.DependentTy; 12700 continue; 12701 } 12702 12703 // We need to have a complete type to look into. 12704 if (RequireCompleteType(OC.LocStart, CurrentType, 12705 diag::err_offsetof_incomplete_type)) 12706 return ExprError(); 12707 12708 // Look for the designated field. 12709 const RecordType *RC = CurrentType->getAs<RecordType>(); 12710 if (!RC) 12711 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 12712 << CurrentType); 12713 RecordDecl *RD = RC->getDecl(); 12714 12715 // C++ [lib.support.types]p5: 12716 // The macro offsetof accepts a restricted set of type arguments in this 12717 // International Standard. type shall be a POD structure or a POD union 12718 // (clause 9). 12719 // C++11 [support.types]p4: 12720 // If type is not a standard-layout class (Clause 9), the results are 12721 // undefined. 12722 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 12723 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 12724 unsigned DiagID = 12725 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 12726 : diag::ext_offsetof_non_pod_type; 12727 12728 if (!IsSafe && !DidWarnAboutNonPOD && 12729 DiagRuntimeBehavior(BuiltinLoc, nullptr, 12730 PDiag(DiagID) 12731 << SourceRange(Components[0].LocStart, OC.LocEnd) 12732 << CurrentType)) 12733 DidWarnAboutNonPOD = true; 12734 } 12735 12736 // Look for the field. 12737 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 12738 LookupQualifiedName(R, RD); 12739 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 12740 IndirectFieldDecl *IndirectMemberDecl = nullptr; 12741 if (!MemberDecl) { 12742 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 12743 MemberDecl = IndirectMemberDecl->getAnonField(); 12744 } 12745 12746 if (!MemberDecl) 12747 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 12748 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 12749 OC.LocEnd)); 12750 12751 // C99 7.17p3: 12752 // (If the specified member is a bit-field, the behavior is undefined.) 12753 // 12754 // We diagnose this as an error. 12755 if (MemberDecl->isBitField()) { 12756 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 12757 << MemberDecl->getDeclName() 12758 << SourceRange(BuiltinLoc, RParenLoc); 12759 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 12760 return ExprError(); 12761 } 12762 12763 RecordDecl *Parent = MemberDecl->getParent(); 12764 if (IndirectMemberDecl) 12765 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 12766 12767 // If the member was found in a base class, introduce OffsetOfNodes for 12768 // the base class indirections. 12769 CXXBasePaths Paths; 12770 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 12771 Paths)) { 12772 if (Paths.getDetectedVirtual()) { 12773 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 12774 << MemberDecl->getDeclName() 12775 << SourceRange(BuiltinLoc, RParenLoc); 12776 return ExprError(); 12777 } 12778 12779 CXXBasePath &Path = Paths.front(); 12780 for (const CXXBasePathElement &B : Path) 12781 Comps.push_back(OffsetOfNode(B.Base)); 12782 } 12783 12784 if (IndirectMemberDecl) { 12785 for (auto *FI : IndirectMemberDecl->chain()) { 12786 assert(isa<FieldDecl>(FI)); 12787 Comps.push_back(OffsetOfNode(OC.LocStart, 12788 cast<FieldDecl>(FI), OC.LocEnd)); 12789 } 12790 } else 12791 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 12792 12793 CurrentType = MemberDecl->getType().getNonReferenceType(); 12794 } 12795 12796 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 12797 Comps, Exprs, RParenLoc); 12798 } 12799 12800 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 12801 SourceLocation BuiltinLoc, 12802 SourceLocation TypeLoc, 12803 ParsedType ParsedArgTy, 12804 ArrayRef<OffsetOfComponent> Components, 12805 SourceLocation RParenLoc) { 12806 12807 TypeSourceInfo *ArgTInfo; 12808 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 12809 if (ArgTy.isNull()) 12810 return ExprError(); 12811 12812 if (!ArgTInfo) 12813 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 12814 12815 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 12816 } 12817 12818 12819 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 12820 Expr *CondExpr, 12821 Expr *LHSExpr, Expr *RHSExpr, 12822 SourceLocation RPLoc) { 12823 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 12824 12825 ExprValueKind VK = VK_RValue; 12826 ExprObjectKind OK = OK_Ordinary; 12827 QualType resType; 12828 bool ValueDependent = false; 12829 bool CondIsTrue = false; 12830 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 12831 resType = Context.DependentTy; 12832 ValueDependent = true; 12833 } else { 12834 // The conditional expression is required to be a constant expression. 12835 llvm::APSInt condEval(32); 12836 ExprResult CondICE 12837 = VerifyIntegerConstantExpression(CondExpr, &condEval, 12838 diag::err_typecheck_choose_expr_requires_constant, false); 12839 if (CondICE.isInvalid()) 12840 return ExprError(); 12841 CondExpr = CondICE.get(); 12842 CondIsTrue = condEval.getZExtValue(); 12843 12844 // If the condition is > zero, then the AST type is the same as the LSHExpr. 12845 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 12846 12847 resType = ActiveExpr->getType(); 12848 ValueDependent = ActiveExpr->isValueDependent(); 12849 VK = ActiveExpr->getValueKind(); 12850 OK = ActiveExpr->getObjectKind(); 12851 } 12852 12853 return new (Context) 12854 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 12855 CondIsTrue, resType->isDependentType(), ValueDependent); 12856 } 12857 12858 //===----------------------------------------------------------------------===// 12859 // Clang Extensions. 12860 //===----------------------------------------------------------------------===// 12861 12862 /// ActOnBlockStart - This callback is invoked when a block literal is started. 12863 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 12864 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 12865 12866 if (LangOpts.CPlusPlus) { 12867 Decl *ManglingContextDecl; 12868 if (MangleNumberingContext *MCtx = 12869 getCurrentMangleNumberContext(Block->getDeclContext(), 12870 ManglingContextDecl)) { 12871 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 12872 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 12873 } 12874 } 12875 12876 PushBlockScope(CurScope, Block); 12877 CurContext->addDecl(Block); 12878 if (CurScope) 12879 PushDeclContext(CurScope, Block); 12880 else 12881 CurContext = Block; 12882 12883 getCurBlock()->HasImplicitReturnType = true; 12884 12885 // Enter a new evaluation context to insulate the block from any 12886 // cleanups from the enclosing full-expression. 12887 PushExpressionEvaluationContext( 12888 ExpressionEvaluationContext::PotentiallyEvaluated); 12889 } 12890 12891 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 12892 Scope *CurScope) { 12893 assert(ParamInfo.getIdentifier() == nullptr && 12894 "block-id should have no identifier!"); 12895 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 12896 BlockScopeInfo *CurBlock = getCurBlock(); 12897 12898 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 12899 QualType T = Sig->getType(); 12900 12901 // FIXME: We should allow unexpanded parameter packs here, but that would, 12902 // in turn, make the block expression contain unexpanded parameter packs. 12903 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 12904 // Drop the parameters. 12905 FunctionProtoType::ExtProtoInfo EPI; 12906 EPI.HasTrailingReturn = false; 12907 EPI.TypeQuals |= DeclSpec::TQ_const; 12908 T = Context.getFunctionType(Context.DependentTy, None, EPI); 12909 Sig = Context.getTrivialTypeSourceInfo(T); 12910 } 12911 12912 // GetTypeForDeclarator always produces a function type for a block 12913 // literal signature. Furthermore, it is always a FunctionProtoType 12914 // unless the function was written with a typedef. 12915 assert(T->isFunctionType() && 12916 "GetTypeForDeclarator made a non-function block signature"); 12917 12918 // Look for an explicit signature in that function type. 12919 FunctionProtoTypeLoc ExplicitSignature; 12920 12921 if ((ExplicitSignature = 12922 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 12923 12924 // Check whether that explicit signature was synthesized by 12925 // GetTypeForDeclarator. If so, don't save that as part of the 12926 // written signature. 12927 if (ExplicitSignature.getLocalRangeBegin() == 12928 ExplicitSignature.getLocalRangeEnd()) { 12929 // This would be much cheaper if we stored TypeLocs instead of 12930 // TypeSourceInfos. 12931 TypeLoc Result = ExplicitSignature.getReturnLoc(); 12932 unsigned Size = Result.getFullDataSize(); 12933 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 12934 Sig->getTypeLoc().initializeFullCopy(Result, Size); 12935 12936 ExplicitSignature = FunctionProtoTypeLoc(); 12937 } 12938 } 12939 12940 CurBlock->TheDecl->setSignatureAsWritten(Sig); 12941 CurBlock->FunctionType = T; 12942 12943 const FunctionType *Fn = T->getAs<FunctionType>(); 12944 QualType RetTy = Fn->getReturnType(); 12945 bool isVariadic = 12946 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 12947 12948 CurBlock->TheDecl->setIsVariadic(isVariadic); 12949 12950 // Context.DependentTy is used as a placeholder for a missing block 12951 // return type. TODO: what should we do with declarators like: 12952 // ^ * { ... } 12953 // If the answer is "apply template argument deduction".... 12954 if (RetTy != Context.DependentTy) { 12955 CurBlock->ReturnType = RetTy; 12956 CurBlock->TheDecl->setBlockMissingReturnType(false); 12957 CurBlock->HasImplicitReturnType = false; 12958 } 12959 12960 // Push block parameters from the declarator if we had them. 12961 SmallVector<ParmVarDecl*, 8> Params; 12962 if (ExplicitSignature) { 12963 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 12964 ParmVarDecl *Param = ExplicitSignature.getParam(I); 12965 if (Param->getIdentifier() == nullptr && 12966 !Param->isImplicit() && 12967 !Param->isInvalidDecl() && 12968 !getLangOpts().CPlusPlus) 12969 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12970 Params.push_back(Param); 12971 } 12972 12973 // Fake up parameter variables if we have a typedef, like 12974 // ^ fntype { ... } 12975 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 12976 for (const auto &I : Fn->param_types()) { 12977 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 12978 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 12979 Params.push_back(Param); 12980 } 12981 } 12982 12983 // Set the parameters on the block decl. 12984 if (!Params.empty()) { 12985 CurBlock->TheDecl->setParams(Params); 12986 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 12987 /*CheckParameterNames=*/false); 12988 } 12989 12990 // Finally we can process decl attributes. 12991 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 12992 12993 // Put the parameter variables in scope. 12994 for (auto AI : CurBlock->TheDecl->parameters()) { 12995 AI->setOwningFunction(CurBlock->TheDecl); 12996 12997 // If this has an identifier, add it to the scope stack. 12998 if (AI->getIdentifier()) { 12999 CheckShadow(CurBlock->TheScope, AI); 13000 13001 PushOnScopeChains(AI, CurBlock->TheScope); 13002 } 13003 } 13004 } 13005 13006 /// ActOnBlockError - If there is an error parsing a block, this callback 13007 /// is invoked to pop the information about the block from the action impl. 13008 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13009 // Leave the expression-evaluation context. 13010 DiscardCleanupsInEvaluationContext(); 13011 PopExpressionEvaluationContext(); 13012 13013 // Pop off CurBlock, handle nested blocks. 13014 PopDeclContext(); 13015 PopFunctionScopeInfo(); 13016 } 13017 13018 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13019 /// literal was successfully completed. ^(int x){...} 13020 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13021 Stmt *Body, Scope *CurScope) { 13022 // If blocks are disabled, emit an error. 13023 if (!LangOpts.Blocks) 13024 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13025 13026 // Leave the expression-evaluation context. 13027 if (hasAnyUnrecoverableErrorsInThisFunction()) 13028 DiscardCleanupsInEvaluationContext(); 13029 assert(!Cleanup.exprNeedsCleanups() && 13030 "cleanups within block not correctly bound!"); 13031 PopExpressionEvaluationContext(); 13032 13033 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13034 13035 if (BSI->HasImplicitReturnType) 13036 deduceClosureReturnType(*BSI); 13037 13038 PopDeclContext(); 13039 13040 QualType RetTy = Context.VoidTy; 13041 if (!BSI->ReturnType.isNull()) 13042 RetTy = BSI->ReturnType; 13043 13044 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13045 QualType BlockTy; 13046 13047 // Set the captured variables on the block. 13048 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13049 SmallVector<BlockDecl::Capture, 4> Captures; 13050 for (Capture &Cap : BSI->Captures) { 13051 if (Cap.isThisCapture()) 13052 continue; 13053 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13054 Cap.isNested(), Cap.getInitExpr()); 13055 Captures.push_back(NewCap); 13056 } 13057 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13058 13059 // If the user wrote a function type in some form, try to use that. 13060 if (!BSI->FunctionType.isNull()) { 13061 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13062 13063 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13064 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13065 13066 // Turn protoless block types into nullary block types. 13067 if (isa<FunctionNoProtoType>(FTy)) { 13068 FunctionProtoType::ExtProtoInfo EPI; 13069 EPI.ExtInfo = Ext; 13070 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13071 13072 // Otherwise, if we don't need to change anything about the function type, 13073 // preserve its sugar structure. 13074 } else if (FTy->getReturnType() == RetTy && 13075 (!NoReturn || FTy->getNoReturnAttr())) { 13076 BlockTy = BSI->FunctionType; 13077 13078 // Otherwise, make the minimal modifications to the function type. 13079 } else { 13080 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13081 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13082 EPI.TypeQuals = 0; // FIXME: silently? 13083 EPI.ExtInfo = Ext; 13084 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13085 } 13086 13087 // If we don't have a function type, just build one from nothing. 13088 } else { 13089 FunctionProtoType::ExtProtoInfo EPI; 13090 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13091 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13092 } 13093 13094 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13095 BlockTy = Context.getBlockPointerType(BlockTy); 13096 13097 // If needed, diagnose invalid gotos and switches in the block. 13098 if (getCurFunction()->NeedsScopeChecking() && 13099 !PP.isCodeCompletionEnabled()) 13100 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13101 13102 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13103 13104 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13105 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13106 13107 // Try to apply the named return value optimization. We have to check again 13108 // if we can do this, though, because blocks keep return statements around 13109 // to deduce an implicit return type. 13110 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13111 !BSI->TheDecl->isDependentContext()) 13112 computeNRVO(Body, BSI); 13113 13114 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13115 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13116 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13117 13118 // If the block isn't obviously global, i.e. it captures anything at 13119 // all, then we need to do a few things in the surrounding context: 13120 if (Result->getBlockDecl()->hasCaptures()) { 13121 // First, this expression has a new cleanup object. 13122 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13123 Cleanup.setExprNeedsCleanups(true); 13124 13125 // It also gets a branch-protected scope if any of the captured 13126 // variables needs destruction. 13127 for (const auto &CI : Result->getBlockDecl()->captures()) { 13128 const VarDecl *var = CI.getVariable(); 13129 if (var->getType().isDestructedType() != QualType::DK_none) { 13130 setFunctionHasBranchProtectedScope(); 13131 break; 13132 } 13133 } 13134 } 13135 13136 return Result; 13137 } 13138 13139 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13140 SourceLocation RPLoc) { 13141 TypeSourceInfo *TInfo; 13142 GetTypeFromParser(Ty, &TInfo); 13143 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13144 } 13145 13146 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13147 Expr *E, TypeSourceInfo *TInfo, 13148 SourceLocation RPLoc) { 13149 Expr *OrigExpr = E; 13150 bool IsMS = false; 13151 13152 // CUDA device code does not support varargs. 13153 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13154 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13155 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13156 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13157 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 13158 } 13159 } 13160 13161 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13162 // as Microsoft ABI on an actual Microsoft platform, where 13163 // __builtin_ms_va_list and __builtin_va_list are the same.) 13164 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13165 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13166 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13167 if (Context.hasSameType(MSVaListType, E->getType())) { 13168 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13169 return ExprError(); 13170 IsMS = true; 13171 } 13172 } 13173 13174 // Get the va_list type 13175 QualType VaListType = Context.getBuiltinVaListType(); 13176 if (!IsMS) { 13177 if (VaListType->isArrayType()) { 13178 // Deal with implicit array decay; for example, on x86-64, 13179 // va_list is an array, but it's supposed to decay to 13180 // a pointer for va_arg. 13181 VaListType = Context.getArrayDecayedType(VaListType); 13182 // Make sure the input expression also decays appropriately. 13183 ExprResult Result = UsualUnaryConversions(E); 13184 if (Result.isInvalid()) 13185 return ExprError(); 13186 E = Result.get(); 13187 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13188 // If va_list is a record type and we are compiling in C++ mode, 13189 // check the argument using reference binding. 13190 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13191 Context, Context.getLValueReferenceType(VaListType), false); 13192 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13193 if (Init.isInvalid()) 13194 return ExprError(); 13195 E = Init.getAs<Expr>(); 13196 } else { 13197 // Otherwise, the va_list argument must be an l-value because 13198 // it is modified by va_arg. 13199 if (!E->isTypeDependent() && 13200 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13201 return ExprError(); 13202 } 13203 } 13204 13205 if (!IsMS && !E->isTypeDependent() && 13206 !Context.hasSameType(VaListType, E->getType())) 13207 return ExprError(Diag(E->getLocStart(), 13208 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13209 << OrigExpr->getType() << E->getSourceRange()); 13210 13211 if (!TInfo->getType()->isDependentType()) { 13212 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13213 diag::err_second_parameter_to_va_arg_incomplete, 13214 TInfo->getTypeLoc())) 13215 return ExprError(); 13216 13217 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13218 TInfo->getType(), 13219 diag::err_second_parameter_to_va_arg_abstract, 13220 TInfo->getTypeLoc())) 13221 return ExprError(); 13222 13223 if (!TInfo->getType().isPODType(Context)) { 13224 Diag(TInfo->getTypeLoc().getBeginLoc(), 13225 TInfo->getType()->isObjCLifetimeType() 13226 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13227 : diag::warn_second_parameter_to_va_arg_not_pod) 13228 << TInfo->getType() 13229 << TInfo->getTypeLoc().getSourceRange(); 13230 } 13231 13232 // Check for va_arg where arguments of the given type will be promoted 13233 // (i.e. this va_arg is guaranteed to have undefined behavior). 13234 QualType PromoteType; 13235 if (TInfo->getType()->isPromotableIntegerType()) { 13236 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13237 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13238 PromoteType = QualType(); 13239 } 13240 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13241 PromoteType = Context.DoubleTy; 13242 if (!PromoteType.isNull()) 13243 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13244 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13245 << TInfo->getType() 13246 << PromoteType 13247 << TInfo->getTypeLoc().getSourceRange()); 13248 } 13249 13250 QualType T = TInfo->getType().getNonLValueExprType(Context); 13251 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13252 } 13253 13254 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13255 // The type of __null will be int or long, depending on the size of 13256 // pointers on the target. 13257 QualType Ty; 13258 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13259 if (pw == Context.getTargetInfo().getIntWidth()) 13260 Ty = Context.IntTy; 13261 else if (pw == Context.getTargetInfo().getLongWidth()) 13262 Ty = Context.LongTy; 13263 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13264 Ty = Context.LongLongTy; 13265 else { 13266 llvm_unreachable("I don't know size of pointer!"); 13267 } 13268 13269 return new (Context) GNUNullExpr(Ty, TokenLoc); 13270 } 13271 13272 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13273 bool Diagnose) { 13274 if (!getLangOpts().ObjC1) 13275 return false; 13276 13277 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13278 if (!PT) 13279 return false; 13280 13281 if (!PT->isObjCIdType()) { 13282 // Check if the destination is the 'NSString' interface. 13283 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13284 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13285 return false; 13286 } 13287 13288 // Ignore any parens, implicit casts (should only be 13289 // array-to-pointer decays), and not-so-opaque values. The last is 13290 // important for making this trigger for property assignments. 13291 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13292 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13293 if (OV->getSourceExpr()) 13294 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13295 13296 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13297 if (!SL || !SL->isAscii()) 13298 return false; 13299 if (Diagnose) { 13300 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 13301 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 13302 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 13303 } 13304 return true; 13305 } 13306 13307 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13308 const Expr *SrcExpr) { 13309 if (!DstType->isFunctionPointerType() || 13310 !SrcExpr->getType()->isFunctionType()) 13311 return false; 13312 13313 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13314 if (!DRE) 13315 return false; 13316 13317 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13318 if (!FD) 13319 return false; 13320 13321 return !S.checkAddressOfFunctionIsAvailable(FD, 13322 /*Complain=*/true, 13323 SrcExpr->getLocStart()); 13324 } 13325 13326 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13327 SourceLocation Loc, 13328 QualType DstType, QualType SrcType, 13329 Expr *SrcExpr, AssignmentAction Action, 13330 bool *Complained) { 13331 if (Complained) 13332 *Complained = false; 13333 13334 // Decode the result (notice that AST's are still created for extensions). 13335 bool CheckInferredResultType = false; 13336 bool isInvalid = false; 13337 unsigned DiagKind = 0; 13338 FixItHint Hint; 13339 ConversionFixItGenerator ConvHints; 13340 bool MayHaveConvFixit = false; 13341 bool MayHaveFunctionDiff = false; 13342 const ObjCInterfaceDecl *IFace = nullptr; 13343 const ObjCProtocolDecl *PDecl = nullptr; 13344 13345 switch (ConvTy) { 13346 case Compatible: 13347 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13348 return false; 13349 13350 case PointerToInt: 13351 DiagKind = diag::ext_typecheck_convert_pointer_int; 13352 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13353 MayHaveConvFixit = true; 13354 break; 13355 case IntToPointer: 13356 DiagKind = diag::ext_typecheck_convert_int_pointer; 13357 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13358 MayHaveConvFixit = true; 13359 break; 13360 case IncompatiblePointer: 13361 if (Action == AA_Passing_CFAudited) 13362 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13363 else if (SrcType->isFunctionPointerType() && 13364 DstType->isFunctionPointerType()) 13365 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13366 else 13367 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13368 13369 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13370 SrcType->isObjCObjectPointerType(); 13371 if (Hint.isNull() && !CheckInferredResultType) { 13372 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13373 } 13374 else if (CheckInferredResultType) { 13375 SrcType = SrcType.getUnqualifiedType(); 13376 DstType = DstType.getUnqualifiedType(); 13377 } 13378 MayHaveConvFixit = true; 13379 break; 13380 case IncompatiblePointerSign: 13381 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13382 break; 13383 case FunctionVoidPointer: 13384 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13385 break; 13386 case IncompatiblePointerDiscardsQualifiers: { 13387 // Perform array-to-pointer decay if necessary. 13388 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13389 13390 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13391 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13392 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13393 DiagKind = diag::err_typecheck_incompatible_address_space; 13394 break; 13395 13396 13397 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13398 DiagKind = diag::err_typecheck_incompatible_ownership; 13399 break; 13400 } 13401 13402 llvm_unreachable("unknown error case for discarding qualifiers!"); 13403 // fallthrough 13404 } 13405 case CompatiblePointerDiscardsQualifiers: 13406 // If the qualifiers lost were because we were applying the 13407 // (deprecated) C++ conversion from a string literal to a char* 13408 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13409 // Ideally, this check would be performed in 13410 // checkPointerTypesForAssignment. However, that would require a 13411 // bit of refactoring (so that the second argument is an 13412 // expression, rather than a type), which should be done as part 13413 // of a larger effort to fix checkPointerTypesForAssignment for 13414 // C++ semantics. 13415 if (getLangOpts().CPlusPlus && 13416 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13417 return false; 13418 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13419 break; 13420 case IncompatibleNestedPointerQualifiers: 13421 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13422 break; 13423 case IntToBlockPointer: 13424 DiagKind = diag::err_int_to_block_pointer; 13425 break; 13426 case IncompatibleBlockPointer: 13427 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13428 break; 13429 case IncompatibleObjCQualifiedId: { 13430 if (SrcType->isObjCQualifiedIdType()) { 13431 const ObjCObjectPointerType *srcOPT = 13432 SrcType->getAs<ObjCObjectPointerType>(); 13433 for (auto *srcProto : srcOPT->quals()) { 13434 PDecl = srcProto; 13435 break; 13436 } 13437 if (const ObjCInterfaceType *IFaceT = 13438 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13439 IFace = IFaceT->getDecl(); 13440 } 13441 else if (DstType->isObjCQualifiedIdType()) { 13442 const ObjCObjectPointerType *dstOPT = 13443 DstType->getAs<ObjCObjectPointerType>(); 13444 for (auto *dstProto : dstOPT->quals()) { 13445 PDecl = dstProto; 13446 break; 13447 } 13448 if (const ObjCInterfaceType *IFaceT = 13449 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13450 IFace = IFaceT->getDecl(); 13451 } 13452 DiagKind = diag::warn_incompatible_qualified_id; 13453 break; 13454 } 13455 case IncompatibleVectors: 13456 DiagKind = diag::warn_incompatible_vectors; 13457 break; 13458 case IncompatibleObjCWeakRef: 13459 DiagKind = diag::err_arc_weak_unavailable_assign; 13460 break; 13461 case Incompatible: 13462 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13463 if (Complained) 13464 *Complained = true; 13465 return true; 13466 } 13467 13468 DiagKind = diag::err_typecheck_convert_incompatible; 13469 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13470 MayHaveConvFixit = true; 13471 isInvalid = true; 13472 MayHaveFunctionDiff = true; 13473 break; 13474 } 13475 13476 QualType FirstType, SecondType; 13477 switch (Action) { 13478 case AA_Assigning: 13479 case AA_Initializing: 13480 // The destination type comes first. 13481 FirstType = DstType; 13482 SecondType = SrcType; 13483 break; 13484 13485 case AA_Returning: 13486 case AA_Passing: 13487 case AA_Passing_CFAudited: 13488 case AA_Converting: 13489 case AA_Sending: 13490 case AA_Casting: 13491 // The source type comes first. 13492 FirstType = SrcType; 13493 SecondType = DstType; 13494 break; 13495 } 13496 13497 PartialDiagnostic FDiag = PDiag(DiagKind); 13498 if (Action == AA_Passing_CFAudited) 13499 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13500 else 13501 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13502 13503 // If we can fix the conversion, suggest the FixIts. 13504 assert(ConvHints.isNull() || Hint.isNull()); 13505 if (!ConvHints.isNull()) { 13506 for (FixItHint &H : ConvHints.Hints) 13507 FDiag << H; 13508 } else { 13509 FDiag << Hint; 13510 } 13511 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13512 13513 if (MayHaveFunctionDiff) 13514 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13515 13516 Diag(Loc, FDiag); 13517 if (DiagKind == diag::warn_incompatible_qualified_id && 13518 PDecl && IFace && !IFace->hasDefinition()) 13519 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13520 << IFace << PDecl; 13521 13522 if (SecondType == Context.OverloadTy) 13523 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13524 FirstType, /*TakingAddress=*/true); 13525 13526 if (CheckInferredResultType) 13527 EmitRelatedResultTypeNote(SrcExpr); 13528 13529 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13530 EmitRelatedResultTypeNoteForReturn(DstType); 13531 13532 if (Complained) 13533 *Complained = true; 13534 return isInvalid; 13535 } 13536 13537 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13538 llvm::APSInt *Result) { 13539 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13540 public: 13541 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13542 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13543 } 13544 } Diagnoser; 13545 13546 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13547 } 13548 13549 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13550 llvm::APSInt *Result, 13551 unsigned DiagID, 13552 bool AllowFold) { 13553 class IDDiagnoser : public VerifyICEDiagnoser { 13554 unsigned DiagID; 13555 13556 public: 13557 IDDiagnoser(unsigned DiagID) 13558 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13559 13560 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13561 S.Diag(Loc, DiagID) << SR; 13562 } 13563 } Diagnoser(DiagID); 13564 13565 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13566 } 13567 13568 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13569 SourceRange SR) { 13570 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13571 } 13572 13573 ExprResult 13574 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13575 VerifyICEDiagnoser &Diagnoser, 13576 bool AllowFold) { 13577 SourceLocation DiagLoc = E->getLocStart(); 13578 13579 if (getLangOpts().CPlusPlus11) { 13580 // C++11 [expr.const]p5: 13581 // If an expression of literal class type is used in a context where an 13582 // integral constant expression is required, then that class type shall 13583 // have a single non-explicit conversion function to an integral or 13584 // unscoped enumeration type 13585 ExprResult Converted; 13586 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13587 public: 13588 CXX11ConvertDiagnoser(bool Silent) 13589 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13590 Silent, true) {} 13591 13592 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13593 QualType T) override { 13594 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13595 } 13596 13597 SemaDiagnosticBuilder diagnoseIncomplete( 13598 Sema &S, SourceLocation Loc, QualType T) override { 13599 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13600 } 13601 13602 SemaDiagnosticBuilder diagnoseExplicitConv( 13603 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13604 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13605 } 13606 13607 SemaDiagnosticBuilder noteExplicitConv( 13608 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13609 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13610 << ConvTy->isEnumeralType() << ConvTy; 13611 } 13612 13613 SemaDiagnosticBuilder diagnoseAmbiguous( 13614 Sema &S, SourceLocation Loc, QualType T) override { 13615 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13616 } 13617 13618 SemaDiagnosticBuilder noteAmbiguous( 13619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13620 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13621 << ConvTy->isEnumeralType() << ConvTy; 13622 } 13623 13624 SemaDiagnosticBuilder diagnoseConversion( 13625 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13626 llvm_unreachable("conversion functions are permitted"); 13627 } 13628 } ConvertDiagnoser(Diagnoser.Suppress); 13629 13630 Converted = PerformContextualImplicitConversion(DiagLoc, E, 13631 ConvertDiagnoser); 13632 if (Converted.isInvalid()) 13633 return Converted; 13634 E = Converted.get(); 13635 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 13636 return ExprError(); 13637 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 13638 // An ICE must be of integral or unscoped enumeration type. 13639 if (!Diagnoser.Suppress) 13640 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13641 return ExprError(); 13642 } 13643 13644 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 13645 // in the non-ICE case. 13646 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 13647 if (Result) 13648 *Result = E->EvaluateKnownConstInt(Context); 13649 return E; 13650 } 13651 13652 Expr::EvalResult EvalResult; 13653 SmallVector<PartialDiagnosticAt, 8> Notes; 13654 EvalResult.Diag = &Notes; 13655 13656 // Try to evaluate the expression, and produce diagnostics explaining why it's 13657 // not a constant expression as a side-effect. 13658 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 13659 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 13660 13661 // In C++11, we can rely on diagnostics being produced for any expression 13662 // which is not a constant expression. If no diagnostics were produced, then 13663 // this is a constant expression. 13664 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 13665 if (Result) 13666 *Result = EvalResult.Val.getInt(); 13667 return E; 13668 } 13669 13670 // If our only note is the usual "invalid subexpression" note, just point 13671 // the caret at its location rather than producing an essentially 13672 // redundant note. 13673 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13674 diag::note_invalid_subexpr_in_const_expr) { 13675 DiagLoc = Notes[0].first; 13676 Notes.clear(); 13677 } 13678 13679 if (!Folded || !AllowFold) { 13680 if (!Diagnoser.Suppress) { 13681 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 13682 for (const PartialDiagnosticAt &Note : Notes) 13683 Diag(Note.first, Note.second); 13684 } 13685 13686 return ExprError(); 13687 } 13688 13689 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 13690 for (const PartialDiagnosticAt &Note : Notes) 13691 Diag(Note.first, Note.second); 13692 13693 if (Result) 13694 *Result = EvalResult.Val.getInt(); 13695 return E; 13696 } 13697 13698 namespace { 13699 // Handle the case where we conclude a expression which we speculatively 13700 // considered to be unevaluated is actually evaluated. 13701 class TransformToPE : public TreeTransform<TransformToPE> { 13702 typedef TreeTransform<TransformToPE> BaseTransform; 13703 13704 public: 13705 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 13706 13707 // Make sure we redo semantic analysis 13708 bool AlwaysRebuild() { return true; } 13709 13710 // Make sure we handle LabelStmts correctly. 13711 // FIXME: This does the right thing, but maybe we need a more general 13712 // fix to TreeTransform? 13713 StmtResult TransformLabelStmt(LabelStmt *S) { 13714 S->getDecl()->setStmt(nullptr); 13715 return BaseTransform::TransformLabelStmt(S); 13716 } 13717 13718 // We need to special-case DeclRefExprs referring to FieldDecls which 13719 // are not part of a member pointer formation; normal TreeTransforming 13720 // doesn't catch this case because of the way we represent them in the AST. 13721 // FIXME: This is a bit ugly; is it really the best way to handle this 13722 // case? 13723 // 13724 // Error on DeclRefExprs referring to FieldDecls. 13725 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 13726 if (isa<FieldDecl>(E->getDecl()) && 13727 !SemaRef.isUnevaluatedContext()) 13728 return SemaRef.Diag(E->getLocation(), 13729 diag::err_invalid_non_static_member_use) 13730 << E->getDecl() << E->getSourceRange(); 13731 13732 return BaseTransform::TransformDeclRefExpr(E); 13733 } 13734 13735 // Exception: filter out member pointer formation 13736 ExprResult TransformUnaryOperator(UnaryOperator *E) { 13737 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 13738 return E; 13739 13740 return BaseTransform::TransformUnaryOperator(E); 13741 } 13742 13743 ExprResult TransformLambdaExpr(LambdaExpr *E) { 13744 // Lambdas never need to be transformed. 13745 return E; 13746 } 13747 }; 13748 } 13749 13750 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 13751 assert(isUnevaluatedContext() && 13752 "Should only transform unevaluated expressions"); 13753 ExprEvalContexts.back().Context = 13754 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 13755 if (isUnevaluatedContext()) 13756 return E; 13757 return TransformToPE(*this).TransformExpr(E); 13758 } 13759 13760 void 13761 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13762 Decl *LambdaContextDecl, 13763 bool IsDecltype) { 13764 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 13765 LambdaContextDecl, IsDecltype); 13766 Cleanup.reset(); 13767 if (!MaybeODRUseExprs.empty()) 13768 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 13769 } 13770 13771 void 13772 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 13773 ReuseLambdaContextDecl_t, 13774 bool IsDecltype) { 13775 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 13776 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 13777 } 13778 13779 void Sema::PopExpressionEvaluationContext() { 13780 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 13781 unsigned NumTypos = Rec.NumTypos; 13782 13783 if (!Rec.Lambdas.empty()) { 13784 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13785 unsigned D; 13786 if (Rec.isUnevaluated()) { 13787 // C++11 [expr.prim.lambda]p2: 13788 // A lambda-expression shall not appear in an unevaluated operand 13789 // (Clause 5). 13790 D = diag::err_lambda_unevaluated_operand; 13791 } else { 13792 // C++1y [expr.const]p2: 13793 // A conditional-expression e is a core constant expression unless the 13794 // evaluation of e, following the rules of the abstract machine, would 13795 // evaluate [...] a lambda-expression. 13796 D = diag::err_lambda_in_constant_expression; 13797 } 13798 13799 // C++1z allows lambda expressions as core constant expressions. 13800 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG 13801 // 1607) from appearing within template-arguments and array-bounds that 13802 // are part of function-signatures. Be mindful that P0315 (Lambdas in 13803 // unevaluated contexts) might lift some of these restrictions in a 13804 // future version. 13805 if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17) 13806 for (const auto *L : Rec.Lambdas) 13807 Diag(L->getLocStart(), D); 13808 } else { 13809 // Mark the capture expressions odr-used. This was deferred 13810 // during lambda expression creation. 13811 for (auto *Lambda : Rec.Lambdas) { 13812 for (auto *C : Lambda->capture_inits()) 13813 MarkDeclarationsReferencedInExpr(C); 13814 } 13815 } 13816 } 13817 13818 // When are coming out of an unevaluated context, clear out any 13819 // temporaries that we may have created as part of the evaluation of 13820 // the expression in that context: they aren't relevant because they 13821 // will never be constructed. 13822 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 13823 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 13824 ExprCleanupObjects.end()); 13825 Cleanup = Rec.ParentCleanup; 13826 CleanupVarDeclMarking(); 13827 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 13828 // Otherwise, merge the contexts together. 13829 } else { 13830 Cleanup.mergeFrom(Rec.ParentCleanup); 13831 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 13832 Rec.SavedMaybeODRUseExprs.end()); 13833 } 13834 13835 // Pop the current expression evaluation context off the stack. 13836 ExprEvalContexts.pop_back(); 13837 13838 if (!ExprEvalContexts.empty()) 13839 ExprEvalContexts.back().NumTypos += NumTypos; 13840 else 13841 assert(NumTypos == 0 && "There are outstanding typos after popping the " 13842 "last ExpressionEvaluationContextRecord"); 13843 } 13844 13845 void Sema::DiscardCleanupsInEvaluationContext() { 13846 ExprCleanupObjects.erase( 13847 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 13848 ExprCleanupObjects.end()); 13849 Cleanup.reset(); 13850 MaybeODRUseExprs.clear(); 13851 } 13852 13853 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 13854 if (!E->getType()->isVariablyModifiedType()) 13855 return E; 13856 return TransformToPotentiallyEvaluated(E); 13857 } 13858 13859 /// Are we within a context in which some evaluation could be performed (be it 13860 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 13861 /// captured by C++'s idea of an "unevaluated context". 13862 static bool isEvaluatableContext(Sema &SemaRef) { 13863 switch (SemaRef.ExprEvalContexts.back().Context) { 13864 case Sema::ExpressionEvaluationContext::Unevaluated: 13865 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13866 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13867 // Expressions in this context are never evaluated. 13868 return false; 13869 13870 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13871 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13872 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13873 // Expressions in this context could be evaluated. 13874 return true; 13875 13876 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13877 // Referenced declarations will only be used if the construct in the 13878 // containing expression is used, at which point we'll be given another 13879 // turn to mark them. 13880 return false; 13881 } 13882 llvm_unreachable("Invalid context"); 13883 } 13884 13885 /// Are we within a context in which references to resolved functions or to 13886 /// variables result in odr-use? 13887 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 13888 // An expression in a template is not really an expression until it's been 13889 // instantiated, so it doesn't trigger odr-use. 13890 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 13891 return false; 13892 13893 switch (SemaRef.ExprEvalContexts.back().Context) { 13894 case Sema::ExpressionEvaluationContext::Unevaluated: 13895 case Sema::ExpressionEvaluationContext::UnevaluatedList: 13896 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 13897 case Sema::ExpressionEvaluationContext::DiscardedStatement: 13898 return false; 13899 13900 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 13901 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 13902 return true; 13903 13904 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 13905 return false; 13906 } 13907 llvm_unreachable("Invalid context"); 13908 } 13909 13910 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 13911 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 13912 return Func->isConstexpr() && 13913 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 13914 } 13915 13916 /// \brief Mark a function referenced, and check whether it is odr-used 13917 /// (C++ [basic.def.odr]p2, C99 6.9p3) 13918 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 13919 bool MightBeOdrUse) { 13920 assert(Func && "No function?"); 13921 13922 Func->setReferenced(); 13923 13924 // C++11 [basic.def.odr]p3: 13925 // A function whose name appears as a potentially-evaluated expression is 13926 // odr-used if it is the unique lookup result or the selected member of a 13927 // set of overloaded functions [...]. 13928 // 13929 // We (incorrectly) mark overload resolution as an unevaluated context, so we 13930 // can just check that here. 13931 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 13932 13933 // Determine whether we require a function definition to exist, per 13934 // C++11 [temp.inst]p3: 13935 // Unless a function template specialization has been explicitly 13936 // instantiated or explicitly specialized, the function template 13937 // specialization is implicitly instantiated when the specialization is 13938 // referenced in a context that requires a function definition to exist. 13939 // 13940 // That is either when this is an odr-use, or when a usage of a constexpr 13941 // function occurs within an evaluatable context. 13942 bool NeedDefinition = 13943 OdrUse || (isEvaluatableContext(*this) && 13944 isImplicitlyDefinableConstexprFunction(Func)); 13945 13946 // C++14 [temp.expl.spec]p6: 13947 // If a template [...] is explicitly specialized then that specialization 13948 // shall be declared before the first use of that specialization that would 13949 // cause an implicit instantiation to take place, in every translation unit 13950 // in which such a use occurs 13951 if (NeedDefinition && 13952 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 13953 Func->getMemberSpecializationInfo())) 13954 checkSpecializationVisibility(Loc, Func); 13955 13956 // C++14 [except.spec]p17: 13957 // An exception-specification is considered to be needed when: 13958 // - the function is odr-used or, if it appears in an unevaluated operand, 13959 // would be odr-used if the expression were potentially-evaluated; 13960 // 13961 // Note, we do this even if MightBeOdrUse is false. That indicates that the 13962 // function is a pure virtual function we're calling, and in that case the 13963 // function was selected by overload resolution and we need to resolve its 13964 // exception specification for a different reason. 13965 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 13966 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 13967 ResolveExceptionSpec(Loc, FPT); 13968 13969 // If we don't need to mark the function as used, and we don't need to 13970 // try to provide a definition, there's nothing more to do. 13971 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 13972 (!NeedDefinition || Func->getBody())) 13973 return; 13974 13975 // Note that this declaration has been used. 13976 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 13977 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 13978 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 13979 if (Constructor->isDefaultConstructor()) { 13980 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 13981 return; 13982 DefineImplicitDefaultConstructor(Loc, Constructor); 13983 } else if (Constructor->isCopyConstructor()) { 13984 DefineImplicitCopyConstructor(Loc, Constructor); 13985 } else if (Constructor->isMoveConstructor()) { 13986 DefineImplicitMoveConstructor(Loc, Constructor); 13987 } 13988 } else if (Constructor->getInheritedConstructor()) { 13989 DefineInheritingConstructor(Loc, Constructor); 13990 } 13991 } else if (CXXDestructorDecl *Destructor = 13992 dyn_cast<CXXDestructorDecl>(Func)) { 13993 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 13994 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 13995 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 13996 return; 13997 DefineImplicitDestructor(Loc, Destructor); 13998 } 13999 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14000 MarkVTableUsed(Loc, Destructor->getParent()); 14001 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14002 if (MethodDecl->isOverloadedOperator() && 14003 MethodDecl->getOverloadedOperator() == OO_Equal) { 14004 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14005 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14006 if (MethodDecl->isCopyAssignmentOperator()) 14007 DefineImplicitCopyAssignment(Loc, MethodDecl); 14008 else if (MethodDecl->isMoveAssignmentOperator()) 14009 DefineImplicitMoveAssignment(Loc, MethodDecl); 14010 } 14011 } else if (isa<CXXConversionDecl>(MethodDecl) && 14012 MethodDecl->getParent()->isLambda()) { 14013 CXXConversionDecl *Conversion = 14014 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14015 if (Conversion->isLambdaToBlockPointerConversion()) 14016 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14017 else 14018 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14019 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14020 MarkVTableUsed(Loc, MethodDecl->getParent()); 14021 } 14022 14023 // Recursive functions should be marked when used from another function. 14024 // FIXME: Is this really right? 14025 if (CurContext == Func) return; 14026 14027 // Implicit instantiation of function templates and member functions of 14028 // class templates. 14029 if (Func->isImplicitlyInstantiable()) { 14030 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14031 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14032 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14033 if (FirstInstantiation) { 14034 PointOfInstantiation = Loc; 14035 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14036 } else if (TSK != TSK_ImplicitInstantiation) { 14037 // Use the point of use as the point of instantiation, instead of the 14038 // point of explicit instantiation (which we track as the actual point of 14039 // instantiation). This gives better backtraces in diagnostics. 14040 PointOfInstantiation = Loc; 14041 } 14042 14043 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14044 Func->isConstexpr()) { 14045 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14046 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14047 CodeSynthesisContexts.size()) 14048 PendingLocalImplicitInstantiations.push_back( 14049 std::make_pair(Func, PointOfInstantiation)); 14050 else if (Func->isConstexpr()) 14051 // Do not defer instantiations of constexpr functions, to avoid the 14052 // expression evaluator needing to call back into Sema if it sees a 14053 // call to such a function. 14054 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14055 else { 14056 Func->setInstantiationIsPending(true); 14057 PendingInstantiations.push_back(std::make_pair(Func, 14058 PointOfInstantiation)); 14059 // Notify the consumer that a function was implicitly instantiated. 14060 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14061 } 14062 } 14063 } else { 14064 // Walk redefinitions, as some of them may be instantiable. 14065 for (auto i : Func->redecls()) { 14066 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14067 MarkFunctionReferenced(Loc, i, OdrUse); 14068 } 14069 } 14070 14071 if (!OdrUse) return; 14072 14073 // Keep track of used but undefined functions. 14074 if (!Func->isDefined()) { 14075 if (mightHaveNonExternalLinkage(Func)) 14076 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14077 else if (Func->getMostRecentDecl()->isInlined() && 14078 !LangOpts.GNUInline && 14079 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14080 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14081 else if (isExternalWithNoLinkageType(Func)) 14082 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14083 } 14084 14085 Func->markUsed(Context); 14086 } 14087 14088 static void 14089 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14090 ValueDecl *var, DeclContext *DC) { 14091 DeclContext *VarDC = var->getDeclContext(); 14092 14093 // If the parameter still belongs to the translation unit, then 14094 // we're actually just using one parameter in the declaration of 14095 // the next. 14096 if (isa<ParmVarDecl>(var) && 14097 isa<TranslationUnitDecl>(VarDC)) 14098 return; 14099 14100 // For C code, don't diagnose about capture if we're not actually in code 14101 // right now; it's impossible to write a non-constant expression outside of 14102 // function context, so we'll get other (more useful) diagnostics later. 14103 // 14104 // For C++, things get a bit more nasty... it would be nice to suppress this 14105 // diagnostic for certain cases like using a local variable in an array bound 14106 // for a member of a local class, but the correct predicate is not obvious. 14107 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14108 return; 14109 14110 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14111 unsigned ContextKind = 3; // unknown 14112 if (isa<CXXMethodDecl>(VarDC) && 14113 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14114 ContextKind = 2; 14115 } else if (isa<FunctionDecl>(VarDC)) { 14116 ContextKind = 0; 14117 } else if (isa<BlockDecl>(VarDC)) { 14118 ContextKind = 1; 14119 } 14120 14121 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14122 << var << ValueKind << ContextKind << VarDC; 14123 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14124 << var; 14125 14126 // FIXME: Add additional diagnostic info about class etc. which prevents 14127 // capture. 14128 } 14129 14130 14131 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14132 bool &SubCapturesAreNested, 14133 QualType &CaptureType, 14134 QualType &DeclRefType) { 14135 // Check whether we've already captured it. 14136 if (CSI->CaptureMap.count(Var)) { 14137 // If we found a capture, any subcaptures are nested. 14138 SubCapturesAreNested = true; 14139 14140 // Retrieve the capture type for this variable. 14141 CaptureType = CSI->getCapture(Var).getCaptureType(); 14142 14143 // Compute the type of an expression that refers to this variable. 14144 DeclRefType = CaptureType.getNonReferenceType(); 14145 14146 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14147 // are mutable in the sense that user can change their value - they are 14148 // private instances of the captured declarations. 14149 const Capture &Cap = CSI->getCapture(Var); 14150 if (Cap.isCopyCapture() && 14151 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14152 !(isa<CapturedRegionScopeInfo>(CSI) && 14153 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14154 DeclRefType.addConst(); 14155 return true; 14156 } 14157 return false; 14158 } 14159 14160 // Only block literals, captured statements, and lambda expressions can 14161 // capture; other scopes don't work. 14162 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14163 SourceLocation Loc, 14164 const bool Diagnose, Sema &S) { 14165 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14166 return getLambdaAwareParentOfDeclContext(DC); 14167 else if (Var->hasLocalStorage()) { 14168 if (Diagnose) 14169 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14170 } 14171 return nullptr; 14172 } 14173 14174 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14175 // certain types of variables (unnamed, variably modified types etc.) 14176 // so check for eligibility. 14177 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14178 SourceLocation Loc, 14179 const bool Diagnose, Sema &S) { 14180 14181 bool IsBlock = isa<BlockScopeInfo>(CSI); 14182 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14183 14184 // Lambdas are not allowed to capture unnamed variables 14185 // (e.g. anonymous unions). 14186 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14187 // assuming that's the intent. 14188 if (IsLambda && !Var->getDeclName()) { 14189 if (Diagnose) { 14190 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14191 S.Diag(Var->getLocation(), diag::note_declared_at); 14192 } 14193 return false; 14194 } 14195 14196 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14197 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14198 if (Diagnose) { 14199 S.Diag(Loc, diag::err_ref_vm_type); 14200 S.Diag(Var->getLocation(), diag::note_previous_decl) 14201 << Var->getDeclName(); 14202 } 14203 return false; 14204 } 14205 // Prohibit structs with flexible array members too. 14206 // We cannot capture what is in the tail end of the struct. 14207 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14208 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14209 if (Diagnose) { 14210 if (IsBlock) 14211 S.Diag(Loc, diag::err_ref_flexarray_type); 14212 else 14213 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14214 << Var->getDeclName(); 14215 S.Diag(Var->getLocation(), diag::note_previous_decl) 14216 << Var->getDeclName(); 14217 } 14218 return false; 14219 } 14220 } 14221 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14222 // Lambdas and captured statements are not allowed to capture __block 14223 // variables; they don't support the expected semantics. 14224 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14225 if (Diagnose) { 14226 S.Diag(Loc, diag::err_capture_block_variable) 14227 << Var->getDeclName() << !IsLambda; 14228 S.Diag(Var->getLocation(), diag::note_previous_decl) 14229 << Var->getDeclName(); 14230 } 14231 return false; 14232 } 14233 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14234 if (S.getLangOpts().OpenCL && IsBlock && 14235 Var->getType()->isBlockPointerType()) { 14236 if (Diagnose) 14237 S.Diag(Loc, diag::err_opencl_block_ref_block); 14238 return false; 14239 } 14240 14241 return true; 14242 } 14243 14244 // Returns true if the capture by block was successful. 14245 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14246 SourceLocation Loc, 14247 const bool BuildAndDiagnose, 14248 QualType &CaptureType, 14249 QualType &DeclRefType, 14250 const bool Nested, 14251 Sema &S) { 14252 Expr *CopyExpr = nullptr; 14253 bool ByRef = false; 14254 14255 // Blocks are not allowed to capture arrays. 14256 if (CaptureType->isArrayType()) { 14257 if (BuildAndDiagnose) { 14258 S.Diag(Loc, diag::err_ref_array_type); 14259 S.Diag(Var->getLocation(), diag::note_previous_decl) 14260 << Var->getDeclName(); 14261 } 14262 return false; 14263 } 14264 14265 // Forbid the block-capture of autoreleasing variables. 14266 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14267 if (BuildAndDiagnose) { 14268 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14269 << /*block*/ 0; 14270 S.Diag(Var->getLocation(), diag::note_previous_decl) 14271 << Var->getDeclName(); 14272 } 14273 return false; 14274 } 14275 14276 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14277 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14278 // This function finds out whether there is an AttributedType of kind 14279 // attr_objc_ownership in Ty. The existence of AttributedType of kind 14280 // attr_objc_ownership implies __autoreleasing was explicitly specified 14281 // rather than being added implicitly by the compiler. 14282 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14283 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14284 if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership) 14285 return true; 14286 14287 // Peel off AttributedTypes that are not of kind objc_ownership. 14288 Ty = AttrTy->getModifiedType(); 14289 } 14290 14291 return false; 14292 }; 14293 14294 QualType PointeeTy = PT->getPointeeType(); 14295 14296 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14297 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14298 !IsObjCOwnershipAttributedType(PointeeTy)) { 14299 if (BuildAndDiagnose) { 14300 SourceLocation VarLoc = Var->getLocation(); 14301 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14302 { 14303 auto AddAutoreleaseNote = 14304 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing); 14305 // Provide a fix-it for the '__autoreleasing' keyword at the 14306 // appropriate location in the variable's type. 14307 if (const auto *TSI = Var->getTypeSourceInfo()) { 14308 PointerTypeLoc PTL = 14309 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>(); 14310 if (PTL) { 14311 SourceLocation Loc = PTL.getPointeeLoc().getEndLoc(); 14312 Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(), 14313 S.getLangOpts()); 14314 if (Loc.isValid()) { 14315 StringRef CharAtLoc = Lexer::getSourceText( 14316 CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)), 14317 S.getSourceManager(), S.getLangOpts()); 14318 AddAutoreleaseNote << FixItHint::CreateInsertion( 14319 Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0]) 14320 ? " __autoreleasing " 14321 : " __autoreleasing"); 14322 } 14323 } 14324 } 14325 } 14326 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14327 } 14328 } 14329 } 14330 14331 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14332 if (HasBlocksAttr || CaptureType->isReferenceType() || 14333 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) { 14334 // Block capture by reference does not change the capture or 14335 // declaration reference types. 14336 ByRef = true; 14337 } else { 14338 // Block capture by copy introduces 'const'. 14339 CaptureType = CaptureType.getNonReferenceType().withConst(); 14340 DeclRefType = CaptureType; 14341 14342 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14343 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14344 // The capture logic needs the destructor, so make sure we mark it. 14345 // Usually this is unnecessary because most local variables have 14346 // their destructors marked at declaration time, but parameters are 14347 // an exception because it's technically only the call site that 14348 // actually requires the destructor. 14349 if (isa<ParmVarDecl>(Var)) 14350 S.FinalizeVarWithDestructor(Var, Record); 14351 14352 // Enter a new evaluation context to insulate the copy 14353 // full-expression. 14354 EnterExpressionEvaluationContext scope( 14355 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14356 14357 // According to the blocks spec, the capture of a variable from 14358 // the stack requires a const copy constructor. This is not true 14359 // of the copy/move done to move a __block variable to the heap. 14360 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14361 DeclRefType.withConst(), 14362 VK_LValue, Loc); 14363 14364 ExprResult Result 14365 = S.PerformCopyInitialization( 14366 InitializedEntity::InitializeBlock(Var->getLocation(), 14367 CaptureType, false), 14368 Loc, DeclRef); 14369 14370 // Build a full-expression copy expression if initialization 14371 // succeeded and used a non-trivial constructor. Recover from 14372 // errors by pretending that the copy isn't necessary. 14373 if (!Result.isInvalid() && 14374 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14375 ->isTrivial()) { 14376 Result = S.MaybeCreateExprWithCleanups(Result); 14377 CopyExpr = Result.get(); 14378 } 14379 } 14380 } 14381 } 14382 14383 // Actually capture the variable. 14384 if (BuildAndDiagnose) 14385 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14386 SourceLocation(), CaptureType, CopyExpr); 14387 14388 return true; 14389 14390 } 14391 14392 14393 /// \brief Capture the given variable in the captured region. 14394 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14395 VarDecl *Var, 14396 SourceLocation Loc, 14397 const bool BuildAndDiagnose, 14398 QualType &CaptureType, 14399 QualType &DeclRefType, 14400 const bool RefersToCapturedVariable, 14401 Sema &S) { 14402 // By default, capture variables by reference. 14403 bool ByRef = true; 14404 // Using an LValue reference type is consistent with Lambdas (see below). 14405 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14406 if (S.IsOpenMPCapturedDecl(Var)) { 14407 bool HasConst = DeclRefType.isConstQualified(); 14408 DeclRefType = DeclRefType.getUnqualifiedType(); 14409 // Don't lose diagnostics about assignments to const. 14410 if (HasConst) 14411 DeclRefType.addConst(); 14412 } 14413 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14414 } 14415 14416 if (ByRef) 14417 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14418 else 14419 CaptureType = DeclRefType; 14420 14421 Expr *CopyExpr = nullptr; 14422 if (BuildAndDiagnose) { 14423 // The current implementation assumes that all variables are captured 14424 // by references. Since there is no capture by copy, no expression 14425 // evaluation will be needed. 14426 RecordDecl *RD = RSI->TheRecordDecl; 14427 14428 FieldDecl *Field 14429 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14430 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14431 nullptr, false, ICIS_NoInit); 14432 Field->setImplicit(true); 14433 Field->setAccess(AS_private); 14434 RD->addDecl(Field); 14435 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14436 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14437 14438 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14439 DeclRefType, VK_LValue, Loc); 14440 Var->setReferenced(true); 14441 Var->markUsed(S.Context); 14442 } 14443 14444 // Actually capture the variable. 14445 if (BuildAndDiagnose) 14446 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14447 SourceLocation(), CaptureType, CopyExpr); 14448 14449 14450 return true; 14451 } 14452 14453 /// \brief Create a field within the lambda class for the variable 14454 /// being captured. 14455 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14456 QualType FieldType, QualType DeclRefType, 14457 SourceLocation Loc, 14458 bool RefersToCapturedVariable) { 14459 CXXRecordDecl *Lambda = LSI->Lambda; 14460 14461 // Build the non-static data member. 14462 FieldDecl *Field 14463 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14464 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14465 nullptr, false, ICIS_NoInit); 14466 Field->setImplicit(true); 14467 Field->setAccess(AS_private); 14468 Lambda->addDecl(Field); 14469 } 14470 14471 /// \brief Capture the given variable in the lambda. 14472 static bool captureInLambda(LambdaScopeInfo *LSI, 14473 VarDecl *Var, 14474 SourceLocation Loc, 14475 const bool BuildAndDiagnose, 14476 QualType &CaptureType, 14477 QualType &DeclRefType, 14478 const bool RefersToCapturedVariable, 14479 const Sema::TryCaptureKind Kind, 14480 SourceLocation EllipsisLoc, 14481 const bool IsTopScope, 14482 Sema &S) { 14483 14484 // Determine whether we are capturing by reference or by value. 14485 bool ByRef = false; 14486 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14487 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14488 } else { 14489 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14490 } 14491 14492 // Compute the type of the field that will capture this variable. 14493 if (ByRef) { 14494 // C++11 [expr.prim.lambda]p15: 14495 // An entity is captured by reference if it is implicitly or 14496 // explicitly captured but not captured by copy. It is 14497 // unspecified whether additional unnamed non-static data 14498 // members are declared in the closure type for entities 14499 // captured by reference. 14500 // 14501 // FIXME: It is not clear whether we want to build an lvalue reference 14502 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14503 // to do the former, while EDG does the latter. Core issue 1249 will 14504 // clarify, but for now we follow GCC because it's a more permissive and 14505 // easily defensible position. 14506 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14507 } else { 14508 // C++11 [expr.prim.lambda]p14: 14509 // For each entity captured by copy, an unnamed non-static 14510 // data member is declared in the closure type. The 14511 // declaration order of these members is unspecified. The type 14512 // of such a data member is the type of the corresponding 14513 // captured entity if the entity is not a reference to an 14514 // object, or the referenced type otherwise. [Note: If the 14515 // captured entity is a reference to a function, the 14516 // corresponding data member is also a reference to a 14517 // function. - end note ] 14518 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14519 if (!RefType->getPointeeType()->isFunctionType()) 14520 CaptureType = RefType->getPointeeType(); 14521 } 14522 14523 // Forbid the lambda copy-capture of autoreleasing variables. 14524 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14525 if (BuildAndDiagnose) { 14526 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14527 S.Diag(Var->getLocation(), diag::note_previous_decl) 14528 << Var->getDeclName(); 14529 } 14530 return false; 14531 } 14532 14533 // Make sure that by-copy captures are of a complete and non-abstract type. 14534 if (BuildAndDiagnose) { 14535 if (!CaptureType->isDependentType() && 14536 S.RequireCompleteType(Loc, CaptureType, 14537 diag::err_capture_of_incomplete_type, 14538 Var->getDeclName())) 14539 return false; 14540 14541 if (S.RequireNonAbstractType(Loc, CaptureType, 14542 diag::err_capture_of_abstract_type)) 14543 return false; 14544 } 14545 } 14546 14547 // Capture this variable in the lambda. 14548 if (BuildAndDiagnose) 14549 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14550 RefersToCapturedVariable); 14551 14552 // Compute the type of a reference to this captured variable. 14553 if (ByRef) 14554 DeclRefType = CaptureType.getNonReferenceType(); 14555 else { 14556 // C++ [expr.prim.lambda]p5: 14557 // The closure type for a lambda-expression has a public inline 14558 // function call operator [...]. This function call operator is 14559 // declared const (9.3.1) if and only if the lambda-expression's 14560 // parameter-declaration-clause is not followed by mutable. 14561 DeclRefType = CaptureType.getNonReferenceType(); 14562 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14563 DeclRefType.addConst(); 14564 } 14565 14566 // Add the capture. 14567 if (BuildAndDiagnose) 14568 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14569 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14570 14571 return true; 14572 } 14573 14574 bool Sema::tryCaptureVariable( 14575 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14576 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14577 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14578 // An init-capture is notionally from the context surrounding its 14579 // declaration, but its parent DC is the lambda class. 14580 DeclContext *VarDC = Var->getDeclContext(); 14581 if (Var->isInitCapture()) 14582 VarDC = VarDC->getParent(); 14583 14584 DeclContext *DC = CurContext; 14585 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14586 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14587 // We need to sync up the Declaration Context with the 14588 // FunctionScopeIndexToStopAt 14589 if (FunctionScopeIndexToStopAt) { 14590 unsigned FSIndex = FunctionScopes.size() - 1; 14591 while (FSIndex != MaxFunctionScopesIndex) { 14592 DC = getLambdaAwareParentOfDeclContext(DC); 14593 --FSIndex; 14594 } 14595 } 14596 14597 14598 // If the variable is declared in the current context, there is no need to 14599 // capture it. 14600 if (VarDC == DC) return true; 14601 14602 // Capture global variables if it is required to use private copy of this 14603 // variable. 14604 bool IsGlobal = !Var->hasLocalStorage(); 14605 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 14606 return true; 14607 Var = Var->getCanonicalDecl(); 14608 14609 // Walk up the stack to determine whether we can capture the variable, 14610 // performing the "simple" checks that don't depend on type. We stop when 14611 // we've either hit the declared scope of the variable or find an existing 14612 // capture of that variable. We start from the innermost capturing-entity 14613 // (the DC) and ensure that all intervening capturing-entities 14614 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14615 // declcontext can either capture the variable or have already captured 14616 // the variable. 14617 CaptureType = Var->getType(); 14618 DeclRefType = CaptureType.getNonReferenceType(); 14619 bool Nested = false; 14620 bool Explicit = (Kind != TryCapture_Implicit); 14621 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14622 do { 14623 // Only block literals, captured statements, and lambda expressions can 14624 // capture; other scopes don't work. 14625 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14626 ExprLoc, 14627 BuildAndDiagnose, 14628 *this); 14629 // We need to check for the parent *first* because, if we *have* 14630 // private-captured a global variable, we need to recursively capture it in 14631 // intermediate blocks, lambdas, etc. 14632 if (!ParentDC) { 14633 if (IsGlobal) { 14634 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14635 break; 14636 } 14637 return true; 14638 } 14639 14640 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14641 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14642 14643 14644 // Check whether we've already captured it. 14645 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14646 DeclRefType)) { 14647 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14648 break; 14649 } 14650 // If we are instantiating a generic lambda call operator body, 14651 // we do not want to capture new variables. What was captured 14652 // during either a lambdas transformation or initial parsing 14653 // should be used. 14654 if (isGenericLambdaCallOperatorSpecialization(DC)) { 14655 if (BuildAndDiagnose) { 14656 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14657 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 14658 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14659 Diag(Var->getLocation(), diag::note_previous_decl) 14660 << Var->getDeclName(); 14661 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 14662 } else 14663 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 14664 } 14665 return true; 14666 } 14667 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14668 // certain types of variables (unnamed, variably modified types etc.) 14669 // so check for eligibility. 14670 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 14671 return true; 14672 14673 // Try to capture variable-length arrays types. 14674 if (Var->getType()->isVariablyModifiedType()) { 14675 // We're going to walk down into the type and look for VLA 14676 // expressions. 14677 QualType QTy = Var->getType(); 14678 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 14679 QTy = PVD->getOriginalType(); 14680 captureVariablyModifiedType(Context, QTy, CSI); 14681 } 14682 14683 if (getLangOpts().OpenMP) { 14684 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14685 // OpenMP private variables should not be captured in outer scope, so 14686 // just break here. Similarly, global variables that are captured in a 14687 // target region should not be captured outside the scope of the region. 14688 if (RSI->CapRegionKind == CR_OpenMP) { 14689 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 14690 auto IsTargetCap = !IsOpenMPPrivateDecl && 14691 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 14692 // When we detect target captures we are looking from inside the 14693 // target region, therefore we need to propagate the capture from the 14694 // enclosing region. Therefore, the capture is not initially nested. 14695 if (IsTargetCap) 14696 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 14697 14698 if (IsTargetCap || IsOpenMPPrivateDecl) { 14699 Nested = !IsTargetCap; 14700 DeclRefType = DeclRefType.getUnqualifiedType(); 14701 CaptureType = Context.getLValueReferenceType(DeclRefType); 14702 break; 14703 } 14704 } 14705 } 14706 } 14707 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 14708 // No capture-default, and this is not an explicit capture 14709 // so cannot capture this variable. 14710 if (BuildAndDiagnose) { 14711 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 14712 Diag(Var->getLocation(), diag::note_previous_decl) 14713 << Var->getDeclName(); 14714 if (cast<LambdaScopeInfo>(CSI)->Lambda) 14715 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 14716 diag::note_lambda_decl); 14717 // FIXME: If we error out because an outer lambda can not implicitly 14718 // capture a variable that an inner lambda explicitly captures, we 14719 // should have the inner lambda do the explicit capture - because 14720 // it makes for cleaner diagnostics later. This would purely be done 14721 // so that the diagnostic does not misleadingly claim that a variable 14722 // can not be captured by a lambda implicitly even though it is captured 14723 // explicitly. Suggestion: 14724 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 14725 // at the function head 14726 // - cache the StartingDeclContext - this must be a lambda 14727 // - captureInLambda in the innermost lambda the variable. 14728 } 14729 return true; 14730 } 14731 14732 FunctionScopesIndex--; 14733 DC = ParentDC; 14734 Explicit = false; 14735 } while (!VarDC->Equals(DC)); 14736 14737 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 14738 // computing the type of the capture at each step, checking type-specific 14739 // requirements, and adding captures if requested. 14740 // If the variable had already been captured previously, we start capturing 14741 // at the lambda nested within that one. 14742 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 14743 ++I) { 14744 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 14745 14746 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 14747 if (!captureInBlock(BSI, Var, ExprLoc, 14748 BuildAndDiagnose, CaptureType, 14749 DeclRefType, Nested, *this)) 14750 return true; 14751 Nested = true; 14752 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 14753 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 14754 BuildAndDiagnose, CaptureType, 14755 DeclRefType, Nested, *this)) 14756 return true; 14757 Nested = true; 14758 } else { 14759 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 14760 if (!captureInLambda(LSI, Var, ExprLoc, 14761 BuildAndDiagnose, CaptureType, 14762 DeclRefType, Nested, Kind, EllipsisLoc, 14763 /*IsTopScope*/I == N - 1, *this)) 14764 return true; 14765 Nested = true; 14766 } 14767 } 14768 return false; 14769 } 14770 14771 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 14772 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 14773 QualType CaptureType; 14774 QualType DeclRefType; 14775 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 14776 /*BuildAndDiagnose=*/true, CaptureType, 14777 DeclRefType, nullptr); 14778 } 14779 14780 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 14781 QualType CaptureType; 14782 QualType DeclRefType; 14783 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14784 /*BuildAndDiagnose=*/false, CaptureType, 14785 DeclRefType, nullptr); 14786 } 14787 14788 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 14789 QualType CaptureType; 14790 QualType DeclRefType; 14791 14792 // Determine whether we can capture this variable. 14793 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 14794 /*BuildAndDiagnose=*/false, CaptureType, 14795 DeclRefType, nullptr)) 14796 return QualType(); 14797 14798 return DeclRefType; 14799 } 14800 14801 14802 14803 // If either the type of the variable or the initializer is dependent, 14804 // return false. Otherwise, determine whether the variable is a constant 14805 // expression. Use this if you need to know if a variable that might or 14806 // might not be dependent is truly a constant expression. 14807 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 14808 ASTContext &Context) { 14809 14810 if (Var->getType()->isDependentType()) 14811 return false; 14812 const VarDecl *DefVD = nullptr; 14813 Var->getAnyInitializer(DefVD); 14814 if (!DefVD) 14815 return false; 14816 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 14817 Expr *Init = cast<Expr>(Eval->Value); 14818 if (Init->isValueDependent()) 14819 return false; 14820 return IsVariableAConstantExpression(Var, Context); 14821 } 14822 14823 14824 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 14825 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 14826 // an object that satisfies the requirements for appearing in a 14827 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 14828 // is immediately applied." This function handles the lvalue-to-rvalue 14829 // conversion part. 14830 MaybeODRUseExprs.erase(E->IgnoreParens()); 14831 14832 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 14833 // to a variable that is a constant expression, and if so, identify it as 14834 // a reference to a variable that does not involve an odr-use of that 14835 // variable. 14836 if (LambdaScopeInfo *LSI = getCurLambda()) { 14837 Expr *SansParensExpr = E->IgnoreParens(); 14838 VarDecl *Var = nullptr; 14839 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 14840 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 14841 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 14842 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 14843 14844 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 14845 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 14846 } 14847 } 14848 14849 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 14850 Res = CorrectDelayedTyposInExpr(Res); 14851 14852 if (!Res.isUsable()) 14853 return Res; 14854 14855 // If a constant-expression is a reference to a variable where we delay 14856 // deciding whether it is an odr-use, just assume we will apply the 14857 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 14858 // (a non-type template argument), we have special handling anyway. 14859 UpdateMarkingForLValueToRValue(Res.get()); 14860 return Res; 14861 } 14862 14863 void Sema::CleanupVarDeclMarking() { 14864 for (Expr *E : MaybeODRUseExprs) { 14865 VarDecl *Var; 14866 SourceLocation Loc; 14867 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14868 Var = cast<VarDecl>(DRE->getDecl()); 14869 Loc = DRE->getLocation(); 14870 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14871 Var = cast<VarDecl>(ME->getMemberDecl()); 14872 Loc = ME->getMemberLoc(); 14873 } else { 14874 llvm_unreachable("Unexpected expression"); 14875 } 14876 14877 MarkVarDeclODRUsed(Var, Loc, *this, 14878 /*MaxFunctionScopeIndex Pointer*/ nullptr); 14879 } 14880 14881 MaybeODRUseExprs.clear(); 14882 } 14883 14884 14885 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 14886 VarDecl *Var, Expr *E) { 14887 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 14888 "Invalid Expr argument to DoMarkVarDeclReferenced"); 14889 Var->setReferenced(); 14890 14891 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 14892 14893 bool OdrUseContext = isOdrUseContext(SemaRef); 14894 bool UsableInConstantExpr = 14895 Var->isUsableInConstantExpressions(SemaRef.Context); 14896 bool NeedDefinition = 14897 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 14898 14899 VarTemplateSpecializationDecl *VarSpec = 14900 dyn_cast<VarTemplateSpecializationDecl>(Var); 14901 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 14902 "Can't instantiate a partial template specialization."); 14903 14904 // If this might be a member specialization of a static data member, check 14905 // the specialization is visible. We already did the checks for variable 14906 // template specializations when we created them. 14907 if (NeedDefinition && TSK != TSK_Undeclared && 14908 !isa<VarTemplateSpecializationDecl>(Var)) 14909 SemaRef.checkSpecializationVisibility(Loc, Var); 14910 14911 // Perform implicit instantiation of static data members, static data member 14912 // templates of class templates, and variable template specializations. Delay 14913 // instantiations of variable templates, except for those that could be used 14914 // in a constant expression. 14915 if (NeedDefinition && isTemplateInstantiation(TSK)) { 14916 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 14917 // instantiation declaration if a variable is usable in a constant 14918 // expression (among other cases). 14919 bool TryInstantiating = 14920 TSK == TSK_ImplicitInstantiation || 14921 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 14922 14923 if (TryInstantiating) { 14924 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 14925 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14926 if (FirstInstantiation) { 14927 PointOfInstantiation = Loc; 14928 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14929 } 14930 14931 bool InstantiationDependent = false; 14932 bool IsNonDependent = 14933 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 14934 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 14935 : true; 14936 14937 // Do not instantiate specializations that are still type-dependent. 14938 if (IsNonDependent) { 14939 if (UsableInConstantExpr) { 14940 // Do not defer instantiations of variables that could be used in a 14941 // constant expression. 14942 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 14943 } else if (FirstInstantiation || 14944 isa<VarTemplateSpecializationDecl>(Var)) { 14945 // FIXME: For a specialization of a variable template, we don't 14946 // distinguish between "declaration and type implicitly instantiated" 14947 // and "implicit instantiation of definition requested", so we have 14948 // no direct way to avoid enqueueing the pending instantiation 14949 // multiple times. 14950 SemaRef.PendingInstantiations 14951 .push_back(std::make_pair(Var, PointOfInstantiation)); 14952 } 14953 } 14954 } 14955 } 14956 14957 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 14958 // the requirements for appearing in a constant expression (5.19) and, if 14959 // it is an object, the lvalue-to-rvalue conversion (4.1) 14960 // is immediately applied." We check the first part here, and 14961 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 14962 // Note that we use the C++11 definition everywhere because nothing in 14963 // C++03 depends on whether we get the C++03 version correct. The second 14964 // part does not apply to references, since they are not objects. 14965 if (OdrUseContext && E && 14966 IsVariableAConstantExpression(Var, SemaRef.Context)) { 14967 // A reference initialized by a constant expression can never be 14968 // odr-used, so simply ignore it. 14969 if (!Var->getType()->isReferenceType() || 14970 (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var))) 14971 SemaRef.MaybeODRUseExprs.insert(E); 14972 } else if (OdrUseContext) { 14973 MarkVarDeclODRUsed(Var, Loc, SemaRef, 14974 /*MaxFunctionScopeIndex ptr*/ nullptr); 14975 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 14976 // If this is a dependent context, we don't need to mark variables as 14977 // odr-used, but we may still need to track them for lambda capture. 14978 // FIXME: Do we also need to do this inside dependent typeid expressions 14979 // (which are modeled as unevaluated at this point)? 14980 const bool RefersToEnclosingScope = 14981 (SemaRef.CurContext != Var->getDeclContext() && 14982 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 14983 if (RefersToEnclosingScope) { 14984 LambdaScopeInfo *const LSI = 14985 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 14986 if (LSI && (!LSI->CallOperator || 14987 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 14988 // If a variable could potentially be odr-used, defer marking it so 14989 // until we finish analyzing the full expression for any 14990 // lvalue-to-rvalue 14991 // or discarded value conversions that would obviate odr-use. 14992 // Add it to the list of potential captures that will be analyzed 14993 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 14994 // unless the variable is a reference that was initialized by a constant 14995 // expression (this will never need to be captured or odr-used). 14996 assert(E && "Capture variable should be used in an expression."); 14997 if (!Var->getType()->isReferenceType() || 14998 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 14999 LSI->addPotentialCapture(E->IgnoreParens()); 15000 } 15001 } 15002 } 15003 } 15004 15005 /// \brief Mark a variable referenced, and check whether it is odr-used 15006 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15007 /// used directly for normal expressions referring to VarDecl. 15008 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15009 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15010 } 15011 15012 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15013 Decl *D, Expr *E, bool MightBeOdrUse) { 15014 if (SemaRef.isInOpenMPDeclareTargetContext()) 15015 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15016 15017 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15018 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15019 return; 15020 } 15021 15022 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15023 15024 // If this is a call to a method via a cast, also mark the method in the 15025 // derived class used in case codegen can devirtualize the call. 15026 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15027 if (!ME) 15028 return; 15029 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15030 if (!MD) 15031 return; 15032 // Only attempt to devirtualize if this is truly a virtual call. 15033 bool IsVirtualCall = MD->isVirtual() && 15034 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15035 if (!IsVirtualCall) 15036 return; 15037 15038 // If it's possible to devirtualize the call, mark the called function 15039 // referenced. 15040 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15041 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15042 if (DM) 15043 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15044 } 15045 15046 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 15047 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15048 // TODO: update this with DR# once a defect report is filed. 15049 // C++11 defect. The address of a pure member should not be an ODR use, even 15050 // if it's a qualified reference. 15051 bool OdrUse = true; 15052 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15053 if (Method->isVirtual() && 15054 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15055 OdrUse = false; 15056 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15057 } 15058 15059 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 15060 void Sema::MarkMemberReferenced(MemberExpr *E) { 15061 // C++11 [basic.def.odr]p2: 15062 // A non-overloaded function whose name appears as a potentially-evaluated 15063 // expression or a member of a set of candidate functions, if selected by 15064 // overload resolution when referred to from a potentially-evaluated 15065 // expression, is odr-used, unless it is a pure virtual function and its 15066 // name is not explicitly qualified. 15067 bool MightBeOdrUse = true; 15068 if (E->performsVirtualDispatch(getLangOpts())) { 15069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15070 if (Method->isPure()) 15071 MightBeOdrUse = false; 15072 } 15073 SourceLocation Loc = E->getMemberLoc().isValid() ? 15074 E->getMemberLoc() : E->getLocStart(); 15075 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15076 } 15077 15078 /// \brief Perform marking for a reference to an arbitrary declaration. It 15079 /// marks the declaration referenced, and performs odr-use checking for 15080 /// functions and variables. This method should not be used when building a 15081 /// normal expression which refers to a variable. 15082 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15083 bool MightBeOdrUse) { 15084 if (MightBeOdrUse) { 15085 if (auto *VD = dyn_cast<VarDecl>(D)) { 15086 MarkVariableReferenced(Loc, VD); 15087 return; 15088 } 15089 } 15090 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15091 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15092 return; 15093 } 15094 D->setReferenced(); 15095 } 15096 15097 namespace { 15098 // Mark all of the declarations used by a type as referenced. 15099 // FIXME: Not fully implemented yet! We need to have a better understanding 15100 // of when we're entering a context we should not recurse into. 15101 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15102 // TreeTransforms rebuilding the type in a new context. Rather than 15103 // duplicating the TreeTransform logic, we should consider reusing it here. 15104 // Currently that causes problems when rebuilding LambdaExprs. 15105 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15106 Sema &S; 15107 SourceLocation Loc; 15108 15109 public: 15110 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15111 15112 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15113 15114 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15115 }; 15116 } 15117 15118 bool MarkReferencedDecls::TraverseTemplateArgument( 15119 const TemplateArgument &Arg) { 15120 { 15121 // A non-type template argument is a constant-evaluated context. 15122 EnterExpressionEvaluationContext Evaluated( 15123 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15124 if (Arg.getKind() == TemplateArgument::Declaration) { 15125 if (Decl *D = Arg.getAsDecl()) 15126 S.MarkAnyDeclReferenced(Loc, D, true); 15127 } else if (Arg.getKind() == TemplateArgument::Expression) { 15128 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15129 } 15130 } 15131 15132 return Inherited::TraverseTemplateArgument(Arg); 15133 } 15134 15135 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15136 MarkReferencedDecls Marker(*this, Loc); 15137 Marker.TraverseType(T); 15138 } 15139 15140 namespace { 15141 /// \brief Helper class that marks all of the declarations referenced by 15142 /// potentially-evaluated subexpressions as "referenced". 15143 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15144 Sema &S; 15145 bool SkipLocalVariables; 15146 15147 public: 15148 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15149 15150 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15151 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15152 15153 void VisitDeclRefExpr(DeclRefExpr *E) { 15154 // If we were asked not to visit local variables, don't. 15155 if (SkipLocalVariables) { 15156 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15157 if (VD->hasLocalStorage()) 15158 return; 15159 } 15160 15161 S.MarkDeclRefReferenced(E); 15162 } 15163 15164 void VisitMemberExpr(MemberExpr *E) { 15165 S.MarkMemberReferenced(E); 15166 Inherited::VisitMemberExpr(E); 15167 } 15168 15169 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15170 S.MarkFunctionReferenced(E->getLocStart(), 15171 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 15172 Visit(E->getSubExpr()); 15173 } 15174 15175 void VisitCXXNewExpr(CXXNewExpr *E) { 15176 if (E->getOperatorNew()) 15177 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 15178 if (E->getOperatorDelete()) 15179 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15180 Inherited::VisitCXXNewExpr(E); 15181 } 15182 15183 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15184 if (E->getOperatorDelete()) 15185 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 15186 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15187 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15188 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15189 S.MarkFunctionReferenced(E->getLocStart(), 15190 S.LookupDestructor(Record)); 15191 } 15192 15193 Inherited::VisitCXXDeleteExpr(E); 15194 } 15195 15196 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15197 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 15198 Inherited::VisitCXXConstructExpr(E); 15199 } 15200 15201 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15202 Visit(E->getExpr()); 15203 } 15204 15205 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15206 Inherited::VisitImplicitCastExpr(E); 15207 15208 if (E->getCastKind() == CK_LValueToRValue) 15209 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15210 } 15211 }; 15212 } 15213 15214 /// \brief Mark any declarations that appear within this expression or any 15215 /// potentially-evaluated subexpressions as "referenced". 15216 /// 15217 /// \param SkipLocalVariables If true, don't mark local variables as 15218 /// 'referenced'. 15219 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15220 bool SkipLocalVariables) { 15221 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15222 } 15223 15224 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 15225 /// of the program being compiled. 15226 /// 15227 /// This routine emits the given diagnostic when the code currently being 15228 /// type-checked is "potentially evaluated", meaning that there is a 15229 /// possibility that the code will actually be executable. Code in sizeof() 15230 /// expressions, code used only during overload resolution, etc., are not 15231 /// potentially evaluated. This routine will suppress such diagnostics or, 15232 /// in the absolutely nutty case of potentially potentially evaluated 15233 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15234 /// later. 15235 /// 15236 /// This routine should be used for all diagnostics that describe the run-time 15237 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15238 /// Failure to do so will likely result in spurious diagnostics or failures 15239 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15240 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15241 const PartialDiagnostic &PD) { 15242 switch (ExprEvalContexts.back().Context) { 15243 case ExpressionEvaluationContext::Unevaluated: 15244 case ExpressionEvaluationContext::UnevaluatedList: 15245 case ExpressionEvaluationContext::UnevaluatedAbstract: 15246 case ExpressionEvaluationContext::DiscardedStatement: 15247 // The argument will never be evaluated, so don't complain. 15248 break; 15249 15250 case ExpressionEvaluationContext::ConstantEvaluated: 15251 // Relevant diagnostics should be produced by constant evaluation. 15252 break; 15253 15254 case ExpressionEvaluationContext::PotentiallyEvaluated: 15255 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15256 if (Statement && getCurFunctionOrMethodDecl()) { 15257 FunctionScopes.back()->PossiblyUnreachableDiags. 15258 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15259 return true; 15260 } 15261 15262 // The initializer of a constexpr variable or of the first declaration of a 15263 // static data member is not syntactically a constant evaluated constant, 15264 // but nonetheless is always required to be a constant expression, so we 15265 // can skip diagnosing. 15266 // FIXME: Using the mangling context here is a hack. 15267 if (auto *VD = dyn_cast_or_null<VarDecl>( 15268 ExprEvalContexts.back().ManglingContextDecl)) { 15269 if (VD->isConstexpr() || 15270 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15271 break; 15272 // FIXME: For any other kind of variable, we should build a CFG for its 15273 // initializer and check whether the context in question is reachable. 15274 } 15275 15276 Diag(Loc, PD); 15277 return true; 15278 } 15279 15280 return false; 15281 } 15282 15283 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15284 CallExpr *CE, FunctionDecl *FD) { 15285 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15286 return false; 15287 15288 // If we're inside a decltype's expression, don't check for a valid return 15289 // type or construct temporaries until we know whether this is the last call. 15290 if (ExprEvalContexts.back().IsDecltype) { 15291 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15292 return false; 15293 } 15294 15295 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15296 FunctionDecl *FD; 15297 CallExpr *CE; 15298 15299 public: 15300 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15301 : FD(FD), CE(CE) { } 15302 15303 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15304 if (!FD) { 15305 S.Diag(Loc, diag::err_call_incomplete_return) 15306 << T << CE->getSourceRange(); 15307 return; 15308 } 15309 15310 S.Diag(Loc, diag::err_call_function_incomplete_return) 15311 << CE->getSourceRange() << FD->getDeclName() << T; 15312 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15313 << FD->getDeclName(); 15314 } 15315 } Diagnoser(FD, CE); 15316 15317 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15318 return true; 15319 15320 return false; 15321 } 15322 15323 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15324 // will prevent this condition from triggering, which is what we want. 15325 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15326 SourceLocation Loc; 15327 15328 unsigned diagnostic = diag::warn_condition_is_assignment; 15329 bool IsOrAssign = false; 15330 15331 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15332 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15333 return; 15334 15335 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15336 15337 // Greylist some idioms by putting them into a warning subcategory. 15338 if (ObjCMessageExpr *ME 15339 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15340 Selector Sel = ME->getSelector(); 15341 15342 // self = [<foo> init...] 15343 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15344 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15345 15346 // <foo> = [<bar> nextObject] 15347 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15348 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15349 } 15350 15351 Loc = Op->getOperatorLoc(); 15352 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15353 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15354 return; 15355 15356 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15357 Loc = Op->getOperatorLoc(); 15358 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15359 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15360 else { 15361 // Not an assignment. 15362 return; 15363 } 15364 15365 Diag(Loc, diagnostic) << E->getSourceRange(); 15366 15367 SourceLocation Open = E->getLocStart(); 15368 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15369 Diag(Loc, diag::note_condition_assign_silence) 15370 << FixItHint::CreateInsertion(Open, "(") 15371 << FixItHint::CreateInsertion(Close, ")"); 15372 15373 if (IsOrAssign) 15374 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15375 << FixItHint::CreateReplacement(Loc, "!="); 15376 else 15377 Diag(Loc, diag::note_condition_assign_to_comparison) 15378 << FixItHint::CreateReplacement(Loc, "=="); 15379 } 15380 15381 /// \brief Redundant parentheses over an equality comparison can indicate 15382 /// that the user intended an assignment used as condition. 15383 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15384 // Don't warn if the parens came from a macro. 15385 SourceLocation parenLoc = ParenE->getLocStart(); 15386 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15387 return; 15388 // Don't warn for dependent expressions. 15389 if (ParenE->isTypeDependent()) 15390 return; 15391 15392 Expr *E = ParenE->IgnoreParens(); 15393 15394 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15395 if (opE->getOpcode() == BO_EQ && 15396 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15397 == Expr::MLV_Valid) { 15398 SourceLocation Loc = opE->getOperatorLoc(); 15399 15400 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15401 SourceRange ParenERange = ParenE->getSourceRange(); 15402 Diag(Loc, diag::note_equality_comparison_silence) 15403 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15404 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15405 Diag(Loc, diag::note_equality_comparison_to_assign) 15406 << FixItHint::CreateReplacement(Loc, "="); 15407 } 15408 } 15409 15410 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15411 bool IsConstexpr) { 15412 DiagnoseAssignmentAsCondition(E); 15413 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15414 DiagnoseEqualityWithExtraParens(parenE); 15415 15416 ExprResult result = CheckPlaceholderExpr(E); 15417 if (result.isInvalid()) return ExprError(); 15418 E = result.get(); 15419 15420 if (!E->isTypeDependent()) { 15421 if (getLangOpts().CPlusPlus) 15422 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15423 15424 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15425 if (ERes.isInvalid()) 15426 return ExprError(); 15427 E = ERes.get(); 15428 15429 QualType T = E->getType(); 15430 if (!T->isScalarType()) { // C99 6.8.4.1p1 15431 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15432 << T << E->getSourceRange(); 15433 return ExprError(); 15434 } 15435 CheckBoolLikeConversion(E, Loc); 15436 } 15437 15438 return E; 15439 } 15440 15441 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15442 Expr *SubExpr, ConditionKind CK) { 15443 // Empty conditions are valid in for-statements. 15444 if (!SubExpr) 15445 return ConditionResult(); 15446 15447 ExprResult Cond; 15448 switch (CK) { 15449 case ConditionKind::Boolean: 15450 Cond = CheckBooleanCondition(Loc, SubExpr); 15451 break; 15452 15453 case ConditionKind::ConstexprIf: 15454 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15455 break; 15456 15457 case ConditionKind::Switch: 15458 Cond = CheckSwitchCondition(Loc, SubExpr); 15459 break; 15460 } 15461 if (Cond.isInvalid()) 15462 return ConditionError(); 15463 15464 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15465 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15466 if (!FullExpr.get()) 15467 return ConditionError(); 15468 15469 return ConditionResult(*this, nullptr, FullExpr, 15470 CK == ConditionKind::ConstexprIf); 15471 } 15472 15473 namespace { 15474 /// A visitor for rebuilding a call to an __unknown_any expression 15475 /// to have an appropriate type. 15476 struct RebuildUnknownAnyFunction 15477 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15478 15479 Sema &S; 15480 15481 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15482 15483 ExprResult VisitStmt(Stmt *S) { 15484 llvm_unreachable("unexpected statement!"); 15485 } 15486 15487 ExprResult VisitExpr(Expr *E) { 15488 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15489 << E->getSourceRange(); 15490 return ExprError(); 15491 } 15492 15493 /// Rebuild an expression which simply semantically wraps another 15494 /// expression which it shares the type and value kind of. 15495 template <class T> ExprResult rebuildSugarExpr(T *E) { 15496 ExprResult SubResult = Visit(E->getSubExpr()); 15497 if (SubResult.isInvalid()) return ExprError(); 15498 15499 Expr *SubExpr = SubResult.get(); 15500 E->setSubExpr(SubExpr); 15501 E->setType(SubExpr->getType()); 15502 E->setValueKind(SubExpr->getValueKind()); 15503 assert(E->getObjectKind() == OK_Ordinary); 15504 return E; 15505 } 15506 15507 ExprResult VisitParenExpr(ParenExpr *E) { 15508 return rebuildSugarExpr(E); 15509 } 15510 15511 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15512 return rebuildSugarExpr(E); 15513 } 15514 15515 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15516 ExprResult SubResult = Visit(E->getSubExpr()); 15517 if (SubResult.isInvalid()) return ExprError(); 15518 15519 Expr *SubExpr = SubResult.get(); 15520 E->setSubExpr(SubExpr); 15521 E->setType(S.Context.getPointerType(SubExpr->getType())); 15522 assert(E->getValueKind() == VK_RValue); 15523 assert(E->getObjectKind() == OK_Ordinary); 15524 return E; 15525 } 15526 15527 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15528 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15529 15530 E->setType(VD->getType()); 15531 15532 assert(E->getValueKind() == VK_RValue); 15533 if (S.getLangOpts().CPlusPlus && 15534 !(isa<CXXMethodDecl>(VD) && 15535 cast<CXXMethodDecl>(VD)->isInstance())) 15536 E->setValueKind(VK_LValue); 15537 15538 return E; 15539 } 15540 15541 ExprResult VisitMemberExpr(MemberExpr *E) { 15542 return resolveDecl(E, E->getMemberDecl()); 15543 } 15544 15545 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15546 return resolveDecl(E, E->getDecl()); 15547 } 15548 }; 15549 } 15550 15551 /// Given a function expression of unknown-any type, try to rebuild it 15552 /// to have a function type. 15553 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15554 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15555 if (Result.isInvalid()) return ExprError(); 15556 return S.DefaultFunctionArrayConversion(Result.get()); 15557 } 15558 15559 namespace { 15560 /// A visitor for rebuilding an expression of type __unknown_anytype 15561 /// into one which resolves the type directly on the referring 15562 /// expression. Strict preservation of the original source 15563 /// structure is not a goal. 15564 struct RebuildUnknownAnyExpr 15565 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15566 15567 Sema &S; 15568 15569 /// The current destination type. 15570 QualType DestType; 15571 15572 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15573 : S(S), DestType(CastType) {} 15574 15575 ExprResult VisitStmt(Stmt *S) { 15576 llvm_unreachable("unexpected statement!"); 15577 } 15578 15579 ExprResult VisitExpr(Expr *E) { 15580 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15581 << E->getSourceRange(); 15582 return ExprError(); 15583 } 15584 15585 ExprResult VisitCallExpr(CallExpr *E); 15586 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15587 15588 /// Rebuild an expression which simply semantically wraps another 15589 /// expression which it shares the type and value kind of. 15590 template <class T> ExprResult rebuildSugarExpr(T *E) { 15591 ExprResult SubResult = Visit(E->getSubExpr()); 15592 if (SubResult.isInvalid()) return ExprError(); 15593 Expr *SubExpr = SubResult.get(); 15594 E->setSubExpr(SubExpr); 15595 E->setType(SubExpr->getType()); 15596 E->setValueKind(SubExpr->getValueKind()); 15597 assert(E->getObjectKind() == OK_Ordinary); 15598 return E; 15599 } 15600 15601 ExprResult VisitParenExpr(ParenExpr *E) { 15602 return rebuildSugarExpr(E); 15603 } 15604 15605 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15606 return rebuildSugarExpr(E); 15607 } 15608 15609 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15610 const PointerType *Ptr = DestType->getAs<PointerType>(); 15611 if (!Ptr) { 15612 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15613 << E->getSourceRange(); 15614 return ExprError(); 15615 } 15616 15617 if (isa<CallExpr>(E->getSubExpr())) { 15618 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15619 << E->getSourceRange(); 15620 return ExprError(); 15621 } 15622 15623 assert(E->getValueKind() == VK_RValue); 15624 assert(E->getObjectKind() == OK_Ordinary); 15625 E->setType(DestType); 15626 15627 // Build the sub-expression as if it were an object of the pointee type. 15628 DestType = Ptr->getPointeeType(); 15629 ExprResult SubResult = Visit(E->getSubExpr()); 15630 if (SubResult.isInvalid()) return ExprError(); 15631 E->setSubExpr(SubResult.get()); 15632 return E; 15633 } 15634 15635 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15636 15637 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15638 15639 ExprResult VisitMemberExpr(MemberExpr *E) { 15640 return resolveDecl(E, E->getMemberDecl()); 15641 } 15642 15643 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15644 return resolveDecl(E, E->getDecl()); 15645 } 15646 }; 15647 } 15648 15649 /// Rebuilds a call expression which yielded __unknown_anytype. 15650 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 15651 Expr *CalleeExpr = E->getCallee(); 15652 15653 enum FnKind { 15654 FK_MemberFunction, 15655 FK_FunctionPointer, 15656 FK_BlockPointer 15657 }; 15658 15659 FnKind Kind; 15660 QualType CalleeType = CalleeExpr->getType(); 15661 if (CalleeType == S.Context.BoundMemberTy) { 15662 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 15663 Kind = FK_MemberFunction; 15664 CalleeType = Expr::findBoundMemberType(CalleeExpr); 15665 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 15666 CalleeType = Ptr->getPointeeType(); 15667 Kind = FK_FunctionPointer; 15668 } else { 15669 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 15670 Kind = FK_BlockPointer; 15671 } 15672 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 15673 15674 // Verify that this is a legal result type of a function. 15675 if (DestType->isArrayType() || DestType->isFunctionType()) { 15676 unsigned diagID = diag::err_func_returning_array_function; 15677 if (Kind == FK_BlockPointer) 15678 diagID = diag::err_block_returning_array_function; 15679 15680 S.Diag(E->getExprLoc(), diagID) 15681 << DestType->isFunctionType() << DestType; 15682 return ExprError(); 15683 } 15684 15685 // Otherwise, go ahead and set DestType as the call's result. 15686 E->setType(DestType.getNonLValueExprType(S.Context)); 15687 E->setValueKind(Expr::getValueKindForType(DestType)); 15688 assert(E->getObjectKind() == OK_Ordinary); 15689 15690 // Rebuild the function type, replacing the result type with DestType. 15691 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 15692 if (Proto) { 15693 // __unknown_anytype(...) is a special case used by the debugger when 15694 // it has no idea what a function's signature is. 15695 // 15696 // We want to build this call essentially under the K&R 15697 // unprototyped rules, but making a FunctionNoProtoType in C++ 15698 // would foul up all sorts of assumptions. However, we cannot 15699 // simply pass all arguments as variadic arguments, nor can we 15700 // portably just call the function under a non-variadic type; see 15701 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 15702 // However, it turns out that in practice it is generally safe to 15703 // call a function declared as "A foo(B,C,D);" under the prototype 15704 // "A foo(B,C,D,...);". The only known exception is with the 15705 // Windows ABI, where any variadic function is implicitly cdecl 15706 // regardless of its normal CC. Therefore we change the parameter 15707 // types to match the types of the arguments. 15708 // 15709 // This is a hack, but it is far superior to moving the 15710 // corresponding target-specific code from IR-gen to Sema/AST. 15711 15712 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 15713 SmallVector<QualType, 8> ArgTypes; 15714 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 15715 ArgTypes.reserve(E->getNumArgs()); 15716 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 15717 Expr *Arg = E->getArg(i); 15718 QualType ArgType = Arg->getType(); 15719 if (E->isLValue()) { 15720 ArgType = S.Context.getLValueReferenceType(ArgType); 15721 } else if (E->isXValue()) { 15722 ArgType = S.Context.getRValueReferenceType(ArgType); 15723 } 15724 ArgTypes.push_back(ArgType); 15725 } 15726 ParamTypes = ArgTypes; 15727 } 15728 DestType = S.Context.getFunctionType(DestType, ParamTypes, 15729 Proto->getExtProtoInfo()); 15730 } else { 15731 DestType = S.Context.getFunctionNoProtoType(DestType, 15732 FnType->getExtInfo()); 15733 } 15734 15735 // Rebuild the appropriate pointer-to-function type. 15736 switch (Kind) { 15737 case FK_MemberFunction: 15738 // Nothing to do. 15739 break; 15740 15741 case FK_FunctionPointer: 15742 DestType = S.Context.getPointerType(DestType); 15743 break; 15744 15745 case FK_BlockPointer: 15746 DestType = S.Context.getBlockPointerType(DestType); 15747 break; 15748 } 15749 15750 // Finally, we can recurse. 15751 ExprResult CalleeResult = Visit(CalleeExpr); 15752 if (!CalleeResult.isUsable()) return ExprError(); 15753 E->setCallee(CalleeResult.get()); 15754 15755 // Bind a temporary if necessary. 15756 return S.MaybeBindToTemporary(E); 15757 } 15758 15759 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 15760 // Verify that this is a legal result type of a call. 15761 if (DestType->isArrayType() || DestType->isFunctionType()) { 15762 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 15763 << DestType->isFunctionType() << DestType; 15764 return ExprError(); 15765 } 15766 15767 // Rewrite the method result type if available. 15768 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 15769 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 15770 Method->setReturnType(DestType); 15771 } 15772 15773 // Change the type of the message. 15774 E->setType(DestType.getNonReferenceType()); 15775 E->setValueKind(Expr::getValueKindForType(DestType)); 15776 15777 return S.MaybeBindToTemporary(E); 15778 } 15779 15780 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 15781 // The only case we should ever see here is a function-to-pointer decay. 15782 if (E->getCastKind() == CK_FunctionToPointerDecay) { 15783 assert(E->getValueKind() == VK_RValue); 15784 assert(E->getObjectKind() == OK_Ordinary); 15785 15786 E->setType(DestType); 15787 15788 // Rebuild the sub-expression as the pointee (function) type. 15789 DestType = DestType->castAs<PointerType>()->getPointeeType(); 15790 15791 ExprResult Result = Visit(E->getSubExpr()); 15792 if (!Result.isUsable()) return ExprError(); 15793 15794 E->setSubExpr(Result.get()); 15795 return E; 15796 } else if (E->getCastKind() == CK_LValueToRValue) { 15797 assert(E->getValueKind() == VK_RValue); 15798 assert(E->getObjectKind() == OK_Ordinary); 15799 15800 assert(isa<BlockPointerType>(E->getType())); 15801 15802 E->setType(DestType); 15803 15804 // The sub-expression has to be a lvalue reference, so rebuild it as such. 15805 DestType = S.Context.getLValueReferenceType(DestType); 15806 15807 ExprResult Result = Visit(E->getSubExpr()); 15808 if (!Result.isUsable()) return ExprError(); 15809 15810 E->setSubExpr(Result.get()); 15811 return E; 15812 } else { 15813 llvm_unreachable("Unhandled cast type!"); 15814 } 15815 } 15816 15817 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 15818 ExprValueKind ValueKind = VK_LValue; 15819 QualType Type = DestType; 15820 15821 // We know how to make this work for certain kinds of decls: 15822 15823 // - functions 15824 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 15825 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 15826 DestType = Ptr->getPointeeType(); 15827 ExprResult Result = resolveDecl(E, VD); 15828 if (Result.isInvalid()) return ExprError(); 15829 return S.ImpCastExprToType(Result.get(), Type, 15830 CK_FunctionToPointerDecay, VK_RValue); 15831 } 15832 15833 if (!Type->isFunctionType()) { 15834 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 15835 << VD << E->getSourceRange(); 15836 return ExprError(); 15837 } 15838 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 15839 // We must match the FunctionDecl's type to the hack introduced in 15840 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 15841 // type. See the lengthy commentary in that routine. 15842 QualType FDT = FD->getType(); 15843 const FunctionType *FnType = FDT->castAs<FunctionType>(); 15844 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 15845 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 15846 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 15847 SourceLocation Loc = FD->getLocation(); 15848 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 15849 FD->getDeclContext(), 15850 Loc, Loc, FD->getNameInfo().getName(), 15851 DestType, FD->getTypeSourceInfo(), 15852 SC_None, false/*isInlineSpecified*/, 15853 FD->hasPrototype(), 15854 false/*isConstexprSpecified*/); 15855 15856 if (FD->getQualifier()) 15857 NewFD->setQualifierInfo(FD->getQualifierLoc()); 15858 15859 SmallVector<ParmVarDecl*, 16> Params; 15860 for (const auto &AI : FT->param_types()) { 15861 ParmVarDecl *Param = 15862 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 15863 Param->setScopeInfo(0, Params.size()); 15864 Params.push_back(Param); 15865 } 15866 NewFD->setParams(Params); 15867 DRE->setDecl(NewFD); 15868 VD = DRE->getDecl(); 15869 } 15870 } 15871 15872 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 15873 if (MD->isInstance()) { 15874 ValueKind = VK_RValue; 15875 Type = S.Context.BoundMemberTy; 15876 } 15877 15878 // Function references aren't l-values in C. 15879 if (!S.getLangOpts().CPlusPlus) 15880 ValueKind = VK_RValue; 15881 15882 // - variables 15883 } else if (isa<VarDecl>(VD)) { 15884 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 15885 Type = RefTy->getPointeeType(); 15886 } else if (Type->isFunctionType()) { 15887 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 15888 << VD << E->getSourceRange(); 15889 return ExprError(); 15890 } 15891 15892 // - nothing else 15893 } else { 15894 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 15895 << VD << E->getSourceRange(); 15896 return ExprError(); 15897 } 15898 15899 // Modifying the declaration like this is friendly to IR-gen but 15900 // also really dangerous. 15901 VD->setType(DestType); 15902 E->setType(Type); 15903 E->setValueKind(ValueKind); 15904 return E; 15905 } 15906 15907 /// Check a cast of an unknown-any type. We intentionally only 15908 /// trigger this for C-style casts. 15909 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 15910 Expr *CastExpr, CastKind &CastKind, 15911 ExprValueKind &VK, CXXCastPath &Path) { 15912 // The type we're casting to must be either void or complete. 15913 if (!CastType->isVoidType() && 15914 RequireCompleteType(TypeRange.getBegin(), CastType, 15915 diag::err_typecheck_cast_to_incomplete)) 15916 return ExprError(); 15917 15918 // Rewrite the casted expression from scratch. 15919 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 15920 if (!result.isUsable()) return ExprError(); 15921 15922 CastExpr = result.get(); 15923 VK = CastExpr->getValueKind(); 15924 CastKind = CK_NoOp; 15925 15926 return CastExpr; 15927 } 15928 15929 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 15930 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 15931 } 15932 15933 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 15934 Expr *arg, QualType ¶mType) { 15935 // If the syntactic form of the argument is not an explicit cast of 15936 // any sort, just do default argument promotion. 15937 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 15938 if (!castArg) { 15939 ExprResult result = DefaultArgumentPromotion(arg); 15940 if (result.isInvalid()) return ExprError(); 15941 paramType = result.get()->getType(); 15942 return result; 15943 } 15944 15945 // Otherwise, use the type that was written in the explicit cast. 15946 assert(!arg->hasPlaceholderType()); 15947 paramType = castArg->getTypeAsWritten(); 15948 15949 // Copy-initialize a parameter of that type. 15950 InitializedEntity entity = 15951 InitializedEntity::InitializeParameter(Context, paramType, 15952 /*consumed*/ false); 15953 return PerformCopyInitialization(entity, callLoc, arg); 15954 } 15955 15956 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 15957 Expr *orig = E; 15958 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 15959 while (true) { 15960 E = E->IgnoreParenImpCasts(); 15961 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 15962 E = call->getCallee(); 15963 diagID = diag::err_uncasted_call_of_unknown_any; 15964 } else { 15965 break; 15966 } 15967 } 15968 15969 SourceLocation loc; 15970 NamedDecl *d; 15971 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 15972 loc = ref->getLocation(); 15973 d = ref->getDecl(); 15974 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 15975 loc = mem->getMemberLoc(); 15976 d = mem->getMemberDecl(); 15977 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 15978 diagID = diag::err_uncasted_call_of_unknown_any; 15979 loc = msg->getSelectorStartLoc(); 15980 d = msg->getMethodDecl(); 15981 if (!d) { 15982 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 15983 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 15984 << orig->getSourceRange(); 15985 return ExprError(); 15986 } 15987 } else { 15988 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15989 << E->getSourceRange(); 15990 return ExprError(); 15991 } 15992 15993 S.Diag(loc, diagID) << d << orig->getSourceRange(); 15994 15995 // Never recoverable. 15996 return ExprError(); 15997 } 15998 15999 /// Check for operands with placeholder types and complain if found. 16000 /// Returns ExprError() if there was an error and no recovery was possible. 16001 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16002 if (!getLangOpts().CPlusPlus) { 16003 // C cannot handle TypoExpr nodes on either side of a binop because it 16004 // doesn't handle dependent types properly, so make sure any TypoExprs have 16005 // been dealt with before checking the operands. 16006 ExprResult Result = CorrectDelayedTyposInExpr(E); 16007 if (!Result.isUsable()) return ExprError(); 16008 E = Result.get(); 16009 } 16010 16011 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16012 if (!placeholderType) return E; 16013 16014 switch (placeholderType->getKind()) { 16015 16016 // Overloaded expressions. 16017 case BuiltinType::Overload: { 16018 // Try to resolve a single function template specialization. 16019 // This is obligatory. 16020 ExprResult Result = E; 16021 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16022 return Result; 16023 16024 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16025 // leaves Result unchanged on failure. 16026 Result = E; 16027 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16028 return Result; 16029 16030 // If that failed, try to recover with a call. 16031 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16032 /*complain*/ true); 16033 return Result; 16034 } 16035 16036 // Bound member functions. 16037 case BuiltinType::BoundMember: { 16038 ExprResult result = E; 16039 const Expr *BME = E->IgnoreParens(); 16040 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16041 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16042 if (isa<CXXPseudoDestructorExpr>(BME)) { 16043 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16044 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16045 if (ME->getMemberNameInfo().getName().getNameKind() == 16046 DeclarationName::CXXDestructorName) 16047 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16048 } 16049 tryToRecoverWithCall(result, PD, 16050 /*complain*/ true); 16051 return result; 16052 } 16053 16054 // ARC unbridged casts. 16055 case BuiltinType::ARCUnbridgedCast: { 16056 Expr *realCast = stripARCUnbridgedCast(E); 16057 diagnoseARCUnbridgedCast(realCast); 16058 return realCast; 16059 } 16060 16061 // Expressions of unknown type. 16062 case BuiltinType::UnknownAny: 16063 return diagnoseUnknownAnyExpr(*this, E); 16064 16065 // Pseudo-objects. 16066 case BuiltinType::PseudoObject: 16067 return checkPseudoObjectRValue(E); 16068 16069 case BuiltinType::BuiltinFn: { 16070 // Accept __noop without parens by implicitly converting it to a call expr. 16071 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16072 if (DRE) { 16073 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16074 if (FD->getBuiltinID() == Builtin::BI__noop) { 16075 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16076 CK_BuiltinFnToFnPtr).get(); 16077 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16078 VK_RValue, SourceLocation()); 16079 } 16080 } 16081 16082 Diag(E->getLocStart(), diag::err_builtin_fn_use); 16083 return ExprError(); 16084 } 16085 16086 // Expressions of unknown type. 16087 case BuiltinType::OMPArraySection: 16088 Diag(E->getLocStart(), diag::err_omp_array_section_use); 16089 return ExprError(); 16090 16091 // Everything else should be impossible. 16092 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16093 case BuiltinType::Id: 16094 #include "clang/Basic/OpenCLImageTypes.def" 16095 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16096 #define PLACEHOLDER_TYPE(Id, SingletonId) 16097 #include "clang/AST/BuiltinTypes.def" 16098 break; 16099 } 16100 16101 llvm_unreachable("invalid placeholder type!"); 16102 } 16103 16104 bool Sema::CheckCaseExpression(Expr *E) { 16105 if (E->isTypeDependent()) 16106 return true; 16107 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16108 return E->getType()->isIntegralOrEnumerationType(); 16109 return false; 16110 } 16111 16112 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16113 ExprResult 16114 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16115 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16116 "Unknown Objective-C Boolean value!"); 16117 QualType BoolT = Context.ObjCBuiltinBoolTy; 16118 if (!Context.getBOOLDecl()) { 16119 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16120 Sema::LookupOrdinaryName); 16121 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16122 NamedDecl *ND = Result.getFoundDecl(); 16123 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16124 Context.setBOOLDecl(TD); 16125 } 16126 } 16127 if (Context.getBOOLDecl()) 16128 BoolT = Context.getBOOLType(); 16129 return new (Context) 16130 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16131 } 16132 16133 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16134 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16135 SourceLocation RParen) { 16136 16137 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16138 16139 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16140 [&](const AvailabilitySpec &Spec) { 16141 return Spec.getPlatform() == Platform; 16142 }); 16143 16144 VersionTuple Version; 16145 if (Spec != AvailSpecs.end()) 16146 Version = Spec->getVersion(); 16147 16148 // The use of `@available` in the enclosing function should be analyzed to 16149 // warn when it's used inappropriately (i.e. not if(@available)). 16150 if (getCurFunctionOrMethodDecl()) 16151 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16152 else if (getCurBlock() || getCurLambda()) 16153 getCurFunction()->HasPotentialAvailabilityViolations = true; 16154 16155 return new (Context) 16156 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16157 } 16158