1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/FixedPoint.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks, 210 ObjCInterfaceDecl *ClassReceiver) { 211 SourceLocation Loc = Locs.front(); 212 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 213 // If there were any diagnostics suppressed by template argument deduction, 214 // emit them now. 215 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 216 if (Pos != SuppressedDiagnostics.end()) { 217 for (const PartialDiagnosticAt &Suppressed : Pos->second) 218 Diag(Suppressed.first, Suppressed.second); 219 220 // Clear out the list of suppressed diagnostics, so that we don't emit 221 // them again for this specialization. However, we don't obsolete this 222 // entry from the table, because we want to avoid ever emitting these 223 // diagnostics again. 224 Pos->second.clear(); 225 } 226 227 // C++ [basic.start.main]p3: 228 // The function 'main' shall not be used within a program. 229 if (cast<FunctionDecl>(D)->isMain()) 230 Diag(Loc, diag::ext_main_used); 231 } 232 233 // See if this is an auto-typed variable whose initializer we are parsing. 234 if (ParsingInitForAutoVars.count(D)) { 235 if (isa<BindingDecl>(D)) { 236 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 237 << D->getDeclName(); 238 } else { 239 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 240 << D->getDeclName() << cast<VarDecl>(D)->getType(); 241 } 242 return true; 243 } 244 245 // See if this is a deleted function. 246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 247 if (FD->isDeleted()) { 248 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 249 if (Ctor && Ctor->isInheritingConstructor()) 250 Diag(Loc, diag::err_deleted_inherited_ctor_use) 251 << Ctor->getParent() 252 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 253 else 254 Diag(Loc, diag::err_deleted_function_use); 255 NoteDeletedFunction(FD); 256 return true; 257 } 258 259 // If the function has a deduced return type, and we can't deduce it, 260 // then we can't use it either. 261 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 262 DeduceReturnType(FD, Loc)) 263 return true; 264 265 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 266 return true; 267 } 268 269 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 270 // Lambdas are only default-constructible or assignable in C++2a onwards. 271 if (MD->getParent()->isLambda() && 272 ((isa<CXXConstructorDecl>(MD) && 273 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 274 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 275 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 276 << !isa<CXXConstructorDecl>(MD); 277 } 278 } 279 280 auto getReferencedObjCProp = [](const NamedDecl *D) -> 281 const ObjCPropertyDecl * { 282 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 283 return MD->findPropertyDecl(); 284 return nullptr; 285 }; 286 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 287 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 288 return true; 289 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 290 return true; 291 } 292 293 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 294 // Only the variables omp_in and omp_out are allowed in the combiner. 295 // Only the variables omp_priv and omp_orig are allowed in the 296 // initializer-clause. 297 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 298 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 299 isa<VarDecl>(D)) { 300 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 301 << getCurFunction()->HasOMPDeclareReductionCombiner; 302 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 303 return true; 304 } 305 306 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 307 AvoidPartialAvailabilityChecks, ClassReceiver); 308 309 DiagnoseUnusedOfDecl(*this, D, Loc); 310 311 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 312 313 return false; 314 } 315 316 /// Retrieve the message suffix that should be added to a 317 /// diagnostic complaining about the given function being deleted or 318 /// unavailable. 319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 320 std::string Message; 321 if (FD->getAvailability(&Message)) 322 return ": " + Message; 323 324 return std::string(); 325 } 326 327 /// DiagnoseSentinelCalls - This routine checks whether a call or 328 /// message-send is to a declaration with the sentinel attribute, and 329 /// if so, it checks that the requirements of the sentinel are 330 /// satisfied. 331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 332 ArrayRef<Expr *> Args) { 333 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 334 if (!attr) 335 return; 336 337 // The number of formal parameters of the declaration. 338 unsigned numFormalParams; 339 340 // The kind of declaration. This is also an index into a %select in 341 // the diagnostic. 342 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 343 344 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 345 numFormalParams = MD->param_size(); 346 calleeType = CT_Method; 347 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 348 numFormalParams = FD->param_size(); 349 calleeType = CT_Function; 350 } else if (isa<VarDecl>(D)) { 351 QualType type = cast<ValueDecl>(D)->getType(); 352 const FunctionType *fn = nullptr; 353 if (const PointerType *ptr = type->getAs<PointerType>()) { 354 fn = ptr->getPointeeType()->getAs<FunctionType>(); 355 if (!fn) return; 356 calleeType = CT_Function; 357 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 358 fn = ptr->getPointeeType()->castAs<FunctionType>(); 359 calleeType = CT_Block; 360 } else { 361 return; 362 } 363 364 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 365 numFormalParams = proto->getNumParams(); 366 } else { 367 numFormalParams = 0; 368 } 369 } else { 370 return; 371 } 372 373 // "nullPos" is the number of formal parameters at the end which 374 // effectively count as part of the variadic arguments. This is 375 // useful if you would prefer to not have *any* formal parameters, 376 // but the language forces you to have at least one. 377 unsigned nullPos = attr->getNullPos(); 378 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 379 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 380 381 // The number of arguments which should follow the sentinel. 382 unsigned numArgsAfterSentinel = attr->getSentinel(); 383 384 // If there aren't enough arguments for all the formal parameters, 385 // the sentinel, and the args after the sentinel, complain. 386 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 387 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 388 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 389 return; 390 } 391 392 // Otherwise, find the sentinel expression. 393 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 394 if (!sentinelExpr) return; 395 if (sentinelExpr->isValueDependent()) return; 396 if (Context.isSentinelNullExpr(sentinelExpr)) return; 397 398 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 399 // or 'NULL' if those are actually defined in the context. Only use 400 // 'nil' for ObjC methods, where it's much more likely that the 401 // variadic arguments form a list of object pointers. 402 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 403 std::string NullValue; 404 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 405 NullValue = "nil"; 406 else if (getLangOpts().CPlusPlus11) 407 NullValue = "nullptr"; 408 else if (PP.isMacroDefined("NULL")) 409 NullValue = "NULL"; 410 else 411 NullValue = "(void*) 0"; 412 413 if (MissingNilLoc.isInvalid()) 414 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 415 else 416 Diag(MissingNilLoc, diag::warn_missing_sentinel) 417 << int(calleeType) 418 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 419 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 420 } 421 422 SourceRange Sema::getExprRange(Expr *E) const { 423 return E ? E->getSourceRange() : SourceRange(); 424 } 425 426 //===----------------------------------------------------------------------===// 427 // Standard Promotions and Conversions 428 //===----------------------------------------------------------------------===// 429 430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 432 // Handle any placeholder expressions which made it here. 433 if (E->getType()->isPlaceholderType()) { 434 ExprResult result = CheckPlaceholderExpr(E); 435 if (result.isInvalid()) return ExprError(); 436 E = result.get(); 437 } 438 439 QualType Ty = E->getType(); 440 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 441 442 if (Ty->isFunctionType()) { 443 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 444 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 445 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 446 return ExprError(); 447 448 E = ImpCastExprToType(E, Context.getPointerType(Ty), 449 CK_FunctionToPointerDecay).get(); 450 } else if (Ty->isArrayType()) { 451 // In C90 mode, arrays only promote to pointers if the array expression is 452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 453 // type 'array of type' is converted to an expression that has type 'pointer 454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 455 // that has type 'array of type' ...". The relevant change is "an lvalue" 456 // (C90) to "an expression" (C99). 457 // 458 // C++ 4.2p1: 459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 460 // T" can be converted to an rvalue of type "pointer to T". 461 // 462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 464 CK_ArrayToPointerDecay).get(); 465 } 466 return E; 467 } 468 469 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 470 // Check to see if we are dereferencing a null pointer. If so, 471 // and if not volatile-qualified, this is undefined behavior that the 472 // optimizer will delete, so warn about it. People sometimes try to use this 473 // to get a deterministic trap and are surprised by clang's behavior. This 474 // only handles the pattern "*null", which is a very syntactic check. 475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 476 if (UO->getOpcode() == UO_Deref && 477 UO->getSubExpr()->IgnoreParenCasts()-> 478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 479 !UO->getType().isVolatileQualified()) { 480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 481 S.PDiag(diag::warn_indirection_through_null) 482 << UO->getSubExpr()->getSourceRange()); 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::note_indirection_through_null)); 485 } 486 } 487 488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 489 SourceLocation AssignLoc, 490 const Expr* RHS) { 491 const ObjCIvarDecl *IV = OIRE->getDecl(); 492 if (!IV) 493 return; 494 495 DeclarationName MemberName = IV->getDeclName(); 496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 497 if (!Member || !Member->isStr("isa")) 498 return; 499 500 const Expr *Base = OIRE->getBase(); 501 QualType BaseType = Base->getType(); 502 if (OIRE->isArrow()) 503 BaseType = BaseType->getPointeeType(); 504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 506 ObjCInterfaceDecl *ClassDeclared = nullptr; 507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 508 if (!ClassDeclared->getSuperClass() 509 && (*ClassDeclared->ivar_begin()) == IV) { 510 if (RHS) { 511 NamedDecl *ObjectSetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_setClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectSetClass) { 516 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 518 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 519 "object_setClass(") 520 << FixItHint::CreateReplacement( 521 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 522 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 523 } 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 526 } else { 527 NamedDecl *ObjectGetClass = 528 S.LookupSingleName(S.TUScope, 529 &S.Context.Idents.get("object_getClass"), 530 SourceLocation(), S.LookupOrdinaryName); 531 if (ObjectGetClass) 532 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 533 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 534 "object_getClass(") 535 << FixItHint::CreateReplacement( 536 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 537 else 538 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 539 } 540 S.Diag(IV->getLocation(), diag::note_ivar_decl); 541 } 542 } 543 } 544 545 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 546 // Handle any placeholder expressions which made it here. 547 if (E->getType()->isPlaceholderType()) { 548 ExprResult result = CheckPlaceholderExpr(E); 549 if (result.isInvalid()) return ExprError(); 550 E = result.get(); 551 } 552 553 // C++ [conv.lval]p1: 554 // A glvalue of a non-function, non-array type T can be 555 // converted to a prvalue. 556 if (!E->isGLValue()) return E; 557 558 QualType T = E->getType(); 559 assert(!T.isNull() && "r-value conversion on typeless expression?"); 560 561 // We don't want to throw lvalue-to-rvalue casts on top of 562 // expressions of certain types in C++. 563 if (getLangOpts().CPlusPlus && 564 (E->getType() == Context.OverloadTy || 565 T->isDependentType() || 566 T->isRecordType())) 567 return E; 568 569 // The C standard is actually really unclear on this point, and 570 // DR106 tells us what the result should be but not why. It's 571 // generally best to say that void types just doesn't undergo 572 // lvalue-to-rvalue at all. Note that expressions of unqualified 573 // 'void' type are never l-values, but qualified void can be. 574 if (T->isVoidType()) 575 return E; 576 577 // OpenCL usually rejects direct accesses to values of 'half' type. 578 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 579 T->isHalfType()) { 580 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 581 << 0 << T; 582 return ExprError(); 583 } 584 585 CheckForNullPointerDereference(*this, E); 586 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 587 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 588 &Context.Idents.get("object_getClass"), 589 SourceLocation(), LookupOrdinaryName); 590 if (ObjectGetClass) 591 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 592 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 593 << FixItHint::CreateReplacement( 594 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 595 else 596 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 597 } 598 else if (const ObjCIvarRefExpr *OIRE = 599 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 600 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 601 602 // C++ [conv.lval]p1: 603 // [...] If T is a non-class type, the type of the prvalue is the 604 // cv-unqualified version of T. Otherwise, the type of the 605 // rvalue is T. 606 // 607 // C99 6.3.2.1p2: 608 // If the lvalue has qualified type, the value has the unqualified 609 // version of the type of the lvalue; otherwise, the value has the 610 // type of the lvalue. 611 if (T.hasQualifiers()) 612 T = T.getUnqualifiedType(); 613 614 // Under the MS ABI, lock down the inheritance model now. 615 if (T->isMemberPointerType() && 616 Context.getTargetInfo().getCXXABI().isMicrosoft()) 617 (void)isCompleteType(E->getExprLoc(), T); 618 619 UpdateMarkingForLValueToRValue(E); 620 621 // Loading a __weak object implicitly retains the value, so we need a cleanup to 622 // balance that. 623 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 624 Cleanup.setExprNeedsCleanups(true); 625 626 // C++ [conv.lval]p3: 627 // If T is cv std::nullptr_t, the result is a null pointer constant. 628 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 629 ExprResult Res = 630 ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 631 632 // C11 6.3.2.1p2: 633 // ... if the lvalue has atomic type, the value has the non-atomic version 634 // of the type of the lvalue ... 635 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 636 T = Atomic->getValueType().getUnqualifiedType(); 637 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 638 nullptr, VK_RValue); 639 } 640 641 return Res; 642 } 643 644 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 645 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 646 if (Res.isInvalid()) 647 return ExprError(); 648 Res = DefaultLvalueConversion(Res.get()); 649 if (Res.isInvalid()) 650 return ExprError(); 651 return Res; 652 } 653 654 /// CallExprUnaryConversions - a special case of an unary conversion 655 /// performed on a function designator of a call expression. 656 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 657 QualType Ty = E->getType(); 658 ExprResult Res = E; 659 // Only do implicit cast for a function type, but not for a pointer 660 // to function type. 661 if (Ty->isFunctionType()) { 662 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 663 CK_FunctionToPointerDecay).get(); 664 if (Res.isInvalid()) 665 return ExprError(); 666 } 667 Res = DefaultLvalueConversion(Res.get()); 668 if (Res.isInvalid()) 669 return ExprError(); 670 return Res.get(); 671 } 672 673 /// UsualUnaryConversions - Performs various conversions that are common to most 674 /// operators (C99 6.3). The conversions of array and function types are 675 /// sometimes suppressed. For example, the array->pointer conversion doesn't 676 /// apply if the array is an argument to the sizeof or address (&) operators. 677 /// In these instances, this routine should *not* be called. 678 ExprResult Sema::UsualUnaryConversions(Expr *E) { 679 // First, convert to an r-value. 680 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 681 if (Res.isInvalid()) 682 return ExprError(); 683 E = Res.get(); 684 685 QualType Ty = E->getType(); 686 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 687 688 // Half FP have to be promoted to float unless it is natively supported 689 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 690 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 691 692 // Try to perform integral promotions if the object has a theoretically 693 // promotable type. 694 if (Ty->isIntegralOrUnscopedEnumerationType()) { 695 // C99 6.3.1.1p2: 696 // 697 // The following may be used in an expression wherever an int or 698 // unsigned int may be used: 699 // - an object or expression with an integer type whose integer 700 // conversion rank is less than or equal to the rank of int 701 // and unsigned int. 702 // - A bit-field of type _Bool, int, signed int, or unsigned int. 703 // 704 // If an int can represent all values of the original type, the 705 // value is converted to an int; otherwise, it is converted to an 706 // unsigned int. These are called the integer promotions. All 707 // other types are unchanged by the integer promotions. 708 709 QualType PTy = Context.isPromotableBitField(E); 710 if (!PTy.isNull()) { 711 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 712 return E; 713 } 714 if (Ty->isPromotableIntegerType()) { 715 QualType PT = Context.getPromotedIntegerType(Ty); 716 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 717 return E; 718 } 719 } 720 return E; 721 } 722 723 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 724 /// do not have a prototype. Arguments that have type float or __fp16 725 /// are promoted to double. All other argument types are converted by 726 /// UsualUnaryConversions(). 727 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 728 QualType Ty = E->getType(); 729 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 730 731 ExprResult Res = UsualUnaryConversions(E); 732 if (Res.isInvalid()) 733 return ExprError(); 734 E = Res.get(); 735 736 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 737 // promote to double. 738 // Note that default argument promotion applies only to float (and 739 // half/fp16); it does not apply to _Float16. 740 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 741 if (BTy && (BTy->getKind() == BuiltinType::Half || 742 BTy->getKind() == BuiltinType::Float)) { 743 if (getLangOpts().OpenCL && 744 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 745 if (BTy->getKind() == BuiltinType::Half) { 746 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 747 } 748 } else { 749 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 750 } 751 } 752 753 // C++ performs lvalue-to-rvalue conversion as a default argument 754 // promotion, even on class types, but note: 755 // C++11 [conv.lval]p2: 756 // When an lvalue-to-rvalue conversion occurs in an unevaluated 757 // operand or a subexpression thereof the value contained in the 758 // referenced object is not accessed. Otherwise, if the glvalue 759 // has a class type, the conversion copy-initializes a temporary 760 // of type T from the glvalue and the result of the conversion 761 // is a prvalue for the temporary. 762 // FIXME: add some way to gate this entire thing for correctness in 763 // potentially potentially evaluated contexts. 764 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 765 ExprResult Temp = PerformCopyInitialization( 766 InitializedEntity::InitializeTemporary(E->getType()), 767 E->getExprLoc(), E); 768 if (Temp.isInvalid()) 769 return ExprError(); 770 E = Temp.get(); 771 } 772 773 return E; 774 } 775 776 /// Determine the degree of POD-ness for an expression. 777 /// Incomplete types are considered POD, since this check can be performed 778 /// when we're in an unevaluated context. 779 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 780 if (Ty->isIncompleteType()) { 781 // C++11 [expr.call]p7: 782 // After these conversions, if the argument does not have arithmetic, 783 // enumeration, pointer, pointer to member, or class type, the program 784 // is ill-formed. 785 // 786 // Since we've already performed array-to-pointer and function-to-pointer 787 // decay, the only such type in C++ is cv void. This also handles 788 // initializer lists as variadic arguments. 789 if (Ty->isVoidType()) 790 return VAK_Invalid; 791 792 if (Ty->isObjCObjectType()) 793 return VAK_Invalid; 794 return VAK_Valid; 795 } 796 797 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 798 return VAK_Invalid; 799 800 if (Ty.isCXX98PODType(Context)) 801 return VAK_Valid; 802 803 // C++11 [expr.call]p7: 804 // Passing a potentially-evaluated argument of class type (Clause 9) 805 // having a non-trivial copy constructor, a non-trivial move constructor, 806 // or a non-trivial destructor, with no corresponding parameter, 807 // is conditionally-supported with implementation-defined semantics. 808 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 809 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 810 if (!Record->hasNonTrivialCopyConstructor() && 811 !Record->hasNonTrivialMoveConstructor() && 812 !Record->hasNonTrivialDestructor()) 813 return VAK_ValidInCXX11; 814 815 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 816 return VAK_Valid; 817 818 if (Ty->isObjCObjectType()) 819 return VAK_Invalid; 820 821 if (getLangOpts().MSVCCompat) 822 return VAK_MSVCUndefined; 823 824 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 825 // permitted to reject them. We should consider doing so. 826 return VAK_Undefined; 827 } 828 829 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 830 // Don't allow one to pass an Objective-C interface to a vararg. 831 const QualType &Ty = E->getType(); 832 VarArgKind VAK = isValidVarArgType(Ty); 833 834 // Complain about passing non-POD types through varargs. 835 switch (VAK) { 836 case VAK_ValidInCXX11: 837 DiagRuntimeBehavior( 838 E->getBeginLoc(), nullptr, 839 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 840 LLVM_FALLTHROUGH; 841 case VAK_Valid: 842 if (Ty->isRecordType()) { 843 // This is unlikely to be what the user intended. If the class has a 844 // 'c_str' member function, the user probably meant to call that. 845 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 846 PDiag(diag::warn_pass_class_arg_to_vararg) 847 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 848 } 849 break; 850 851 case VAK_Undefined: 852 case VAK_MSVCUndefined: 853 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 854 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 855 << getLangOpts().CPlusPlus11 << Ty << CT); 856 break; 857 858 case VAK_Invalid: 859 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 860 Diag(E->getBeginLoc(), 861 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 862 << Ty << CT; 863 else if (Ty->isObjCObjectType()) 864 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 865 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 866 << Ty << CT); 867 else 868 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 869 << isa<InitListExpr>(E) << Ty << CT; 870 break; 871 } 872 } 873 874 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 875 /// will create a trap if the resulting type is not a POD type. 876 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 877 FunctionDecl *FDecl) { 878 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 879 // Strip the unbridged-cast placeholder expression off, if applicable. 880 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 881 (CT == VariadicMethod || 882 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 883 E = stripARCUnbridgedCast(E); 884 885 // Otherwise, do normal placeholder checking. 886 } else { 887 ExprResult ExprRes = CheckPlaceholderExpr(E); 888 if (ExprRes.isInvalid()) 889 return ExprError(); 890 E = ExprRes.get(); 891 } 892 } 893 894 ExprResult ExprRes = DefaultArgumentPromotion(E); 895 if (ExprRes.isInvalid()) 896 return ExprError(); 897 E = ExprRes.get(); 898 899 // Diagnostics regarding non-POD argument types are 900 // emitted along with format string checking in Sema::CheckFunctionCall(). 901 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 902 // Turn this into a trap. 903 CXXScopeSpec SS; 904 SourceLocation TemplateKWLoc; 905 UnqualifiedId Name; 906 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 907 E->getBeginLoc()); 908 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 909 Name, true, false); 910 if (TrapFn.isInvalid()) 911 return ExprError(); 912 913 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 914 None, E->getEndLoc()); 915 if (Call.isInvalid()) 916 return ExprError(); 917 918 ExprResult Comma = 919 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 920 if (Comma.isInvalid()) 921 return ExprError(); 922 return Comma.get(); 923 } 924 925 if (!getLangOpts().CPlusPlus && 926 RequireCompleteType(E->getExprLoc(), E->getType(), 927 diag::err_call_incomplete_argument)) 928 return ExprError(); 929 930 return E; 931 } 932 933 /// Converts an integer to complex float type. Helper function of 934 /// UsualArithmeticConversions() 935 /// 936 /// \return false if the integer expression is an integer type and is 937 /// successfully converted to the complex type. 938 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 939 ExprResult &ComplexExpr, 940 QualType IntTy, 941 QualType ComplexTy, 942 bool SkipCast) { 943 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 944 if (SkipCast) return false; 945 if (IntTy->isIntegerType()) { 946 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 947 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 948 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 949 CK_FloatingRealToComplex); 950 } else { 951 assert(IntTy->isComplexIntegerType()); 952 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 953 CK_IntegralComplexToFloatingComplex); 954 } 955 return false; 956 } 957 958 /// Handle arithmetic conversion with complex types. Helper function of 959 /// UsualArithmeticConversions() 960 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 961 ExprResult &RHS, QualType LHSType, 962 QualType RHSType, 963 bool IsCompAssign) { 964 // if we have an integer operand, the result is the complex type. 965 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 966 /*skipCast*/false)) 967 return LHSType; 968 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 969 /*skipCast*/IsCompAssign)) 970 return RHSType; 971 972 // This handles complex/complex, complex/float, or float/complex. 973 // When both operands are complex, the shorter operand is converted to the 974 // type of the longer, and that is the type of the result. This corresponds 975 // to what is done when combining two real floating-point operands. 976 // The fun begins when size promotion occur across type domains. 977 // From H&S 6.3.4: When one operand is complex and the other is a real 978 // floating-point type, the less precise type is converted, within it's 979 // real or complex domain, to the precision of the other type. For example, 980 // when combining a "long double" with a "double _Complex", the 981 // "double _Complex" is promoted to "long double _Complex". 982 983 // Compute the rank of the two types, regardless of whether they are complex. 984 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 985 986 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 987 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 988 QualType LHSElementType = 989 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 990 QualType RHSElementType = 991 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 992 993 QualType ResultType = S.Context.getComplexType(LHSElementType); 994 if (Order < 0) { 995 // Promote the precision of the LHS if not an assignment. 996 ResultType = S.Context.getComplexType(RHSElementType); 997 if (!IsCompAssign) { 998 if (LHSComplexType) 999 LHS = 1000 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1001 else 1002 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1003 } 1004 } else if (Order > 0) { 1005 // Promote the precision of the RHS. 1006 if (RHSComplexType) 1007 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1008 else 1009 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1010 } 1011 return ResultType; 1012 } 1013 1014 /// Handle arithmetic conversion from integer to float. Helper function 1015 /// of UsualArithmeticConversions() 1016 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1017 ExprResult &IntExpr, 1018 QualType FloatTy, QualType IntTy, 1019 bool ConvertFloat, bool ConvertInt) { 1020 if (IntTy->isIntegerType()) { 1021 if (ConvertInt) 1022 // Convert intExpr to the lhs floating point type. 1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1024 CK_IntegralToFloating); 1025 return FloatTy; 1026 } 1027 1028 // Convert both sides to the appropriate complex float. 1029 assert(IntTy->isComplexIntegerType()); 1030 QualType result = S.Context.getComplexType(FloatTy); 1031 1032 // _Complex int -> _Complex float 1033 if (ConvertInt) 1034 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1035 CK_IntegralComplexToFloatingComplex); 1036 1037 // float -> _Complex float 1038 if (ConvertFloat) 1039 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1040 CK_FloatingRealToComplex); 1041 1042 return result; 1043 } 1044 1045 /// Handle arithmethic conversion with floating point types. Helper 1046 /// function of UsualArithmeticConversions() 1047 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1048 ExprResult &RHS, QualType LHSType, 1049 QualType RHSType, bool IsCompAssign) { 1050 bool LHSFloat = LHSType->isRealFloatingType(); 1051 bool RHSFloat = RHSType->isRealFloatingType(); 1052 1053 // If we have two real floating types, convert the smaller operand 1054 // to the bigger result. 1055 if (LHSFloat && RHSFloat) { 1056 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1057 if (order > 0) { 1058 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1059 return LHSType; 1060 } 1061 1062 assert(order < 0 && "illegal float comparison"); 1063 if (!IsCompAssign) 1064 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1065 return RHSType; 1066 } 1067 1068 if (LHSFloat) { 1069 // Half FP has to be promoted to float unless it is natively supported 1070 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1071 LHSType = S.Context.FloatTy; 1072 1073 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1074 /*convertFloat=*/!IsCompAssign, 1075 /*convertInt=*/ true); 1076 } 1077 assert(RHSFloat); 1078 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1079 /*convertInt=*/ true, 1080 /*convertFloat=*/!IsCompAssign); 1081 } 1082 1083 /// Diagnose attempts to convert between __float128 and long double if 1084 /// there is no support for such conversion. Helper function of 1085 /// UsualArithmeticConversions(). 1086 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1087 QualType RHSType) { 1088 /* No issue converting if at least one of the types is not a floating point 1089 type or the two types have the same rank. 1090 */ 1091 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1092 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1093 return false; 1094 1095 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1096 "The remaining types must be floating point types."); 1097 1098 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1099 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1100 1101 QualType LHSElemType = LHSComplex ? 1102 LHSComplex->getElementType() : LHSType; 1103 QualType RHSElemType = RHSComplex ? 1104 RHSComplex->getElementType() : RHSType; 1105 1106 // No issue if the two types have the same representation 1107 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1108 &S.Context.getFloatTypeSemantics(RHSElemType)) 1109 return false; 1110 1111 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1112 RHSElemType == S.Context.LongDoubleTy); 1113 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1114 RHSElemType == S.Context.Float128Ty); 1115 1116 // We've handled the situation where __float128 and long double have the same 1117 // representation. We allow all conversions for all possible long double types 1118 // except PPC's double double. 1119 return Float128AndLongDouble && 1120 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1121 &llvm::APFloat::PPCDoubleDouble()); 1122 } 1123 1124 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1125 1126 namespace { 1127 /// These helper callbacks are placed in an anonymous namespace to 1128 /// permit their use as function template parameters. 1129 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1130 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1131 } 1132 1133 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1134 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1135 CK_IntegralComplexCast); 1136 } 1137 } 1138 1139 /// Handle integer arithmetic conversions. Helper function of 1140 /// UsualArithmeticConversions() 1141 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1142 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1143 ExprResult &RHS, QualType LHSType, 1144 QualType RHSType, bool IsCompAssign) { 1145 // The rules for this case are in C99 6.3.1.8 1146 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1147 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1148 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1149 if (LHSSigned == RHSSigned) { 1150 // Same signedness; use the higher-ranked type 1151 if (order >= 0) { 1152 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1153 return LHSType; 1154 } else if (!IsCompAssign) 1155 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1156 return RHSType; 1157 } else if (order != (LHSSigned ? 1 : -1)) { 1158 // The unsigned type has greater than or equal rank to the 1159 // signed type, so use the unsigned type 1160 if (RHSSigned) { 1161 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1162 return LHSType; 1163 } else if (!IsCompAssign) 1164 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1165 return RHSType; 1166 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1167 // The two types are different widths; if we are here, that 1168 // means the signed type is larger than the unsigned type, so 1169 // use the signed type. 1170 if (LHSSigned) { 1171 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1172 return LHSType; 1173 } else if (!IsCompAssign) 1174 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1175 return RHSType; 1176 } else { 1177 // The signed type is higher-ranked than the unsigned type, 1178 // but isn't actually any bigger (like unsigned int and long 1179 // on most 32-bit systems). Use the unsigned type corresponding 1180 // to the signed type. 1181 QualType result = 1182 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1183 RHS = (*doRHSCast)(S, RHS.get(), result); 1184 if (!IsCompAssign) 1185 LHS = (*doLHSCast)(S, LHS.get(), result); 1186 return result; 1187 } 1188 } 1189 1190 /// Handle conversions with GCC complex int extension. Helper function 1191 /// of UsualArithmeticConversions() 1192 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1193 ExprResult &RHS, QualType LHSType, 1194 QualType RHSType, 1195 bool IsCompAssign) { 1196 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1197 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1198 1199 if (LHSComplexInt && RHSComplexInt) { 1200 QualType LHSEltType = LHSComplexInt->getElementType(); 1201 QualType RHSEltType = RHSComplexInt->getElementType(); 1202 QualType ScalarType = 1203 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1204 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1205 1206 return S.Context.getComplexType(ScalarType); 1207 } 1208 1209 if (LHSComplexInt) { 1210 QualType LHSEltType = LHSComplexInt->getElementType(); 1211 QualType ScalarType = 1212 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1213 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1214 QualType ComplexType = S.Context.getComplexType(ScalarType); 1215 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 1218 return ComplexType; 1219 } 1220 1221 assert(RHSComplexInt); 1222 1223 QualType RHSEltType = RHSComplexInt->getElementType(); 1224 QualType ScalarType = 1225 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1226 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1227 QualType ComplexType = S.Context.getComplexType(ScalarType); 1228 1229 if (!IsCompAssign) 1230 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1231 CK_IntegralRealToComplex); 1232 return ComplexType; 1233 } 1234 1235 /// UsualArithmeticConversions - Performs various conversions that are common to 1236 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1237 /// routine returns the first non-arithmetic type found. The client is 1238 /// responsible for emitting appropriate error diagnostics. 1239 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1240 bool IsCompAssign) { 1241 if (!IsCompAssign) { 1242 LHS = UsualUnaryConversions(LHS.get()); 1243 if (LHS.isInvalid()) 1244 return QualType(); 1245 } 1246 1247 RHS = UsualUnaryConversions(RHS.get()); 1248 if (RHS.isInvalid()) 1249 return QualType(); 1250 1251 // For conversion purposes, we ignore any qualifiers. 1252 // For example, "const float" and "float" are equivalent. 1253 QualType LHSType = 1254 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1255 QualType RHSType = 1256 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1257 1258 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1259 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1260 LHSType = AtomicLHS->getValueType(); 1261 1262 // If both types are identical, no conversion is needed. 1263 if (LHSType == RHSType) 1264 return LHSType; 1265 1266 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1267 // The caller can deal with this (e.g. pointer + int). 1268 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1269 return QualType(); 1270 1271 // Apply unary and bitfield promotions to the LHS's type. 1272 QualType LHSUnpromotedType = LHSType; 1273 if (LHSType->isPromotableIntegerType()) 1274 LHSType = Context.getPromotedIntegerType(LHSType); 1275 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1276 if (!LHSBitfieldPromoteTy.isNull()) 1277 LHSType = LHSBitfieldPromoteTy; 1278 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1279 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1280 1281 // If both types are identical, no conversion is needed. 1282 if (LHSType == RHSType) 1283 return LHSType; 1284 1285 // At this point, we have two different arithmetic types. 1286 1287 // Diagnose attempts to convert between __float128 and long double where 1288 // such conversions currently can't be handled. 1289 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1290 return QualType(); 1291 1292 // Handle complex types first (C99 6.3.1.8p1). 1293 if (LHSType->isComplexType() || RHSType->isComplexType()) 1294 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1295 IsCompAssign); 1296 1297 // Now handle "real" floating types (i.e. float, double, long double). 1298 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1299 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1300 IsCompAssign); 1301 1302 // Handle GCC complex int extension. 1303 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1304 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1305 IsCompAssign); 1306 1307 // Finally, we have two differing integer types. 1308 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1309 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1310 } 1311 1312 1313 //===----------------------------------------------------------------------===// 1314 // Semantic Analysis for various Expression Types 1315 //===----------------------------------------------------------------------===// 1316 1317 1318 ExprResult 1319 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1320 SourceLocation DefaultLoc, 1321 SourceLocation RParenLoc, 1322 Expr *ControllingExpr, 1323 ArrayRef<ParsedType> ArgTypes, 1324 ArrayRef<Expr *> ArgExprs) { 1325 unsigned NumAssocs = ArgTypes.size(); 1326 assert(NumAssocs == ArgExprs.size()); 1327 1328 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1329 for (unsigned i = 0; i < NumAssocs; ++i) { 1330 if (ArgTypes[i]) 1331 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1332 else 1333 Types[i] = nullptr; 1334 } 1335 1336 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1337 ControllingExpr, 1338 llvm::makeArrayRef(Types, NumAssocs), 1339 ArgExprs); 1340 delete [] Types; 1341 return ER; 1342 } 1343 1344 ExprResult 1345 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1346 SourceLocation DefaultLoc, 1347 SourceLocation RParenLoc, 1348 Expr *ControllingExpr, 1349 ArrayRef<TypeSourceInfo *> Types, 1350 ArrayRef<Expr *> Exprs) { 1351 unsigned NumAssocs = Types.size(); 1352 assert(NumAssocs == Exprs.size()); 1353 1354 // Decay and strip qualifiers for the controlling expression type, and handle 1355 // placeholder type replacement. See committee discussion from WG14 DR423. 1356 { 1357 EnterExpressionEvaluationContext Unevaluated( 1358 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1359 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1360 if (R.isInvalid()) 1361 return ExprError(); 1362 ControllingExpr = R.get(); 1363 } 1364 1365 // The controlling expression is an unevaluated operand, so side effects are 1366 // likely unintended. 1367 if (!inTemplateInstantiation() && 1368 ControllingExpr->HasSideEffects(Context, false)) 1369 Diag(ControllingExpr->getExprLoc(), 1370 diag::warn_side_effects_unevaluated_context); 1371 1372 bool TypeErrorFound = false, 1373 IsResultDependent = ControllingExpr->isTypeDependent(), 1374 ContainsUnexpandedParameterPack 1375 = ControllingExpr->containsUnexpandedParameterPack(); 1376 1377 for (unsigned i = 0; i < NumAssocs; ++i) { 1378 if (Exprs[i]->containsUnexpandedParameterPack()) 1379 ContainsUnexpandedParameterPack = true; 1380 1381 if (Types[i]) { 1382 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1383 ContainsUnexpandedParameterPack = true; 1384 1385 if (Types[i]->getType()->isDependentType()) { 1386 IsResultDependent = true; 1387 } else { 1388 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1389 // complete object type other than a variably modified type." 1390 unsigned D = 0; 1391 if (Types[i]->getType()->isIncompleteType()) 1392 D = diag::err_assoc_type_incomplete; 1393 else if (!Types[i]->getType()->isObjectType()) 1394 D = diag::err_assoc_type_nonobject; 1395 else if (Types[i]->getType()->isVariablyModifiedType()) 1396 D = diag::err_assoc_type_variably_modified; 1397 1398 if (D != 0) { 1399 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1400 << Types[i]->getTypeLoc().getSourceRange() 1401 << Types[i]->getType(); 1402 TypeErrorFound = true; 1403 } 1404 1405 // C11 6.5.1.1p2 "No two generic associations in the same generic 1406 // selection shall specify compatible types." 1407 for (unsigned j = i+1; j < NumAssocs; ++j) 1408 if (Types[j] && !Types[j]->getType()->isDependentType() && 1409 Context.typesAreCompatible(Types[i]->getType(), 1410 Types[j]->getType())) { 1411 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1412 diag::err_assoc_compatible_types) 1413 << Types[j]->getTypeLoc().getSourceRange() 1414 << Types[j]->getType() 1415 << Types[i]->getType(); 1416 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1417 diag::note_compat_assoc) 1418 << Types[i]->getTypeLoc().getSourceRange() 1419 << Types[i]->getType(); 1420 TypeErrorFound = true; 1421 } 1422 } 1423 } 1424 } 1425 if (TypeErrorFound) 1426 return ExprError(); 1427 1428 // If we determined that the generic selection is result-dependent, don't 1429 // try to compute the result expression. 1430 if (IsResultDependent) 1431 return new (Context) GenericSelectionExpr( 1432 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1433 ContainsUnexpandedParameterPack); 1434 1435 SmallVector<unsigned, 1> CompatIndices; 1436 unsigned DefaultIndex = -1U; 1437 for (unsigned i = 0; i < NumAssocs; ++i) { 1438 if (!Types[i]) 1439 DefaultIndex = i; 1440 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1441 Types[i]->getType())) 1442 CompatIndices.push_back(i); 1443 } 1444 1445 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1446 // type compatible with at most one of the types named in its generic 1447 // association list." 1448 if (CompatIndices.size() > 1) { 1449 // We strip parens here because the controlling expression is typically 1450 // parenthesized in macro definitions. 1451 ControllingExpr = ControllingExpr->IgnoreParens(); 1452 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1453 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1454 << (unsigned)CompatIndices.size(); 1455 for (unsigned I : CompatIndices) { 1456 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1457 diag::note_compat_assoc) 1458 << Types[I]->getTypeLoc().getSourceRange() 1459 << Types[I]->getType(); 1460 } 1461 return ExprError(); 1462 } 1463 1464 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1465 // its controlling expression shall have type compatible with exactly one of 1466 // the types named in its generic association list." 1467 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1468 // We strip parens here because the controlling expression is typically 1469 // parenthesized in macro definitions. 1470 ControllingExpr = ControllingExpr->IgnoreParens(); 1471 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1472 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1473 return ExprError(); 1474 } 1475 1476 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1477 // type name that is compatible with the type of the controlling expression, 1478 // then the result expression of the generic selection is the expression 1479 // in that generic association. Otherwise, the result expression of the 1480 // generic selection is the expression in the default generic association." 1481 unsigned ResultIndex = 1482 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1483 1484 return new (Context) GenericSelectionExpr( 1485 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1486 ContainsUnexpandedParameterPack, ResultIndex); 1487 } 1488 1489 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1490 /// location of the token and the offset of the ud-suffix within it. 1491 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1492 unsigned Offset) { 1493 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1494 S.getLangOpts()); 1495 } 1496 1497 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1498 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1499 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1500 IdentifierInfo *UDSuffix, 1501 SourceLocation UDSuffixLoc, 1502 ArrayRef<Expr*> Args, 1503 SourceLocation LitEndLoc) { 1504 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1505 1506 QualType ArgTy[2]; 1507 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1508 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1509 if (ArgTy[ArgIdx]->isArrayType()) 1510 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1511 } 1512 1513 DeclarationName OpName = 1514 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1515 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1516 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1517 1518 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1519 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1520 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1521 /*AllowStringTemplate*/ false, 1522 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1523 return ExprError(); 1524 1525 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1526 } 1527 1528 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1529 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1530 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1531 /// multiple tokens. However, the common case is that StringToks points to one 1532 /// string. 1533 /// 1534 ExprResult 1535 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1536 assert(!StringToks.empty() && "Must have at least one string!"); 1537 1538 StringLiteralParser Literal(StringToks, PP); 1539 if (Literal.hadError) 1540 return ExprError(); 1541 1542 SmallVector<SourceLocation, 4> StringTokLocs; 1543 for (const Token &Tok : StringToks) 1544 StringTokLocs.push_back(Tok.getLocation()); 1545 1546 QualType CharTy = Context.CharTy; 1547 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1548 if (Literal.isWide()) { 1549 CharTy = Context.getWideCharType(); 1550 Kind = StringLiteral::Wide; 1551 } else if (Literal.isUTF8()) { 1552 if (getLangOpts().Char8) 1553 CharTy = Context.Char8Ty; 1554 Kind = StringLiteral::UTF8; 1555 } else if (Literal.isUTF16()) { 1556 CharTy = Context.Char16Ty; 1557 Kind = StringLiteral::UTF16; 1558 } else if (Literal.isUTF32()) { 1559 CharTy = Context.Char32Ty; 1560 Kind = StringLiteral::UTF32; 1561 } else if (Literal.isPascal()) { 1562 CharTy = Context.UnsignedCharTy; 1563 } 1564 1565 QualType CharTyConst = CharTy; 1566 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1567 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1568 CharTyConst.addConst(); 1569 1570 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1571 1572 // Get an array type for the string, according to C99 6.4.5. This includes 1573 // the nul terminator character as well as the string length for pascal 1574 // strings. 1575 QualType StrTy = Context.getConstantArrayType( 1576 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1577 ArrayType::Normal, 0); 1578 1579 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1580 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1581 Kind, Literal.Pascal, StrTy, 1582 &StringTokLocs[0], 1583 StringTokLocs.size()); 1584 if (Literal.getUDSuffix().empty()) 1585 return Lit; 1586 1587 // We're building a user-defined literal. 1588 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1589 SourceLocation UDSuffixLoc = 1590 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1591 Literal.getUDSuffixOffset()); 1592 1593 // Make sure we're allowed user-defined literals here. 1594 if (!UDLScope) 1595 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1596 1597 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1598 // operator "" X (str, len) 1599 QualType SizeType = Context.getSizeType(); 1600 1601 DeclarationName OpName = 1602 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1603 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1604 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1605 1606 QualType ArgTy[] = { 1607 Context.getArrayDecayedType(StrTy), SizeType 1608 }; 1609 1610 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1611 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1612 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1613 /*AllowStringTemplate*/ true, 1614 /*DiagnoseMissing*/ true)) { 1615 1616 case LOLR_Cooked: { 1617 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1618 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1619 StringTokLocs[0]); 1620 Expr *Args[] = { Lit, LenArg }; 1621 1622 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1623 } 1624 1625 case LOLR_StringTemplate: { 1626 TemplateArgumentListInfo ExplicitArgs; 1627 1628 unsigned CharBits = Context.getIntWidth(CharTy); 1629 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1630 llvm::APSInt Value(CharBits, CharIsUnsigned); 1631 1632 TemplateArgument TypeArg(CharTy); 1633 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1634 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1635 1636 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1637 Value = Lit->getCodeUnit(I); 1638 TemplateArgument Arg(Context, Value, CharTy); 1639 TemplateArgumentLocInfo ArgInfo; 1640 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1641 } 1642 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1643 &ExplicitArgs); 1644 } 1645 case LOLR_Raw: 1646 case LOLR_Template: 1647 case LOLR_ErrorNoDiagnostic: 1648 llvm_unreachable("unexpected literal operator lookup result"); 1649 case LOLR_Error: 1650 return ExprError(); 1651 } 1652 llvm_unreachable("unexpected literal operator lookup result"); 1653 } 1654 1655 ExprResult 1656 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1657 SourceLocation Loc, 1658 const CXXScopeSpec *SS) { 1659 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1660 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1661 } 1662 1663 /// BuildDeclRefExpr - Build an expression that references a 1664 /// declaration that does not require a closure capture. 1665 ExprResult 1666 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1667 const DeclarationNameInfo &NameInfo, 1668 const CXXScopeSpec *SS, NamedDecl *FoundD, 1669 const TemplateArgumentListInfo *TemplateArgs) { 1670 bool RefersToCapturedVariable = 1671 isa<VarDecl>(D) && 1672 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1673 1674 DeclRefExpr *E; 1675 if (isa<VarTemplateSpecializationDecl>(D)) { 1676 VarTemplateSpecializationDecl *VarSpec = 1677 cast<VarTemplateSpecializationDecl>(D); 1678 1679 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1680 : NestedNameSpecifierLoc(), 1681 VarSpec->getTemplateKeywordLoc(), D, 1682 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1683 FoundD, TemplateArgs); 1684 } else { 1685 assert(!TemplateArgs && "No template arguments for non-variable" 1686 " template specialization references"); 1687 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1688 : NestedNameSpecifierLoc(), 1689 SourceLocation(), D, RefersToCapturedVariable, 1690 NameInfo, Ty, VK, FoundD); 1691 } 1692 1693 MarkDeclRefReferenced(E); 1694 1695 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1696 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1697 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1698 getCurFunction()->recordUseOfWeak(E); 1699 1700 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1701 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1702 FD = IFD->getAnonField(); 1703 if (FD) { 1704 UnusedPrivateFields.remove(FD); 1705 // Just in case we're building an illegal pointer-to-member. 1706 if (FD->isBitField()) 1707 E->setObjectKind(OK_BitField); 1708 } 1709 1710 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1711 // designates a bit-field. 1712 if (auto *BD = dyn_cast<BindingDecl>(D)) 1713 if (auto *BE = BD->getBinding()) 1714 E->setObjectKind(BE->getObjectKind()); 1715 1716 return E; 1717 } 1718 1719 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1720 /// possibly a list of template arguments. 1721 /// 1722 /// If this produces template arguments, it is permitted to call 1723 /// DecomposeTemplateName. 1724 /// 1725 /// This actually loses a lot of source location information for 1726 /// non-standard name kinds; we should consider preserving that in 1727 /// some way. 1728 void 1729 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1730 TemplateArgumentListInfo &Buffer, 1731 DeclarationNameInfo &NameInfo, 1732 const TemplateArgumentListInfo *&TemplateArgs) { 1733 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1734 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1735 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1736 1737 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1738 Id.TemplateId->NumArgs); 1739 translateTemplateArguments(TemplateArgsPtr, Buffer); 1740 1741 TemplateName TName = Id.TemplateId->Template.get(); 1742 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1743 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1744 TemplateArgs = &Buffer; 1745 } else { 1746 NameInfo = GetNameFromUnqualifiedId(Id); 1747 TemplateArgs = nullptr; 1748 } 1749 } 1750 1751 static void emitEmptyLookupTypoDiagnostic( 1752 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1753 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1754 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1755 DeclContext *Ctx = 1756 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1757 if (!TC) { 1758 // Emit a special diagnostic for failed member lookups. 1759 // FIXME: computing the declaration context might fail here (?) 1760 if (Ctx) 1761 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1762 << SS.getRange(); 1763 else 1764 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1765 return; 1766 } 1767 1768 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1769 bool DroppedSpecifier = 1770 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1771 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1772 ? diag::note_implicit_param_decl 1773 : diag::note_previous_decl; 1774 if (!Ctx) 1775 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1776 SemaRef.PDiag(NoteID)); 1777 else 1778 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1779 << Typo << Ctx << DroppedSpecifier 1780 << SS.getRange(), 1781 SemaRef.PDiag(NoteID)); 1782 } 1783 1784 /// Diagnose an empty lookup. 1785 /// 1786 /// \return false if new lookup candidates were found 1787 bool 1788 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1789 std::unique_ptr<CorrectionCandidateCallback> CCC, 1790 TemplateArgumentListInfo *ExplicitTemplateArgs, 1791 ArrayRef<Expr *> Args, TypoExpr **Out) { 1792 DeclarationName Name = R.getLookupName(); 1793 1794 unsigned diagnostic = diag::err_undeclared_var_use; 1795 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1796 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1797 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1799 diagnostic = diag::err_undeclared_use; 1800 diagnostic_suggest = diag::err_undeclared_use_suggest; 1801 } 1802 1803 // If the original lookup was an unqualified lookup, fake an 1804 // unqualified lookup. This is useful when (for example) the 1805 // original lookup would not have found something because it was a 1806 // dependent name. 1807 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1808 while (DC) { 1809 if (isa<CXXRecordDecl>(DC)) { 1810 LookupQualifiedName(R, DC); 1811 1812 if (!R.empty()) { 1813 // Don't give errors about ambiguities in this lookup. 1814 R.suppressDiagnostics(); 1815 1816 // During a default argument instantiation the CurContext points 1817 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1818 // function parameter list, hence add an explicit check. 1819 bool isDefaultArgument = 1820 !CodeSynthesisContexts.empty() && 1821 CodeSynthesisContexts.back().Kind == 1822 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1823 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1824 bool isInstance = CurMethod && 1825 CurMethod->isInstance() && 1826 DC == CurMethod->getParent() && !isDefaultArgument; 1827 1828 // Give a code modification hint to insert 'this->'. 1829 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1830 // Actually quite difficult! 1831 if (getLangOpts().MSVCCompat) 1832 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1833 if (isInstance) { 1834 Diag(R.getNameLoc(), diagnostic) << Name 1835 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1836 CheckCXXThisCapture(R.getNameLoc()); 1837 } else { 1838 Diag(R.getNameLoc(), diagnostic) << Name; 1839 } 1840 1841 // Do we really want to note all of these? 1842 for (NamedDecl *D : R) 1843 Diag(D->getLocation(), diag::note_dependent_var_use); 1844 1845 // Return true if we are inside a default argument instantiation 1846 // and the found name refers to an instance member function, otherwise 1847 // the function calling DiagnoseEmptyLookup will try to create an 1848 // implicit member call and this is wrong for default argument. 1849 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1850 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1851 return true; 1852 } 1853 1854 // Tell the callee to try to recover. 1855 return false; 1856 } 1857 1858 R.clear(); 1859 } 1860 1861 // In Microsoft mode, if we are performing lookup from within a friend 1862 // function definition declared at class scope then we must set 1863 // DC to the lexical parent to be able to search into the parent 1864 // class. 1865 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1866 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1867 DC->getLexicalParent()->isRecord()) 1868 DC = DC->getLexicalParent(); 1869 else 1870 DC = DC->getParent(); 1871 } 1872 1873 // We didn't find anything, so try to correct for a typo. 1874 TypoCorrection Corrected; 1875 if (S && Out) { 1876 SourceLocation TypoLoc = R.getNameLoc(); 1877 assert(!ExplicitTemplateArgs && 1878 "Diagnosing an empty lookup with explicit template args!"); 1879 *Out = CorrectTypoDelayed( 1880 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1881 [=](const TypoCorrection &TC) { 1882 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1883 diagnostic, diagnostic_suggest); 1884 }, 1885 nullptr, CTK_ErrorRecovery); 1886 if (*Out) 1887 return true; 1888 } else if (S && (Corrected = 1889 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1890 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1891 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1892 bool DroppedSpecifier = 1893 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1894 R.setLookupName(Corrected.getCorrection()); 1895 1896 bool AcceptableWithRecovery = false; 1897 bool AcceptableWithoutRecovery = false; 1898 NamedDecl *ND = Corrected.getFoundDecl(); 1899 if (ND) { 1900 if (Corrected.isOverloaded()) { 1901 OverloadCandidateSet OCS(R.getNameLoc(), 1902 OverloadCandidateSet::CSK_Normal); 1903 OverloadCandidateSet::iterator Best; 1904 for (NamedDecl *CD : Corrected) { 1905 if (FunctionTemplateDecl *FTD = 1906 dyn_cast<FunctionTemplateDecl>(CD)) 1907 AddTemplateOverloadCandidate( 1908 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1909 Args, OCS); 1910 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1911 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1912 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1913 Args, OCS); 1914 } 1915 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1916 case OR_Success: 1917 ND = Best->FoundDecl; 1918 Corrected.setCorrectionDecl(ND); 1919 break; 1920 default: 1921 // FIXME: Arbitrarily pick the first declaration for the note. 1922 Corrected.setCorrectionDecl(ND); 1923 break; 1924 } 1925 } 1926 R.addDecl(ND); 1927 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1928 CXXRecordDecl *Record = nullptr; 1929 if (Corrected.getCorrectionSpecifier()) { 1930 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1931 Record = Ty->getAsCXXRecordDecl(); 1932 } 1933 if (!Record) 1934 Record = cast<CXXRecordDecl>( 1935 ND->getDeclContext()->getRedeclContext()); 1936 R.setNamingClass(Record); 1937 } 1938 1939 auto *UnderlyingND = ND->getUnderlyingDecl(); 1940 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1941 isa<FunctionTemplateDecl>(UnderlyingND); 1942 // FIXME: If we ended up with a typo for a type name or 1943 // Objective-C class name, we're in trouble because the parser 1944 // is in the wrong place to recover. Suggest the typo 1945 // correction, but don't make it a fix-it since we're not going 1946 // to recover well anyway. 1947 AcceptableWithoutRecovery = 1948 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1949 } else { 1950 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1951 // because we aren't able to recover. 1952 AcceptableWithoutRecovery = true; 1953 } 1954 1955 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1956 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1957 ? diag::note_implicit_param_decl 1958 : diag::note_previous_decl; 1959 if (SS.isEmpty()) 1960 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1961 PDiag(NoteID), AcceptableWithRecovery); 1962 else 1963 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1964 << Name << computeDeclContext(SS, false) 1965 << DroppedSpecifier << SS.getRange(), 1966 PDiag(NoteID), AcceptableWithRecovery); 1967 1968 // Tell the callee whether to try to recover. 1969 return !AcceptableWithRecovery; 1970 } 1971 } 1972 R.clear(); 1973 1974 // Emit a special diagnostic for failed member lookups. 1975 // FIXME: computing the declaration context might fail here (?) 1976 if (!SS.isEmpty()) { 1977 Diag(R.getNameLoc(), diag::err_no_member) 1978 << Name << computeDeclContext(SS, false) 1979 << SS.getRange(); 1980 return true; 1981 } 1982 1983 // Give up, we can't recover. 1984 Diag(R.getNameLoc(), diagnostic) << Name; 1985 return true; 1986 } 1987 1988 /// In Microsoft mode, if we are inside a template class whose parent class has 1989 /// dependent base classes, and we can't resolve an unqualified identifier, then 1990 /// assume the identifier is a member of a dependent base class. We can only 1991 /// recover successfully in static methods, instance methods, and other contexts 1992 /// where 'this' is available. This doesn't precisely match MSVC's 1993 /// instantiation model, but it's close enough. 1994 static Expr * 1995 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1996 DeclarationNameInfo &NameInfo, 1997 SourceLocation TemplateKWLoc, 1998 const TemplateArgumentListInfo *TemplateArgs) { 1999 // Only try to recover from lookup into dependent bases in static methods or 2000 // contexts where 'this' is available. 2001 QualType ThisType = S.getCurrentThisType(); 2002 const CXXRecordDecl *RD = nullptr; 2003 if (!ThisType.isNull()) 2004 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2005 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2006 RD = MD->getParent(); 2007 if (!RD || !RD->hasAnyDependentBases()) 2008 return nullptr; 2009 2010 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2011 // is available, suggest inserting 'this->' as a fixit. 2012 SourceLocation Loc = NameInfo.getLoc(); 2013 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2014 DB << NameInfo.getName() << RD; 2015 2016 if (!ThisType.isNull()) { 2017 DB << FixItHint::CreateInsertion(Loc, "this->"); 2018 return CXXDependentScopeMemberExpr::Create( 2019 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2020 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2021 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2022 } 2023 2024 // Synthesize a fake NNS that points to the derived class. This will 2025 // perform name lookup during template instantiation. 2026 CXXScopeSpec SS; 2027 auto *NNS = 2028 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2029 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2030 return DependentScopeDeclRefExpr::Create( 2031 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2032 TemplateArgs); 2033 } 2034 2035 ExprResult 2036 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2037 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2038 bool HasTrailingLParen, bool IsAddressOfOperand, 2039 std::unique_ptr<CorrectionCandidateCallback> CCC, 2040 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2041 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2042 "cannot be direct & operand and have a trailing lparen"); 2043 if (SS.isInvalid()) 2044 return ExprError(); 2045 2046 TemplateArgumentListInfo TemplateArgsBuffer; 2047 2048 // Decompose the UnqualifiedId into the following data. 2049 DeclarationNameInfo NameInfo; 2050 const TemplateArgumentListInfo *TemplateArgs; 2051 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2052 2053 DeclarationName Name = NameInfo.getName(); 2054 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2055 SourceLocation NameLoc = NameInfo.getLoc(); 2056 2057 if (II && II->isEditorPlaceholder()) { 2058 // FIXME: When typed placeholders are supported we can create a typed 2059 // placeholder expression node. 2060 return ExprError(); 2061 } 2062 2063 // C++ [temp.dep.expr]p3: 2064 // An id-expression is type-dependent if it contains: 2065 // -- an identifier that was declared with a dependent type, 2066 // (note: handled after lookup) 2067 // -- a template-id that is dependent, 2068 // (note: handled in BuildTemplateIdExpr) 2069 // -- a conversion-function-id that specifies a dependent type, 2070 // -- a nested-name-specifier that contains a class-name that 2071 // names a dependent type. 2072 // Determine whether this is a member of an unknown specialization; 2073 // we need to handle these differently. 2074 bool DependentID = false; 2075 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2076 Name.getCXXNameType()->isDependentType()) { 2077 DependentID = true; 2078 } else if (SS.isSet()) { 2079 if (DeclContext *DC = computeDeclContext(SS, false)) { 2080 if (RequireCompleteDeclContext(SS, DC)) 2081 return ExprError(); 2082 } else { 2083 DependentID = true; 2084 } 2085 } 2086 2087 if (DependentID) 2088 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2089 IsAddressOfOperand, TemplateArgs); 2090 2091 // Perform the required lookup. 2092 LookupResult R(*this, NameInfo, 2093 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2094 ? LookupObjCImplicitSelfParam 2095 : LookupOrdinaryName); 2096 if (TemplateKWLoc.isValid() || TemplateArgs) { 2097 // Lookup the template name again to correctly establish the context in 2098 // which it was found. This is really unfortunate as we already did the 2099 // lookup to determine that it was a template name in the first place. If 2100 // this becomes a performance hit, we can work harder to preserve those 2101 // results until we get here but it's likely not worth it. 2102 bool MemberOfUnknownSpecialization; 2103 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2104 MemberOfUnknownSpecialization, TemplateKWLoc)) 2105 return ExprError(); 2106 2107 if (MemberOfUnknownSpecialization || 2108 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2109 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2110 IsAddressOfOperand, TemplateArgs); 2111 } else { 2112 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2113 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2114 2115 // If the result might be in a dependent base class, this is a dependent 2116 // id-expression. 2117 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2118 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2119 IsAddressOfOperand, TemplateArgs); 2120 2121 // If this reference is in an Objective-C method, then we need to do 2122 // some special Objective-C lookup, too. 2123 if (IvarLookupFollowUp) { 2124 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2125 if (E.isInvalid()) 2126 return ExprError(); 2127 2128 if (Expr *Ex = E.getAs<Expr>()) 2129 return Ex; 2130 } 2131 } 2132 2133 if (R.isAmbiguous()) 2134 return ExprError(); 2135 2136 // This could be an implicitly declared function reference (legal in C90, 2137 // extension in C99, forbidden in C++). 2138 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2139 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2140 if (D) R.addDecl(D); 2141 } 2142 2143 // Determine whether this name might be a candidate for 2144 // argument-dependent lookup. 2145 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2146 2147 if (R.empty() && !ADL) { 2148 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2149 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2150 TemplateKWLoc, TemplateArgs)) 2151 return E; 2152 } 2153 2154 // Don't diagnose an empty lookup for inline assembly. 2155 if (IsInlineAsmIdentifier) 2156 return ExprError(); 2157 2158 // If this name wasn't predeclared and if this is not a function 2159 // call, diagnose the problem. 2160 TypoExpr *TE = nullptr; 2161 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2162 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2163 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2164 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2165 "Typo correction callback misconfigured"); 2166 if (CCC) { 2167 // Make sure the callback knows what the typo being diagnosed is. 2168 CCC->setTypoName(II); 2169 if (SS.isValid()) 2170 CCC->setTypoNNS(SS.getScopeRep()); 2171 } 2172 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2173 // a template name, but we happen to have always already looked up the name 2174 // before we get here if it must be a template name. 2175 if (DiagnoseEmptyLookup(S, SS, R, 2176 CCC ? std::move(CCC) : std::move(DefaultValidator), 2177 nullptr, None, &TE)) { 2178 if (TE && KeywordReplacement) { 2179 auto &State = getTypoExprState(TE); 2180 auto BestTC = State.Consumer->getNextCorrection(); 2181 if (BestTC.isKeyword()) { 2182 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2183 if (State.DiagHandler) 2184 State.DiagHandler(BestTC); 2185 KeywordReplacement->startToken(); 2186 KeywordReplacement->setKind(II->getTokenID()); 2187 KeywordReplacement->setIdentifierInfo(II); 2188 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2189 // Clean up the state associated with the TypoExpr, since it has 2190 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2191 clearDelayedTypo(TE); 2192 // Signal that a correction to a keyword was performed by returning a 2193 // valid-but-null ExprResult. 2194 return (Expr*)nullptr; 2195 } 2196 State.Consumer->resetCorrectionStream(); 2197 } 2198 return TE ? TE : ExprError(); 2199 } 2200 2201 assert(!R.empty() && 2202 "DiagnoseEmptyLookup returned false but added no results"); 2203 2204 // If we found an Objective-C instance variable, let 2205 // LookupInObjCMethod build the appropriate expression to 2206 // reference the ivar. 2207 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2208 R.clear(); 2209 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2210 // In a hopelessly buggy code, Objective-C instance variable 2211 // lookup fails and no expression will be built to reference it. 2212 if (!E.isInvalid() && !E.get()) 2213 return ExprError(); 2214 return E; 2215 } 2216 } 2217 2218 // This is guaranteed from this point on. 2219 assert(!R.empty() || ADL); 2220 2221 // Check whether this might be a C++ implicit instance member access. 2222 // C++ [class.mfct.non-static]p3: 2223 // When an id-expression that is not part of a class member access 2224 // syntax and not used to form a pointer to member is used in the 2225 // body of a non-static member function of class X, if name lookup 2226 // resolves the name in the id-expression to a non-static non-type 2227 // member of some class C, the id-expression is transformed into a 2228 // class member access expression using (*this) as the 2229 // postfix-expression to the left of the . operator. 2230 // 2231 // But we don't actually need to do this for '&' operands if R 2232 // resolved to a function or overloaded function set, because the 2233 // expression is ill-formed if it actually works out to be a 2234 // non-static member function: 2235 // 2236 // C++ [expr.ref]p4: 2237 // Otherwise, if E1.E2 refers to a non-static member function. . . 2238 // [t]he expression can be used only as the left-hand operand of a 2239 // member function call. 2240 // 2241 // There are other safeguards against such uses, but it's important 2242 // to get this right here so that we don't end up making a 2243 // spuriously dependent expression if we're inside a dependent 2244 // instance method. 2245 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2246 bool MightBeImplicitMember; 2247 if (!IsAddressOfOperand) 2248 MightBeImplicitMember = true; 2249 else if (!SS.isEmpty()) 2250 MightBeImplicitMember = false; 2251 else if (R.isOverloadedResult()) 2252 MightBeImplicitMember = false; 2253 else if (R.isUnresolvableResult()) 2254 MightBeImplicitMember = true; 2255 else 2256 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2257 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2258 isa<MSPropertyDecl>(R.getFoundDecl()); 2259 2260 if (MightBeImplicitMember) 2261 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2262 R, TemplateArgs, S); 2263 } 2264 2265 if (TemplateArgs || TemplateKWLoc.isValid()) { 2266 2267 // In C++1y, if this is a variable template id, then check it 2268 // in BuildTemplateIdExpr(). 2269 // The single lookup result must be a variable template declaration. 2270 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2271 Id.TemplateId->Kind == TNK_Var_template) { 2272 assert(R.getAsSingle<VarTemplateDecl>() && 2273 "There should only be one declaration found."); 2274 } 2275 2276 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2277 } 2278 2279 return BuildDeclarationNameExpr(SS, R, ADL); 2280 } 2281 2282 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2283 /// declaration name, generally during template instantiation. 2284 /// There's a large number of things which don't need to be done along 2285 /// this path. 2286 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2287 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2288 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2289 DeclContext *DC = computeDeclContext(SS, false); 2290 if (!DC) 2291 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2292 NameInfo, /*TemplateArgs=*/nullptr); 2293 2294 if (RequireCompleteDeclContext(SS, DC)) 2295 return ExprError(); 2296 2297 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2298 LookupQualifiedName(R, DC); 2299 2300 if (R.isAmbiguous()) 2301 return ExprError(); 2302 2303 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2304 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2305 NameInfo, /*TemplateArgs=*/nullptr); 2306 2307 if (R.empty()) { 2308 Diag(NameInfo.getLoc(), diag::err_no_member) 2309 << NameInfo.getName() << DC << SS.getRange(); 2310 return ExprError(); 2311 } 2312 2313 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2314 // Diagnose a missing typename if this resolved unambiguously to a type in 2315 // a dependent context. If we can recover with a type, downgrade this to 2316 // a warning in Microsoft compatibility mode. 2317 unsigned DiagID = diag::err_typename_missing; 2318 if (RecoveryTSI && getLangOpts().MSVCCompat) 2319 DiagID = diag::ext_typename_missing; 2320 SourceLocation Loc = SS.getBeginLoc(); 2321 auto D = Diag(Loc, DiagID); 2322 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2323 << SourceRange(Loc, NameInfo.getEndLoc()); 2324 2325 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2326 // context. 2327 if (!RecoveryTSI) 2328 return ExprError(); 2329 2330 // Only issue the fixit if we're prepared to recover. 2331 D << FixItHint::CreateInsertion(Loc, "typename "); 2332 2333 // Recover by pretending this was an elaborated type. 2334 QualType Ty = Context.getTypeDeclType(TD); 2335 TypeLocBuilder TLB; 2336 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2337 2338 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2339 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2340 QTL.setElaboratedKeywordLoc(SourceLocation()); 2341 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2342 2343 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2344 2345 return ExprEmpty(); 2346 } 2347 2348 // Defend against this resolving to an implicit member access. We usually 2349 // won't get here if this might be a legitimate a class member (we end up in 2350 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2351 // a pointer-to-member or in an unevaluated context in C++11. 2352 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2353 return BuildPossibleImplicitMemberExpr(SS, 2354 /*TemplateKWLoc=*/SourceLocation(), 2355 R, /*TemplateArgs=*/nullptr, S); 2356 2357 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2358 } 2359 2360 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2361 /// detected that we're currently inside an ObjC method. Perform some 2362 /// additional lookup. 2363 /// 2364 /// Ideally, most of this would be done by lookup, but there's 2365 /// actually quite a lot of extra work involved. 2366 /// 2367 /// Returns a null sentinel to indicate trivial success. 2368 ExprResult 2369 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2370 IdentifierInfo *II, bool AllowBuiltinCreation) { 2371 SourceLocation Loc = Lookup.getNameLoc(); 2372 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2373 2374 // Check for error condition which is already reported. 2375 if (!CurMethod) 2376 return ExprError(); 2377 2378 // There are two cases to handle here. 1) scoped lookup could have failed, 2379 // in which case we should look for an ivar. 2) scoped lookup could have 2380 // found a decl, but that decl is outside the current instance method (i.e. 2381 // a global variable). In these two cases, we do a lookup for an ivar with 2382 // this name, if the lookup sucedes, we replace it our current decl. 2383 2384 // If we're in a class method, we don't normally want to look for 2385 // ivars. But if we don't find anything else, and there's an 2386 // ivar, that's an error. 2387 bool IsClassMethod = CurMethod->isClassMethod(); 2388 2389 bool LookForIvars; 2390 if (Lookup.empty()) 2391 LookForIvars = true; 2392 else if (IsClassMethod) 2393 LookForIvars = false; 2394 else 2395 LookForIvars = (Lookup.isSingleResult() && 2396 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2397 ObjCInterfaceDecl *IFace = nullptr; 2398 if (LookForIvars) { 2399 IFace = CurMethod->getClassInterface(); 2400 ObjCInterfaceDecl *ClassDeclared; 2401 ObjCIvarDecl *IV = nullptr; 2402 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2403 // Diagnose using an ivar in a class method. 2404 if (IsClassMethod) 2405 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2406 << IV->getDeclName()); 2407 2408 // If we're referencing an invalid decl, just return this as a silent 2409 // error node. The error diagnostic was already emitted on the decl. 2410 if (IV->isInvalidDecl()) 2411 return ExprError(); 2412 2413 // Check if referencing a field with __attribute__((deprecated)). 2414 if (DiagnoseUseOfDecl(IV, Loc)) 2415 return ExprError(); 2416 2417 // Diagnose the use of an ivar outside of the declaring class. 2418 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2419 !declaresSameEntity(ClassDeclared, IFace) && 2420 !getLangOpts().DebuggerSupport) 2421 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2422 2423 // FIXME: This should use a new expr for a direct reference, don't 2424 // turn this into Self->ivar, just return a BareIVarExpr or something. 2425 IdentifierInfo &II = Context.Idents.get("self"); 2426 UnqualifiedId SelfName; 2427 SelfName.setIdentifier(&II, SourceLocation()); 2428 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2429 CXXScopeSpec SelfScopeSpec; 2430 SourceLocation TemplateKWLoc; 2431 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2432 SelfName, false, false); 2433 if (SelfExpr.isInvalid()) 2434 return ExprError(); 2435 2436 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2437 if (SelfExpr.isInvalid()) 2438 return ExprError(); 2439 2440 MarkAnyDeclReferenced(Loc, IV, true); 2441 2442 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2443 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2444 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2445 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2446 2447 ObjCIvarRefExpr *Result = new (Context) 2448 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2449 IV->getLocation(), SelfExpr.get(), true, true); 2450 2451 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2452 if (!isUnevaluatedContext() && 2453 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2454 getCurFunction()->recordUseOfWeak(Result); 2455 } 2456 if (getLangOpts().ObjCAutoRefCount) { 2457 if (CurContext->isClosure()) 2458 Diag(Loc, diag::warn_implicitly_retains_self) 2459 << FixItHint::CreateInsertion(Loc, "self->"); 2460 } 2461 2462 return Result; 2463 } 2464 } else if (CurMethod->isInstanceMethod()) { 2465 // We should warn if a local variable hides an ivar. 2466 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2467 ObjCInterfaceDecl *ClassDeclared; 2468 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2469 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2470 declaresSameEntity(IFace, ClassDeclared)) 2471 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2472 } 2473 } 2474 } else if (Lookup.isSingleResult() && 2475 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2476 // If accessing a stand-alone ivar in a class method, this is an error. 2477 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2478 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2479 << IV->getDeclName()); 2480 } 2481 2482 if (Lookup.empty() && II && AllowBuiltinCreation) { 2483 // FIXME. Consolidate this with similar code in LookupName. 2484 if (unsigned BuiltinID = II->getBuiltinID()) { 2485 if (!(getLangOpts().CPlusPlus && 2486 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2487 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2488 S, Lookup.isForRedeclaration(), 2489 Lookup.getNameLoc()); 2490 if (D) Lookup.addDecl(D); 2491 } 2492 } 2493 } 2494 // Sentinel value saying that we didn't do anything special. 2495 return ExprResult((Expr *)nullptr); 2496 } 2497 2498 /// Cast a base object to a member's actual type. 2499 /// 2500 /// Logically this happens in three phases: 2501 /// 2502 /// * First we cast from the base type to the naming class. 2503 /// The naming class is the class into which we were looking 2504 /// when we found the member; it's the qualifier type if a 2505 /// qualifier was provided, and otherwise it's the base type. 2506 /// 2507 /// * Next we cast from the naming class to the declaring class. 2508 /// If the member we found was brought into a class's scope by 2509 /// a using declaration, this is that class; otherwise it's 2510 /// the class declaring the member. 2511 /// 2512 /// * Finally we cast from the declaring class to the "true" 2513 /// declaring class of the member. This conversion does not 2514 /// obey access control. 2515 ExprResult 2516 Sema::PerformObjectMemberConversion(Expr *From, 2517 NestedNameSpecifier *Qualifier, 2518 NamedDecl *FoundDecl, 2519 NamedDecl *Member) { 2520 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2521 if (!RD) 2522 return From; 2523 2524 QualType DestRecordType; 2525 QualType DestType; 2526 QualType FromRecordType; 2527 QualType FromType = From->getType(); 2528 bool PointerConversions = false; 2529 if (isa<FieldDecl>(Member)) { 2530 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2531 2532 if (FromType->getAs<PointerType>()) { 2533 DestType = Context.getPointerType(DestRecordType); 2534 FromRecordType = FromType->getPointeeType(); 2535 PointerConversions = true; 2536 } else { 2537 DestType = DestRecordType; 2538 FromRecordType = FromType; 2539 } 2540 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2541 if (Method->isStatic()) 2542 return From; 2543 2544 DestType = Method->getThisType(Context); 2545 DestRecordType = DestType->getPointeeType(); 2546 2547 if (FromType->getAs<PointerType>()) { 2548 FromRecordType = FromType->getPointeeType(); 2549 PointerConversions = true; 2550 } else { 2551 FromRecordType = FromType; 2552 DestType = DestRecordType; 2553 } 2554 } else { 2555 // No conversion necessary. 2556 return From; 2557 } 2558 2559 if (DestType->isDependentType() || FromType->isDependentType()) 2560 return From; 2561 2562 // If the unqualified types are the same, no conversion is necessary. 2563 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2564 return From; 2565 2566 SourceRange FromRange = From->getSourceRange(); 2567 SourceLocation FromLoc = FromRange.getBegin(); 2568 2569 ExprValueKind VK = From->getValueKind(); 2570 2571 // C++ [class.member.lookup]p8: 2572 // [...] Ambiguities can often be resolved by qualifying a name with its 2573 // class name. 2574 // 2575 // If the member was a qualified name and the qualified referred to a 2576 // specific base subobject type, we'll cast to that intermediate type 2577 // first and then to the object in which the member is declared. That allows 2578 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2579 // 2580 // class Base { public: int x; }; 2581 // class Derived1 : public Base { }; 2582 // class Derived2 : public Base { }; 2583 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2584 // 2585 // void VeryDerived::f() { 2586 // x = 17; // error: ambiguous base subobjects 2587 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2588 // } 2589 if (Qualifier && Qualifier->getAsType()) { 2590 QualType QType = QualType(Qualifier->getAsType(), 0); 2591 assert(QType->isRecordType() && "lookup done with non-record type"); 2592 2593 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2594 2595 // In C++98, the qualifier type doesn't actually have to be a base 2596 // type of the object type, in which case we just ignore it. 2597 // Otherwise build the appropriate casts. 2598 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2599 CXXCastPath BasePath; 2600 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2601 FromLoc, FromRange, &BasePath)) 2602 return ExprError(); 2603 2604 if (PointerConversions) 2605 QType = Context.getPointerType(QType); 2606 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2607 VK, &BasePath).get(); 2608 2609 FromType = QType; 2610 FromRecordType = QRecordType; 2611 2612 // If the qualifier type was the same as the destination type, 2613 // we're done. 2614 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2615 return From; 2616 } 2617 } 2618 2619 bool IgnoreAccess = false; 2620 2621 // If we actually found the member through a using declaration, cast 2622 // down to the using declaration's type. 2623 // 2624 // Pointer equality is fine here because only one declaration of a 2625 // class ever has member declarations. 2626 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2627 assert(isa<UsingShadowDecl>(FoundDecl)); 2628 QualType URecordType = Context.getTypeDeclType( 2629 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2630 2631 // We only need to do this if the naming-class to declaring-class 2632 // conversion is non-trivial. 2633 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2634 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2635 CXXCastPath BasePath; 2636 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2637 FromLoc, FromRange, &BasePath)) 2638 return ExprError(); 2639 2640 QualType UType = URecordType; 2641 if (PointerConversions) 2642 UType = Context.getPointerType(UType); 2643 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2644 VK, &BasePath).get(); 2645 FromType = UType; 2646 FromRecordType = URecordType; 2647 } 2648 2649 // We don't do access control for the conversion from the 2650 // declaring class to the true declaring class. 2651 IgnoreAccess = true; 2652 } 2653 2654 CXXCastPath BasePath; 2655 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2656 FromLoc, FromRange, &BasePath, 2657 IgnoreAccess)) 2658 return ExprError(); 2659 2660 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2661 VK, &BasePath); 2662 } 2663 2664 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2665 const LookupResult &R, 2666 bool HasTrailingLParen) { 2667 // Only when used directly as the postfix-expression of a call. 2668 if (!HasTrailingLParen) 2669 return false; 2670 2671 // Never if a scope specifier was provided. 2672 if (SS.isSet()) 2673 return false; 2674 2675 // Only in C++ or ObjC++. 2676 if (!getLangOpts().CPlusPlus) 2677 return false; 2678 2679 // Turn off ADL when we find certain kinds of declarations during 2680 // normal lookup: 2681 for (NamedDecl *D : R) { 2682 // C++0x [basic.lookup.argdep]p3: 2683 // -- a declaration of a class member 2684 // Since using decls preserve this property, we check this on the 2685 // original decl. 2686 if (D->isCXXClassMember()) 2687 return false; 2688 2689 // C++0x [basic.lookup.argdep]p3: 2690 // -- a block-scope function declaration that is not a 2691 // using-declaration 2692 // NOTE: we also trigger this for function templates (in fact, we 2693 // don't check the decl type at all, since all other decl types 2694 // turn off ADL anyway). 2695 if (isa<UsingShadowDecl>(D)) 2696 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2697 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2698 return false; 2699 2700 // C++0x [basic.lookup.argdep]p3: 2701 // -- a declaration that is neither a function or a function 2702 // template 2703 // And also for builtin functions. 2704 if (isa<FunctionDecl>(D)) { 2705 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2706 2707 // But also builtin functions. 2708 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2709 return false; 2710 } else if (!isa<FunctionTemplateDecl>(D)) 2711 return false; 2712 } 2713 2714 return true; 2715 } 2716 2717 2718 /// Diagnoses obvious problems with the use of the given declaration 2719 /// as an expression. This is only actually called for lookups that 2720 /// were not overloaded, and it doesn't promise that the declaration 2721 /// will in fact be used. 2722 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2723 if (D->isInvalidDecl()) 2724 return true; 2725 2726 if (isa<TypedefNameDecl>(D)) { 2727 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2728 return true; 2729 } 2730 2731 if (isa<ObjCInterfaceDecl>(D)) { 2732 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2733 return true; 2734 } 2735 2736 if (isa<NamespaceDecl>(D)) { 2737 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2738 return true; 2739 } 2740 2741 return false; 2742 } 2743 2744 // Certain multiversion types should be treated as overloaded even when there is 2745 // only one result. 2746 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2747 assert(R.isSingleResult() && "Expected only a single result"); 2748 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2749 return FD && 2750 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2751 } 2752 2753 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2754 LookupResult &R, bool NeedsADL, 2755 bool AcceptInvalidDecl) { 2756 // If this is a single, fully-resolved result and we don't need ADL, 2757 // just build an ordinary singleton decl ref. 2758 if (!NeedsADL && R.isSingleResult() && 2759 !R.getAsSingle<FunctionTemplateDecl>() && 2760 !ShouldLookupResultBeMultiVersionOverload(R)) 2761 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2762 R.getRepresentativeDecl(), nullptr, 2763 AcceptInvalidDecl); 2764 2765 // We only need to check the declaration if there's exactly one 2766 // result, because in the overloaded case the results can only be 2767 // functions and function templates. 2768 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2769 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2770 return ExprError(); 2771 2772 // Otherwise, just build an unresolved lookup expression. Suppress 2773 // any lookup-related diagnostics; we'll hash these out later, when 2774 // we've picked a target. 2775 R.suppressDiagnostics(); 2776 2777 UnresolvedLookupExpr *ULE 2778 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2779 SS.getWithLocInContext(Context), 2780 R.getLookupNameInfo(), 2781 NeedsADL, R.isOverloadedResult(), 2782 R.begin(), R.end()); 2783 2784 return ULE; 2785 } 2786 2787 static void 2788 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2789 ValueDecl *var, DeclContext *DC); 2790 2791 /// Complete semantic analysis for a reference to the given declaration. 2792 ExprResult Sema::BuildDeclarationNameExpr( 2793 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2794 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2795 bool AcceptInvalidDecl) { 2796 assert(D && "Cannot refer to a NULL declaration"); 2797 assert(!isa<FunctionTemplateDecl>(D) && 2798 "Cannot refer unambiguously to a function template"); 2799 2800 SourceLocation Loc = NameInfo.getLoc(); 2801 if (CheckDeclInExpr(*this, Loc, D)) 2802 return ExprError(); 2803 2804 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2805 // Specifically diagnose references to class templates that are missing 2806 // a template argument list. 2807 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2808 return ExprError(); 2809 } 2810 2811 // Make sure that we're referring to a value. 2812 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2813 if (!VD) { 2814 Diag(Loc, diag::err_ref_non_value) 2815 << D << SS.getRange(); 2816 Diag(D->getLocation(), diag::note_declared_at); 2817 return ExprError(); 2818 } 2819 2820 // Check whether this declaration can be used. Note that we suppress 2821 // this check when we're going to perform argument-dependent lookup 2822 // on this function name, because this might not be the function 2823 // that overload resolution actually selects. 2824 if (DiagnoseUseOfDecl(VD, Loc)) 2825 return ExprError(); 2826 2827 // Only create DeclRefExpr's for valid Decl's. 2828 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2829 return ExprError(); 2830 2831 // Handle members of anonymous structs and unions. If we got here, 2832 // and the reference is to a class member indirect field, then this 2833 // must be the subject of a pointer-to-member expression. 2834 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2835 if (!indirectField->isCXXClassMember()) 2836 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2837 indirectField); 2838 2839 { 2840 QualType type = VD->getType(); 2841 if (type.isNull()) 2842 return ExprError(); 2843 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2844 // C++ [except.spec]p17: 2845 // An exception-specification is considered to be needed when: 2846 // - in an expression, the function is the unique lookup result or 2847 // the selected member of a set of overloaded functions. 2848 ResolveExceptionSpec(Loc, FPT); 2849 type = VD->getType(); 2850 } 2851 ExprValueKind valueKind = VK_RValue; 2852 2853 switch (D->getKind()) { 2854 // Ignore all the non-ValueDecl kinds. 2855 #define ABSTRACT_DECL(kind) 2856 #define VALUE(type, base) 2857 #define DECL(type, base) \ 2858 case Decl::type: 2859 #include "clang/AST/DeclNodes.inc" 2860 llvm_unreachable("invalid value decl kind"); 2861 2862 // These shouldn't make it here. 2863 case Decl::ObjCAtDefsField: 2864 case Decl::ObjCIvar: 2865 llvm_unreachable("forming non-member reference to ivar?"); 2866 2867 // Enum constants are always r-values and never references. 2868 // Unresolved using declarations are dependent. 2869 case Decl::EnumConstant: 2870 case Decl::UnresolvedUsingValue: 2871 case Decl::OMPDeclareReduction: 2872 valueKind = VK_RValue; 2873 break; 2874 2875 // Fields and indirect fields that got here must be for 2876 // pointer-to-member expressions; we just call them l-values for 2877 // internal consistency, because this subexpression doesn't really 2878 // exist in the high-level semantics. 2879 case Decl::Field: 2880 case Decl::IndirectField: 2881 assert(getLangOpts().CPlusPlus && 2882 "building reference to field in C?"); 2883 2884 // These can't have reference type in well-formed programs, but 2885 // for internal consistency we do this anyway. 2886 type = type.getNonReferenceType(); 2887 valueKind = VK_LValue; 2888 break; 2889 2890 // Non-type template parameters are either l-values or r-values 2891 // depending on the type. 2892 case Decl::NonTypeTemplateParm: { 2893 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2894 type = reftype->getPointeeType(); 2895 valueKind = VK_LValue; // even if the parameter is an r-value reference 2896 break; 2897 } 2898 2899 // For non-references, we need to strip qualifiers just in case 2900 // the template parameter was declared as 'const int' or whatever. 2901 valueKind = VK_RValue; 2902 type = type.getUnqualifiedType(); 2903 break; 2904 } 2905 2906 case Decl::Var: 2907 case Decl::VarTemplateSpecialization: 2908 case Decl::VarTemplatePartialSpecialization: 2909 case Decl::Decomposition: 2910 case Decl::OMPCapturedExpr: 2911 // In C, "extern void blah;" is valid and is an r-value. 2912 if (!getLangOpts().CPlusPlus && 2913 !type.hasQualifiers() && 2914 type->isVoidType()) { 2915 valueKind = VK_RValue; 2916 break; 2917 } 2918 LLVM_FALLTHROUGH; 2919 2920 case Decl::ImplicitParam: 2921 case Decl::ParmVar: { 2922 // These are always l-values. 2923 valueKind = VK_LValue; 2924 type = type.getNonReferenceType(); 2925 2926 // FIXME: Does the addition of const really only apply in 2927 // potentially-evaluated contexts? Since the variable isn't actually 2928 // captured in an unevaluated context, it seems that the answer is no. 2929 if (!isUnevaluatedContext()) { 2930 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2931 if (!CapturedType.isNull()) 2932 type = CapturedType; 2933 } 2934 2935 break; 2936 } 2937 2938 case Decl::Binding: { 2939 // These are always lvalues. 2940 valueKind = VK_LValue; 2941 type = type.getNonReferenceType(); 2942 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2943 // decides how that's supposed to work. 2944 auto *BD = cast<BindingDecl>(VD); 2945 if (BD->getDeclContext()->isFunctionOrMethod() && 2946 BD->getDeclContext() != CurContext) 2947 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2948 break; 2949 } 2950 2951 case Decl::Function: { 2952 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2953 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2954 type = Context.BuiltinFnTy; 2955 valueKind = VK_RValue; 2956 break; 2957 } 2958 } 2959 2960 const FunctionType *fty = type->castAs<FunctionType>(); 2961 2962 // If we're referring to a function with an __unknown_anytype 2963 // result type, make the entire expression __unknown_anytype. 2964 if (fty->getReturnType() == Context.UnknownAnyTy) { 2965 type = Context.UnknownAnyTy; 2966 valueKind = VK_RValue; 2967 break; 2968 } 2969 2970 // Functions are l-values in C++. 2971 if (getLangOpts().CPlusPlus) { 2972 valueKind = VK_LValue; 2973 break; 2974 } 2975 2976 // C99 DR 316 says that, if a function type comes from a 2977 // function definition (without a prototype), that type is only 2978 // used for checking compatibility. Therefore, when referencing 2979 // the function, we pretend that we don't have the full function 2980 // type. 2981 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2982 isa<FunctionProtoType>(fty)) 2983 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2984 fty->getExtInfo()); 2985 2986 // Functions are r-values in C. 2987 valueKind = VK_RValue; 2988 break; 2989 } 2990 2991 case Decl::CXXDeductionGuide: 2992 llvm_unreachable("building reference to deduction guide"); 2993 2994 case Decl::MSProperty: 2995 valueKind = VK_LValue; 2996 break; 2997 2998 case Decl::CXXMethod: 2999 // If we're referring to a method with an __unknown_anytype 3000 // result type, make the entire expression __unknown_anytype. 3001 // This should only be possible with a type written directly. 3002 if (const FunctionProtoType *proto 3003 = dyn_cast<FunctionProtoType>(VD->getType())) 3004 if (proto->getReturnType() == Context.UnknownAnyTy) { 3005 type = Context.UnknownAnyTy; 3006 valueKind = VK_RValue; 3007 break; 3008 } 3009 3010 // C++ methods are l-values if static, r-values if non-static. 3011 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3012 valueKind = VK_LValue; 3013 break; 3014 } 3015 LLVM_FALLTHROUGH; 3016 3017 case Decl::CXXConversion: 3018 case Decl::CXXDestructor: 3019 case Decl::CXXConstructor: 3020 valueKind = VK_RValue; 3021 break; 3022 } 3023 3024 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3025 TemplateArgs); 3026 } 3027 } 3028 3029 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3030 SmallString<32> &Target) { 3031 Target.resize(CharByteWidth * (Source.size() + 1)); 3032 char *ResultPtr = &Target[0]; 3033 const llvm::UTF8 *ErrorPtr; 3034 bool success = 3035 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3036 (void)success; 3037 assert(success); 3038 Target.resize(ResultPtr - &Target[0]); 3039 } 3040 3041 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3042 PredefinedExpr::IdentKind IK) { 3043 // Pick the current block, lambda, captured statement or function. 3044 Decl *currentDecl = nullptr; 3045 if (const BlockScopeInfo *BSI = getCurBlock()) 3046 currentDecl = BSI->TheDecl; 3047 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3048 currentDecl = LSI->CallOperator; 3049 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3050 currentDecl = CSI->TheCapturedDecl; 3051 else 3052 currentDecl = getCurFunctionOrMethodDecl(); 3053 3054 if (!currentDecl) { 3055 Diag(Loc, diag::ext_predef_outside_function); 3056 currentDecl = Context.getTranslationUnitDecl(); 3057 } 3058 3059 QualType ResTy; 3060 StringLiteral *SL = nullptr; 3061 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3062 ResTy = Context.DependentTy; 3063 else { 3064 // Pre-defined identifiers are of type char[x], where x is the length of 3065 // the string. 3066 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3067 unsigned Length = Str.length(); 3068 3069 llvm::APInt LengthI(32, Length + 1); 3070 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3071 ResTy = 3072 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3073 SmallString<32> RawChars; 3074 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3075 Str, RawChars); 3076 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3077 /*IndexTypeQuals*/ 0); 3078 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3079 /*Pascal*/ false, ResTy, Loc); 3080 } else { 3081 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3082 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3083 /*IndexTypeQuals*/ 0); 3084 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3085 /*Pascal*/ false, ResTy, Loc); 3086 } 3087 } 3088 3089 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3090 } 3091 3092 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3093 PredefinedExpr::IdentKind IK; 3094 3095 switch (Kind) { 3096 default: llvm_unreachable("Unknown simple primary expr!"); 3097 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3098 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3099 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3100 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3101 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3102 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3103 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3104 } 3105 3106 return BuildPredefinedExpr(Loc, IK); 3107 } 3108 3109 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3110 SmallString<16> CharBuffer; 3111 bool Invalid = false; 3112 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3113 if (Invalid) 3114 return ExprError(); 3115 3116 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3117 PP, Tok.getKind()); 3118 if (Literal.hadError()) 3119 return ExprError(); 3120 3121 QualType Ty; 3122 if (Literal.isWide()) 3123 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3124 else if (Literal.isUTF8() && getLangOpts().Char8) 3125 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3126 else if (Literal.isUTF16()) 3127 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3128 else if (Literal.isUTF32()) 3129 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3130 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3131 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3132 else 3133 Ty = Context.CharTy; // 'x' -> char in C++ 3134 3135 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3136 if (Literal.isWide()) 3137 Kind = CharacterLiteral::Wide; 3138 else if (Literal.isUTF16()) 3139 Kind = CharacterLiteral::UTF16; 3140 else if (Literal.isUTF32()) 3141 Kind = CharacterLiteral::UTF32; 3142 else if (Literal.isUTF8()) 3143 Kind = CharacterLiteral::UTF8; 3144 3145 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3146 Tok.getLocation()); 3147 3148 if (Literal.getUDSuffix().empty()) 3149 return Lit; 3150 3151 // We're building a user-defined literal. 3152 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3153 SourceLocation UDSuffixLoc = 3154 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3155 3156 // Make sure we're allowed user-defined literals here. 3157 if (!UDLScope) 3158 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3159 3160 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3161 // operator "" X (ch) 3162 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3163 Lit, Tok.getLocation()); 3164 } 3165 3166 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3167 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3168 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3169 Context.IntTy, Loc); 3170 } 3171 3172 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3173 QualType Ty, SourceLocation Loc) { 3174 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3175 3176 using llvm::APFloat; 3177 APFloat Val(Format); 3178 3179 APFloat::opStatus result = Literal.GetFloatValue(Val); 3180 3181 // Overflow is always an error, but underflow is only an error if 3182 // we underflowed to zero (APFloat reports denormals as underflow). 3183 if ((result & APFloat::opOverflow) || 3184 ((result & APFloat::opUnderflow) && Val.isZero())) { 3185 unsigned diagnostic; 3186 SmallString<20> buffer; 3187 if (result & APFloat::opOverflow) { 3188 diagnostic = diag::warn_float_overflow; 3189 APFloat::getLargest(Format).toString(buffer); 3190 } else { 3191 diagnostic = diag::warn_float_underflow; 3192 APFloat::getSmallest(Format).toString(buffer); 3193 } 3194 3195 S.Diag(Loc, diagnostic) 3196 << Ty 3197 << StringRef(buffer.data(), buffer.size()); 3198 } 3199 3200 bool isExact = (result == APFloat::opOK); 3201 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3202 } 3203 3204 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3205 assert(E && "Invalid expression"); 3206 3207 if (E->isValueDependent()) 3208 return false; 3209 3210 QualType QT = E->getType(); 3211 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3212 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3213 return true; 3214 } 3215 3216 llvm::APSInt ValueAPS; 3217 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3218 3219 if (R.isInvalid()) 3220 return true; 3221 3222 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3223 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3224 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3225 << ValueAPS.toString(10) << ValueIsPositive; 3226 return true; 3227 } 3228 3229 return false; 3230 } 3231 3232 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3233 // Fast path for a single digit (which is quite common). A single digit 3234 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3235 if (Tok.getLength() == 1) { 3236 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3237 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3238 } 3239 3240 SmallString<128> SpellingBuffer; 3241 // NumericLiteralParser wants to overread by one character. Add padding to 3242 // the buffer in case the token is copied to the buffer. If getSpelling() 3243 // returns a StringRef to the memory buffer, it should have a null char at 3244 // the EOF, so it is also safe. 3245 SpellingBuffer.resize(Tok.getLength() + 1); 3246 3247 // Get the spelling of the token, which eliminates trigraphs, etc. 3248 bool Invalid = false; 3249 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3250 if (Invalid) 3251 return ExprError(); 3252 3253 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3254 if (Literal.hadError) 3255 return ExprError(); 3256 3257 if (Literal.hasUDSuffix()) { 3258 // We're building a user-defined literal. 3259 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3260 SourceLocation UDSuffixLoc = 3261 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3262 3263 // Make sure we're allowed user-defined literals here. 3264 if (!UDLScope) 3265 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3266 3267 QualType CookedTy; 3268 if (Literal.isFloatingLiteral()) { 3269 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3270 // long double, the literal is treated as a call of the form 3271 // operator "" X (f L) 3272 CookedTy = Context.LongDoubleTy; 3273 } else { 3274 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3275 // unsigned long long, the literal is treated as a call of the form 3276 // operator "" X (n ULL) 3277 CookedTy = Context.UnsignedLongLongTy; 3278 } 3279 3280 DeclarationName OpName = 3281 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3282 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3283 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3284 3285 SourceLocation TokLoc = Tok.getLocation(); 3286 3287 // Perform literal operator lookup to determine if we're building a raw 3288 // literal or a cooked one. 3289 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3290 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3291 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3292 /*AllowStringTemplate*/ false, 3293 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3294 case LOLR_ErrorNoDiagnostic: 3295 // Lookup failure for imaginary constants isn't fatal, there's still the 3296 // GNU extension producing _Complex types. 3297 break; 3298 case LOLR_Error: 3299 return ExprError(); 3300 case LOLR_Cooked: { 3301 Expr *Lit; 3302 if (Literal.isFloatingLiteral()) { 3303 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3304 } else { 3305 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3306 if (Literal.GetIntegerValue(ResultVal)) 3307 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3308 << /* Unsigned */ 1; 3309 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3310 Tok.getLocation()); 3311 } 3312 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3313 } 3314 3315 case LOLR_Raw: { 3316 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3317 // literal is treated as a call of the form 3318 // operator "" X ("n") 3319 unsigned Length = Literal.getUDSuffixOffset(); 3320 QualType StrTy = Context.getConstantArrayType( 3321 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3322 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3323 Expr *Lit = StringLiteral::Create( 3324 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3325 /*Pascal*/false, StrTy, &TokLoc, 1); 3326 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3327 } 3328 3329 case LOLR_Template: { 3330 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3331 // template), L is treated as a call fo the form 3332 // operator "" X <'c1', 'c2', ... 'ck'>() 3333 // where n is the source character sequence c1 c2 ... ck. 3334 TemplateArgumentListInfo ExplicitArgs; 3335 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3336 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3337 llvm::APSInt Value(CharBits, CharIsUnsigned); 3338 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3339 Value = TokSpelling[I]; 3340 TemplateArgument Arg(Context, Value, Context.CharTy); 3341 TemplateArgumentLocInfo ArgInfo; 3342 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3343 } 3344 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3345 &ExplicitArgs); 3346 } 3347 case LOLR_StringTemplate: 3348 llvm_unreachable("unexpected literal operator lookup result"); 3349 } 3350 } 3351 3352 Expr *Res; 3353 3354 if (Literal.isFixedPointLiteral()) { 3355 QualType Ty; 3356 3357 if (Literal.isAccum) { 3358 if (Literal.isHalf) { 3359 Ty = Context.ShortAccumTy; 3360 } else if (Literal.isLong) { 3361 Ty = Context.LongAccumTy; 3362 } else { 3363 Ty = Context.AccumTy; 3364 } 3365 } else if (Literal.isFract) { 3366 if (Literal.isHalf) { 3367 Ty = Context.ShortFractTy; 3368 } else if (Literal.isLong) { 3369 Ty = Context.LongFractTy; 3370 } else { 3371 Ty = Context.FractTy; 3372 } 3373 } 3374 3375 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3376 3377 bool isSigned = !Literal.isUnsigned; 3378 unsigned scale = Context.getFixedPointScale(Ty); 3379 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3380 3381 llvm::APInt Val(bit_width, 0, isSigned); 3382 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3383 bool ValIsZero = Val.isNullValue() && !Overflowed; 3384 3385 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3386 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3387 // Clause 6.4.4 - The value of a constant shall be in the range of 3388 // representable values for its type, with exception for constants of a 3389 // fract type with a value of exactly 1; such a constant shall denote 3390 // the maximal value for the type. 3391 --Val; 3392 else if (Val.ugt(MaxVal) || Overflowed) 3393 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3394 3395 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3396 Tok.getLocation(), scale); 3397 } else if (Literal.isFloatingLiteral()) { 3398 QualType Ty; 3399 if (Literal.isHalf){ 3400 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3401 Ty = Context.HalfTy; 3402 else { 3403 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3404 return ExprError(); 3405 } 3406 } else if (Literal.isFloat) 3407 Ty = Context.FloatTy; 3408 else if (Literal.isLong) 3409 Ty = Context.LongDoubleTy; 3410 else if (Literal.isFloat16) 3411 Ty = Context.Float16Ty; 3412 else if (Literal.isFloat128) 3413 Ty = Context.Float128Ty; 3414 else 3415 Ty = Context.DoubleTy; 3416 3417 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3418 3419 if (Ty == Context.DoubleTy) { 3420 if (getLangOpts().SinglePrecisionConstants) { 3421 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3422 if (BTy->getKind() != BuiltinType::Float) { 3423 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3424 } 3425 } else if (getLangOpts().OpenCL && 3426 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3427 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3428 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3429 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3430 } 3431 } 3432 } else if (!Literal.isIntegerLiteral()) { 3433 return ExprError(); 3434 } else { 3435 QualType Ty; 3436 3437 // 'long long' is a C99 or C++11 feature. 3438 if (!getLangOpts().C99 && Literal.isLongLong) { 3439 if (getLangOpts().CPlusPlus) 3440 Diag(Tok.getLocation(), 3441 getLangOpts().CPlusPlus11 ? 3442 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3443 else 3444 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3445 } 3446 3447 // Get the value in the widest-possible width. 3448 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3449 llvm::APInt ResultVal(MaxWidth, 0); 3450 3451 if (Literal.GetIntegerValue(ResultVal)) { 3452 // If this value didn't fit into uintmax_t, error and force to ull. 3453 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3454 << /* Unsigned */ 1; 3455 Ty = Context.UnsignedLongLongTy; 3456 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3457 "long long is not intmax_t?"); 3458 } else { 3459 // If this value fits into a ULL, try to figure out what else it fits into 3460 // according to the rules of C99 6.4.4.1p5. 3461 3462 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3463 // be an unsigned int. 3464 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3465 3466 // Check from smallest to largest, picking the smallest type we can. 3467 unsigned Width = 0; 3468 3469 // Microsoft specific integer suffixes are explicitly sized. 3470 if (Literal.MicrosoftInteger) { 3471 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3472 Width = 8; 3473 Ty = Context.CharTy; 3474 } else { 3475 Width = Literal.MicrosoftInteger; 3476 Ty = Context.getIntTypeForBitwidth(Width, 3477 /*Signed=*/!Literal.isUnsigned); 3478 } 3479 } 3480 3481 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3482 // Are int/unsigned possibilities? 3483 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3484 3485 // Does it fit in a unsigned int? 3486 if (ResultVal.isIntN(IntSize)) { 3487 // Does it fit in a signed int? 3488 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3489 Ty = Context.IntTy; 3490 else if (AllowUnsigned) 3491 Ty = Context.UnsignedIntTy; 3492 Width = IntSize; 3493 } 3494 } 3495 3496 // Are long/unsigned long possibilities? 3497 if (Ty.isNull() && !Literal.isLongLong) { 3498 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3499 3500 // Does it fit in a unsigned long? 3501 if (ResultVal.isIntN(LongSize)) { 3502 // Does it fit in a signed long? 3503 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3504 Ty = Context.LongTy; 3505 else if (AllowUnsigned) 3506 Ty = Context.UnsignedLongTy; 3507 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3508 // is compatible. 3509 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3510 const unsigned LongLongSize = 3511 Context.getTargetInfo().getLongLongWidth(); 3512 Diag(Tok.getLocation(), 3513 getLangOpts().CPlusPlus 3514 ? Literal.isLong 3515 ? diag::warn_old_implicitly_unsigned_long_cxx 3516 : /*C++98 UB*/ diag:: 3517 ext_old_implicitly_unsigned_long_cxx 3518 : diag::warn_old_implicitly_unsigned_long) 3519 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3520 : /*will be ill-formed*/ 1); 3521 Ty = Context.UnsignedLongTy; 3522 } 3523 Width = LongSize; 3524 } 3525 } 3526 3527 // Check long long if needed. 3528 if (Ty.isNull()) { 3529 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3530 3531 // Does it fit in a unsigned long long? 3532 if (ResultVal.isIntN(LongLongSize)) { 3533 // Does it fit in a signed long long? 3534 // To be compatible with MSVC, hex integer literals ending with the 3535 // LL or i64 suffix are always signed in Microsoft mode. 3536 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3537 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3538 Ty = Context.LongLongTy; 3539 else if (AllowUnsigned) 3540 Ty = Context.UnsignedLongLongTy; 3541 Width = LongLongSize; 3542 } 3543 } 3544 3545 // If we still couldn't decide a type, we probably have something that 3546 // does not fit in a signed long long, but has no U suffix. 3547 if (Ty.isNull()) { 3548 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3549 Ty = Context.UnsignedLongLongTy; 3550 Width = Context.getTargetInfo().getLongLongWidth(); 3551 } 3552 3553 if (ResultVal.getBitWidth() != Width) 3554 ResultVal = ResultVal.trunc(Width); 3555 } 3556 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3557 } 3558 3559 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3560 if (Literal.isImaginary) { 3561 Res = new (Context) ImaginaryLiteral(Res, 3562 Context.getComplexType(Res->getType())); 3563 3564 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3565 } 3566 return Res; 3567 } 3568 3569 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3570 assert(E && "ActOnParenExpr() missing expr"); 3571 return new (Context) ParenExpr(L, R, E); 3572 } 3573 3574 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3575 SourceLocation Loc, 3576 SourceRange ArgRange) { 3577 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3578 // scalar or vector data type argument..." 3579 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3580 // type (C99 6.2.5p18) or void. 3581 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3582 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3583 << T << ArgRange; 3584 return true; 3585 } 3586 3587 assert((T->isVoidType() || !T->isIncompleteType()) && 3588 "Scalar types should always be complete"); 3589 return false; 3590 } 3591 3592 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3593 SourceLocation Loc, 3594 SourceRange ArgRange, 3595 UnaryExprOrTypeTrait TraitKind) { 3596 // Invalid types must be hard errors for SFINAE in C++. 3597 if (S.LangOpts.CPlusPlus) 3598 return true; 3599 3600 // C99 6.5.3.4p1: 3601 if (T->isFunctionType() && 3602 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3603 TraitKind == UETT_PreferredAlignOf)) { 3604 // sizeof(function)/alignof(function) is allowed as an extension. 3605 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3606 << TraitKind << ArgRange; 3607 return false; 3608 } 3609 3610 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3611 // this is an error (OpenCL v1.1 s6.3.k) 3612 if (T->isVoidType()) { 3613 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3614 : diag::ext_sizeof_alignof_void_type; 3615 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3616 return false; 3617 } 3618 3619 return true; 3620 } 3621 3622 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3623 SourceLocation Loc, 3624 SourceRange ArgRange, 3625 UnaryExprOrTypeTrait TraitKind) { 3626 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3627 // runtime doesn't allow it. 3628 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3629 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3630 << T << (TraitKind == UETT_SizeOf) 3631 << ArgRange; 3632 return true; 3633 } 3634 3635 return false; 3636 } 3637 3638 /// Check whether E is a pointer from a decayed array type (the decayed 3639 /// pointer type is equal to T) and emit a warning if it is. 3640 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3641 Expr *E) { 3642 // Don't warn if the operation changed the type. 3643 if (T != E->getType()) 3644 return; 3645 3646 // Now look for array decays. 3647 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3648 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3649 return; 3650 3651 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3652 << ICE->getType() 3653 << ICE->getSubExpr()->getType(); 3654 } 3655 3656 /// Check the constraints on expression operands to unary type expression 3657 /// and type traits. 3658 /// 3659 /// Completes any types necessary and validates the constraints on the operand 3660 /// expression. The logic mostly mirrors the type-based overload, but may modify 3661 /// the expression as it completes the type for that expression through template 3662 /// instantiation, etc. 3663 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3664 UnaryExprOrTypeTrait ExprKind) { 3665 QualType ExprTy = E->getType(); 3666 assert(!ExprTy->isReferenceType()); 3667 3668 if (ExprKind == UETT_VecStep) 3669 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3670 E->getSourceRange()); 3671 3672 // Whitelist some types as extensions 3673 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3674 E->getSourceRange(), ExprKind)) 3675 return false; 3676 3677 // 'alignof' applied to an expression only requires the base element type of 3678 // the expression to be complete. 'sizeof' requires the expression's type to 3679 // be complete (and will attempt to complete it if it's an array of unknown 3680 // bound). 3681 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3682 if (RequireCompleteType(E->getExprLoc(), 3683 Context.getBaseElementType(E->getType()), 3684 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3685 E->getSourceRange())) 3686 return true; 3687 } else { 3688 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3689 ExprKind, E->getSourceRange())) 3690 return true; 3691 } 3692 3693 // Completing the expression's type may have changed it. 3694 ExprTy = E->getType(); 3695 assert(!ExprTy->isReferenceType()); 3696 3697 if (ExprTy->isFunctionType()) { 3698 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3699 << ExprKind << E->getSourceRange(); 3700 return true; 3701 } 3702 3703 // The operand for sizeof and alignof is in an unevaluated expression context, 3704 // so side effects could result in unintended consequences. 3705 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3706 ExprKind == UETT_PreferredAlignOf) && 3707 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3708 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3709 3710 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3711 E->getSourceRange(), ExprKind)) 3712 return true; 3713 3714 if (ExprKind == UETT_SizeOf) { 3715 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3716 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3717 QualType OType = PVD->getOriginalType(); 3718 QualType Type = PVD->getType(); 3719 if (Type->isPointerType() && OType->isArrayType()) { 3720 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3721 << Type << OType; 3722 Diag(PVD->getLocation(), diag::note_declared_at); 3723 } 3724 } 3725 } 3726 3727 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3728 // decays into a pointer and returns an unintended result. This is most 3729 // likely a typo for "sizeof(array) op x". 3730 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3731 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3732 BO->getLHS()); 3733 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3734 BO->getRHS()); 3735 } 3736 } 3737 3738 return false; 3739 } 3740 3741 /// Check the constraints on operands to unary expression and type 3742 /// traits. 3743 /// 3744 /// This will complete any types necessary, and validate the various constraints 3745 /// on those operands. 3746 /// 3747 /// The UsualUnaryConversions() function is *not* called by this routine. 3748 /// C99 6.3.2.1p[2-4] all state: 3749 /// Except when it is the operand of the sizeof operator ... 3750 /// 3751 /// C++ [expr.sizeof]p4 3752 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3753 /// standard conversions are not applied to the operand of sizeof. 3754 /// 3755 /// This policy is followed for all of the unary trait expressions. 3756 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3757 SourceLocation OpLoc, 3758 SourceRange ExprRange, 3759 UnaryExprOrTypeTrait ExprKind) { 3760 if (ExprType->isDependentType()) 3761 return false; 3762 3763 // C++ [expr.sizeof]p2: 3764 // When applied to a reference or a reference type, the result 3765 // is the size of the referenced type. 3766 // C++11 [expr.alignof]p3: 3767 // When alignof is applied to a reference type, the result 3768 // shall be the alignment of the referenced type. 3769 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3770 ExprType = Ref->getPointeeType(); 3771 3772 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3773 // When alignof or _Alignof is applied to an array type, the result 3774 // is the alignment of the element type. 3775 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3776 ExprKind == UETT_OpenMPRequiredSimdAlign) 3777 ExprType = Context.getBaseElementType(ExprType); 3778 3779 if (ExprKind == UETT_VecStep) 3780 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3781 3782 // Whitelist some types as extensions 3783 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3784 ExprKind)) 3785 return false; 3786 3787 if (RequireCompleteType(OpLoc, ExprType, 3788 diag::err_sizeof_alignof_incomplete_type, 3789 ExprKind, ExprRange)) 3790 return true; 3791 3792 if (ExprType->isFunctionType()) { 3793 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3794 << ExprKind << ExprRange; 3795 return true; 3796 } 3797 3798 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3799 ExprKind)) 3800 return true; 3801 3802 return false; 3803 } 3804 3805 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3806 E = E->IgnoreParens(); 3807 3808 // Cannot know anything else if the expression is dependent. 3809 if (E->isTypeDependent()) 3810 return false; 3811 3812 if (E->getObjectKind() == OK_BitField) { 3813 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3814 << 1 << E->getSourceRange(); 3815 return true; 3816 } 3817 3818 ValueDecl *D = nullptr; 3819 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3820 D = DRE->getDecl(); 3821 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3822 D = ME->getMemberDecl(); 3823 } 3824 3825 // If it's a field, require the containing struct to have a 3826 // complete definition so that we can compute the layout. 3827 // 3828 // This can happen in C++11 onwards, either by naming the member 3829 // in a way that is not transformed into a member access expression 3830 // (in an unevaluated operand, for instance), or by naming the member 3831 // in a trailing-return-type. 3832 // 3833 // For the record, since __alignof__ on expressions is a GCC 3834 // extension, GCC seems to permit this but always gives the 3835 // nonsensical answer 0. 3836 // 3837 // We don't really need the layout here --- we could instead just 3838 // directly check for all the appropriate alignment-lowing 3839 // attributes --- but that would require duplicating a lot of 3840 // logic that just isn't worth duplicating for such a marginal 3841 // use-case. 3842 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3843 // Fast path this check, since we at least know the record has a 3844 // definition if we can find a member of it. 3845 if (!FD->getParent()->isCompleteDefinition()) { 3846 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3847 << E->getSourceRange(); 3848 return true; 3849 } 3850 3851 // Otherwise, if it's a field, and the field doesn't have 3852 // reference type, then it must have a complete type (or be a 3853 // flexible array member, which we explicitly want to 3854 // white-list anyway), which makes the following checks trivial. 3855 if (!FD->getType()->isReferenceType()) 3856 return false; 3857 } 3858 3859 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3860 } 3861 3862 bool Sema::CheckVecStepExpr(Expr *E) { 3863 E = E->IgnoreParens(); 3864 3865 // Cannot know anything else if the expression is dependent. 3866 if (E->isTypeDependent()) 3867 return false; 3868 3869 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3870 } 3871 3872 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3873 CapturingScopeInfo *CSI) { 3874 assert(T->isVariablyModifiedType()); 3875 assert(CSI != nullptr); 3876 3877 // We're going to walk down into the type and look for VLA expressions. 3878 do { 3879 const Type *Ty = T.getTypePtr(); 3880 switch (Ty->getTypeClass()) { 3881 #define TYPE(Class, Base) 3882 #define ABSTRACT_TYPE(Class, Base) 3883 #define NON_CANONICAL_TYPE(Class, Base) 3884 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3885 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3886 #include "clang/AST/TypeNodes.def" 3887 T = QualType(); 3888 break; 3889 // These types are never variably-modified. 3890 case Type::Builtin: 3891 case Type::Complex: 3892 case Type::Vector: 3893 case Type::ExtVector: 3894 case Type::Record: 3895 case Type::Enum: 3896 case Type::Elaborated: 3897 case Type::TemplateSpecialization: 3898 case Type::ObjCObject: 3899 case Type::ObjCInterface: 3900 case Type::ObjCObjectPointer: 3901 case Type::ObjCTypeParam: 3902 case Type::Pipe: 3903 llvm_unreachable("type class is never variably-modified!"); 3904 case Type::Adjusted: 3905 T = cast<AdjustedType>(Ty)->getOriginalType(); 3906 break; 3907 case Type::Decayed: 3908 T = cast<DecayedType>(Ty)->getPointeeType(); 3909 break; 3910 case Type::Pointer: 3911 T = cast<PointerType>(Ty)->getPointeeType(); 3912 break; 3913 case Type::BlockPointer: 3914 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3915 break; 3916 case Type::LValueReference: 3917 case Type::RValueReference: 3918 T = cast<ReferenceType>(Ty)->getPointeeType(); 3919 break; 3920 case Type::MemberPointer: 3921 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3922 break; 3923 case Type::ConstantArray: 3924 case Type::IncompleteArray: 3925 // Losing element qualification here is fine. 3926 T = cast<ArrayType>(Ty)->getElementType(); 3927 break; 3928 case Type::VariableArray: { 3929 // Losing element qualification here is fine. 3930 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3931 3932 // Unknown size indication requires no size computation. 3933 // Otherwise, evaluate and record it. 3934 if (auto Size = VAT->getSizeExpr()) { 3935 if (!CSI->isVLATypeCaptured(VAT)) { 3936 RecordDecl *CapRecord = nullptr; 3937 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3938 CapRecord = LSI->Lambda; 3939 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3940 CapRecord = CRSI->TheRecordDecl; 3941 } 3942 if (CapRecord) { 3943 auto ExprLoc = Size->getExprLoc(); 3944 auto SizeType = Context.getSizeType(); 3945 // Build the non-static data member. 3946 auto Field = 3947 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3948 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3949 /*BW*/ nullptr, /*Mutable*/ false, 3950 /*InitStyle*/ ICIS_NoInit); 3951 Field->setImplicit(true); 3952 Field->setAccess(AS_private); 3953 Field->setCapturedVLAType(VAT); 3954 CapRecord->addDecl(Field); 3955 3956 CSI->addVLATypeCapture(ExprLoc, SizeType); 3957 } 3958 } 3959 } 3960 T = VAT->getElementType(); 3961 break; 3962 } 3963 case Type::FunctionProto: 3964 case Type::FunctionNoProto: 3965 T = cast<FunctionType>(Ty)->getReturnType(); 3966 break; 3967 case Type::Paren: 3968 case Type::TypeOf: 3969 case Type::UnaryTransform: 3970 case Type::Attributed: 3971 case Type::SubstTemplateTypeParm: 3972 case Type::PackExpansion: 3973 // Keep walking after single level desugaring. 3974 T = T.getSingleStepDesugaredType(Context); 3975 break; 3976 case Type::Typedef: 3977 T = cast<TypedefType>(Ty)->desugar(); 3978 break; 3979 case Type::Decltype: 3980 T = cast<DecltypeType>(Ty)->desugar(); 3981 break; 3982 case Type::Auto: 3983 case Type::DeducedTemplateSpecialization: 3984 T = cast<DeducedType>(Ty)->getDeducedType(); 3985 break; 3986 case Type::TypeOfExpr: 3987 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3988 break; 3989 case Type::Atomic: 3990 T = cast<AtomicType>(Ty)->getValueType(); 3991 break; 3992 } 3993 } while (!T.isNull() && T->isVariablyModifiedType()); 3994 } 3995 3996 /// Build a sizeof or alignof expression given a type operand. 3997 ExprResult 3998 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3999 SourceLocation OpLoc, 4000 UnaryExprOrTypeTrait ExprKind, 4001 SourceRange R) { 4002 if (!TInfo) 4003 return ExprError(); 4004 4005 QualType T = TInfo->getType(); 4006 4007 if (!T->isDependentType() && 4008 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4009 return ExprError(); 4010 4011 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4012 if (auto *TT = T->getAs<TypedefType>()) { 4013 for (auto I = FunctionScopes.rbegin(), 4014 E = std::prev(FunctionScopes.rend()); 4015 I != E; ++I) { 4016 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4017 if (CSI == nullptr) 4018 break; 4019 DeclContext *DC = nullptr; 4020 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4021 DC = LSI->CallOperator; 4022 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4023 DC = CRSI->TheCapturedDecl; 4024 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4025 DC = BSI->TheDecl; 4026 if (DC) { 4027 if (DC->containsDecl(TT->getDecl())) 4028 break; 4029 captureVariablyModifiedType(Context, T, CSI); 4030 } 4031 } 4032 } 4033 } 4034 4035 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4036 return new (Context) UnaryExprOrTypeTraitExpr( 4037 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4038 } 4039 4040 /// Build a sizeof or alignof expression given an expression 4041 /// operand. 4042 ExprResult 4043 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4044 UnaryExprOrTypeTrait ExprKind) { 4045 ExprResult PE = CheckPlaceholderExpr(E); 4046 if (PE.isInvalid()) 4047 return ExprError(); 4048 4049 E = PE.get(); 4050 4051 // Verify that the operand is valid. 4052 bool isInvalid = false; 4053 if (E->isTypeDependent()) { 4054 // Delay type-checking for type-dependent expressions. 4055 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4056 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4057 } else if (ExprKind == UETT_VecStep) { 4058 isInvalid = CheckVecStepExpr(E); 4059 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4060 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4061 isInvalid = true; 4062 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4063 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4064 isInvalid = true; 4065 } else { 4066 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4067 } 4068 4069 if (isInvalid) 4070 return ExprError(); 4071 4072 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4073 PE = TransformToPotentiallyEvaluated(E); 4074 if (PE.isInvalid()) return ExprError(); 4075 E = PE.get(); 4076 } 4077 4078 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4079 return new (Context) UnaryExprOrTypeTraitExpr( 4080 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4081 } 4082 4083 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4084 /// expr and the same for @c alignof and @c __alignof 4085 /// Note that the ArgRange is invalid if isType is false. 4086 ExprResult 4087 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4088 UnaryExprOrTypeTrait ExprKind, bool IsType, 4089 void *TyOrEx, SourceRange ArgRange) { 4090 // If error parsing type, ignore. 4091 if (!TyOrEx) return ExprError(); 4092 4093 if (IsType) { 4094 TypeSourceInfo *TInfo; 4095 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4096 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4097 } 4098 4099 Expr *ArgEx = (Expr *)TyOrEx; 4100 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4101 return Result; 4102 } 4103 4104 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4105 bool IsReal) { 4106 if (V.get()->isTypeDependent()) 4107 return S.Context.DependentTy; 4108 4109 // _Real and _Imag are only l-values for normal l-values. 4110 if (V.get()->getObjectKind() != OK_Ordinary) { 4111 V = S.DefaultLvalueConversion(V.get()); 4112 if (V.isInvalid()) 4113 return QualType(); 4114 } 4115 4116 // These operators return the element type of a complex type. 4117 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4118 return CT->getElementType(); 4119 4120 // Otherwise they pass through real integer and floating point types here. 4121 if (V.get()->getType()->isArithmeticType()) 4122 return V.get()->getType(); 4123 4124 // Test for placeholders. 4125 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4126 if (PR.isInvalid()) return QualType(); 4127 if (PR.get() != V.get()) { 4128 V = PR; 4129 return CheckRealImagOperand(S, V, Loc, IsReal); 4130 } 4131 4132 // Reject anything else. 4133 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4134 << (IsReal ? "__real" : "__imag"); 4135 return QualType(); 4136 } 4137 4138 4139 4140 ExprResult 4141 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4142 tok::TokenKind Kind, Expr *Input) { 4143 UnaryOperatorKind Opc; 4144 switch (Kind) { 4145 default: llvm_unreachable("Unknown unary op!"); 4146 case tok::plusplus: Opc = UO_PostInc; break; 4147 case tok::minusminus: Opc = UO_PostDec; break; 4148 } 4149 4150 // Since this might is a postfix expression, get rid of ParenListExprs. 4151 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4152 if (Result.isInvalid()) return ExprError(); 4153 Input = Result.get(); 4154 4155 return BuildUnaryOp(S, OpLoc, Opc, Input); 4156 } 4157 4158 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4159 /// 4160 /// \return true on error 4161 static bool checkArithmeticOnObjCPointer(Sema &S, 4162 SourceLocation opLoc, 4163 Expr *op) { 4164 assert(op->getType()->isObjCObjectPointerType()); 4165 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4166 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4167 return false; 4168 4169 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4170 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4171 << op->getSourceRange(); 4172 return true; 4173 } 4174 4175 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4176 auto *BaseNoParens = Base->IgnoreParens(); 4177 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4178 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4179 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4180 } 4181 4182 ExprResult 4183 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4184 Expr *idx, SourceLocation rbLoc) { 4185 if (base && !base->getType().isNull() && 4186 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4187 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4188 /*Length=*/nullptr, rbLoc); 4189 4190 // Since this might be a postfix expression, get rid of ParenListExprs. 4191 if (isa<ParenListExpr>(base)) { 4192 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4193 if (result.isInvalid()) return ExprError(); 4194 base = result.get(); 4195 } 4196 4197 // Handle any non-overload placeholder types in the base and index 4198 // expressions. We can't handle overloads here because the other 4199 // operand might be an overloadable type, in which case the overload 4200 // resolution for the operator overload should get the first crack 4201 // at the overload. 4202 bool IsMSPropertySubscript = false; 4203 if (base->getType()->isNonOverloadPlaceholderType()) { 4204 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4205 if (!IsMSPropertySubscript) { 4206 ExprResult result = CheckPlaceholderExpr(base); 4207 if (result.isInvalid()) 4208 return ExprError(); 4209 base = result.get(); 4210 } 4211 } 4212 if (idx->getType()->isNonOverloadPlaceholderType()) { 4213 ExprResult result = CheckPlaceholderExpr(idx); 4214 if (result.isInvalid()) return ExprError(); 4215 idx = result.get(); 4216 } 4217 4218 // Build an unanalyzed expression if either operand is type-dependent. 4219 if (getLangOpts().CPlusPlus && 4220 (base->isTypeDependent() || idx->isTypeDependent())) { 4221 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4222 VK_LValue, OK_Ordinary, rbLoc); 4223 } 4224 4225 // MSDN, property (C++) 4226 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4227 // This attribute can also be used in the declaration of an empty array in a 4228 // class or structure definition. For example: 4229 // __declspec(property(get=GetX, put=PutX)) int x[]; 4230 // The above statement indicates that x[] can be used with one or more array 4231 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4232 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4233 if (IsMSPropertySubscript) { 4234 // Build MS property subscript expression if base is MS property reference 4235 // or MS property subscript. 4236 return new (Context) MSPropertySubscriptExpr( 4237 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4238 } 4239 4240 // Use C++ overloaded-operator rules if either operand has record 4241 // type. The spec says to do this if either type is *overloadable*, 4242 // but enum types can't declare subscript operators or conversion 4243 // operators, so there's nothing interesting for overload resolution 4244 // to do if there aren't any record types involved. 4245 // 4246 // ObjC pointers have their own subscripting logic that is not tied 4247 // to overload resolution and so should not take this path. 4248 if (getLangOpts().CPlusPlus && 4249 (base->getType()->isRecordType() || 4250 (!base->getType()->isObjCObjectPointerType() && 4251 idx->getType()->isRecordType()))) { 4252 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4253 } 4254 4255 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4256 } 4257 4258 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4259 Expr *LowerBound, 4260 SourceLocation ColonLoc, Expr *Length, 4261 SourceLocation RBLoc) { 4262 if (Base->getType()->isPlaceholderType() && 4263 !Base->getType()->isSpecificPlaceholderType( 4264 BuiltinType::OMPArraySection)) { 4265 ExprResult Result = CheckPlaceholderExpr(Base); 4266 if (Result.isInvalid()) 4267 return ExprError(); 4268 Base = Result.get(); 4269 } 4270 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4271 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4272 if (Result.isInvalid()) 4273 return ExprError(); 4274 Result = DefaultLvalueConversion(Result.get()); 4275 if (Result.isInvalid()) 4276 return ExprError(); 4277 LowerBound = Result.get(); 4278 } 4279 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4280 ExprResult Result = CheckPlaceholderExpr(Length); 4281 if (Result.isInvalid()) 4282 return ExprError(); 4283 Result = DefaultLvalueConversion(Result.get()); 4284 if (Result.isInvalid()) 4285 return ExprError(); 4286 Length = Result.get(); 4287 } 4288 4289 // Build an unanalyzed expression if either operand is type-dependent. 4290 if (Base->isTypeDependent() || 4291 (LowerBound && 4292 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4293 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4294 return new (Context) 4295 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4296 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4297 } 4298 4299 // Perform default conversions. 4300 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4301 QualType ResultTy; 4302 if (OriginalTy->isAnyPointerType()) { 4303 ResultTy = OriginalTy->getPointeeType(); 4304 } else if (OriginalTy->isArrayType()) { 4305 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4306 } else { 4307 return ExprError( 4308 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4309 << Base->getSourceRange()); 4310 } 4311 // C99 6.5.2.1p1 4312 if (LowerBound) { 4313 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4314 LowerBound); 4315 if (Res.isInvalid()) 4316 return ExprError(Diag(LowerBound->getExprLoc(), 4317 diag::err_omp_typecheck_section_not_integer) 4318 << 0 << LowerBound->getSourceRange()); 4319 LowerBound = Res.get(); 4320 4321 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4322 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4323 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4324 << 0 << LowerBound->getSourceRange(); 4325 } 4326 if (Length) { 4327 auto Res = 4328 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4329 if (Res.isInvalid()) 4330 return ExprError(Diag(Length->getExprLoc(), 4331 diag::err_omp_typecheck_section_not_integer) 4332 << 1 << Length->getSourceRange()); 4333 Length = Res.get(); 4334 4335 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4336 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4337 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4338 << 1 << Length->getSourceRange(); 4339 } 4340 4341 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4342 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4343 // type. Note that functions are not objects, and that (in C99 parlance) 4344 // incomplete types are not object types. 4345 if (ResultTy->isFunctionType()) { 4346 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4347 << ResultTy << Base->getSourceRange(); 4348 return ExprError(); 4349 } 4350 4351 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4352 diag::err_omp_section_incomplete_type, Base)) 4353 return ExprError(); 4354 4355 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4356 llvm::APSInt LowerBoundValue; 4357 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4358 // OpenMP 4.5, [2.4 Array Sections] 4359 // The array section must be a subset of the original array. 4360 if (LowerBoundValue.isNegative()) { 4361 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4362 << LowerBound->getSourceRange(); 4363 return ExprError(); 4364 } 4365 } 4366 } 4367 4368 if (Length) { 4369 llvm::APSInt LengthValue; 4370 if (Length->EvaluateAsInt(LengthValue, Context)) { 4371 // OpenMP 4.5, [2.4 Array Sections] 4372 // The length must evaluate to non-negative integers. 4373 if (LengthValue.isNegative()) { 4374 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4375 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4376 << Length->getSourceRange(); 4377 return ExprError(); 4378 } 4379 } 4380 } else if (ColonLoc.isValid() && 4381 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4382 !OriginalTy->isVariableArrayType()))) { 4383 // OpenMP 4.5, [2.4 Array Sections] 4384 // When the size of the array dimension is not known, the length must be 4385 // specified explicitly. 4386 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4387 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4388 return ExprError(); 4389 } 4390 4391 if (!Base->getType()->isSpecificPlaceholderType( 4392 BuiltinType::OMPArraySection)) { 4393 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4394 if (Result.isInvalid()) 4395 return ExprError(); 4396 Base = Result.get(); 4397 } 4398 return new (Context) 4399 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4400 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4401 } 4402 4403 ExprResult 4404 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4405 Expr *Idx, SourceLocation RLoc) { 4406 Expr *LHSExp = Base; 4407 Expr *RHSExp = Idx; 4408 4409 ExprValueKind VK = VK_LValue; 4410 ExprObjectKind OK = OK_Ordinary; 4411 4412 // Per C++ core issue 1213, the result is an xvalue if either operand is 4413 // a non-lvalue array, and an lvalue otherwise. 4414 if (getLangOpts().CPlusPlus11) { 4415 for (auto *Op : {LHSExp, RHSExp}) { 4416 Op = Op->IgnoreImplicit(); 4417 if (Op->getType()->isArrayType() && !Op->isLValue()) 4418 VK = VK_XValue; 4419 } 4420 } 4421 4422 // Perform default conversions. 4423 if (!LHSExp->getType()->getAs<VectorType>()) { 4424 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4425 if (Result.isInvalid()) 4426 return ExprError(); 4427 LHSExp = Result.get(); 4428 } 4429 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4430 if (Result.isInvalid()) 4431 return ExprError(); 4432 RHSExp = Result.get(); 4433 4434 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4435 4436 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4437 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4438 // in the subscript position. As a result, we need to derive the array base 4439 // and index from the expression types. 4440 Expr *BaseExpr, *IndexExpr; 4441 QualType ResultType; 4442 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4443 BaseExpr = LHSExp; 4444 IndexExpr = RHSExp; 4445 ResultType = Context.DependentTy; 4446 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4447 BaseExpr = LHSExp; 4448 IndexExpr = RHSExp; 4449 ResultType = PTy->getPointeeType(); 4450 } else if (const ObjCObjectPointerType *PTy = 4451 LHSTy->getAs<ObjCObjectPointerType>()) { 4452 BaseExpr = LHSExp; 4453 IndexExpr = RHSExp; 4454 4455 // Use custom logic if this should be the pseudo-object subscript 4456 // expression. 4457 if (!LangOpts.isSubscriptPointerArithmetic()) 4458 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4459 nullptr); 4460 4461 ResultType = PTy->getPointeeType(); 4462 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4463 // Handle the uncommon case of "123[Ptr]". 4464 BaseExpr = RHSExp; 4465 IndexExpr = LHSExp; 4466 ResultType = PTy->getPointeeType(); 4467 } else if (const ObjCObjectPointerType *PTy = 4468 RHSTy->getAs<ObjCObjectPointerType>()) { 4469 // Handle the uncommon case of "123[Ptr]". 4470 BaseExpr = RHSExp; 4471 IndexExpr = LHSExp; 4472 ResultType = PTy->getPointeeType(); 4473 if (!LangOpts.isSubscriptPointerArithmetic()) { 4474 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4475 << ResultType << BaseExpr->getSourceRange(); 4476 return ExprError(); 4477 } 4478 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4479 BaseExpr = LHSExp; // vectors: V[123] 4480 IndexExpr = RHSExp; 4481 // We apply C++ DR1213 to vector subscripting too. 4482 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4483 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4484 if (Materialized.isInvalid()) 4485 return ExprError(); 4486 LHSExp = Materialized.get(); 4487 } 4488 VK = LHSExp->getValueKind(); 4489 if (VK != VK_RValue) 4490 OK = OK_VectorComponent; 4491 4492 ResultType = VTy->getElementType(); 4493 QualType BaseType = BaseExpr->getType(); 4494 Qualifiers BaseQuals = BaseType.getQualifiers(); 4495 Qualifiers MemberQuals = ResultType.getQualifiers(); 4496 Qualifiers Combined = BaseQuals + MemberQuals; 4497 if (Combined != MemberQuals) 4498 ResultType = Context.getQualifiedType(ResultType, Combined); 4499 } else if (LHSTy->isArrayType()) { 4500 // If we see an array that wasn't promoted by 4501 // DefaultFunctionArrayLvalueConversion, it must be an array that 4502 // wasn't promoted because of the C90 rule that doesn't 4503 // allow promoting non-lvalue arrays. Warn, then 4504 // force the promotion here. 4505 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4506 << LHSExp->getSourceRange(); 4507 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4508 CK_ArrayToPointerDecay).get(); 4509 LHSTy = LHSExp->getType(); 4510 4511 BaseExpr = LHSExp; 4512 IndexExpr = RHSExp; 4513 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4514 } else if (RHSTy->isArrayType()) { 4515 // Same as previous, except for 123[f().a] case 4516 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4517 << RHSExp->getSourceRange(); 4518 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4519 CK_ArrayToPointerDecay).get(); 4520 RHSTy = RHSExp->getType(); 4521 4522 BaseExpr = RHSExp; 4523 IndexExpr = LHSExp; 4524 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4525 } else { 4526 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4527 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4528 } 4529 // C99 6.5.2.1p1 4530 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4531 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4532 << IndexExpr->getSourceRange()); 4533 4534 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4535 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4536 && !IndexExpr->isTypeDependent()) 4537 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4538 4539 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4540 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4541 // type. Note that Functions are not objects, and that (in C99 parlance) 4542 // incomplete types are not object types. 4543 if (ResultType->isFunctionType()) { 4544 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4545 << ResultType << BaseExpr->getSourceRange(); 4546 return ExprError(); 4547 } 4548 4549 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4550 // GNU extension: subscripting on pointer to void 4551 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4552 << BaseExpr->getSourceRange(); 4553 4554 // C forbids expressions of unqualified void type from being l-values. 4555 // See IsCForbiddenLValueType. 4556 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4557 } else if (!ResultType->isDependentType() && 4558 RequireCompleteType(LLoc, ResultType, 4559 diag::err_subscript_incomplete_type, BaseExpr)) 4560 return ExprError(); 4561 4562 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4563 !ResultType.isCForbiddenLValueType()); 4564 4565 return new (Context) 4566 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4567 } 4568 4569 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4570 ParmVarDecl *Param) { 4571 if (Param->hasUnparsedDefaultArg()) { 4572 Diag(CallLoc, 4573 diag::err_use_of_default_argument_to_function_declared_later) << 4574 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4575 Diag(UnparsedDefaultArgLocs[Param], 4576 diag::note_default_argument_declared_here); 4577 return true; 4578 } 4579 4580 if (Param->hasUninstantiatedDefaultArg()) { 4581 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4582 4583 EnterExpressionEvaluationContext EvalContext( 4584 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4585 4586 // Instantiate the expression. 4587 // 4588 // FIXME: Pass in a correct Pattern argument, otherwise 4589 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4590 // 4591 // template<typename T> 4592 // struct A { 4593 // static int FooImpl(); 4594 // 4595 // template<typename Tp> 4596 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4597 // // template argument list [[T], [Tp]], should be [[Tp]]. 4598 // friend A<Tp> Foo(int a); 4599 // }; 4600 // 4601 // template<typename T> 4602 // A<T> Foo(int a = A<T>::FooImpl()); 4603 MultiLevelTemplateArgumentList MutiLevelArgList 4604 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4605 4606 InstantiatingTemplate Inst(*this, CallLoc, Param, 4607 MutiLevelArgList.getInnermost()); 4608 if (Inst.isInvalid()) 4609 return true; 4610 if (Inst.isAlreadyInstantiating()) { 4611 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4612 Param->setInvalidDecl(); 4613 return true; 4614 } 4615 4616 ExprResult Result; 4617 { 4618 // C++ [dcl.fct.default]p5: 4619 // The names in the [default argument] expression are bound, and 4620 // the semantic constraints are checked, at the point where the 4621 // default argument expression appears. 4622 ContextRAII SavedContext(*this, FD); 4623 LocalInstantiationScope Local(*this); 4624 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4625 /*DirectInit*/false); 4626 } 4627 if (Result.isInvalid()) 4628 return true; 4629 4630 // Check the expression as an initializer for the parameter. 4631 InitializedEntity Entity 4632 = InitializedEntity::InitializeParameter(Context, Param); 4633 InitializationKind Kind = InitializationKind::CreateCopy( 4634 Param->getLocation(), 4635 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4636 Expr *ResultE = Result.getAs<Expr>(); 4637 4638 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4639 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4640 if (Result.isInvalid()) 4641 return true; 4642 4643 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4644 Param->getOuterLocStart()); 4645 if (Result.isInvalid()) 4646 return true; 4647 4648 // Remember the instantiated default argument. 4649 Param->setDefaultArg(Result.getAs<Expr>()); 4650 if (ASTMutationListener *L = getASTMutationListener()) { 4651 L->DefaultArgumentInstantiated(Param); 4652 } 4653 } 4654 4655 // If the default argument expression is not set yet, we are building it now. 4656 if (!Param->hasInit()) { 4657 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4658 Param->setInvalidDecl(); 4659 return true; 4660 } 4661 4662 // If the default expression creates temporaries, we need to 4663 // push them to the current stack of expression temporaries so they'll 4664 // be properly destroyed. 4665 // FIXME: We should really be rebuilding the default argument with new 4666 // bound temporaries; see the comment in PR5810. 4667 // We don't need to do that with block decls, though, because 4668 // blocks in default argument expression can never capture anything. 4669 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4670 // Set the "needs cleanups" bit regardless of whether there are 4671 // any explicit objects. 4672 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4673 4674 // Append all the objects to the cleanup list. Right now, this 4675 // should always be a no-op, because blocks in default argument 4676 // expressions should never be able to capture anything. 4677 assert(!Init->getNumObjects() && 4678 "default argument expression has capturing blocks?"); 4679 } 4680 4681 // We already type-checked the argument, so we know it works. 4682 // Just mark all of the declarations in this potentially-evaluated expression 4683 // as being "referenced". 4684 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4685 /*SkipLocalVariables=*/true); 4686 return false; 4687 } 4688 4689 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4690 FunctionDecl *FD, ParmVarDecl *Param) { 4691 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4692 return ExprError(); 4693 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4694 } 4695 4696 Sema::VariadicCallType 4697 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4698 Expr *Fn) { 4699 if (Proto && Proto->isVariadic()) { 4700 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4701 return VariadicConstructor; 4702 else if (Fn && Fn->getType()->isBlockPointerType()) 4703 return VariadicBlock; 4704 else if (FDecl) { 4705 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4706 if (Method->isInstance()) 4707 return VariadicMethod; 4708 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4709 return VariadicMethod; 4710 return VariadicFunction; 4711 } 4712 return VariadicDoesNotApply; 4713 } 4714 4715 namespace { 4716 class FunctionCallCCC : public FunctionCallFilterCCC { 4717 public: 4718 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4719 unsigned NumArgs, MemberExpr *ME) 4720 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4721 FunctionName(FuncName) {} 4722 4723 bool ValidateCandidate(const TypoCorrection &candidate) override { 4724 if (!candidate.getCorrectionSpecifier() || 4725 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4726 return false; 4727 } 4728 4729 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4730 } 4731 4732 private: 4733 const IdentifierInfo *const FunctionName; 4734 }; 4735 } 4736 4737 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4738 FunctionDecl *FDecl, 4739 ArrayRef<Expr *> Args) { 4740 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4741 DeclarationName FuncName = FDecl->getDeclName(); 4742 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4743 4744 if (TypoCorrection Corrected = S.CorrectTypo( 4745 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4746 S.getScopeForContext(S.CurContext), nullptr, 4747 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4748 Args.size(), ME), 4749 Sema::CTK_ErrorRecovery)) { 4750 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4751 if (Corrected.isOverloaded()) { 4752 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4753 OverloadCandidateSet::iterator Best; 4754 for (NamedDecl *CD : Corrected) { 4755 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4756 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4757 OCS); 4758 } 4759 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4760 case OR_Success: 4761 ND = Best->FoundDecl; 4762 Corrected.setCorrectionDecl(ND); 4763 break; 4764 default: 4765 break; 4766 } 4767 } 4768 ND = ND->getUnderlyingDecl(); 4769 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4770 return Corrected; 4771 } 4772 } 4773 return TypoCorrection(); 4774 } 4775 4776 /// ConvertArgumentsForCall - Converts the arguments specified in 4777 /// Args/NumArgs to the parameter types of the function FDecl with 4778 /// function prototype Proto. Call is the call expression itself, and 4779 /// Fn is the function expression. For a C++ member function, this 4780 /// routine does not attempt to convert the object argument. Returns 4781 /// true if the call is ill-formed. 4782 bool 4783 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4784 FunctionDecl *FDecl, 4785 const FunctionProtoType *Proto, 4786 ArrayRef<Expr *> Args, 4787 SourceLocation RParenLoc, 4788 bool IsExecConfig) { 4789 // Bail out early if calling a builtin with custom typechecking. 4790 if (FDecl) 4791 if (unsigned ID = FDecl->getBuiltinID()) 4792 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4793 return false; 4794 4795 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4796 // assignment, to the types of the corresponding parameter, ... 4797 unsigned NumParams = Proto->getNumParams(); 4798 bool Invalid = false; 4799 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4800 unsigned FnKind = Fn->getType()->isBlockPointerType() 4801 ? 1 /* block */ 4802 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4803 : 0 /* function */); 4804 4805 // If too few arguments are available (and we don't have default 4806 // arguments for the remaining parameters), don't make the call. 4807 if (Args.size() < NumParams) { 4808 if (Args.size() < MinArgs) { 4809 TypoCorrection TC; 4810 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4811 unsigned diag_id = 4812 MinArgs == NumParams && !Proto->isVariadic() 4813 ? diag::err_typecheck_call_too_few_args_suggest 4814 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4815 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4816 << static_cast<unsigned>(Args.size()) 4817 << TC.getCorrectionRange()); 4818 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4819 Diag(RParenLoc, 4820 MinArgs == NumParams && !Proto->isVariadic() 4821 ? diag::err_typecheck_call_too_few_args_one 4822 : diag::err_typecheck_call_too_few_args_at_least_one) 4823 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4824 else 4825 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4826 ? diag::err_typecheck_call_too_few_args 4827 : diag::err_typecheck_call_too_few_args_at_least) 4828 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4829 << Fn->getSourceRange(); 4830 4831 // Emit the location of the prototype. 4832 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4833 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4834 4835 return true; 4836 } 4837 Call->setNumArgs(Context, NumParams); 4838 } 4839 4840 // If too many are passed and not variadic, error on the extras and drop 4841 // them. 4842 if (Args.size() > NumParams) { 4843 if (!Proto->isVariadic()) { 4844 TypoCorrection TC; 4845 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4846 unsigned diag_id = 4847 MinArgs == NumParams && !Proto->isVariadic() 4848 ? diag::err_typecheck_call_too_many_args_suggest 4849 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4850 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4851 << static_cast<unsigned>(Args.size()) 4852 << TC.getCorrectionRange()); 4853 } else if (NumParams == 1 && FDecl && 4854 FDecl->getParamDecl(0)->getDeclName()) 4855 Diag(Args[NumParams]->getBeginLoc(), 4856 MinArgs == NumParams 4857 ? diag::err_typecheck_call_too_many_args_one 4858 : diag::err_typecheck_call_too_many_args_at_most_one) 4859 << FnKind << FDecl->getParamDecl(0) 4860 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4861 << SourceRange(Args[NumParams]->getBeginLoc(), 4862 Args.back()->getEndLoc()); 4863 else 4864 Diag(Args[NumParams]->getBeginLoc(), 4865 MinArgs == NumParams 4866 ? diag::err_typecheck_call_too_many_args 4867 : diag::err_typecheck_call_too_many_args_at_most) 4868 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4869 << Fn->getSourceRange() 4870 << SourceRange(Args[NumParams]->getBeginLoc(), 4871 Args.back()->getEndLoc()); 4872 4873 // Emit the location of the prototype. 4874 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4875 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4876 4877 // This deletes the extra arguments. 4878 Call->setNumArgs(Context, NumParams); 4879 return true; 4880 } 4881 } 4882 SmallVector<Expr *, 8> AllArgs; 4883 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4884 4885 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4886 AllArgs, CallType); 4887 if (Invalid) 4888 return true; 4889 unsigned TotalNumArgs = AllArgs.size(); 4890 for (unsigned i = 0; i < TotalNumArgs; ++i) 4891 Call->setArg(i, AllArgs[i]); 4892 4893 return false; 4894 } 4895 4896 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4897 const FunctionProtoType *Proto, 4898 unsigned FirstParam, ArrayRef<Expr *> Args, 4899 SmallVectorImpl<Expr *> &AllArgs, 4900 VariadicCallType CallType, bool AllowExplicit, 4901 bool IsListInitialization) { 4902 unsigned NumParams = Proto->getNumParams(); 4903 bool Invalid = false; 4904 size_t ArgIx = 0; 4905 // Continue to check argument types (even if we have too few/many args). 4906 for (unsigned i = FirstParam; i < NumParams; i++) { 4907 QualType ProtoArgType = Proto->getParamType(i); 4908 4909 Expr *Arg; 4910 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4911 if (ArgIx < Args.size()) { 4912 Arg = Args[ArgIx++]; 4913 4914 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4915 diag::err_call_incomplete_argument, Arg)) 4916 return true; 4917 4918 // Strip the unbridged-cast placeholder expression off, if applicable. 4919 bool CFAudited = false; 4920 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4921 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4922 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4923 Arg = stripARCUnbridgedCast(Arg); 4924 else if (getLangOpts().ObjCAutoRefCount && 4925 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4926 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4927 CFAudited = true; 4928 4929 if (Proto->getExtParameterInfo(i).isNoEscape()) 4930 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4931 BE->getBlockDecl()->setDoesNotEscape(); 4932 4933 InitializedEntity Entity = 4934 Param ? InitializedEntity::InitializeParameter(Context, Param, 4935 ProtoArgType) 4936 : InitializedEntity::InitializeParameter( 4937 Context, ProtoArgType, Proto->isParamConsumed(i)); 4938 4939 // Remember that parameter belongs to a CF audited API. 4940 if (CFAudited) 4941 Entity.setParameterCFAudited(); 4942 4943 ExprResult ArgE = PerformCopyInitialization( 4944 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4945 if (ArgE.isInvalid()) 4946 return true; 4947 4948 Arg = ArgE.getAs<Expr>(); 4949 } else { 4950 assert(Param && "can't use default arguments without a known callee"); 4951 4952 ExprResult ArgExpr = 4953 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4954 if (ArgExpr.isInvalid()) 4955 return true; 4956 4957 Arg = ArgExpr.getAs<Expr>(); 4958 } 4959 4960 // Check for array bounds violations for each argument to the call. This 4961 // check only triggers warnings when the argument isn't a more complex Expr 4962 // with its own checking, such as a BinaryOperator. 4963 CheckArrayAccess(Arg); 4964 4965 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4966 CheckStaticArrayArgument(CallLoc, Param, Arg); 4967 4968 AllArgs.push_back(Arg); 4969 } 4970 4971 // If this is a variadic call, handle args passed through "...". 4972 if (CallType != VariadicDoesNotApply) { 4973 // Assume that extern "C" functions with variadic arguments that 4974 // return __unknown_anytype aren't *really* variadic. 4975 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4976 FDecl->isExternC()) { 4977 for (Expr *A : Args.slice(ArgIx)) { 4978 QualType paramType; // ignored 4979 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4980 Invalid |= arg.isInvalid(); 4981 AllArgs.push_back(arg.get()); 4982 } 4983 4984 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4985 } else { 4986 for (Expr *A : Args.slice(ArgIx)) { 4987 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4988 Invalid |= Arg.isInvalid(); 4989 AllArgs.push_back(Arg.get()); 4990 } 4991 } 4992 4993 // Check for array bounds violations. 4994 for (Expr *A : Args.slice(ArgIx)) 4995 CheckArrayAccess(A); 4996 } 4997 return Invalid; 4998 } 4999 5000 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5001 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5002 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5003 TL = DTL.getOriginalLoc(); 5004 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5005 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5006 << ATL.getLocalSourceRange(); 5007 } 5008 5009 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5010 /// array parameter, check that it is non-null, and that if it is formed by 5011 /// array-to-pointer decay, the underlying array is sufficiently large. 5012 /// 5013 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5014 /// array type derivation, then for each call to the function, the value of the 5015 /// corresponding actual argument shall provide access to the first element of 5016 /// an array with at least as many elements as specified by the size expression. 5017 void 5018 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5019 ParmVarDecl *Param, 5020 const Expr *ArgExpr) { 5021 // Static array parameters are not supported in C++. 5022 if (!Param || getLangOpts().CPlusPlus) 5023 return; 5024 5025 QualType OrigTy = Param->getOriginalType(); 5026 5027 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5028 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5029 return; 5030 5031 if (ArgExpr->isNullPointerConstant(Context, 5032 Expr::NPC_NeverValueDependent)) { 5033 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5034 DiagnoseCalleeStaticArrayParam(*this, Param); 5035 return; 5036 } 5037 5038 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5039 if (!CAT) 5040 return; 5041 5042 const ConstantArrayType *ArgCAT = 5043 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5044 if (!ArgCAT) 5045 return; 5046 5047 if (ArgCAT->getSize().ult(CAT->getSize())) { 5048 Diag(CallLoc, diag::warn_static_array_too_small) 5049 << ArgExpr->getSourceRange() 5050 << (unsigned) ArgCAT->getSize().getZExtValue() 5051 << (unsigned) CAT->getSize().getZExtValue(); 5052 DiagnoseCalleeStaticArrayParam(*this, Param); 5053 } 5054 } 5055 5056 /// Given a function expression of unknown-any type, try to rebuild it 5057 /// to have a function type. 5058 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5059 5060 /// Is the given type a placeholder that we need to lower out 5061 /// immediately during argument processing? 5062 static bool isPlaceholderToRemoveAsArg(QualType type) { 5063 // Placeholders are never sugared. 5064 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5065 if (!placeholder) return false; 5066 5067 switch (placeholder->getKind()) { 5068 // Ignore all the non-placeholder types. 5069 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5070 case BuiltinType::Id: 5071 #include "clang/Basic/OpenCLImageTypes.def" 5072 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5073 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5074 #include "clang/AST/BuiltinTypes.def" 5075 return false; 5076 5077 // We cannot lower out overload sets; they might validly be resolved 5078 // by the call machinery. 5079 case BuiltinType::Overload: 5080 return false; 5081 5082 // Unbridged casts in ARC can be handled in some call positions and 5083 // should be left in place. 5084 case BuiltinType::ARCUnbridgedCast: 5085 return false; 5086 5087 // Pseudo-objects should be converted as soon as possible. 5088 case BuiltinType::PseudoObject: 5089 return true; 5090 5091 // The debugger mode could theoretically but currently does not try 5092 // to resolve unknown-typed arguments based on known parameter types. 5093 case BuiltinType::UnknownAny: 5094 return true; 5095 5096 // These are always invalid as call arguments and should be reported. 5097 case BuiltinType::BoundMember: 5098 case BuiltinType::BuiltinFn: 5099 case BuiltinType::OMPArraySection: 5100 return true; 5101 5102 } 5103 llvm_unreachable("bad builtin type kind"); 5104 } 5105 5106 /// Check an argument list for placeholders that we won't try to 5107 /// handle later. 5108 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5109 // Apply this processing to all the arguments at once instead of 5110 // dying at the first failure. 5111 bool hasInvalid = false; 5112 for (size_t i = 0, e = args.size(); i != e; i++) { 5113 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5114 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5115 if (result.isInvalid()) hasInvalid = true; 5116 else args[i] = result.get(); 5117 } else if (hasInvalid) { 5118 (void)S.CorrectDelayedTyposInExpr(args[i]); 5119 } 5120 } 5121 return hasInvalid; 5122 } 5123 5124 /// If a builtin function has a pointer argument with no explicit address 5125 /// space, then it should be able to accept a pointer to any address 5126 /// space as input. In order to do this, we need to replace the 5127 /// standard builtin declaration with one that uses the same address space 5128 /// as the call. 5129 /// 5130 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5131 /// it does not contain any pointer arguments without 5132 /// an address space qualifer. Otherwise the rewritten 5133 /// FunctionDecl is returned. 5134 /// TODO: Handle pointer return types. 5135 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5136 const FunctionDecl *FDecl, 5137 MultiExprArg ArgExprs) { 5138 5139 QualType DeclType = FDecl->getType(); 5140 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5141 5142 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5143 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5144 return nullptr; 5145 5146 bool NeedsNewDecl = false; 5147 unsigned i = 0; 5148 SmallVector<QualType, 8> OverloadParams; 5149 5150 for (QualType ParamType : FT->param_types()) { 5151 5152 // Convert array arguments to pointer to simplify type lookup. 5153 ExprResult ArgRes = 5154 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5155 if (ArgRes.isInvalid()) 5156 return nullptr; 5157 Expr *Arg = ArgRes.get(); 5158 QualType ArgType = Arg->getType(); 5159 if (!ParamType->isPointerType() || 5160 ParamType.getQualifiers().hasAddressSpace() || 5161 !ArgType->isPointerType() || 5162 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5163 OverloadParams.push_back(ParamType); 5164 continue; 5165 } 5166 5167 QualType PointeeType = ParamType->getPointeeType(); 5168 if (PointeeType.getQualifiers().hasAddressSpace()) 5169 continue; 5170 5171 NeedsNewDecl = true; 5172 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5173 5174 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5175 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5176 } 5177 5178 if (!NeedsNewDecl) 5179 return nullptr; 5180 5181 FunctionProtoType::ExtProtoInfo EPI; 5182 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5183 OverloadParams, EPI); 5184 DeclContext *Parent = Context.getTranslationUnitDecl(); 5185 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5186 FDecl->getLocation(), 5187 FDecl->getLocation(), 5188 FDecl->getIdentifier(), 5189 OverloadTy, 5190 /*TInfo=*/nullptr, 5191 SC_Extern, false, 5192 /*hasPrototype=*/true); 5193 SmallVector<ParmVarDecl*, 16> Params; 5194 FT = cast<FunctionProtoType>(OverloadTy); 5195 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5196 QualType ParamType = FT->getParamType(i); 5197 ParmVarDecl *Parm = 5198 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5199 SourceLocation(), nullptr, ParamType, 5200 /*TInfo=*/nullptr, SC_None, nullptr); 5201 Parm->setScopeInfo(0, i); 5202 Params.push_back(Parm); 5203 } 5204 OverloadDecl->setParams(Params); 5205 return OverloadDecl; 5206 } 5207 5208 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5209 FunctionDecl *Callee, 5210 MultiExprArg ArgExprs) { 5211 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5212 // similar attributes) really don't like it when functions are called with an 5213 // invalid number of args. 5214 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5215 /*PartialOverloading=*/false) && 5216 !Callee->isVariadic()) 5217 return; 5218 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5219 return; 5220 5221 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5222 S.Diag(Fn->getBeginLoc(), 5223 isa<CXXMethodDecl>(Callee) 5224 ? diag::err_ovl_no_viable_member_function_in_call 5225 : diag::err_ovl_no_viable_function_in_call) 5226 << Callee << Callee->getSourceRange(); 5227 S.Diag(Callee->getLocation(), 5228 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5229 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5230 return; 5231 } 5232 } 5233 5234 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5235 const UnresolvedMemberExpr *const UME, Sema &S) { 5236 5237 const auto GetFunctionLevelDCIfCXXClass = 5238 [](Sema &S) -> const CXXRecordDecl * { 5239 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5240 if (!DC || !DC->getParent()) 5241 return nullptr; 5242 5243 // If the call to some member function was made from within a member 5244 // function body 'M' return return 'M's parent. 5245 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5246 return MD->getParent()->getCanonicalDecl(); 5247 // else the call was made from within a default member initializer of a 5248 // class, so return the class. 5249 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5250 return RD->getCanonicalDecl(); 5251 return nullptr; 5252 }; 5253 // If our DeclContext is neither a member function nor a class (in the 5254 // case of a lambda in a default member initializer), we can't have an 5255 // enclosing 'this'. 5256 5257 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5258 if (!CurParentClass) 5259 return false; 5260 5261 // The naming class for implicit member functions call is the class in which 5262 // name lookup starts. 5263 const CXXRecordDecl *const NamingClass = 5264 UME->getNamingClass()->getCanonicalDecl(); 5265 assert(NamingClass && "Must have naming class even for implicit access"); 5266 5267 // If the unresolved member functions were found in a 'naming class' that is 5268 // related (either the same or derived from) to the class that contains the 5269 // member function that itself contained the implicit member access. 5270 5271 return CurParentClass == NamingClass || 5272 CurParentClass->isDerivedFrom(NamingClass); 5273 } 5274 5275 static void 5276 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5277 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5278 5279 if (!UME) 5280 return; 5281 5282 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5283 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5284 // already been captured, or if this is an implicit member function call (if 5285 // it isn't, an attempt to capture 'this' should already have been made). 5286 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5287 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5288 return; 5289 5290 // Check if the naming class in which the unresolved members were found is 5291 // related (same as or is a base of) to the enclosing class. 5292 5293 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5294 return; 5295 5296 5297 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5298 // If the enclosing function is not dependent, then this lambda is 5299 // capture ready, so if we can capture this, do so. 5300 if (!EnclosingFunctionCtx->isDependentContext()) { 5301 // If the current lambda and all enclosing lambdas can capture 'this' - 5302 // then go ahead and capture 'this' (since our unresolved overload set 5303 // contains at least one non-static member function). 5304 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5305 S.CheckCXXThisCapture(CallLoc); 5306 } else if (S.CurContext->isDependentContext()) { 5307 // ... since this is an implicit member reference, that might potentially 5308 // involve a 'this' capture, mark 'this' for potential capture in 5309 // enclosing lambdas. 5310 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5311 CurLSI->addPotentialThisCapture(CallLoc); 5312 } 5313 } 5314 5315 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5316 /// This provides the location of the left/right parens and a list of comma 5317 /// locations. 5318 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5319 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5320 Expr *ExecConfig, bool IsExecConfig) { 5321 // Since this might be a postfix expression, get rid of ParenListExprs. 5322 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5323 if (Result.isInvalid()) return ExprError(); 5324 Fn = Result.get(); 5325 5326 if (checkArgsForPlaceholders(*this, ArgExprs)) 5327 return ExprError(); 5328 5329 if (getLangOpts().CPlusPlus) { 5330 // If this is a pseudo-destructor expression, build the call immediately. 5331 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5332 if (!ArgExprs.empty()) { 5333 // Pseudo-destructor calls should not have any arguments. 5334 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5335 << FixItHint::CreateRemoval( 5336 SourceRange(ArgExprs.front()->getBeginLoc(), 5337 ArgExprs.back()->getEndLoc())); 5338 } 5339 5340 return new (Context) 5341 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5342 } 5343 if (Fn->getType() == Context.PseudoObjectTy) { 5344 ExprResult result = CheckPlaceholderExpr(Fn); 5345 if (result.isInvalid()) return ExprError(); 5346 Fn = result.get(); 5347 } 5348 5349 // Determine whether this is a dependent call inside a C++ template, 5350 // in which case we won't do any semantic analysis now. 5351 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5352 if (ExecConfig) { 5353 return new (Context) CUDAKernelCallExpr( 5354 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5355 Context.DependentTy, VK_RValue, RParenLoc); 5356 } else { 5357 5358 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5359 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5360 Fn->getBeginLoc()); 5361 5362 return new (Context) CallExpr( 5363 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5364 } 5365 } 5366 5367 // Determine whether this is a call to an object (C++ [over.call.object]). 5368 if (Fn->getType()->isRecordType()) 5369 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5370 RParenLoc); 5371 5372 if (Fn->getType() == Context.UnknownAnyTy) { 5373 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5374 if (result.isInvalid()) return ExprError(); 5375 Fn = result.get(); 5376 } 5377 5378 if (Fn->getType() == Context.BoundMemberTy) { 5379 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5380 RParenLoc); 5381 } 5382 } 5383 5384 // Check for overloaded calls. This can happen even in C due to extensions. 5385 if (Fn->getType() == Context.OverloadTy) { 5386 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5387 5388 // We aren't supposed to apply this logic if there's an '&' involved. 5389 if (!find.HasFormOfMemberPointer) { 5390 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5391 return new (Context) CallExpr( 5392 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5393 OverloadExpr *ovl = find.Expression; 5394 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5395 return BuildOverloadedCallExpr( 5396 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5397 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5398 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5399 RParenLoc); 5400 } 5401 } 5402 5403 // If we're directly calling a function, get the appropriate declaration. 5404 if (Fn->getType() == Context.UnknownAnyTy) { 5405 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5406 if (result.isInvalid()) return ExprError(); 5407 Fn = result.get(); 5408 } 5409 5410 Expr *NakedFn = Fn->IgnoreParens(); 5411 5412 bool CallingNDeclIndirectly = false; 5413 NamedDecl *NDecl = nullptr; 5414 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5415 if (UnOp->getOpcode() == UO_AddrOf) { 5416 CallingNDeclIndirectly = true; 5417 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5418 } 5419 } 5420 5421 if (isa<DeclRefExpr>(NakedFn)) { 5422 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5423 5424 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5425 if (FDecl && FDecl->getBuiltinID()) { 5426 // Rewrite the function decl for this builtin by replacing parameters 5427 // with no explicit address space with the address space of the arguments 5428 // in ArgExprs. 5429 if ((FDecl = 5430 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5431 NDecl = FDecl; 5432 Fn = DeclRefExpr::Create( 5433 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5434 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5435 } 5436 } 5437 } else if (isa<MemberExpr>(NakedFn)) 5438 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5439 5440 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5441 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5442 FD, /*Complain=*/true, Fn->getBeginLoc())) 5443 return ExprError(); 5444 5445 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5446 return ExprError(); 5447 5448 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5449 } 5450 5451 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5452 ExecConfig, IsExecConfig); 5453 } 5454 5455 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5456 /// 5457 /// __builtin_astype( value, dst type ) 5458 /// 5459 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5460 SourceLocation BuiltinLoc, 5461 SourceLocation RParenLoc) { 5462 ExprValueKind VK = VK_RValue; 5463 ExprObjectKind OK = OK_Ordinary; 5464 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5465 QualType SrcTy = E->getType(); 5466 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5467 return ExprError(Diag(BuiltinLoc, 5468 diag::err_invalid_astype_of_different_size) 5469 << DstTy 5470 << SrcTy 5471 << E->getSourceRange()); 5472 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5473 } 5474 5475 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5476 /// provided arguments. 5477 /// 5478 /// __builtin_convertvector( value, dst type ) 5479 /// 5480 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5481 SourceLocation BuiltinLoc, 5482 SourceLocation RParenLoc) { 5483 TypeSourceInfo *TInfo; 5484 GetTypeFromParser(ParsedDestTy, &TInfo); 5485 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5486 } 5487 5488 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5489 /// i.e. an expression not of \p OverloadTy. The expression should 5490 /// unary-convert to an expression of function-pointer or 5491 /// block-pointer type. 5492 /// 5493 /// \param NDecl the declaration being called, if available 5494 ExprResult 5495 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5496 SourceLocation LParenLoc, 5497 ArrayRef<Expr *> Args, 5498 SourceLocation RParenLoc, 5499 Expr *Config, bool IsExecConfig) { 5500 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5501 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5502 5503 // Functions with 'interrupt' attribute cannot be called directly. 5504 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5505 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5506 return ExprError(); 5507 } 5508 5509 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5510 // so there's some risk when calling out to non-interrupt handler functions 5511 // that the callee might not preserve them. This is easy to diagnose here, 5512 // but can be very challenging to debug. 5513 if (auto *Caller = getCurFunctionDecl()) 5514 if (Caller->hasAttr<ARMInterruptAttr>()) { 5515 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5516 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5517 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5518 } 5519 5520 // Promote the function operand. 5521 // We special-case function promotion here because we only allow promoting 5522 // builtin functions to function pointers in the callee of a call. 5523 ExprResult Result; 5524 if (BuiltinID && 5525 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5526 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5527 CK_BuiltinFnToFnPtr).get(); 5528 } else { 5529 Result = CallExprUnaryConversions(Fn); 5530 } 5531 if (Result.isInvalid()) 5532 return ExprError(); 5533 Fn = Result.get(); 5534 5535 // Make the call expr early, before semantic checks. This guarantees cleanup 5536 // of arguments and function on error. 5537 CallExpr *TheCall; 5538 if (Config) 5539 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5540 cast<CallExpr>(Config), Args, 5541 Context.BoolTy, VK_RValue, 5542 RParenLoc); 5543 else 5544 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5545 VK_RValue, RParenLoc); 5546 5547 if (!getLangOpts().CPlusPlus) { 5548 // C cannot always handle TypoExpr nodes in builtin calls and direct 5549 // function calls as their argument checking don't necessarily handle 5550 // dependent types properly, so make sure any TypoExprs have been 5551 // dealt with. 5552 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5553 if (!Result.isUsable()) return ExprError(); 5554 TheCall = dyn_cast<CallExpr>(Result.get()); 5555 if (!TheCall) return Result; 5556 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5557 } 5558 5559 // Bail out early if calling a builtin with custom typechecking. 5560 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5561 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5562 5563 retry: 5564 const FunctionType *FuncT; 5565 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5566 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5567 // have type pointer to function". 5568 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5569 if (!FuncT) 5570 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5571 << Fn->getType() << Fn->getSourceRange()); 5572 } else if (const BlockPointerType *BPT = 5573 Fn->getType()->getAs<BlockPointerType>()) { 5574 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5575 } else { 5576 // Handle calls to expressions of unknown-any type. 5577 if (Fn->getType() == Context.UnknownAnyTy) { 5578 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5579 if (rewrite.isInvalid()) return ExprError(); 5580 Fn = rewrite.get(); 5581 TheCall->setCallee(Fn); 5582 goto retry; 5583 } 5584 5585 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5586 << Fn->getType() << Fn->getSourceRange()); 5587 } 5588 5589 if (getLangOpts().CUDA) { 5590 if (Config) { 5591 // CUDA: Kernel calls must be to global functions 5592 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5593 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5594 << FDecl << Fn->getSourceRange()); 5595 5596 // CUDA: Kernel function must have 'void' return type 5597 if (!FuncT->getReturnType()->isVoidType()) 5598 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5599 << Fn->getType() << Fn->getSourceRange()); 5600 } else { 5601 // CUDA: Calls to global functions must be configured 5602 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5603 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5604 << FDecl << Fn->getSourceRange()); 5605 } 5606 } 5607 5608 // Check for a valid return type 5609 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5610 FDecl)) 5611 return ExprError(); 5612 5613 // We know the result type of the call, set it. 5614 TheCall->setType(FuncT->getCallResultType(Context)); 5615 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5616 5617 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5618 if (Proto) { 5619 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5620 IsExecConfig)) 5621 return ExprError(); 5622 } else { 5623 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5624 5625 if (FDecl) { 5626 // Check if we have too few/too many template arguments, based 5627 // on our knowledge of the function definition. 5628 const FunctionDecl *Def = nullptr; 5629 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5630 Proto = Def->getType()->getAs<FunctionProtoType>(); 5631 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5632 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5633 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5634 } 5635 5636 // If the function we're calling isn't a function prototype, but we have 5637 // a function prototype from a prior declaratiom, use that prototype. 5638 if (!FDecl->hasPrototype()) 5639 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5640 } 5641 5642 // Promote the arguments (C99 6.5.2.2p6). 5643 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5644 Expr *Arg = Args[i]; 5645 5646 if (Proto && i < Proto->getNumParams()) { 5647 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5648 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5649 ExprResult ArgE = 5650 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5651 if (ArgE.isInvalid()) 5652 return true; 5653 5654 Arg = ArgE.getAs<Expr>(); 5655 5656 } else { 5657 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5658 5659 if (ArgE.isInvalid()) 5660 return true; 5661 5662 Arg = ArgE.getAs<Expr>(); 5663 } 5664 5665 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5666 diag::err_call_incomplete_argument, Arg)) 5667 return ExprError(); 5668 5669 TheCall->setArg(i, Arg); 5670 } 5671 } 5672 5673 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5674 if (!Method->isStatic()) 5675 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5676 << Fn->getSourceRange()); 5677 5678 // Check for sentinels 5679 if (NDecl) 5680 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5681 5682 // Do special checking on direct calls to functions. 5683 if (FDecl) { 5684 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5685 return ExprError(); 5686 5687 if (BuiltinID) 5688 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5689 } else if (NDecl) { 5690 if (CheckPointerCall(NDecl, TheCall, Proto)) 5691 return ExprError(); 5692 } else { 5693 if (CheckOtherCall(TheCall, Proto)) 5694 return ExprError(); 5695 } 5696 5697 return MaybeBindToTemporary(TheCall); 5698 } 5699 5700 ExprResult 5701 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5702 SourceLocation RParenLoc, Expr *InitExpr) { 5703 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5704 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5705 5706 TypeSourceInfo *TInfo; 5707 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5708 if (!TInfo) 5709 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5710 5711 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5712 } 5713 5714 ExprResult 5715 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5716 SourceLocation RParenLoc, Expr *LiteralExpr) { 5717 QualType literalType = TInfo->getType(); 5718 5719 if (literalType->isArrayType()) { 5720 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5721 diag::err_illegal_decl_array_incomplete_type, 5722 SourceRange(LParenLoc, 5723 LiteralExpr->getSourceRange().getEnd()))) 5724 return ExprError(); 5725 if (literalType->isVariableArrayType()) 5726 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5727 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5728 } else if (!literalType->isDependentType() && 5729 RequireCompleteType(LParenLoc, literalType, 5730 diag::err_typecheck_decl_incomplete_type, 5731 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5732 return ExprError(); 5733 5734 InitializedEntity Entity 5735 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5736 InitializationKind Kind 5737 = InitializationKind::CreateCStyleCast(LParenLoc, 5738 SourceRange(LParenLoc, RParenLoc), 5739 /*InitList=*/true); 5740 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5741 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5742 &literalType); 5743 if (Result.isInvalid()) 5744 return ExprError(); 5745 LiteralExpr = Result.get(); 5746 5747 bool isFileScope = !CurContext->isFunctionOrMethod(); 5748 if (isFileScope) { 5749 if (!LiteralExpr->isTypeDependent() && 5750 !LiteralExpr->isValueDependent() && 5751 !literalType->isDependentType()) // C99 6.5.2.5p3 5752 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5753 return ExprError(); 5754 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5755 literalType.getAddressSpace() != LangAS::Default) { 5756 // Embedded-C extensions to C99 6.5.2.5: 5757 // "If the compound literal occurs inside the body of a function, the 5758 // type name shall not be qualified by an address-space qualifier." 5759 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5760 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5761 return ExprError(); 5762 } 5763 5764 // In C, compound literals are l-values for some reason. 5765 // For GCC compatibility, in C++, file-scope array compound literals with 5766 // constant initializers are also l-values, and compound literals are 5767 // otherwise prvalues. 5768 // 5769 // (GCC also treats C++ list-initialized file-scope array prvalues with 5770 // constant initializers as l-values, but that's non-conforming, so we don't 5771 // follow it there.) 5772 // 5773 // FIXME: It would be better to handle the lvalue cases as materializing and 5774 // lifetime-extending a temporary object, but our materialized temporaries 5775 // representation only supports lifetime extension from a variable, not "out 5776 // of thin air". 5777 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5778 // is bound to the result of applying array-to-pointer decay to the compound 5779 // literal. 5780 // FIXME: GCC supports compound literals of reference type, which should 5781 // obviously have a value kind derived from the kind of reference involved. 5782 ExprValueKind VK = 5783 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5784 ? VK_RValue 5785 : VK_LValue; 5786 5787 return MaybeBindToTemporary( 5788 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5789 VK, LiteralExpr, isFileScope)); 5790 } 5791 5792 ExprResult 5793 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5794 SourceLocation RBraceLoc) { 5795 // Immediately handle non-overload placeholders. Overloads can be 5796 // resolved contextually, but everything else here can't. 5797 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5798 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5799 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5800 5801 // Ignore failures; dropping the entire initializer list because 5802 // of one failure would be terrible for indexing/etc. 5803 if (result.isInvalid()) continue; 5804 5805 InitArgList[I] = result.get(); 5806 } 5807 } 5808 5809 // Semantic analysis for initializers is done by ActOnDeclarator() and 5810 // CheckInitializer() - it requires knowledge of the object being initialized. 5811 5812 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5813 RBraceLoc); 5814 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5815 return E; 5816 } 5817 5818 /// Do an explicit extend of the given block pointer if we're in ARC. 5819 void Sema::maybeExtendBlockObject(ExprResult &E) { 5820 assert(E.get()->getType()->isBlockPointerType()); 5821 assert(E.get()->isRValue()); 5822 5823 // Only do this in an r-value context. 5824 if (!getLangOpts().ObjCAutoRefCount) return; 5825 5826 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5827 CK_ARCExtendBlockObject, E.get(), 5828 /*base path*/ nullptr, VK_RValue); 5829 Cleanup.setExprNeedsCleanups(true); 5830 } 5831 5832 /// Prepare a conversion of the given expression to an ObjC object 5833 /// pointer type. 5834 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5835 QualType type = E.get()->getType(); 5836 if (type->isObjCObjectPointerType()) { 5837 return CK_BitCast; 5838 } else if (type->isBlockPointerType()) { 5839 maybeExtendBlockObject(E); 5840 return CK_BlockPointerToObjCPointerCast; 5841 } else { 5842 assert(type->isPointerType()); 5843 return CK_CPointerToObjCPointerCast; 5844 } 5845 } 5846 5847 /// Prepares for a scalar cast, performing all the necessary stages 5848 /// except the final cast and returning the kind required. 5849 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5850 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5851 // Also, callers should have filtered out the invalid cases with 5852 // pointers. Everything else should be possible. 5853 5854 QualType SrcTy = Src.get()->getType(); 5855 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5856 return CK_NoOp; 5857 5858 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5859 case Type::STK_MemberPointer: 5860 llvm_unreachable("member pointer type in C"); 5861 5862 case Type::STK_CPointer: 5863 case Type::STK_BlockPointer: 5864 case Type::STK_ObjCObjectPointer: 5865 switch (DestTy->getScalarTypeKind()) { 5866 case Type::STK_CPointer: { 5867 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5868 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5869 if (SrcAS != DestAS) 5870 return CK_AddressSpaceConversion; 5871 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 5872 return CK_NoOp; 5873 return CK_BitCast; 5874 } 5875 case Type::STK_BlockPointer: 5876 return (SrcKind == Type::STK_BlockPointer 5877 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5878 case Type::STK_ObjCObjectPointer: 5879 if (SrcKind == Type::STK_ObjCObjectPointer) 5880 return CK_BitCast; 5881 if (SrcKind == Type::STK_CPointer) 5882 return CK_CPointerToObjCPointerCast; 5883 maybeExtendBlockObject(Src); 5884 return CK_BlockPointerToObjCPointerCast; 5885 case Type::STK_Bool: 5886 return CK_PointerToBoolean; 5887 case Type::STK_Integral: 5888 return CK_PointerToIntegral; 5889 case Type::STK_Floating: 5890 case Type::STK_FloatingComplex: 5891 case Type::STK_IntegralComplex: 5892 case Type::STK_MemberPointer: 5893 case Type::STK_FixedPoint: 5894 llvm_unreachable("illegal cast from pointer"); 5895 } 5896 llvm_unreachable("Should have returned before this"); 5897 5898 case Type::STK_FixedPoint: 5899 switch (DestTy->getScalarTypeKind()) { 5900 case Type::STK_FixedPoint: 5901 return CK_FixedPointCast; 5902 case Type::STK_Bool: 5903 return CK_FixedPointToBoolean; 5904 case Type::STK_Integral: 5905 case Type::STK_Floating: 5906 case Type::STK_IntegralComplex: 5907 case Type::STK_FloatingComplex: 5908 Diag(Src.get()->getExprLoc(), 5909 diag::err_unimplemented_conversion_with_fixed_point_type) 5910 << DestTy; 5911 return CK_IntegralCast; 5912 case Type::STK_CPointer: 5913 case Type::STK_ObjCObjectPointer: 5914 case Type::STK_BlockPointer: 5915 case Type::STK_MemberPointer: 5916 llvm_unreachable("illegal cast to pointer type"); 5917 } 5918 llvm_unreachable("Should have returned before this"); 5919 5920 case Type::STK_Bool: // casting from bool is like casting from an integer 5921 case Type::STK_Integral: 5922 switch (DestTy->getScalarTypeKind()) { 5923 case Type::STK_CPointer: 5924 case Type::STK_ObjCObjectPointer: 5925 case Type::STK_BlockPointer: 5926 if (Src.get()->isNullPointerConstant(Context, 5927 Expr::NPC_ValueDependentIsNull)) 5928 return CK_NullToPointer; 5929 return CK_IntegralToPointer; 5930 case Type::STK_Bool: 5931 return CK_IntegralToBoolean; 5932 case Type::STK_Integral: 5933 return CK_IntegralCast; 5934 case Type::STK_Floating: 5935 return CK_IntegralToFloating; 5936 case Type::STK_IntegralComplex: 5937 Src = ImpCastExprToType(Src.get(), 5938 DestTy->castAs<ComplexType>()->getElementType(), 5939 CK_IntegralCast); 5940 return CK_IntegralRealToComplex; 5941 case Type::STK_FloatingComplex: 5942 Src = ImpCastExprToType(Src.get(), 5943 DestTy->castAs<ComplexType>()->getElementType(), 5944 CK_IntegralToFloating); 5945 return CK_FloatingRealToComplex; 5946 case Type::STK_MemberPointer: 5947 llvm_unreachable("member pointer type in C"); 5948 case Type::STK_FixedPoint: 5949 Diag(Src.get()->getExprLoc(), 5950 diag::err_unimplemented_conversion_with_fixed_point_type) 5951 << SrcTy; 5952 return CK_IntegralCast; 5953 } 5954 llvm_unreachable("Should have returned before this"); 5955 5956 case Type::STK_Floating: 5957 switch (DestTy->getScalarTypeKind()) { 5958 case Type::STK_Floating: 5959 return CK_FloatingCast; 5960 case Type::STK_Bool: 5961 return CK_FloatingToBoolean; 5962 case Type::STK_Integral: 5963 return CK_FloatingToIntegral; 5964 case Type::STK_FloatingComplex: 5965 Src = ImpCastExprToType(Src.get(), 5966 DestTy->castAs<ComplexType>()->getElementType(), 5967 CK_FloatingCast); 5968 return CK_FloatingRealToComplex; 5969 case Type::STK_IntegralComplex: 5970 Src = ImpCastExprToType(Src.get(), 5971 DestTy->castAs<ComplexType>()->getElementType(), 5972 CK_FloatingToIntegral); 5973 return CK_IntegralRealToComplex; 5974 case Type::STK_CPointer: 5975 case Type::STK_ObjCObjectPointer: 5976 case Type::STK_BlockPointer: 5977 llvm_unreachable("valid float->pointer cast?"); 5978 case Type::STK_MemberPointer: 5979 llvm_unreachable("member pointer type in C"); 5980 case Type::STK_FixedPoint: 5981 Diag(Src.get()->getExprLoc(), 5982 diag::err_unimplemented_conversion_with_fixed_point_type) 5983 << SrcTy; 5984 return CK_IntegralCast; 5985 } 5986 llvm_unreachable("Should have returned before this"); 5987 5988 case Type::STK_FloatingComplex: 5989 switch (DestTy->getScalarTypeKind()) { 5990 case Type::STK_FloatingComplex: 5991 return CK_FloatingComplexCast; 5992 case Type::STK_IntegralComplex: 5993 return CK_FloatingComplexToIntegralComplex; 5994 case Type::STK_Floating: { 5995 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5996 if (Context.hasSameType(ET, DestTy)) 5997 return CK_FloatingComplexToReal; 5998 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5999 return CK_FloatingCast; 6000 } 6001 case Type::STK_Bool: 6002 return CK_FloatingComplexToBoolean; 6003 case Type::STK_Integral: 6004 Src = ImpCastExprToType(Src.get(), 6005 SrcTy->castAs<ComplexType>()->getElementType(), 6006 CK_FloatingComplexToReal); 6007 return CK_FloatingToIntegral; 6008 case Type::STK_CPointer: 6009 case Type::STK_ObjCObjectPointer: 6010 case Type::STK_BlockPointer: 6011 llvm_unreachable("valid complex float->pointer cast?"); 6012 case Type::STK_MemberPointer: 6013 llvm_unreachable("member pointer type in C"); 6014 case Type::STK_FixedPoint: 6015 Diag(Src.get()->getExprLoc(), 6016 diag::err_unimplemented_conversion_with_fixed_point_type) 6017 << SrcTy; 6018 return CK_IntegralCast; 6019 } 6020 llvm_unreachable("Should have returned before this"); 6021 6022 case Type::STK_IntegralComplex: 6023 switch (DestTy->getScalarTypeKind()) { 6024 case Type::STK_FloatingComplex: 6025 return CK_IntegralComplexToFloatingComplex; 6026 case Type::STK_IntegralComplex: 6027 return CK_IntegralComplexCast; 6028 case Type::STK_Integral: { 6029 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6030 if (Context.hasSameType(ET, DestTy)) 6031 return CK_IntegralComplexToReal; 6032 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6033 return CK_IntegralCast; 6034 } 6035 case Type::STK_Bool: 6036 return CK_IntegralComplexToBoolean; 6037 case Type::STK_Floating: 6038 Src = ImpCastExprToType(Src.get(), 6039 SrcTy->castAs<ComplexType>()->getElementType(), 6040 CK_IntegralComplexToReal); 6041 return CK_IntegralToFloating; 6042 case Type::STK_CPointer: 6043 case Type::STK_ObjCObjectPointer: 6044 case Type::STK_BlockPointer: 6045 llvm_unreachable("valid complex int->pointer cast?"); 6046 case Type::STK_MemberPointer: 6047 llvm_unreachable("member pointer type in C"); 6048 case Type::STK_FixedPoint: 6049 Diag(Src.get()->getExprLoc(), 6050 diag::err_unimplemented_conversion_with_fixed_point_type) 6051 << SrcTy; 6052 return CK_IntegralCast; 6053 } 6054 llvm_unreachable("Should have returned before this"); 6055 } 6056 6057 llvm_unreachable("Unhandled scalar cast"); 6058 } 6059 6060 static bool breakDownVectorType(QualType type, uint64_t &len, 6061 QualType &eltType) { 6062 // Vectors are simple. 6063 if (const VectorType *vecType = type->getAs<VectorType>()) { 6064 len = vecType->getNumElements(); 6065 eltType = vecType->getElementType(); 6066 assert(eltType->isScalarType()); 6067 return true; 6068 } 6069 6070 // We allow lax conversion to and from non-vector types, but only if 6071 // they're real types (i.e. non-complex, non-pointer scalar types). 6072 if (!type->isRealType()) return false; 6073 6074 len = 1; 6075 eltType = type; 6076 return true; 6077 } 6078 6079 /// Are the two types lax-compatible vector types? That is, given 6080 /// that one of them is a vector, do they have equal storage sizes, 6081 /// where the storage size is the number of elements times the element 6082 /// size? 6083 /// 6084 /// This will also return false if either of the types is neither a 6085 /// vector nor a real type. 6086 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6087 assert(destTy->isVectorType() || srcTy->isVectorType()); 6088 6089 // Disallow lax conversions between scalars and ExtVectors (these 6090 // conversions are allowed for other vector types because common headers 6091 // depend on them). Most scalar OP ExtVector cases are handled by the 6092 // splat path anyway, which does what we want (convert, not bitcast). 6093 // What this rules out for ExtVectors is crazy things like char4*float. 6094 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6095 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6096 6097 uint64_t srcLen, destLen; 6098 QualType srcEltTy, destEltTy; 6099 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6100 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6101 6102 // ASTContext::getTypeSize will return the size rounded up to a 6103 // power of 2, so instead of using that, we need to use the raw 6104 // element size multiplied by the element count. 6105 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6106 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6107 6108 return (srcLen * srcEltSize == destLen * destEltSize); 6109 } 6110 6111 /// Is this a legal conversion between two types, one of which is 6112 /// known to be a vector type? 6113 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6114 assert(destTy->isVectorType() || srcTy->isVectorType()); 6115 6116 if (!Context.getLangOpts().LaxVectorConversions) 6117 return false; 6118 return areLaxCompatibleVectorTypes(srcTy, destTy); 6119 } 6120 6121 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6122 CastKind &Kind) { 6123 assert(VectorTy->isVectorType() && "Not a vector type!"); 6124 6125 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6126 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6127 return Diag(R.getBegin(), 6128 Ty->isVectorType() ? 6129 diag::err_invalid_conversion_between_vectors : 6130 diag::err_invalid_conversion_between_vector_and_integer) 6131 << VectorTy << Ty << R; 6132 } else 6133 return Diag(R.getBegin(), 6134 diag::err_invalid_conversion_between_vector_and_scalar) 6135 << VectorTy << Ty << R; 6136 6137 Kind = CK_BitCast; 6138 return false; 6139 } 6140 6141 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6142 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6143 6144 if (DestElemTy == SplattedExpr->getType()) 6145 return SplattedExpr; 6146 6147 assert(DestElemTy->isFloatingType() || 6148 DestElemTy->isIntegralOrEnumerationType()); 6149 6150 CastKind CK; 6151 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6152 // OpenCL requires that we convert `true` boolean expressions to -1, but 6153 // only when splatting vectors. 6154 if (DestElemTy->isFloatingType()) { 6155 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6156 // in two steps: boolean to signed integral, then to floating. 6157 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6158 CK_BooleanToSignedIntegral); 6159 SplattedExpr = CastExprRes.get(); 6160 CK = CK_IntegralToFloating; 6161 } else { 6162 CK = CK_BooleanToSignedIntegral; 6163 } 6164 } else { 6165 ExprResult CastExprRes = SplattedExpr; 6166 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6167 if (CastExprRes.isInvalid()) 6168 return ExprError(); 6169 SplattedExpr = CastExprRes.get(); 6170 } 6171 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6172 } 6173 6174 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6175 Expr *CastExpr, CastKind &Kind) { 6176 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6177 6178 QualType SrcTy = CastExpr->getType(); 6179 6180 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6181 // an ExtVectorType. 6182 // In OpenCL, casts between vectors of different types are not allowed. 6183 // (See OpenCL 6.2). 6184 if (SrcTy->isVectorType()) { 6185 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6186 (getLangOpts().OpenCL && 6187 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6188 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6189 << DestTy << SrcTy << R; 6190 return ExprError(); 6191 } 6192 Kind = CK_BitCast; 6193 return CastExpr; 6194 } 6195 6196 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6197 // conversion will take place first from scalar to elt type, and then 6198 // splat from elt type to vector. 6199 if (SrcTy->isPointerType()) 6200 return Diag(R.getBegin(), 6201 diag::err_invalid_conversion_between_vector_and_scalar) 6202 << DestTy << SrcTy << R; 6203 6204 Kind = CK_VectorSplat; 6205 return prepareVectorSplat(DestTy, CastExpr); 6206 } 6207 6208 ExprResult 6209 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6210 Declarator &D, ParsedType &Ty, 6211 SourceLocation RParenLoc, Expr *CastExpr) { 6212 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6213 "ActOnCastExpr(): missing type or expr"); 6214 6215 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6216 if (D.isInvalidType()) 6217 return ExprError(); 6218 6219 if (getLangOpts().CPlusPlus) { 6220 // Check that there are no default arguments (C++ only). 6221 CheckExtraCXXDefaultArguments(D); 6222 } else { 6223 // Make sure any TypoExprs have been dealt with. 6224 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6225 if (!Res.isUsable()) 6226 return ExprError(); 6227 CastExpr = Res.get(); 6228 } 6229 6230 checkUnusedDeclAttributes(D); 6231 6232 QualType castType = castTInfo->getType(); 6233 Ty = CreateParsedType(castType, castTInfo); 6234 6235 bool isVectorLiteral = false; 6236 6237 // Check for an altivec or OpenCL literal, 6238 // i.e. all the elements are integer constants. 6239 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6240 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6241 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6242 && castType->isVectorType() && (PE || PLE)) { 6243 if (PLE && PLE->getNumExprs() == 0) { 6244 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6245 return ExprError(); 6246 } 6247 if (PE || PLE->getNumExprs() == 1) { 6248 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6249 if (!E->getType()->isVectorType()) 6250 isVectorLiteral = true; 6251 } 6252 else 6253 isVectorLiteral = true; 6254 } 6255 6256 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6257 // then handle it as such. 6258 if (isVectorLiteral) 6259 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6260 6261 // If the Expr being casted is a ParenListExpr, handle it specially. 6262 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6263 // sequence of BinOp comma operators. 6264 if (isa<ParenListExpr>(CastExpr)) { 6265 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6266 if (Result.isInvalid()) return ExprError(); 6267 CastExpr = Result.get(); 6268 } 6269 6270 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6271 !getSourceManager().isInSystemMacro(LParenLoc)) 6272 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6273 6274 CheckTollFreeBridgeCast(castType, CastExpr); 6275 6276 CheckObjCBridgeRelatedCast(castType, CastExpr); 6277 6278 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6279 6280 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6281 } 6282 6283 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6284 SourceLocation RParenLoc, Expr *E, 6285 TypeSourceInfo *TInfo) { 6286 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6287 "Expected paren or paren list expression"); 6288 6289 Expr **exprs; 6290 unsigned numExprs; 6291 Expr *subExpr; 6292 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6293 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6294 LiteralLParenLoc = PE->getLParenLoc(); 6295 LiteralRParenLoc = PE->getRParenLoc(); 6296 exprs = PE->getExprs(); 6297 numExprs = PE->getNumExprs(); 6298 } else { // isa<ParenExpr> by assertion at function entrance 6299 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6300 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6301 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6302 exprs = &subExpr; 6303 numExprs = 1; 6304 } 6305 6306 QualType Ty = TInfo->getType(); 6307 assert(Ty->isVectorType() && "Expected vector type"); 6308 6309 SmallVector<Expr *, 8> initExprs; 6310 const VectorType *VTy = Ty->getAs<VectorType>(); 6311 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6312 6313 // '(...)' form of vector initialization in AltiVec: the number of 6314 // initializers must be one or must match the size of the vector. 6315 // If a single value is specified in the initializer then it will be 6316 // replicated to all the components of the vector 6317 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6318 // The number of initializers must be one or must match the size of the 6319 // vector. If a single value is specified in the initializer then it will 6320 // be replicated to all the components of the vector 6321 if (numExprs == 1) { 6322 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6323 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6324 if (Literal.isInvalid()) 6325 return ExprError(); 6326 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6327 PrepareScalarCast(Literal, ElemTy)); 6328 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6329 } 6330 else if (numExprs < numElems) { 6331 Diag(E->getExprLoc(), 6332 diag::err_incorrect_number_of_vector_initializers); 6333 return ExprError(); 6334 } 6335 else 6336 initExprs.append(exprs, exprs + numExprs); 6337 } 6338 else { 6339 // For OpenCL, when the number of initializers is a single value, 6340 // it will be replicated to all components of the vector. 6341 if (getLangOpts().OpenCL && 6342 VTy->getVectorKind() == VectorType::GenericVector && 6343 numExprs == 1) { 6344 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6345 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6346 if (Literal.isInvalid()) 6347 return ExprError(); 6348 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6349 PrepareScalarCast(Literal, ElemTy)); 6350 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6351 } 6352 6353 initExprs.append(exprs, exprs + numExprs); 6354 } 6355 // FIXME: This means that pretty-printing the final AST will produce curly 6356 // braces instead of the original commas. 6357 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6358 initExprs, LiteralRParenLoc); 6359 initE->setType(Ty); 6360 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6361 } 6362 6363 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6364 /// the ParenListExpr into a sequence of comma binary operators. 6365 ExprResult 6366 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6367 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6368 if (!E) 6369 return OrigExpr; 6370 6371 ExprResult Result(E->getExpr(0)); 6372 6373 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6374 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6375 E->getExpr(i)); 6376 6377 if (Result.isInvalid()) return ExprError(); 6378 6379 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6380 } 6381 6382 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6383 SourceLocation R, 6384 MultiExprArg Val) { 6385 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6386 return expr; 6387 } 6388 6389 /// Emit a specialized diagnostic when one expression is a null pointer 6390 /// constant and the other is not a pointer. Returns true if a diagnostic is 6391 /// emitted. 6392 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6393 SourceLocation QuestionLoc) { 6394 Expr *NullExpr = LHSExpr; 6395 Expr *NonPointerExpr = RHSExpr; 6396 Expr::NullPointerConstantKind NullKind = 6397 NullExpr->isNullPointerConstant(Context, 6398 Expr::NPC_ValueDependentIsNotNull); 6399 6400 if (NullKind == Expr::NPCK_NotNull) { 6401 NullExpr = RHSExpr; 6402 NonPointerExpr = LHSExpr; 6403 NullKind = 6404 NullExpr->isNullPointerConstant(Context, 6405 Expr::NPC_ValueDependentIsNotNull); 6406 } 6407 6408 if (NullKind == Expr::NPCK_NotNull) 6409 return false; 6410 6411 if (NullKind == Expr::NPCK_ZeroExpression) 6412 return false; 6413 6414 if (NullKind == Expr::NPCK_ZeroLiteral) { 6415 // In this case, check to make sure that we got here from a "NULL" 6416 // string in the source code. 6417 NullExpr = NullExpr->IgnoreParenImpCasts(); 6418 SourceLocation loc = NullExpr->getExprLoc(); 6419 if (!findMacroSpelling(loc, "NULL")) 6420 return false; 6421 } 6422 6423 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6424 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6425 << NonPointerExpr->getType() << DiagType 6426 << NonPointerExpr->getSourceRange(); 6427 return true; 6428 } 6429 6430 /// Return false if the condition expression is valid, true otherwise. 6431 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6432 QualType CondTy = Cond->getType(); 6433 6434 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6435 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6436 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6437 << CondTy << Cond->getSourceRange(); 6438 return true; 6439 } 6440 6441 // C99 6.5.15p2 6442 if (CondTy->isScalarType()) return false; 6443 6444 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6445 << CondTy << Cond->getSourceRange(); 6446 return true; 6447 } 6448 6449 /// Handle when one or both operands are void type. 6450 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6451 ExprResult &RHS) { 6452 Expr *LHSExpr = LHS.get(); 6453 Expr *RHSExpr = RHS.get(); 6454 6455 if (!LHSExpr->getType()->isVoidType()) 6456 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6457 << RHSExpr->getSourceRange(); 6458 if (!RHSExpr->getType()->isVoidType()) 6459 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6460 << LHSExpr->getSourceRange(); 6461 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6462 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6463 return S.Context.VoidTy; 6464 } 6465 6466 /// Return false if the NullExpr can be promoted to PointerTy, 6467 /// true otherwise. 6468 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6469 QualType PointerTy) { 6470 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6471 !NullExpr.get()->isNullPointerConstant(S.Context, 6472 Expr::NPC_ValueDependentIsNull)) 6473 return true; 6474 6475 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6476 return false; 6477 } 6478 6479 /// Checks compatibility between two pointers and return the resulting 6480 /// type. 6481 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6482 ExprResult &RHS, 6483 SourceLocation Loc) { 6484 QualType LHSTy = LHS.get()->getType(); 6485 QualType RHSTy = RHS.get()->getType(); 6486 6487 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6488 // Two identical pointers types are always compatible. 6489 return LHSTy; 6490 } 6491 6492 QualType lhptee, rhptee; 6493 6494 // Get the pointee types. 6495 bool IsBlockPointer = false; 6496 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6497 lhptee = LHSBTy->getPointeeType(); 6498 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6499 IsBlockPointer = true; 6500 } else { 6501 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6502 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6503 } 6504 6505 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6506 // differently qualified versions of compatible types, the result type is 6507 // a pointer to an appropriately qualified version of the composite 6508 // type. 6509 6510 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6511 // clause doesn't make sense for our extensions. E.g. address space 2 should 6512 // be incompatible with address space 3: they may live on different devices or 6513 // anything. 6514 Qualifiers lhQual = lhptee.getQualifiers(); 6515 Qualifiers rhQual = rhptee.getQualifiers(); 6516 6517 LangAS ResultAddrSpace = LangAS::Default; 6518 LangAS LAddrSpace = lhQual.getAddressSpace(); 6519 LangAS RAddrSpace = rhQual.getAddressSpace(); 6520 6521 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6522 // spaces is disallowed. 6523 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6524 ResultAddrSpace = LAddrSpace; 6525 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6526 ResultAddrSpace = RAddrSpace; 6527 else { 6528 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6529 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6530 << RHS.get()->getSourceRange(); 6531 return QualType(); 6532 } 6533 6534 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6535 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6536 lhQual.removeCVRQualifiers(); 6537 rhQual.removeCVRQualifiers(); 6538 6539 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6540 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6541 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6542 // qual types are compatible iff 6543 // * corresponded types are compatible 6544 // * CVR qualifiers are equal 6545 // * address spaces are equal 6546 // Thus for conditional operator we merge CVR and address space unqualified 6547 // pointees and if there is a composite type we return a pointer to it with 6548 // merged qualifiers. 6549 LHSCastKind = 6550 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6551 RHSCastKind = 6552 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6553 lhQual.removeAddressSpace(); 6554 rhQual.removeAddressSpace(); 6555 6556 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6557 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6558 6559 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6560 6561 if (CompositeTy.isNull()) { 6562 // In this situation, we assume void* type. No especially good 6563 // reason, but this is what gcc does, and we do have to pick 6564 // to get a consistent AST. 6565 QualType incompatTy; 6566 incompatTy = S.Context.getPointerType( 6567 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6568 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6569 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6570 6571 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6572 // for casts between types with incompatible address space qualifiers. 6573 // For the following code the compiler produces casts between global and 6574 // local address spaces of the corresponded innermost pointees: 6575 // local int *global *a; 6576 // global int *global *b; 6577 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6578 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6579 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6580 << RHS.get()->getSourceRange(); 6581 6582 return incompatTy; 6583 } 6584 6585 // The pointer types are compatible. 6586 // In case of OpenCL ResultTy should have the address space qualifier 6587 // which is a superset of address spaces of both the 2nd and the 3rd 6588 // operands of the conditional operator. 6589 QualType ResultTy = [&, ResultAddrSpace]() { 6590 if (S.getLangOpts().OpenCL) { 6591 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6592 CompositeQuals.setAddressSpace(ResultAddrSpace); 6593 return S.Context 6594 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6595 .withCVRQualifiers(MergedCVRQual); 6596 } 6597 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6598 }(); 6599 if (IsBlockPointer) 6600 ResultTy = S.Context.getBlockPointerType(ResultTy); 6601 else 6602 ResultTy = S.Context.getPointerType(ResultTy); 6603 6604 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6605 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6606 return ResultTy; 6607 } 6608 6609 /// Return the resulting type when the operands are both block pointers. 6610 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6611 ExprResult &LHS, 6612 ExprResult &RHS, 6613 SourceLocation Loc) { 6614 QualType LHSTy = LHS.get()->getType(); 6615 QualType RHSTy = RHS.get()->getType(); 6616 6617 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6618 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6619 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6620 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6621 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6622 return destType; 6623 } 6624 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6625 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6626 << RHS.get()->getSourceRange(); 6627 return QualType(); 6628 } 6629 6630 // We have 2 block pointer types. 6631 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6632 } 6633 6634 /// Return the resulting type when the operands are both pointers. 6635 static QualType 6636 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6637 ExprResult &RHS, 6638 SourceLocation Loc) { 6639 // get the pointer types 6640 QualType LHSTy = LHS.get()->getType(); 6641 QualType RHSTy = RHS.get()->getType(); 6642 6643 // get the "pointed to" types 6644 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6645 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6646 6647 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6648 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6649 // Figure out necessary qualifiers (C99 6.5.15p6) 6650 QualType destPointee 6651 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6652 QualType destType = S.Context.getPointerType(destPointee); 6653 // Add qualifiers if necessary. 6654 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6655 // Promote to void*. 6656 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6657 return destType; 6658 } 6659 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6660 QualType destPointee 6661 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6662 QualType destType = S.Context.getPointerType(destPointee); 6663 // Add qualifiers if necessary. 6664 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6665 // Promote to void*. 6666 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6667 return destType; 6668 } 6669 6670 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6671 } 6672 6673 /// Return false if the first expression is not an integer and the second 6674 /// expression is not a pointer, true otherwise. 6675 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6676 Expr* PointerExpr, SourceLocation Loc, 6677 bool IsIntFirstExpr) { 6678 if (!PointerExpr->getType()->isPointerType() || 6679 !Int.get()->getType()->isIntegerType()) 6680 return false; 6681 6682 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6683 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6684 6685 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6686 << Expr1->getType() << Expr2->getType() 6687 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6688 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6689 CK_IntegralToPointer); 6690 return true; 6691 } 6692 6693 /// Simple conversion between integer and floating point types. 6694 /// 6695 /// Used when handling the OpenCL conditional operator where the 6696 /// condition is a vector while the other operands are scalar. 6697 /// 6698 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6699 /// types are either integer or floating type. Between the two 6700 /// operands, the type with the higher rank is defined as the "result 6701 /// type". The other operand needs to be promoted to the same type. No 6702 /// other type promotion is allowed. We cannot use 6703 /// UsualArithmeticConversions() for this purpose, since it always 6704 /// promotes promotable types. 6705 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6706 ExprResult &RHS, 6707 SourceLocation QuestionLoc) { 6708 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6709 if (LHS.isInvalid()) 6710 return QualType(); 6711 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6712 if (RHS.isInvalid()) 6713 return QualType(); 6714 6715 // For conversion purposes, we ignore any qualifiers. 6716 // For example, "const float" and "float" are equivalent. 6717 QualType LHSType = 6718 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6719 QualType RHSType = 6720 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6721 6722 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6723 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6724 << LHSType << LHS.get()->getSourceRange(); 6725 return QualType(); 6726 } 6727 6728 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6729 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6730 << RHSType << RHS.get()->getSourceRange(); 6731 return QualType(); 6732 } 6733 6734 // If both types are identical, no conversion is needed. 6735 if (LHSType == RHSType) 6736 return LHSType; 6737 6738 // Now handle "real" floating types (i.e. float, double, long double). 6739 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6740 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6741 /*IsCompAssign = */ false); 6742 6743 // Finally, we have two differing integer types. 6744 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6745 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6746 } 6747 6748 /// Convert scalar operands to a vector that matches the 6749 /// condition in length. 6750 /// 6751 /// Used when handling the OpenCL conditional operator where the 6752 /// condition is a vector while the other operands are scalar. 6753 /// 6754 /// We first compute the "result type" for the scalar operands 6755 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6756 /// into a vector of that type where the length matches the condition 6757 /// vector type. s6.11.6 requires that the element types of the result 6758 /// and the condition must have the same number of bits. 6759 static QualType 6760 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6761 QualType CondTy, SourceLocation QuestionLoc) { 6762 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6763 if (ResTy.isNull()) return QualType(); 6764 6765 const VectorType *CV = CondTy->getAs<VectorType>(); 6766 assert(CV); 6767 6768 // Determine the vector result type 6769 unsigned NumElements = CV->getNumElements(); 6770 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6771 6772 // Ensure that all types have the same number of bits 6773 if (S.Context.getTypeSize(CV->getElementType()) 6774 != S.Context.getTypeSize(ResTy)) { 6775 // Since VectorTy is created internally, it does not pretty print 6776 // with an OpenCL name. Instead, we just print a description. 6777 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6778 SmallString<64> Str; 6779 llvm::raw_svector_ostream OS(Str); 6780 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6781 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6782 << CondTy << OS.str(); 6783 return QualType(); 6784 } 6785 6786 // Convert operands to the vector result type 6787 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6788 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6789 6790 return VectorTy; 6791 } 6792 6793 /// Return false if this is a valid OpenCL condition vector 6794 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6795 SourceLocation QuestionLoc) { 6796 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6797 // integral type. 6798 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6799 assert(CondTy); 6800 QualType EleTy = CondTy->getElementType(); 6801 if (EleTy->isIntegerType()) return false; 6802 6803 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6804 << Cond->getType() << Cond->getSourceRange(); 6805 return true; 6806 } 6807 6808 /// Return false if the vector condition type and the vector 6809 /// result type are compatible. 6810 /// 6811 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6812 /// number of elements, and their element types have the same number 6813 /// of bits. 6814 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6815 SourceLocation QuestionLoc) { 6816 const VectorType *CV = CondTy->getAs<VectorType>(); 6817 const VectorType *RV = VecResTy->getAs<VectorType>(); 6818 assert(CV && RV); 6819 6820 if (CV->getNumElements() != RV->getNumElements()) { 6821 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6822 << CondTy << VecResTy; 6823 return true; 6824 } 6825 6826 QualType CVE = CV->getElementType(); 6827 QualType RVE = RV->getElementType(); 6828 6829 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6830 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6831 << CondTy << VecResTy; 6832 return true; 6833 } 6834 6835 return false; 6836 } 6837 6838 /// Return the resulting type for the conditional operator in 6839 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6840 /// s6.3.i) when the condition is a vector type. 6841 static QualType 6842 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6843 ExprResult &LHS, ExprResult &RHS, 6844 SourceLocation QuestionLoc) { 6845 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6846 if (Cond.isInvalid()) 6847 return QualType(); 6848 QualType CondTy = Cond.get()->getType(); 6849 6850 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6851 return QualType(); 6852 6853 // If either operand is a vector then find the vector type of the 6854 // result as specified in OpenCL v1.1 s6.3.i. 6855 if (LHS.get()->getType()->isVectorType() || 6856 RHS.get()->getType()->isVectorType()) { 6857 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6858 /*isCompAssign*/false, 6859 /*AllowBothBool*/true, 6860 /*AllowBoolConversions*/false); 6861 if (VecResTy.isNull()) return QualType(); 6862 // The result type must match the condition type as specified in 6863 // OpenCL v1.1 s6.11.6. 6864 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6865 return QualType(); 6866 return VecResTy; 6867 } 6868 6869 // Both operands are scalar. 6870 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6871 } 6872 6873 /// Return true if the Expr is block type 6874 static bool checkBlockType(Sema &S, const Expr *E) { 6875 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6876 QualType Ty = CE->getCallee()->getType(); 6877 if (Ty->isBlockPointerType()) { 6878 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6879 return true; 6880 } 6881 } 6882 return false; 6883 } 6884 6885 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6886 /// In that case, LHS = cond. 6887 /// C99 6.5.15 6888 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6889 ExprResult &RHS, ExprValueKind &VK, 6890 ExprObjectKind &OK, 6891 SourceLocation QuestionLoc) { 6892 6893 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6894 if (!LHSResult.isUsable()) return QualType(); 6895 LHS = LHSResult; 6896 6897 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6898 if (!RHSResult.isUsable()) return QualType(); 6899 RHS = RHSResult; 6900 6901 // C++ is sufficiently different to merit its own checker. 6902 if (getLangOpts().CPlusPlus) 6903 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6904 6905 VK = VK_RValue; 6906 OK = OK_Ordinary; 6907 6908 // The OpenCL operator with a vector condition is sufficiently 6909 // different to merit its own checker. 6910 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6911 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6912 6913 // First, check the condition. 6914 Cond = UsualUnaryConversions(Cond.get()); 6915 if (Cond.isInvalid()) 6916 return QualType(); 6917 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6918 return QualType(); 6919 6920 // Now check the two expressions. 6921 if (LHS.get()->getType()->isVectorType() || 6922 RHS.get()->getType()->isVectorType()) 6923 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6924 /*AllowBothBool*/true, 6925 /*AllowBoolConversions*/false); 6926 6927 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6928 if (LHS.isInvalid() || RHS.isInvalid()) 6929 return QualType(); 6930 6931 QualType LHSTy = LHS.get()->getType(); 6932 QualType RHSTy = RHS.get()->getType(); 6933 6934 // Diagnose attempts to convert between __float128 and long double where 6935 // such conversions currently can't be handled. 6936 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6937 Diag(QuestionLoc, 6938 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6939 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6940 return QualType(); 6941 } 6942 6943 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6944 // selection operator (?:). 6945 if (getLangOpts().OpenCL && 6946 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6947 return QualType(); 6948 } 6949 6950 // If both operands have arithmetic type, do the usual arithmetic conversions 6951 // to find a common type: C99 6.5.15p3,5. 6952 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6953 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6954 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6955 6956 return ResTy; 6957 } 6958 6959 // If both operands are the same structure or union type, the result is that 6960 // type. 6961 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6962 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6963 if (LHSRT->getDecl() == RHSRT->getDecl()) 6964 // "If both the operands have structure or union type, the result has 6965 // that type." This implies that CV qualifiers are dropped. 6966 return LHSTy.getUnqualifiedType(); 6967 // FIXME: Type of conditional expression must be complete in C mode. 6968 } 6969 6970 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6971 // The following || allows only one side to be void (a GCC-ism). 6972 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6973 return checkConditionalVoidType(*this, LHS, RHS); 6974 } 6975 6976 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6977 // the type of the other operand." 6978 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6979 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6980 6981 // All objective-c pointer type analysis is done here. 6982 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6983 QuestionLoc); 6984 if (LHS.isInvalid() || RHS.isInvalid()) 6985 return QualType(); 6986 if (!compositeType.isNull()) 6987 return compositeType; 6988 6989 6990 // Handle block pointer types. 6991 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6992 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6993 QuestionLoc); 6994 6995 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6996 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6997 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6998 QuestionLoc); 6999 7000 // GCC compatibility: soften pointer/integer mismatch. Note that 7001 // null pointers have been filtered out by this point. 7002 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7003 /*isIntFirstExpr=*/true)) 7004 return RHSTy; 7005 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7006 /*isIntFirstExpr=*/false)) 7007 return LHSTy; 7008 7009 // Emit a better diagnostic if one of the expressions is a null pointer 7010 // constant and the other is not a pointer type. In this case, the user most 7011 // likely forgot to take the address of the other expression. 7012 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7013 return QualType(); 7014 7015 // Otherwise, the operands are not compatible. 7016 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7017 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7018 << RHS.get()->getSourceRange(); 7019 return QualType(); 7020 } 7021 7022 /// FindCompositeObjCPointerType - Helper method to find composite type of 7023 /// two objective-c pointer types of the two input expressions. 7024 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7025 SourceLocation QuestionLoc) { 7026 QualType LHSTy = LHS.get()->getType(); 7027 QualType RHSTy = RHS.get()->getType(); 7028 7029 // Handle things like Class and struct objc_class*. Here we case the result 7030 // to the pseudo-builtin, because that will be implicitly cast back to the 7031 // redefinition type if an attempt is made to access its fields. 7032 if (LHSTy->isObjCClassType() && 7033 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7034 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7035 return LHSTy; 7036 } 7037 if (RHSTy->isObjCClassType() && 7038 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7039 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7040 return RHSTy; 7041 } 7042 // And the same for struct objc_object* / id 7043 if (LHSTy->isObjCIdType() && 7044 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7045 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7046 return LHSTy; 7047 } 7048 if (RHSTy->isObjCIdType() && 7049 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7050 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7051 return RHSTy; 7052 } 7053 // And the same for struct objc_selector* / SEL 7054 if (Context.isObjCSelType(LHSTy) && 7055 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7056 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7057 return LHSTy; 7058 } 7059 if (Context.isObjCSelType(RHSTy) && 7060 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7061 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7062 return RHSTy; 7063 } 7064 // Check constraints for Objective-C object pointers types. 7065 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7066 7067 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7068 // Two identical object pointer types are always compatible. 7069 return LHSTy; 7070 } 7071 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7072 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7073 QualType compositeType = LHSTy; 7074 7075 // If both operands are interfaces and either operand can be 7076 // assigned to the other, use that type as the composite 7077 // type. This allows 7078 // xxx ? (A*) a : (B*) b 7079 // where B is a subclass of A. 7080 // 7081 // Additionally, as for assignment, if either type is 'id' 7082 // allow silent coercion. Finally, if the types are 7083 // incompatible then make sure to use 'id' as the composite 7084 // type so the result is acceptable for sending messages to. 7085 7086 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7087 // It could return the composite type. 7088 if (!(compositeType = 7089 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7090 // Nothing more to do. 7091 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7092 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7093 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7094 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7095 } else if ((LHSTy->isObjCQualifiedIdType() || 7096 RHSTy->isObjCQualifiedIdType()) && 7097 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7098 // Need to handle "id<xx>" explicitly. 7099 // GCC allows qualified id and any Objective-C type to devolve to 7100 // id. Currently localizing to here until clear this should be 7101 // part of ObjCQualifiedIdTypesAreCompatible. 7102 compositeType = Context.getObjCIdType(); 7103 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7104 compositeType = Context.getObjCIdType(); 7105 } else { 7106 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7107 << LHSTy << RHSTy 7108 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7109 QualType incompatTy = Context.getObjCIdType(); 7110 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7111 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7112 return incompatTy; 7113 } 7114 // The object pointer types are compatible. 7115 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7116 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7117 return compositeType; 7118 } 7119 // Check Objective-C object pointer types and 'void *' 7120 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7121 if (getLangOpts().ObjCAutoRefCount) { 7122 // ARC forbids the implicit conversion of object pointers to 'void *', 7123 // so these types are not compatible. 7124 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7125 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7126 LHS = RHS = true; 7127 return QualType(); 7128 } 7129 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7130 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7131 QualType destPointee 7132 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7133 QualType destType = Context.getPointerType(destPointee); 7134 // Add qualifiers if necessary. 7135 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7136 // Promote to void*. 7137 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7138 return destType; 7139 } 7140 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7141 if (getLangOpts().ObjCAutoRefCount) { 7142 // ARC forbids the implicit conversion of object pointers to 'void *', 7143 // so these types are not compatible. 7144 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7145 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7146 LHS = RHS = true; 7147 return QualType(); 7148 } 7149 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7150 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7151 QualType destPointee 7152 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7153 QualType destType = Context.getPointerType(destPointee); 7154 // Add qualifiers if necessary. 7155 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7156 // Promote to void*. 7157 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7158 return destType; 7159 } 7160 return QualType(); 7161 } 7162 7163 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7164 /// ParenRange in parentheses. 7165 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7166 const PartialDiagnostic &Note, 7167 SourceRange ParenRange) { 7168 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7169 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7170 EndLoc.isValid()) { 7171 Self.Diag(Loc, Note) 7172 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7173 << FixItHint::CreateInsertion(EndLoc, ")"); 7174 } else { 7175 // We can't display the parentheses, so just show the bare note. 7176 Self.Diag(Loc, Note) << ParenRange; 7177 } 7178 } 7179 7180 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7181 return BinaryOperator::isAdditiveOp(Opc) || 7182 BinaryOperator::isMultiplicativeOp(Opc) || 7183 BinaryOperator::isShiftOp(Opc); 7184 } 7185 7186 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7187 /// expression, either using a built-in or overloaded operator, 7188 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7189 /// expression. 7190 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7191 Expr **RHSExprs) { 7192 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7193 E = E->IgnoreImpCasts(); 7194 E = E->IgnoreConversionOperator(); 7195 E = E->IgnoreImpCasts(); 7196 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7197 E = MTE->GetTemporaryExpr(); 7198 E = E->IgnoreImpCasts(); 7199 } 7200 7201 // Built-in binary operator. 7202 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7203 if (IsArithmeticOp(OP->getOpcode())) { 7204 *Opcode = OP->getOpcode(); 7205 *RHSExprs = OP->getRHS(); 7206 return true; 7207 } 7208 } 7209 7210 // Overloaded operator. 7211 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7212 if (Call->getNumArgs() != 2) 7213 return false; 7214 7215 // Make sure this is really a binary operator that is safe to pass into 7216 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7217 OverloadedOperatorKind OO = Call->getOperator(); 7218 if (OO < OO_Plus || OO > OO_Arrow || 7219 OO == OO_PlusPlus || OO == OO_MinusMinus) 7220 return false; 7221 7222 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7223 if (IsArithmeticOp(OpKind)) { 7224 *Opcode = OpKind; 7225 *RHSExprs = Call->getArg(1); 7226 return true; 7227 } 7228 } 7229 7230 return false; 7231 } 7232 7233 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7234 /// or is a logical expression such as (x==y) which has int type, but is 7235 /// commonly interpreted as boolean. 7236 static bool ExprLooksBoolean(Expr *E) { 7237 E = E->IgnoreParenImpCasts(); 7238 7239 if (E->getType()->isBooleanType()) 7240 return true; 7241 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7242 return OP->isComparisonOp() || OP->isLogicalOp(); 7243 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7244 return OP->getOpcode() == UO_LNot; 7245 if (E->getType()->isPointerType()) 7246 return true; 7247 // FIXME: What about overloaded operator calls returning "unspecified boolean 7248 // type"s (commonly pointer-to-members)? 7249 7250 return false; 7251 } 7252 7253 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7254 /// and binary operator are mixed in a way that suggests the programmer assumed 7255 /// the conditional operator has higher precedence, for example: 7256 /// "int x = a + someBinaryCondition ? 1 : 2". 7257 static void DiagnoseConditionalPrecedence(Sema &Self, 7258 SourceLocation OpLoc, 7259 Expr *Condition, 7260 Expr *LHSExpr, 7261 Expr *RHSExpr) { 7262 BinaryOperatorKind CondOpcode; 7263 Expr *CondRHS; 7264 7265 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7266 return; 7267 if (!ExprLooksBoolean(CondRHS)) 7268 return; 7269 7270 // The condition is an arithmetic binary expression, with a right- 7271 // hand side that looks boolean, so warn. 7272 7273 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7274 << Condition->getSourceRange() 7275 << BinaryOperator::getOpcodeStr(CondOpcode); 7276 7277 SuggestParentheses( 7278 Self, OpLoc, 7279 Self.PDiag(diag::note_precedence_silence) 7280 << BinaryOperator::getOpcodeStr(CondOpcode), 7281 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7282 7283 SuggestParentheses(Self, OpLoc, 7284 Self.PDiag(diag::note_precedence_conditional_first), 7285 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7286 } 7287 7288 /// Compute the nullability of a conditional expression. 7289 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7290 QualType LHSTy, QualType RHSTy, 7291 ASTContext &Ctx) { 7292 if (!ResTy->isAnyPointerType()) 7293 return ResTy; 7294 7295 auto GetNullability = [&Ctx](QualType Ty) { 7296 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7297 if (Kind) 7298 return *Kind; 7299 return NullabilityKind::Unspecified; 7300 }; 7301 7302 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7303 NullabilityKind MergedKind; 7304 7305 // Compute nullability of a binary conditional expression. 7306 if (IsBin) { 7307 if (LHSKind == NullabilityKind::NonNull) 7308 MergedKind = NullabilityKind::NonNull; 7309 else 7310 MergedKind = RHSKind; 7311 // Compute nullability of a normal conditional expression. 7312 } else { 7313 if (LHSKind == NullabilityKind::Nullable || 7314 RHSKind == NullabilityKind::Nullable) 7315 MergedKind = NullabilityKind::Nullable; 7316 else if (LHSKind == NullabilityKind::NonNull) 7317 MergedKind = RHSKind; 7318 else if (RHSKind == NullabilityKind::NonNull) 7319 MergedKind = LHSKind; 7320 else 7321 MergedKind = NullabilityKind::Unspecified; 7322 } 7323 7324 // Return if ResTy already has the correct nullability. 7325 if (GetNullability(ResTy) == MergedKind) 7326 return ResTy; 7327 7328 // Strip all nullability from ResTy. 7329 while (ResTy->getNullability(Ctx)) 7330 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7331 7332 // Create a new AttributedType with the new nullability kind. 7333 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7334 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7335 } 7336 7337 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7338 /// in the case of a the GNU conditional expr extension. 7339 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7340 SourceLocation ColonLoc, 7341 Expr *CondExpr, Expr *LHSExpr, 7342 Expr *RHSExpr) { 7343 if (!getLangOpts().CPlusPlus) { 7344 // C cannot handle TypoExpr nodes in the condition because it 7345 // doesn't handle dependent types properly, so make sure any TypoExprs have 7346 // been dealt with before checking the operands. 7347 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7348 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7349 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7350 7351 if (!CondResult.isUsable()) 7352 return ExprError(); 7353 7354 if (LHSExpr) { 7355 if (!LHSResult.isUsable()) 7356 return ExprError(); 7357 } 7358 7359 if (!RHSResult.isUsable()) 7360 return ExprError(); 7361 7362 CondExpr = CondResult.get(); 7363 LHSExpr = LHSResult.get(); 7364 RHSExpr = RHSResult.get(); 7365 } 7366 7367 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7368 // was the condition. 7369 OpaqueValueExpr *opaqueValue = nullptr; 7370 Expr *commonExpr = nullptr; 7371 if (!LHSExpr) { 7372 commonExpr = CondExpr; 7373 // Lower out placeholder types first. This is important so that we don't 7374 // try to capture a placeholder. This happens in few cases in C++; such 7375 // as Objective-C++'s dictionary subscripting syntax. 7376 if (commonExpr->hasPlaceholderType()) { 7377 ExprResult result = CheckPlaceholderExpr(commonExpr); 7378 if (!result.isUsable()) return ExprError(); 7379 commonExpr = result.get(); 7380 } 7381 // We usually want to apply unary conversions *before* saving, except 7382 // in the special case of a C++ l-value conditional. 7383 if (!(getLangOpts().CPlusPlus 7384 && !commonExpr->isTypeDependent() 7385 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7386 && commonExpr->isGLValue() 7387 && commonExpr->isOrdinaryOrBitFieldObject() 7388 && RHSExpr->isOrdinaryOrBitFieldObject() 7389 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7390 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7391 if (commonRes.isInvalid()) 7392 return ExprError(); 7393 commonExpr = commonRes.get(); 7394 } 7395 7396 // If the common expression is a class or array prvalue, materialize it 7397 // so that we can safely refer to it multiple times. 7398 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7399 commonExpr->getType()->isArrayType())) { 7400 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7401 if (MatExpr.isInvalid()) 7402 return ExprError(); 7403 commonExpr = MatExpr.get(); 7404 } 7405 7406 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7407 commonExpr->getType(), 7408 commonExpr->getValueKind(), 7409 commonExpr->getObjectKind(), 7410 commonExpr); 7411 LHSExpr = CondExpr = opaqueValue; 7412 } 7413 7414 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7415 ExprValueKind VK = VK_RValue; 7416 ExprObjectKind OK = OK_Ordinary; 7417 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7418 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7419 VK, OK, QuestionLoc); 7420 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7421 RHS.isInvalid()) 7422 return ExprError(); 7423 7424 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7425 RHS.get()); 7426 7427 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7428 7429 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7430 Context); 7431 7432 if (!commonExpr) 7433 return new (Context) 7434 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7435 RHS.get(), result, VK, OK); 7436 7437 return new (Context) BinaryConditionalOperator( 7438 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7439 ColonLoc, result, VK, OK); 7440 } 7441 7442 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7443 // being closely modeled after the C99 spec:-). The odd characteristic of this 7444 // routine is it effectively iqnores the qualifiers on the top level pointee. 7445 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7446 // FIXME: add a couple examples in this comment. 7447 static Sema::AssignConvertType 7448 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7449 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7450 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7451 7452 // get the "pointed to" type (ignoring qualifiers at the top level) 7453 const Type *lhptee, *rhptee; 7454 Qualifiers lhq, rhq; 7455 std::tie(lhptee, lhq) = 7456 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7457 std::tie(rhptee, rhq) = 7458 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7459 7460 Sema::AssignConvertType ConvTy = Sema::Compatible; 7461 7462 // C99 6.5.16.1p1: This following citation is common to constraints 7463 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7464 // qualifiers of the type *pointed to* by the right; 7465 7466 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7467 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7468 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7469 // Ignore lifetime for further calculation. 7470 lhq.removeObjCLifetime(); 7471 rhq.removeObjCLifetime(); 7472 } 7473 7474 if (!lhq.compatiblyIncludes(rhq)) { 7475 // Treat address-space mismatches as fatal. TODO: address subspaces 7476 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7477 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7478 7479 // It's okay to add or remove GC or lifetime qualifiers when converting to 7480 // and from void*. 7481 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7482 .compatiblyIncludes( 7483 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7484 && (lhptee->isVoidType() || rhptee->isVoidType())) 7485 ; // keep old 7486 7487 // Treat lifetime mismatches as fatal. 7488 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7489 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7490 7491 // For GCC/MS compatibility, other qualifier mismatches are treated 7492 // as still compatible in C. 7493 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7494 } 7495 7496 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7497 // incomplete type and the other is a pointer to a qualified or unqualified 7498 // version of void... 7499 if (lhptee->isVoidType()) { 7500 if (rhptee->isIncompleteOrObjectType()) 7501 return ConvTy; 7502 7503 // As an extension, we allow cast to/from void* to function pointer. 7504 assert(rhptee->isFunctionType()); 7505 return Sema::FunctionVoidPointer; 7506 } 7507 7508 if (rhptee->isVoidType()) { 7509 if (lhptee->isIncompleteOrObjectType()) 7510 return ConvTy; 7511 7512 // As an extension, we allow cast to/from void* to function pointer. 7513 assert(lhptee->isFunctionType()); 7514 return Sema::FunctionVoidPointer; 7515 } 7516 7517 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7518 // unqualified versions of compatible types, ... 7519 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7520 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7521 // Check if the pointee types are compatible ignoring the sign. 7522 // We explicitly check for char so that we catch "char" vs 7523 // "unsigned char" on systems where "char" is unsigned. 7524 if (lhptee->isCharType()) 7525 ltrans = S.Context.UnsignedCharTy; 7526 else if (lhptee->hasSignedIntegerRepresentation()) 7527 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7528 7529 if (rhptee->isCharType()) 7530 rtrans = S.Context.UnsignedCharTy; 7531 else if (rhptee->hasSignedIntegerRepresentation()) 7532 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7533 7534 if (ltrans == rtrans) { 7535 // Types are compatible ignoring the sign. Qualifier incompatibility 7536 // takes priority over sign incompatibility because the sign 7537 // warning can be disabled. 7538 if (ConvTy != Sema::Compatible) 7539 return ConvTy; 7540 7541 return Sema::IncompatiblePointerSign; 7542 } 7543 7544 // If we are a multi-level pointer, it's possible that our issue is simply 7545 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7546 // the eventual target type is the same and the pointers have the same 7547 // level of indirection, this must be the issue. 7548 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7549 do { 7550 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7551 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7552 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7553 7554 if (lhptee == rhptee) 7555 return Sema::IncompatibleNestedPointerQualifiers; 7556 } 7557 7558 // General pointer incompatibility takes priority over qualifiers. 7559 return Sema::IncompatiblePointer; 7560 } 7561 if (!S.getLangOpts().CPlusPlus && 7562 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7563 return Sema::IncompatiblePointer; 7564 return ConvTy; 7565 } 7566 7567 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7568 /// block pointer types are compatible or whether a block and normal pointer 7569 /// are compatible. It is more restrict than comparing two function pointer 7570 // types. 7571 static Sema::AssignConvertType 7572 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7573 QualType RHSType) { 7574 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7575 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7576 7577 QualType lhptee, rhptee; 7578 7579 // get the "pointed to" type (ignoring qualifiers at the top level) 7580 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7581 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7582 7583 // In C++, the types have to match exactly. 7584 if (S.getLangOpts().CPlusPlus) 7585 return Sema::IncompatibleBlockPointer; 7586 7587 Sema::AssignConvertType ConvTy = Sema::Compatible; 7588 7589 // For blocks we enforce that qualifiers are identical. 7590 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7591 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7592 if (S.getLangOpts().OpenCL) { 7593 LQuals.removeAddressSpace(); 7594 RQuals.removeAddressSpace(); 7595 } 7596 if (LQuals != RQuals) 7597 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7598 7599 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7600 // assignment. 7601 // The current behavior is similar to C++ lambdas. A block might be 7602 // assigned to a variable iff its return type and parameters are compatible 7603 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7604 // an assignment. Presumably it should behave in way that a function pointer 7605 // assignment does in C, so for each parameter and return type: 7606 // * CVR and address space of LHS should be a superset of CVR and address 7607 // space of RHS. 7608 // * unqualified types should be compatible. 7609 if (S.getLangOpts().OpenCL) { 7610 if (!S.Context.typesAreBlockPointerCompatible( 7611 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7612 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7613 return Sema::IncompatibleBlockPointer; 7614 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7615 return Sema::IncompatibleBlockPointer; 7616 7617 return ConvTy; 7618 } 7619 7620 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7621 /// for assignment compatibility. 7622 static Sema::AssignConvertType 7623 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7624 QualType RHSType) { 7625 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7626 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7627 7628 if (LHSType->isObjCBuiltinType()) { 7629 // Class is not compatible with ObjC object pointers. 7630 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7631 !RHSType->isObjCQualifiedClassType()) 7632 return Sema::IncompatiblePointer; 7633 return Sema::Compatible; 7634 } 7635 if (RHSType->isObjCBuiltinType()) { 7636 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7637 !LHSType->isObjCQualifiedClassType()) 7638 return Sema::IncompatiblePointer; 7639 return Sema::Compatible; 7640 } 7641 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7642 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7643 7644 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7645 // make an exception for id<P> 7646 !LHSType->isObjCQualifiedIdType()) 7647 return Sema::CompatiblePointerDiscardsQualifiers; 7648 7649 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7650 return Sema::Compatible; 7651 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7652 return Sema::IncompatibleObjCQualifiedId; 7653 return Sema::IncompatiblePointer; 7654 } 7655 7656 Sema::AssignConvertType 7657 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7658 QualType LHSType, QualType RHSType) { 7659 // Fake up an opaque expression. We don't actually care about what 7660 // cast operations are required, so if CheckAssignmentConstraints 7661 // adds casts to this they'll be wasted, but fortunately that doesn't 7662 // usually happen on valid code. 7663 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7664 ExprResult RHSPtr = &RHSExpr; 7665 CastKind K; 7666 7667 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7668 } 7669 7670 /// This helper function returns true if QT is a vector type that has element 7671 /// type ElementType. 7672 static bool isVector(QualType QT, QualType ElementType) { 7673 if (const VectorType *VT = QT->getAs<VectorType>()) 7674 return VT->getElementType() == ElementType; 7675 return false; 7676 } 7677 7678 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7679 /// has code to accommodate several GCC extensions when type checking 7680 /// pointers. Here are some objectionable examples that GCC considers warnings: 7681 /// 7682 /// int a, *pint; 7683 /// short *pshort; 7684 /// struct foo *pfoo; 7685 /// 7686 /// pint = pshort; // warning: assignment from incompatible pointer type 7687 /// a = pint; // warning: assignment makes integer from pointer without a cast 7688 /// pint = a; // warning: assignment makes pointer from integer without a cast 7689 /// pint = pfoo; // warning: assignment from incompatible pointer type 7690 /// 7691 /// As a result, the code for dealing with pointers is more complex than the 7692 /// C99 spec dictates. 7693 /// 7694 /// Sets 'Kind' for any result kind except Incompatible. 7695 Sema::AssignConvertType 7696 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7697 CastKind &Kind, bool ConvertRHS) { 7698 QualType RHSType = RHS.get()->getType(); 7699 QualType OrigLHSType = LHSType; 7700 7701 // Get canonical types. We're not formatting these types, just comparing 7702 // them. 7703 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7704 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7705 7706 // Common case: no conversion required. 7707 if (LHSType == RHSType) { 7708 Kind = CK_NoOp; 7709 return Compatible; 7710 } 7711 7712 // If we have an atomic type, try a non-atomic assignment, then just add an 7713 // atomic qualification step. 7714 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7715 Sema::AssignConvertType result = 7716 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7717 if (result != Compatible) 7718 return result; 7719 if (Kind != CK_NoOp && ConvertRHS) 7720 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7721 Kind = CK_NonAtomicToAtomic; 7722 return Compatible; 7723 } 7724 7725 // If the left-hand side is a reference type, then we are in a 7726 // (rare!) case where we've allowed the use of references in C, 7727 // e.g., as a parameter type in a built-in function. In this case, 7728 // just make sure that the type referenced is compatible with the 7729 // right-hand side type. The caller is responsible for adjusting 7730 // LHSType so that the resulting expression does not have reference 7731 // type. 7732 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7733 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7734 Kind = CK_LValueBitCast; 7735 return Compatible; 7736 } 7737 return Incompatible; 7738 } 7739 7740 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7741 // to the same ExtVector type. 7742 if (LHSType->isExtVectorType()) { 7743 if (RHSType->isExtVectorType()) 7744 return Incompatible; 7745 if (RHSType->isArithmeticType()) { 7746 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7747 if (ConvertRHS) 7748 RHS = prepareVectorSplat(LHSType, RHS.get()); 7749 Kind = CK_VectorSplat; 7750 return Compatible; 7751 } 7752 } 7753 7754 // Conversions to or from vector type. 7755 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7756 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7757 // Allow assignments of an AltiVec vector type to an equivalent GCC 7758 // vector type and vice versa 7759 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7760 Kind = CK_BitCast; 7761 return Compatible; 7762 } 7763 7764 // If we are allowing lax vector conversions, and LHS and RHS are both 7765 // vectors, the total size only needs to be the same. This is a bitcast; 7766 // no bits are changed but the result type is different. 7767 if (isLaxVectorConversion(RHSType, LHSType)) { 7768 Kind = CK_BitCast; 7769 return IncompatibleVectors; 7770 } 7771 } 7772 7773 // When the RHS comes from another lax conversion (e.g. binops between 7774 // scalars and vectors) the result is canonicalized as a vector. When the 7775 // LHS is also a vector, the lax is allowed by the condition above. Handle 7776 // the case where LHS is a scalar. 7777 if (LHSType->isScalarType()) { 7778 const VectorType *VecType = RHSType->getAs<VectorType>(); 7779 if (VecType && VecType->getNumElements() == 1 && 7780 isLaxVectorConversion(RHSType, LHSType)) { 7781 ExprResult *VecExpr = &RHS; 7782 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7783 Kind = CK_BitCast; 7784 return Compatible; 7785 } 7786 } 7787 7788 return Incompatible; 7789 } 7790 7791 // Diagnose attempts to convert between __float128 and long double where 7792 // such conversions currently can't be handled. 7793 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7794 return Incompatible; 7795 7796 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7797 // discards the imaginary part. 7798 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7799 !LHSType->getAs<ComplexType>()) 7800 return Incompatible; 7801 7802 // Arithmetic conversions. 7803 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7804 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7805 if (ConvertRHS) 7806 Kind = PrepareScalarCast(RHS, LHSType); 7807 return Compatible; 7808 } 7809 7810 // Conversions to normal pointers. 7811 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7812 // U* -> T* 7813 if (isa<PointerType>(RHSType)) { 7814 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7815 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7816 if (AddrSpaceL != AddrSpaceR) 7817 Kind = CK_AddressSpaceConversion; 7818 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 7819 Kind = CK_NoOp; 7820 else 7821 Kind = CK_BitCast; 7822 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7823 } 7824 7825 // int -> T* 7826 if (RHSType->isIntegerType()) { 7827 Kind = CK_IntegralToPointer; // FIXME: null? 7828 return IntToPointer; 7829 } 7830 7831 // C pointers are not compatible with ObjC object pointers, 7832 // with two exceptions: 7833 if (isa<ObjCObjectPointerType>(RHSType)) { 7834 // - conversions to void* 7835 if (LHSPointer->getPointeeType()->isVoidType()) { 7836 Kind = CK_BitCast; 7837 return Compatible; 7838 } 7839 7840 // - conversions from 'Class' to the redefinition type 7841 if (RHSType->isObjCClassType() && 7842 Context.hasSameType(LHSType, 7843 Context.getObjCClassRedefinitionType())) { 7844 Kind = CK_BitCast; 7845 return Compatible; 7846 } 7847 7848 Kind = CK_BitCast; 7849 return IncompatiblePointer; 7850 } 7851 7852 // U^ -> void* 7853 if (RHSType->getAs<BlockPointerType>()) { 7854 if (LHSPointer->getPointeeType()->isVoidType()) { 7855 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7856 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7857 ->getPointeeType() 7858 .getAddressSpace(); 7859 Kind = 7860 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7861 return Compatible; 7862 } 7863 } 7864 7865 return Incompatible; 7866 } 7867 7868 // Conversions to block pointers. 7869 if (isa<BlockPointerType>(LHSType)) { 7870 // U^ -> T^ 7871 if (RHSType->isBlockPointerType()) { 7872 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7873 ->getPointeeType() 7874 .getAddressSpace(); 7875 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7876 ->getPointeeType() 7877 .getAddressSpace(); 7878 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7879 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7880 } 7881 7882 // int or null -> T^ 7883 if (RHSType->isIntegerType()) { 7884 Kind = CK_IntegralToPointer; // FIXME: null 7885 return IntToBlockPointer; 7886 } 7887 7888 // id -> T^ 7889 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7890 Kind = CK_AnyPointerToBlockPointerCast; 7891 return Compatible; 7892 } 7893 7894 // void* -> T^ 7895 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7896 if (RHSPT->getPointeeType()->isVoidType()) { 7897 Kind = CK_AnyPointerToBlockPointerCast; 7898 return Compatible; 7899 } 7900 7901 return Incompatible; 7902 } 7903 7904 // Conversions to Objective-C pointers. 7905 if (isa<ObjCObjectPointerType>(LHSType)) { 7906 // A* -> B* 7907 if (RHSType->isObjCObjectPointerType()) { 7908 Kind = CK_BitCast; 7909 Sema::AssignConvertType result = 7910 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7911 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7912 result == Compatible && 7913 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7914 result = IncompatibleObjCWeakRef; 7915 return result; 7916 } 7917 7918 // int or null -> A* 7919 if (RHSType->isIntegerType()) { 7920 Kind = CK_IntegralToPointer; // FIXME: null 7921 return IntToPointer; 7922 } 7923 7924 // In general, C pointers are not compatible with ObjC object pointers, 7925 // with two exceptions: 7926 if (isa<PointerType>(RHSType)) { 7927 Kind = CK_CPointerToObjCPointerCast; 7928 7929 // - conversions from 'void*' 7930 if (RHSType->isVoidPointerType()) { 7931 return Compatible; 7932 } 7933 7934 // - conversions to 'Class' from its redefinition type 7935 if (LHSType->isObjCClassType() && 7936 Context.hasSameType(RHSType, 7937 Context.getObjCClassRedefinitionType())) { 7938 return Compatible; 7939 } 7940 7941 return IncompatiblePointer; 7942 } 7943 7944 // Only under strict condition T^ is compatible with an Objective-C pointer. 7945 if (RHSType->isBlockPointerType() && 7946 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7947 if (ConvertRHS) 7948 maybeExtendBlockObject(RHS); 7949 Kind = CK_BlockPointerToObjCPointerCast; 7950 return Compatible; 7951 } 7952 7953 return Incompatible; 7954 } 7955 7956 // Conversions from pointers that are not covered by the above. 7957 if (isa<PointerType>(RHSType)) { 7958 // T* -> _Bool 7959 if (LHSType == Context.BoolTy) { 7960 Kind = CK_PointerToBoolean; 7961 return Compatible; 7962 } 7963 7964 // T* -> int 7965 if (LHSType->isIntegerType()) { 7966 Kind = CK_PointerToIntegral; 7967 return PointerToInt; 7968 } 7969 7970 return Incompatible; 7971 } 7972 7973 // Conversions from Objective-C pointers that are not covered by the above. 7974 if (isa<ObjCObjectPointerType>(RHSType)) { 7975 // T* -> _Bool 7976 if (LHSType == Context.BoolTy) { 7977 Kind = CK_PointerToBoolean; 7978 return Compatible; 7979 } 7980 7981 // T* -> int 7982 if (LHSType->isIntegerType()) { 7983 Kind = CK_PointerToIntegral; 7984 return PointerToInt; 7985 } 7986 7987 return Incompatible; 7988 } 7989 7990 // struct A -> struct B 7991 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7992 if (Context.typesAreCompatible(LHSType, RHSType)) { 7993 Kind = CK_NoOp; 7994 return Compatible; 7995 } 7996 } 7997 7998 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7999 Kind = CK_IntToOCLSampler; 8000 return Compatible; 8001 } 8002 8003 return Incompatible; 8004 } 8005 8006 /// Constructs a transparent union from an expression that is 8007 /// used to initialize the transparent union. 8008 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8009 ExprResult &EResult, QualType UnionType, 8010 FieldDecl *Field) { 8011 // Build an initializer list that designates the appropriate member 8012 // of the transparent union. 8013 Expr *E = EResult.get(); 8014 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8015 E, SourceLocation()); 8016 Initializer->setType(UnionType); 8017 Initializer->setInitializedFieldInUnion(Field); 8018 8019 // Build a compound literal constructing a value of the transparent 8020 // union type from this initializer list. 8021 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8022 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8023 VK_RValue, Initializer, false); 8024 } 8025 8026 Sema::AssignConvertType 8027 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8028 ExprResult &RHS) { 8029 QualType RHSType = RHS.get()->getType(); 8030 8031 // If the ArgType is a Union type, we want to handle a potential 8032 // transparent_union GCC extension. 8033 const RecordType *UT = ArgType->getAsUnionType(); 8034 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8035 return Incompatible; 8036 8037 // The field to initialize within the transparent union. 8038 RecordDecl *UD = UT->getDecl(); 8039 FieldDecl *InitField = nullptr; 8040 // It's compatible if the expression matches any of the fields. 8041 for (auto *it : UD->fields()) { 8042 if (it->getType()->isPointerType()) { 8043 // If the transparent union contains a pointer type, we allow: 8044 // 1) void pointer 8045 // 2) null pointer constant 8046 if (RHSType->isPointerType()) 8047 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8048 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8049 InitField = it; 8050 break; 8051 } 8052 8053 if (RHS.get()->isNullPointerConstant(Context, 8054 Expr::NPC_ValueDependentIsNull)) { 8055 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8056 CK_NullToPointer); 8057 InitField = it; 8058 break; 8059 } 8060 } 8061 8062 CastKind Kind; 8063 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8064 == Compatible) { 8065 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8066 InitField = it; 8067 break; 8068 } 8069 } 8070 8071 if (!InitField) 8072 return Incompatible; 8073 8074 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8075 return Compatible; 8076 } 8077 8078 Sema::AssignConvertType 8079 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8080 bool Diagnose, 8081 bool DiagnoseCFAudited, 8082 bool ConvertRHS) { 8083 // We need to be able to tell the caller whether we diagnosed a problem, if 8084 // they ask us to issue diagnostics. 8085 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8086 8087 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8088 // we can't avoid *all* modifications at the moment, so we need some somewhere 8089 // to put the updated value. 8090 ExprResult LocalRHS = CallerRHS; 8091 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8092 8093 if (getLangOpts().CPlusPlus) { 8094 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8095 // C++ 5.17p3: If the left operand is not of class type, the 8096 // expression is implicitly converted (C++ 4) to the 8097 // cv-unqualified type of the left operand. 8098 QualType RHSType = RHS.get()->getType(); 8099 if (Diagnose) { 8100 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8101 AA_Assigning); 8102 } else { 8103 ImplicitConversionSequence ICS = 8104 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8105 /*SuppressUserConversions=*/false, 8106 /*AllowExplicit=*/false, 8107 /*InOverloadResolution=*/false, 8108 /*CStyle=*/false, 8109 /*AllowObjCWritebackConversion=*/false); 8110 if (ICS.isFailure()) 8111 return Incompatible; 8112 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8113 ICS, AA_Assigning); 8114 } 8115 if (RHS.isInvalid()) 8116 return Incompatible; 8117 Sema::AssignConvertType result = Compatible; 8118 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8119 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8120 result = IncompatibleObjCWeakRef; 8121 return result; 8122 } 8123 8124 // FIXME: Currently, we fall through and treat C++ classes like C 8125 // structures. 8126 // FIXME: We also fall through for atomics; not sure what should 8127 // happen there, though. 8128 } else if (RHS.get()->getType() == Context.OverloadTy) { 8129 // As a set of extensions to C, we support overloading on functions. These 8130 // functions need to be resolved here. 8131 DeclAccessPair DAP; 8132 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8133 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8134 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8135 else 8136 return Incompatible; 8137 } 8138 8139 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8140 // a null pointer constant. 8141 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8142 LHSType->isBlockPointerType()) && 8143 RHS.get()->isNullPointerConstant(Context, 8144 Expr::NPC_ValueDependentIsNull)) { 8145 if (Diagnose || ConvertRHS) { 8146 CastKind Kind; 8147 CXXCastPath Path; 8148 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8149 /*IgnoreBaseAccess=*/false, Diagnose); 8150 if (ConvertRHS) 8151 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8152 } 8153 return Compatible; 8154 } 8155 8156 // OpenCL queue_t type assignment. 8157 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8158 Context, Expr::NPC_ValueDependentIsNull)) { 8159 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8160 return Compatible; 8161 } 8162 8163 // This check seems unnatural, however it is necessary to ensure the proper 8164 // conversion of functions/arrays. If the conversion were done for all 8165 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8166 // expressions that suppress this implicit conversion (&, sizeof). 8167 // 8168 // Suppress this for references: C++ 8.5.3p5. 8169 if (!LHSType->isReferenceType()) { 8170 // FIXME: We potentially allocate here even if ConvertRHS is false. 8171 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8172 if (RHS.isInvalid()) 8173 return Incompatible; 8174 } 8175 CastKind Kind; 8176 Sema::AssignConvertType result = 8177 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8178 8179 // C99 6.5.16.1p2: The value of the right operand is converted to the 8180 // type of the assignment expression. 8181 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8182 // so that we can use references in built-in functions even in C. 8183 // The getNonReferenceType() call makes sure that the resulting expression 8184 // does not have reference type. 8185 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8186 QualType Ty = LHSType.getNonLValueExprType(Context); 8187 Expr *E = RHS.get(); 8188 8189 // Check for various Objective-C errors. If we are not reporting 8190 // diagnostics and just checking for errors, e.g., during overload 8191 // resolution, return Incompatible to indicate the failure. 8192 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8193 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8194 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8195 if (!Diagnose) 8196 return Incompatible; 8197 } 8198 if (getLangOpts().ObjC1 && 8199 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8200 E->getType(), E, Diagnose) || 8201 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8202 if (!Diagnose) 8203 return Incompatible; 8204 // Replace the expression with a corrected version and continue so we 8205 // can find further errors. 8206 RHS = E; 8207 return Compatible; 8208 } 8209 8210 if (ConvertRHS) 8211 RHS = ImpCastExprToType(E, Ty, Kind); 8212 } 8213 return result; 8214 } 8215 8216 namespace { 8217 /// The original operand to an operator, prior to the application of the usual 8218 /// arithmetic conversions and converting the arguments of a builtin operator 8219 /// candidate. 8220 struct OriginalOperand { 8221 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8222 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8223 Op = MTE->GetTemporaryExpr(); 8224 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8225 Op = BTE->getSubExpr(); 8226 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8227 Orig = ICE->getSubExprAsWritten(); 8228 Conversion = ICE->getConversionFunction(); 8229 } 8230 } 8231 8232 QualType getType() const { return Orig->getType(); } 8233 8234 Expr *Orig; 8235 NamedDecl *Conversion; 8236 }; 8237 } 8238 8239 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8240 ExprResult &RHS) { 8241 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8242 8243 Diag(Loc, diag::err_typecheck_invalid_operands) 8244 << OrigLHS.getType() << OrigRHS.getType() 8245 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8246 8247 // If a user-defined conversion was applied to either of the operands prior 8248 // to applying the built-in operator rules, tell the user about it. 8249 if (OrigLHS.Conversion) { 8250 Diag(OrigLHS.Conversion->getLocation(), 8251 diag::note_typecheck_invalid_operands_converted) 8252 << 0 << LHS.get()->getType(); 8253 } 8254 if (OrigRHS.Conversion) { 8255 Diag(OrigRHS.Conversion->getLocation(), 8256 diag::note_typecheck_invalid_operands_converted) 8257 << 1 << RHS.get()->getType(); 8258 } 8259 8260 return QualType(); 8261 } 8262 8263 // Diagnose cases where a scalar was implicitly converted to a vector and 8264 // diagnose the underlying types. Otherwise, diagnose the error 8265 // as invalid vector logical operands for non-C++ cases. 8266 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8267 ExprResult &RHS) { 8268 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8269 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8270 8271 bool LHSNatVec = LHSType->isVectorType(); 8272 bool RHSNatVec = RHSType->isVectorType(); 8273 8274 if (!(LHSNatVec && RHSNatVec)) { 8275 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8276 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8277 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8278 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8279 << Vector->getSourceRange(); 8280 return QualType(); 8281 } 8282 8283 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8284 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8285 << RHS.get()->getSourceRange(); 8286 8287 return QualType(); 8288 } 8289 8290 /// Try to convert a value of non-vector type to a vector type by converting 8291 /// the type to the element type of the vector and then performing a splat. 8292 /// If the language is OpenCL, we only use conversions that promote scalar 8293 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8294 /// for float->int. 8295 /// 8296 /// OpenCL V2.0 6.2.6.p2: 8297 /// An error shall occur if any scalar operand type has greater rank 8298 /// than the type of the vector element. 8299 /// 8300 /// \param scalar - if non-null, actually perform the conversions 8301 /// \return true if the operation fails (but without diagnosing the failure) 8302 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8303 QualType scalarTy, 8304 QualType vectorEltTy, 8305 QualType vectorTy, 8306 unsigned &DiagID) { 8307 // The conversion to apply to the scalar before splatting it, 8308 // if necessary. 8309 CastKind scalarCast = CK_NoOp; 8310 8311 if (vectorEltTy->isIntegralType(S.Context)) { 8312 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8313 (scalarTy->isIntegerType() && 8314 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8315 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8316 return true; 8317 } 8318 if (!scalarTy->isIntegralType(S.Context)) 8319 return true; 8320 scalarCast = CK_IntegralCast; 8321 } else if (vectorEltTy->isRealFloatingType()) { 8322 if (scalarTy->isRealFloatingType()) { 8323 if (S.getLangOpts().OpenCL && 8324 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8325 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8326 return true; 8327 } 8328 scalarCast = CK_FloatingCast; 8329 } 8330 else if (scalarTy->isIntegralType(S.Context)) 8331 scalarCast = CK_IntegralToFloating; 8332 else 8333 return true; 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 /// Convert vector E to a vector with the same number of elements but different 8348 /// element type. 8349 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8350 const auto *VecTy = E->getType()->getAs<VectorType>(); 8351 assert(VecTy && "Expression E must be a vector"); 8352 QualType NewVecTy = S.Context.getVectorType(ElementType, 8353 VecTy->getNumElements(), 8354 VecTy->getVectorKind()); 8355 8356 // Look through the implicit cast. Return the subexpression if its type is 8357 // NewVecTy. 8358 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8359 if (ICE->getSubExpr()->getType() == NewVecTy) 8360 return ICE->getSubExpr(); 8361 8362 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8363 return S.ImpCastExprToType(E, NewVecTy, Cast); 8364 } 8365 8366 /// Test if a (constant) integer Int can be casted to another integer type 8367 /// IntTy without losing precision. 8368 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8369 QualType OtherIntTy) { 8370 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8371 8372 // Reject cases where the value of the Int is unknown as that would 8373 // possibly cause truncation, but accept cases where the scalar can be 8374 // demoted without loss of precision. 8375 llvm::APSInt Result; 8376 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8377 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8378 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8379 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8380 8381 if (CstInt) { 8382 // If the scalar is constant and is of a higher order and has more active 8383 // bits that the vector element type, reject it. 8384 unsigned NumBits = IntSigned 8385 ? (Result.isNegative() ? Result.getMinSignedBits() 8386 : Result.getActiveBits()) 8387 : Result.getActiveBits(); 8388 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8389 return true; 8390 8391 // If the signedness of the scalar type and the vector element type 8392 // differs and the number of bits is greater than that of the vector 8393 // element reject it. 8394 return (IntSigned != OtherIntSigned && 8395 NumBits > S.Context.getIntWidth(OtherIntTy)); 8396 } 8397 8398 // Reject cases where the value of the scalar is not constant and it's 8399 // order is greater than that of the vector element type. 8400 return (Order < 0); 8401 } 8402 8403 /// Test if a (constant) integer Int can be casted to floating point type 8404 /// FloatTy without losing precision. 8405 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8406 QualType FloatTy) { 8407 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8408 8409 // Determine if the integer constant can be expressed as a floating point 8410 // number of the appropriate type. 8411 llvm::APSInt Result; 8412 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8413 uint64_t Bits = 0; 8414 if (CstInt) { 8415 // Reject constants that would be truncated if they were converted to 8416 // the floating point type. Test by simple to/from conversion. 8417 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8418 // could be avoided if there was a convertFromAPInt method 8419 // which could signal back if implicit truncation occurred. 8420 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8421 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8422 llvm::APFloat::rmTowardZero); 8423 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8424 !IntTy->hasSignedIntegerRepresentation()); 8425 bool Ignored = false; 8426 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8427 &Ignored); 8428 if (Result != ConvertBack) 8429 return true; 8430 } else { 8431 // Reject types that cannot be fully encoded into the mantissa of 8432 // the float. 8433 Bits = S.Context.getTypeSize(IntTy); 8434 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8435 S.Context.getFloatTypeSemantics(FloatTy)); 8436 if (Bits > FloatPrec) 8437 return true; 8438 } 8439 8440 return false; 8441 } 8442 8443 /// Attempt to convert and splat Scalar into a vector whose types matches 8444 /// Vector following GCC conversion rules. The rule is that implicit 8445 /// conversion can occur when Scalar can be casted to match Vector's element 8446 /// type without causing truncation of Scalar. 8447 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8448 ExprResult *Vector) { 8449 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8450 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8451 const VectorType *VT = VectorTy->getAs<VectorType>(); 8452 8453 assert(!isa<ExtVectorType>(VT) && 8454 "ExtVectorTypes should not be handled here!"); 8455 8456 QualType VectorEltTy = VT->getElementType(); 8457 8458 // Reject cases where the vector element type or the scalar element type are 8459 // not integral or floating point types. 8460 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8461 return true; 8462 8463 // The conversion to apply to the scalar before splatting it, 8464 // if necessary. 8465 CastKind ScalarCast = CK_NoOp; 8466 8467 // Accept cases where the vector elements are integers and the scalar is 8468 // an integer. 8469 // FIXME: Notionally if the scalar was a floating point value with a precise 8470 // integral representation, we could cast it to an appropriate integer 8471 // type and then perform the rest of the checks here. GCC will perform 8472 // this conversion in some cases as determined by the input language. 8473 // We should accept it on a language independent basis. 8474 if (VectorEltTy->isIntegralType(S.Context) && 8475 ScalarTy->isIntegralType(S.Context) && 8476 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8477 8478 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8479 return true; 8480 8481 ScalarCast = CK_IntegralCast; 8482 } else if (VectorEltTy->isRealFloatingType()) { 8483 if (ScalarTy->isRealFloatingType()) { 8484 8485 // Reject cases where the scalar type is not a constant and has a higher 8486 // Order than the vector element type. 8487 llvm::APFloat Result(0.0); 8488 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8489 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8490 if (!CstScalar && Order < 0) 8491 return true; 8492 8493 // If the scalar cannot be safely casted to the vector element type, 8494 // reject it. 8495 if (CstScalar) { 8496 bool Truncated = false; 8497 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8498 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8499 if (Truncated) 8500 return true; 8501 } 8502 8503 ScalarCast = CK_FloatingCast; 8504 } else if (ScalarTy->isIntegralType(S.Context)) { 8505 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8506 return true; 8507 8508 ScalarCast = CK_IntegralToFloating; 8509 } else 8510 return true; 8511 } 8512 8513 // Adjust scalar if desired. 8514 if (Scalar) { 8515 if (ScalarCast != CK_NoOp) 8516 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8517 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8518 } 8519 return false; 8520 } 8521 8522 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8523 SourceLocation Loc, bool IsCompAssign, 8524 bool AllowBothBool, 8525 bool AllowBoolConversions) { 8526 if (!IsCompAssign) { 8527 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8528 if (LHS.isInvalid()) 8529 return QualType(); 8530 } 8531 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8532 if (RHS.isInvalid()) 8533 return QualType(); 8534 8535 // For conversion purposes, we ignore any qualifiers. 8536 // For example, "const float" and "float" are equivalent. 8537 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8538 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8539 8540 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8541 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8542 assert(LHSVecType || RHSVecType); 8543 8544 // AltiVec-style "vector bool op vector bool" combinations are allowed 8545 // for some operators but not others. 8546 if (!AllowBothBool && 8547 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8548 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8549 return InvalidOperands(Loc, LHS, RHS); 8550 8551 // If the vector types are identical, return. 8552 if (Context.hasSameType(LHSType, RHSType)) 8553 return LHSType; 8554 8555 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8556 if (LHSVecType && RHSVecType && 8557 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8558 if (isa<ExtVectorType>(LHSVecType)) { 8559 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8560 return LHSType; 8561 } 8562 8563 if (!IsCompAssign) 8564 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8565 return RHSType; 8566 } 8567 8568 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8569 // can be mixed, with the result being the non-bool type. The non-bool 8570 // operand must have integer element type. 8571 if (AllowBoolConversions && LHSVecType && RHSVecType && 8572 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8573 (Context.getTypeSize(LHSVecType->getElementType()) == 8574 Context.getTypeSize(RHSVecType->getElementType()))) { 8575 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8576 LHSVecType->getElementType()->isIntegerType() && 8577 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8578 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8579 return LHSType; 8580 } 8581 if (!IsCompAssign && 8582 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8583 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8584 RHSVecType->getElementType()->isIntegerType()) { 8585 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8586 return RHSType; 8587 } 8588 } 8589 8590 // If there's a vector type and a scalar, try to convert the scalar to 8591 // the vector element type and splat. 8592 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8593 if (!RHSVecType) { 8594 if (isa<ExtVectorType>(LHSVecType)) { 8595 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8596 LHSVecType->getElementType(), LHSType, 8597 DiagID)) 8598 return LHSType; 8599 } else { 8600 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8601 return LHSType; 8602 } 8603 } 8604 if (!LHSVecType) { 8605 if (isa<ExtVectorType>(RHSVecType)) { 8606 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8607 LHSType, RHSVecType->getElementType(), 8608 RHSType, DiagID)) 8609 return RHSType; 8610 } else { 8611 if (LHS.get()->getValueKind() == VK_LValue || 8612 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8613 return RHSType; 8614 } 8615 } 8616 8617 // FIXME: The code below also handles conversion between vectors and 8618 // non-scalars, we should break this down into fine grained specific checks 8619 // and emit proper diagnostics. 8620 QualType VecType = LHSVecType ? LHSType : RHSType; 8621 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8622 QualType OtherType = LHSVecType ? RHSType : LHSType; 8623 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8624 if (isLaxVectorConversion(OtherType, VecType)) { 8625 // If we're allowing lax vector conversions, only the total (data) size 8626 // needs to be the same. For non compound assignment, if one of the types is 8627 // scalar, the result is always the vector type. 8628 if (!IsCompAssign) { 8629 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8630 return VecType; 8631 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8632 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8633 // type. Note that this is already done by non-compound assignments in 8634 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8635 // <1 x T> -> T. The result is also a vector type. 8636 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8637 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8638 ExprResult *RHSExpr = &RHS; 8639 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8640 return VecType; 8641 } 8642 } 8643 8644 // Okay, the expression is invalid. 8645 8646 // If there's a non-vector, non-real operand, diagnose that. 8647 if ((!RHSVecType && !RHSType->isRealType()) || 8648 (!LHSVecType && !LHSType->isRealType())) { 8649 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8650 << LHSType << RHSType 8651 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8652 return QualType(); 8653 } 8654 8655 // OpenCL V1.1 6.2.6.p1: 8656 // If the operands are of more than one vector type, then an error shall 8657 // occur. Implicit conversions between vector types are not permitted, per 8658 // section 6.2.1. 8659 if (getLangOpts().OpenCL && 8660 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8661 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8662 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8663 << RHSType; 8664 return QualType(); 8665 } 8666 8667 8668 // If there is a vector type that is not a ExtVector and a scalar, we reach 8669 // this point if scalar could not be converted to the vector's element type 8670 // without truncation. 8671 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8672 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8673 QualType Scalar = LHSVecType ? RHSType : LHSType; 8674 QualType Vector = LHSVecType ? LHSType : RHSType; 8675 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8676 Diag(Loc, 8677 diag::err_typecheck_vector_not_convertable_implict_truncation) 8678 << ScalarOrVector << Scalar << Vector; 8679 8680 return QualType(); 8681 } 8682 8683 // Otherwise, use the generic diagnostic. 8684 Diag(Loc, DiagID) 8685 << LHSType << RHSType 8686 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8687 return QualType(); 8688 } 8689 8690 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8691 // expression. These are mainly cases where the null pointer is used as an 8692 // integer instead of a pointer. 8693 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8694 SourceLocation Loc, bool IsCompare) { 8695 // The canonical way to check for a GNU null is with isNullPointerConstant, 8696 // but we use a bit of a hack here for speed; this is a relatively 8697 // hot path, and isNullPointerConstant is slow. 8698 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8699 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8700 8701 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8702 8703 // Avoid analyzing cases where the result will either be invalid (and 8704 // diagnosed as such) or entirely valid and not something to warn about. 8705 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8706 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8707 return; 8708 8709 // Comparison operations would not make sense with a null pointer no matter 8710 // what the other expression is. 8711 if (!IsCompare) { 8712 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8713 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8714 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8715 return; 8716 } 8717 8718 // The rest of the operations only make sense with a null pointer 8719 // if the other expression is a pointer. 8720 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8721 NonNullType->canDecayToPointerType()) 8722 return; 8723 8724 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8725 << LHSNull /* LHS is NULL */ << NonNullType 8726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8727 } 8728 8729 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8730 ExprResult &RHS, 8731 SourceLocation Loc, bool IsDiv) { 8732 // Check for division/remainder by zero. 8733 llvm::APSInt RHSValue; 8734 if (!RHS.get()->isValueDependent() && 8735 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8736 S.DiagRuntimeBehavior(Loc, RHS.get(), 8737 S.PDiag(diag::warn_remainder_division_by_zero) 8738 << IsDiv << RHS.get()->getSourceRange()); 8739 } 8740 8741 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8742 SourceLocation Loc, 8743 bool IsCompAssign, bool IsDiv) { 8744 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8745 8746 if (LHS.get()->getType()->isVectorType() || 8747 RHS.get()->getType()->isVectorType()) 8748 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8749 /*AllowBothBool*/getLangOpts().AltiVec, 8750 /*AllowBoolConversions*/false); 8751 8752 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8753 if (LHS.isInvalid() || RHS.isInvalid()) 8754 return QualType(); 8755 8756 8757 if (compType.isNull() || !compType->isArithmeticType()) 8758 return InvalidOperands(Loc, LHS, RHS); 8759 if (IsDiv) 8760 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8761 return compType; 8762 } 8763 8764 QualType Sema::CheckRemainderOperands( 8765 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8766 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8767 8768 if (LHS.get()->getType()->isVectorType() || 8769 RHS.get()->getType()->isVectorType()) { 8770 if (LHS.get()->getType()->hasIntegerRepresentation() && 8771 RHS.get()->getType()->hasIntegerRepresentation()) 8772 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8773 /*AllowBothBool*/getLangOpts().AltiVec, 8774 /*AllowBoolConversions*/false); 8775 return InvalidOperands(Loc, LHS, RHS); 8776 } 8777 8778 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8779 if (LHS.isInvalid() || RHS.isInvalid()) 8780 return QualType(); 8781 8782 if (compType.isNull() || !compType->isIntegerType()) 8783 return InvalidOperands(Loc, LHS, RHS); 8784 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8785 return compType; 8786 } 8787 8788 /// Diagnose invalid arithmetic on two void pointers. 8789 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8790 Expr *LHSExpr, Expr *RHSExpr) { 8791 S.Diag(Loc, S.getLangOpts().CPlusPlus 8792 ? diag::err_typecheck_pointer_arith_void_type 8793 : diag::ext_gnu_void_ptr) 8794 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8795 << RHSExpr->getSourceRange(); 8796 } 8797 8798 /// Diagnose invalid arithmetic on a void pointer. 8799 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8800 Expr *Pointer) { 8801 S.Diag(Loc, S.getLangOpts().CPlusPlus 8802 ? diag::err_typecheck_pointer_arith_void_type 8803 : diag::ext_gnu_void_ptr) 8804 << 0 /* one pointer */ << Pointer->getSourceRange(); 8805 } 8806 8807 /// Diagnose invalid arithmetic on a null pointer. 8808 /// 8809 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8810 /// idiom, which we recognize as a GNU extension. 8811 /// 8812 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8813 Expr *Pointer, bool IsGNUIdiom) { 8814 if (IsGNUIdiom) 8815 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8816 << Pointer->getSourceRange(); 8817 else 8818 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8819 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8820 } 8821 8822 /// Diagnose invalid arithmetic on two function pointers. 8823 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8824 Expr *LHS, Expr *RHS) { 8825 assert(LHS->getType()->isAnyPointerType()); 8826 assert(RHS->getType()->isAnyPointerType()); 8827 S.Diag(Loc, S.getLangOpts().CPlusPlus 8828 ? diag::err_typecheck_pointer_arith_function_type 8829 : diag::ext_gnu_ptr_func_arith) 8830 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8831 // We only show the second type if it differs from the first. 8832 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8833 RHS->getType()) 8834 << RHS->getType()->getPointeeType() 8835 << LHS->getSourceRange() << RHS->getSourceRange(); 8836 } 8837 8838 /// Diagnose invalid arithmetic on a function pointer. 8839 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8840 Expr *Pointer) { 8841 assert(Pointer->getType()->isAnyPointerType()); 8842 S.Diag(Loc, S.getLangOpts().CPlusPlus 8843 ? diag::err_typecheck_pointer_arith_function_type 8844 : diag::ext_gnu_ptr_func_arith) 8845 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8846 << 0 /* one pointer, so only one type */ 8847 << Pointer->getSourceRange(); 8848 } 8849 8850 /// Emit error if Operand is incomplete pointer type 8851 /// 8852 /// \returns True if pointer has incomplete type 8853 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8854 Expr *Operand) { 8855 QualType ResType = Operand->getType(); 8856 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8857 ResType = ResAtomicType->getValueType(); 8858 8859 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8860 QualType PointeeTy = ResType->getPointeeType(); 8861 return S.RequireCompleteType(Loc, PointeeTy, 8862 diag::err_typecheck_arithmetic_incomplete_type, 8863 PointeeTy, Operand->getSourceRange()); 8864 } 8865 8866 /// Check the validity of an arithmetic pointer operand. 8867 /// 8868 /// If the operand has pointer type, this code will check for pointer types 8869 /// which are invalid in arithmetic operations. These will be diagnosed 8870 /// appropriately, including whether or not the use is supported as an 8871 /// extension. 8872 /// 8873 /// \returns True when the operand is valid to use (even if as an extension). 8874 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8875 Expr *Operand) { 8876 QualType ResType = Operand->getType(); 8877 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8878 ResType = ResAtomicType->getValueType(); 8879 8880 if (!ResType->isAnyPointerType()) return true; 8881 8882 QualType PointeeTy = ResType->getPointeeType(); 8883 if (PointeeTy->isVoidType()) { 8884 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8885 return !S.getLangOpts().CPlusPlus; 8886 } 8887 if (PointeeTy->isFunctionType()) { 8888 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8889 return !S.getLangOpts().CPlusPlus; 8890 } 8891 8892 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8893 8894 return true; 8895 } 8896 8897 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8898 /// operands. 8899 /// 8900 /// This routine will diagnose any invalid arithmetic on pointer operands much 8901 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8902 /// for emitting a single diagnostic even for operations where both LHS and RHS 8903 /// are (potentially problematic) pointers. 8904 /// 8905 /// \returns True when the operand is valid to use (even if as an extension). 8906 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8907 Expr *LHSExpr, Expr *RHSExpr) { 8908 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8909 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8910 if (!isLHSPointer && !isRHSPointer) return true; 8911 8912 QualType LHSPointeeTy, RHSPointeeTy; 8913 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8914 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8915 8916 // if both are pointers check if operation is valid wrt address spaces 8917 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8918 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8919 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8920 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8921 S.Diag(Loc, 8922 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8923 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8924 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8925 return false; 8926 } 8927 } 8928 8929 // Check for arithmetic on pointers to incomplete types. 8930 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8931 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8932 if (isLHSVoidPtr || isRHSVoidPtr) { 8933 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8934 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8935 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8936 8937 return !S.getLangOpts().CPlusPlus; 8938 } 8939 8940 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8941 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8942 if (isLHSFuncPtr || isRHSFuncPtr) { 8943 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8944 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8945 RHSExpr); 8946 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8947 8948 return !S.getLangOpts().CPlusPlus; 8949 } 8950 8951 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8952 return false; 8953 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8954 return false; 8955 8956 return true; 8957 } 8958 8959 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8960 /// literal. 8961 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8962 Expr *LHSExpr, Expr *RHSExpr) { 8963 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8964 Expr* IndexExpr = RHSExpr; 8965 if (!StrExpr) { 8966 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8967 IndexExpr = LHSExpr; 8968 } 8969 8970 bool IsStringPlusInt = StrExpr && 8971 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8972 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8973 return; 8974 8975 llvm::APSInt index; 8976 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8977 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8978 if (index.isNonNegative() && 8979 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8980 index.isUnsigned())) 8981 return; 8982 } 8983 8984 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8985 Self.Diag(OpLoc, diag::warn_string_plus_int) 8986 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8987 8988 // Only print a fixit for "str" + int, not for int + "str". 8989 if (IndexExpr == RHSExpr) { 8990 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8991 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8992 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8993 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8994 << FixItHint::CreateInsertion(EndLoc, "]"); 8995 } else 8996 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8997 } 8998 8999 /// Emit a warning when adding a char literal to a string. 9000 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9001 Expr *LHSExpr, Expr *RHSExpr) { 9002 const Expr *StringRefExpr = LHSExpr; 9003 const CharacterLiteral *CharExpr = 9004 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9005 9006 if (!CharExpr) { 9007 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9008 StringRefExpr = RHSExpr; 9009 } 9010 9011 if (!CharExpr || !StringRefExpr) 9012 return; 9013 9014 const QualType StringType = StringRefExpr->getType(); 9015 9016 // Return if not a PointerType. 9017 if (!StringType->isAnyPointerType()) 9018 return; 9019 9020 // Return if not a CharacterType. 9021 if (!StringType->getPointeeType()->isAnyCharacterType()) 9022 return; 9023 9024 ASTContext &Ctx = Self.getASTContext(); 9025 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9026 9027 const QualType CharType = CharExpr->getType(); 9028 if (!CharType->isAnyCharacterType() && 9029 CharType->isIntegerType() && 9030 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9031 Self.Diag(OpLoc, diag::warn_string_plus_char) 9032 << DiagRange << Ctx.CharTy; 9033 } else { 9034 Self.Diag(OpLoc, diag::warn_string_plus_char) 9035 << DiagRange << CharExpr->getType(); 9036 } 9037 9038 // Only print a fixit for str + char, not for char + str. 9039 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9040 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9041 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9042 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9043 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9044 << FixItHint::CreateInsertion(EndLoc, "]"); 9045 } else { 9046 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9047 } 9048 } 9049 9050 /// Emit error when two pointers are incompatible. 9051 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9052 Expr *LHSExpr, Expr *RHSExpr) { 9053 assert(LHSExpr->getType()->isAnyPointerType()); 9054 assert(RHSExpr->getType()->isAnyPointerType()); 9055 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9056 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9057 << RHSExpr->getSourceRange(); 9058 } 9059 9060 // C99 6.5.6 9061 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9062 SourceLocation Loc, BinaryOperatorKind Opc, 9063 QualType* CompLHSTy) { 9064 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9065 9066 if (LHS.get()->getType()->isVectorType() || 9067 RHS.get()->getType()->isVectorType()) { 9068 QualType compType = CheckVectorOperands( 9069 LHS, RHS, Loc, CompLHSTy, 9070 /*AllowBothBool*/getLangOpts().AltiVec, 9071 /*AllowBoolConversions*/getLangOpts().ZVector); 9072 if (CompLHSTy) *CompLHSTy = compType; 9073 return compType; 9074 } 9075 9076 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9077 if (LHS.isInvalid() || RHS.isInvalid()) 9078 return QualType(); 9079 9080 // Diagnose "string literal" '+' int and string '+' "char literal". 9081 if (Opc == BO_Add) { 9082 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9083 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9084 } 9085 9086 // handle the common case first (both operands are arithmetic). 9087 if (!compType.isNull() && compType->isArithmeticType()) { 9088 if (CompLHSTy) *CompLHSTy = compType; 9089 return compType; 9090 } 9091 9092 // Type-checking. Ultimately the pointer's going to be in PExp; 9093 // note that we bias towards the LHS being the pointer. 9094 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9095 9096 bool isObjCPointer; 9097 if (PExp->getType()->isPointerType()) { 9098 isObjCPointer = false; 9099 } else if (PExp->getType()->isObjCObjectPointerType()) { 9100 isObjCPointer = true; 9101 } else { 9102 std::swap(PExp, IExp); 9103 if (PExp->getType()->isPointerType()) { 9104 isObjCPointer = false; 9105 } else if (PExp->getType()->isObjCObjectPointerType()) { 9106 isObjCPointer = true; 9107 } else { 9108 return InvalidOperands(Loc, LHS, RHS); 9109 } 9110 } 9111 assert(PExp->getType()->isAnyPointerType()); 9112 9113 if (!IExp->getType()->isIntegerType()) 9114 return InvalidOperands(Loc, LHS, RHS); 9115 9116 // Adding to a null pointer results in undefined behavior. 9117 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9118 Context, Expr::NPC_ValueDependentIsNotNull)) { 9119 // In C++ adding zero to a null pointer is defined. 9120 llvm::APSInt KnownVal; 9121 if (!getLangOpts().CPlusPlus || 9122 (!IExp->isValueDependent() && 9123 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9124 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9125 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9126 Context, BO_Add, PExp, IExp); 9127 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9128 } 9129 } 9130 9131 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9132 return QualType(); 9133 9134 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9135 return QualType(); 9136 9137 // Check array bounds for pointer arithemtic 9138 CheckArrayAccess(PExp, IExp); 9139 9140 if (CompLHSTy) { 9141 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9142 if (LHSTy.isNull()) { 9143 LHSTy = LHS.get()->getType(); 9144 if (LHSTy->isPromotableIntegerType()) 9145 LHSTy = Context.getPromotedIntegerType(LHSTy); 9146 } 9147 *CompLHSTy = LHSTy; 9148 } 9149 9150 return PExp->getType(); 9151 } 9152 9153 // C99 6.5.6 9154 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9155 SourceLocation Loc, 9156 QualType* CompLHSTy) { 9157 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9158 9159 if (LHS.get()->getType()->isVectorType() || 9160 RHS.get()->getType()->isVectorType()) { 9161 QualType compType = CheckVectorOperands( 9162 LHS, RHS, Loc, CompLHSTy, 9163 /*AllowBothBool*/getLangOpts().AltiVec, 9164 /*AllowBoolConversions*/getLangOpts().ZVector); 9165 if (CompLHSTy) *CompLHSTy = compType; 9166 return compType; 9167 } 9168 9169 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9170 if (LHS.isInvalid() || RHS.isInvalid()) 9171 return QualType(); 9172 9173 // Enforce type constraints: C99 6.5.6p3. 9174 9175 // Handle the common case first (both operands are arithmetic). 9176 if (!compType.isNull() && compType->isArithmeticType()) { 9177 if (CompLHSTy) *CompLHSTy = compType; 9178 return compType; 9179 } 9180 9181 // Either ptr - int or ptr - ptr. 9182 if (LHS.get()->getType()->isAnyPointerType()) { 9183 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9184 9185 // Diagnose bad cases where we step over interface counts. 9186 if (LHS.get()->getType()->isObjCObjectPointerType() && 9187 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9188 return QualType(); 9189 9190 // The result type of a pointer-int computation is the pointer type. 9191 if (RHS.get()->getType()->isIntegerType()) { 9192 // Subtracting from a null pointer should produce a warning. 9193 // The last argument to the diagnose call says this doesn't match the 9194 // GNU int-to-pointer idiom. 9195 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9196 Expr::NPC_ValueDependentIsNotNull)) { 9197 // In C++ adding zero to a null pointer is defined. 9198 llvm::APSInt KnownVal; 9199 if (!getLangOpts().CPlusPlus || 9200 (!RHS.get()->isValueDependent() && 9201 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9202 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9203 } 9204 } 9205 9206 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9207 return QualType(); 9208 9209 // Check array bounds for pointer arithemtic 9210 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9211 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9212 9213 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9214 return LHS.get()->getType(); 9215 } 9216 9217 // Handle pointer-pointer subtractions. 9218 if (const PointerType *RHSPTy 9219 = RHS.get()->getType()->getAs<PointerType>()) { 9220 QualType rpointee = RHSPTy->getPointeeType(); 9221 9222 if (getLangOpts().CPlusPlus) { 9223 // Pointee types must be the same: C++ [expr.add] 9224 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9225 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9226 } 9227 } else { 9228 // Pointee types must be compatible C99 6.5.6p3 9229 if (!Context.typesAreCompatible( 9230 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9231 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9232 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9233 return QualType(); 9234 } 9235 } 9236 9237 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9238 LHS.get(), RHS.get())) 9239 return QualType(); 9240 9241 // FIXME: Add warnings for nullptr - ptr. 9242 9243 // The pointee type may have zero size. As an extension, a structure or 9244 // union may have zero size or an array may have zero length. In this 9245 // case subtraction does not make sense. 9246 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9247 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9248 if (ElementSize.isZero()) { 9249 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9250 << rpointee.getUnqualifiedType() 9251 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9252 } 9253 } 9254 9255 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9256 return Context.getPointerDiffType(); 9257 } 9258 } 9259 9260 return InvalidOperands(Loc, LHS, RHS); 9261 } 9262 9263 static bool isScopedEnumerationType(QualType T) { 9264 if (const EnumType *ET = T->getAs<EnumType>()) 9265 return ET->getDecl()->isScoped(); 9266 return false; 9267 } 9268 9269 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9270 SourceLocation Loc, BinaryOperatorKind Opc, 9271 QualType LHSType) { 9272 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9273 // so skip remaining warnings as we don't want to modify values within Sema. 9274 if (S.getLangOpts().OpenCL) 9275 return; 9276 9277 llvm::APSInt Right; 9278 // Check right/shifter operand 9279 if (RHS.get()->isValueDependent() || 9280 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9281 return; 9282 9283 if (Right.isNegative()) { 9284 S.DiagRuntimeBehavior(Loc, RHS.get(), 9285 S.PDiag(diag::warn_shift_negative) 9286 << RHS.get()->getSourceRange()); 9287 return; 9288 } 9289 llvm::APInt LeftBits(Right.getBitWidth(), 9290 S.Context.getTypeSize(LHS.get()->getType())); 9291 if (Right.uge(LeftBits)) { 9292 S.DiagRuntimeBehavior(Loc, RHS.get(), 9293 S.PDiag(diag::warn_shift_gt_typewidth) 9294 << RHS.get()->getSourceRange()); 9295 return; 9296 } 9297 if (Opc != BO_Shl) 9298 return; 9299 9300 // When left shifting an ICE which is signed, we can check for overflow which 9301 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9302 // integers have defined behavior modulo one more than the maximum value 9303 // representable in the result type, so never warn for those. 9304 llvm::APSInt Left; 9305 if (LHS.get()->isValueDependent() || 9306 LHSType->hasUnsignedIntegerRepresentation() || 9307 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9308 return; 9309 9310 // If LHS does not have a signed type and non-negative value 9311 // then, the behavior is undefined. Warn about it. 9312 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9313 S.DiagRuntimeBehavior(Loc, LHS.get(), 9314 S.PDiag(diag::warn_shift_lhs_negative) 9315 << LHS.get()->getSourceRange()); 9316 return; 9317 } 9318 9319 llvm::APInt ResultBits = 9320 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9321 if (LeftBits.uge(ResultBits)) 9322 return; 9323 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9324 Result = Result.shl(Right); 9325 9326 // Print the bit representation of the signed integer as an unsigned 9327 // hexadecimal number. 9328 SmallString<40> HexResult; 9329 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9330 9331 // If we are only missing a sign bit, this is less likely to result in actual 9332 // bugs -- if the result is cast back to an unsigned type, it will have the 9333 // expected value. Thus we place this behind a different warning that can be 9334 // turned off separately if needed. 9335 if (LeftBits == ResultBits - 1) { 9336 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9337 << HexResult << LHSType 9338 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9339 return; 9340 } 9341 9342 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9343 << HexResult.str() << Result.getMinSignedBits() << LHSType 9344 << Left.getBitWidth() << LHS.get()->getSourceRange() 9345 << RHS.get()->getSourceRange(); 9346 } 9347 9348 /// Return the resulting type when a vector is shifted 9349 /// by a scalar or vector shift amount. 9350 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9351 SourceLocation Loc, bool IsCompAssign) { 9352 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9353 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9354 !LHS.get()->getType()->isVectorType()) { 9355 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9356 << RHS.get()->getType() << LHS.get()->getType() 9357 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9358 return QualType(); 9359 } 9360 9361 if (!IsCompAssign) { 9362 LHS = S.UsualUnaryConversions(LHS.get()); 9363 if (LHS.isInvalid()) return QualType(); 9364 } 9365 9366 RHS = S.UsualUnaryConversions(RHS.get()); 9367 if (RHS.isInvalid()) return QualType(); 9368 9369 QualType LHSType = LHS.get()->getType(); 9370 // Note that LHS might be a scalar because the routine calls not only in 9371 // OpenCL case. 9372 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9373 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9374 9375 // Note that RHS might not be a vector. 9376 QualType RHSType = RHS.get()->getType(); 9377 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9378 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9379 9380 // The operands need to be integers. 9381 if (!LHSEleType->isIntegerType()) { 9382 S.Diag(Loc, diag::err_typecheck_expect_int) 9383 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9384 return QualType(); 9385 } 9386 9387 if (!RHSEleType->isIntegerType()) { 9388 S.Diag(Loc, diag::err_typecheck_expect_int) 9389 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9390 return QualType(); 9391 } 9392 9393 if (!LHSVecTy) { 9394 assert(RHSVecTy); 9395 if (IsCompAssign) 9396 return RHSType; 9397 if (LHSEleType != RHSEleType) { 9398 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9399 LHSEleType = RHSEleType; 9400 } 9401 QualType VecTy = 9402 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9403 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9404 LHSType = VecTy; 9405 } else if (RHSVecTy) { 9406 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9407 // are applied component-wise. So if RHS is a vector, then ensure 9408 // that the number of elements is the same as LHS... 9409 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9410 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9411 << LHS.get()->getType() << RHS.get()->getType() 9412 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9413 return QualType(); 9414 } 9415 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9416 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9417 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9418 if (LHSBT != RHSBT && 9419 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9420 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9421 << LHS.get()->getType() << RHS.get()->getType() 9422 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9423 } 9424 } 9425 } else { 9426 // ...else expand RHS to match the number of elements in LHS. 9427 QualType VecTy = 9428 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9429 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9430 } 9431 9432 return LHSType; 9433 } 9434 9435 // C99 6.5.7 9436 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9437 SourceLocation Loc, BinaryOperatorKind Opc, 9438 bool IsCompAssign) { 9439 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9440 9441 // Vector shifts promote their scalar inputs to vector type. 9442 if (LHS.get()->getType()->isVectorType() || 9443 RHS.get()->getType()->isVectorType()) { 9444 if (LangOpts.ZVector) { 9445 // The shift operators for the z vector extensions work basically 9446 // like general shifts, except that neither the LHS nor the RHS is 9447 // allowed to be a "vector bool". 9448 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9449 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9450 return InvalidOperands(Loc, LHS, RHS); 9451 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9452 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9453 return InvalidOperands(Loc, LHS, RHS); 9454 } 9455 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9456 } 9457 9458 // Shifts don't perform usual arithmetic conversions, they just do integer 9459 // promotions on each operand. C99 6.5.7p3 9460 9461 // For the LHS, do usual unary conversions, but then reset them away 9462 // if this is a compound assignment. 9463 ExprResult OldLHS = LHS; 9464 LHS = UsualUnaryConversions(LHS.get()); 9465 if (LHS.isInvalid()) 9466 return QualType(); 9467 QualType LHSType = LHS.get()->getType(); 9468 if (IsCompAssign) LHS = OldLHS; 9469 9470 // The RHS is simpler. 9471 RHS = UsualUnaryConversions(RHS.get()); 9472 if (RHS.isInvalid()) 9473 return QualType(); 9474 QualType RHSType = RHS.get()->getType(); 9475 9476 // C99 6.5.7p2: Each of the operands shall have integer type. 9477 if (!LHSType->hasIntegerRepresentation() || 9478 !RHSType->hasIntegerRepresentation()) 9479 return InvalidOperands(Loc, LHS, RHS); 9480 9481 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9482 // hasIntegerRepresentation() above instead of this. 9483 if (isScopedEnumerationType(LHSType) || 9484 isScopedEnumerationType(RHSType)) { 9485 return InvalidOperands(Loc, LHS, RHS); 9486 } 9487 // Sanity-check shift operands 9488 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9489 9490 // "The type of the result is that of the promoted left operand." 9491 return LHSType; 9492 } 9493 9494 /// If two different enums are compared, raise a warning. 9495 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9496 Expr *RHS) { 9497 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9498 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9499 9500 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9501 if (!LHSEnumType) 9502 return; 9503 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9504 if (!RHSEnumType) 9505 return; 9506 9507 // Ignore anonymous enums. 9508 if (!LHSEnumType->getDecl()->getIdentifier() && 9509 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9510 return; 9511 if (!RHSEnumType->getDecl()->getIdentifier() && 9512 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9513 return; 9514 9515 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9516 return; 9517 9518 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9519 << LHSStrippedType << RHSStrippedType 9520 << LHS->getSourceRange() << RHS->getSourceRange(); 9521 } 9522 9523 /// Diagnose bad pointer comparisons. 9524 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9525 ExprResult &LHS, ExprResult &RHS, 9526 bool IsError) { 9527 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9528 : diag::ext_typecheck_comparison_of_distinct_pointers) 9529 << LHS.get()->getType() << RHS.get()->getType() 9530 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9531 } 9532 9533 /// Returns false if the pointers are converted to a composite type, 9534 /// true otherwise. 9535 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9536 ExprResult &LHS, ExprResult &RHS) { 9537 // C++ [expr.rel]p2: 9538 // [...] Pointer conversions (4.10) and qualification 9539 // conversions (4.4) are performed on pointer operands (or on 9540 // a pointer operand and a null pointer constant) to bring 9541 // them to their composite pointer type. [...] 9542 // 9543 // C++ [expr.eq]p1 uses the same notion for (in)equality 9544 // comparisons of pointers. 9545 9546 QualType LHSType = LHS.get()->getType(); 9547 QualType RHSType = RHS.get()->getType(); 9548 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9549 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9550 9551 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9552 if (T.isNull()) { 9553 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9554 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9555 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9556 else 9557 S.InvalidOperands(Loc, LHS, RHS); 9558 return true; 9559 } 9560 9561 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9562 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9563 return false; 9564 } 9565 9566 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9567 ExprResult &LHS, 9568 ExprResult &RHS, 9569 bool IsError) { 9570 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9571 : diag::ext_typecheck_comparison_of_fptr_to_void) 9572 << LHS.get()->getType() << RHS.get()->getType() 9573 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9574 } 9575 9576 static bool isObjCObjectLiteral(ExprResult &E) { 9577 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9578 case Stmt::ObjCArrayLiteralClass: 9579 case Stmt::ObjCDictionaryLiteralClass: 9580 case Stmt::ObjCStringLiteralClass: 9581 case Stmt::ObjCBoxedExprClass: 9582 return true; 9583 default: 9584 // Note that ObjCBoolLiteral is NOT an object literal! 9585 return false; 9586 } 9587 } 9588 9589 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9590 const ObjCObjectPointerType *Type = 9591 LHS->getType()->getAs<ObjCObjectPointerType>(); 9592 9593 // If this is not actually an Objective-C object, bail out. 9594 if (!Type) 9595 return false; 9596 9597 // Get the LHS object's interface type. 9598 QualType InterfaceType = Type->getPointeeType(); 9599 9600 // If the RHS isn't an Objective-C object, bail out. 9601 if (!RHS->getType()->isObjCObjectPointerType()) 9602 return false; 9603 9604 // Try to find the -isEqual: method. 9605 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9606 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9607 InterfaceType, 9608 /*instance=*/true); 9609 if (!Method) { 9610 if (Type->isObjCIdType()) { 9611 // For 'id', just check the global pool. 9612 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9613 /*receiverId=*/true); 9614 } else { 9615 // Check protocols. 9616 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9617 /*instance=*/true); 9618 } 9619 } 9620 9621 if (!Method) 9622 return false; 9623 9624 QualType T = Method->parameters()[0]->getType(); 9625 if (!T->isObjCObjectPointerType()) 9626 return false; 9627 9628 QualType R = Method->getReturnType(); 9629 if (!R->isScalarType()) 9630 return false; 9631 9632 return true; 9633 } 9634 9635 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9636 FromE = FromE->IgnoreParenImpCasts(); 9637 switch (FromE->getStmtClass()) { 9638 default: 9639 break; 9640 case Stmt::ObjCStringLiteralClass: 9641 // "string literal" 9642 return LK_String; 9643 case Stmt::ObjCArrayLiteralClass: 9644 // "array literal" 9645 return LK_Array; 9646 case Stmt::ObjCDictionaryLiteralClass: 9647 // "dictionary literal" 9648 return LK_Dictionary; 9649 case Stmt::BlockExprClass: 9650 return LK_Block; 9651 case Stmt::ObjCBoxedExprClass: { 9652 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9653 switch (Inner->getStmtClass()) { 9654 case Stmt::IntegerLiteralClass: 9655 case Stmt::FloatingLiteralClass: 9656 case Stmt::CharacterLiteralClass: 9657 case Stmt::ObjCBoolLiteralExprClass: 9658 case Stmt::CXXBoolLiteralExprClass: 9659 // "numeric literal" 9660 return LK_Numeric; 9661 case Stmt::ImplicitCastExprClass: { 9662 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9663 // Boolean literals can be represented by implicit casts. 9664 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9665 return LK_Numeric; 9666 break; 9667 } 9668 default: 9669 break; 9670 } 9671 return LK_Boxed; 9672 } 9673 } 9674 return LK_None; 9675 } 9676 9677 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9678 ExprResult &LHS, ExprResult &RHS, 9679 BinaryOperator::Opcode Opc){ 9680 Expr *Literal; 9681 Expr *Other; 9682 if (isObjCObjectLiteral(LHS)) { 9683 Literal = LHS.get(); 9684 Other = RHS.get(); 9685 } else { 9686 Literal = RHS.get(); 9687 Other = LHS.get(); 9688 } 9689 9690 // Don't warn on comparisons against nil. 9691 Other = Other->IgnoreParenCasts(); 9692 if (Other->isNullPointerConstant(S.getASTContext(), 9693 Expr::NPC_ValueDependentIsNotNull)) 9694 return; 9695 9696 // This should be kept in sync with warn_objc_literal_comparison. 9697 // LK_String should always be after the other literals, since it has its own 9698 // warning flag. 9699 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9700 assert(LiteralKind != Sema::LK_Block); 9701 if (LiteralKind == Sema::LK_None) { 9702 llvm_unreachable("Unknown Objective-C object literal kind"); 9703 } 9704 9705 if (LiteralKind == Sema::LK_String) 9706 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9707 << Literal->getSourceRange(); 9708 else 9709 S.Diag(Loc, diag::warn_objc_literal_comparison) 9710 << LiteralKind << Literal->getSourceRange(); 9711 9712 if (BinaryOperator::isEqualityOp(Opc) && 9713 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9714 SourceLocation Start = LHS.get()->getBeginLoc(); 9715 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9716 CharSourceRange OpRange = 9717 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9718 9719 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9720 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9721 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9722 << FixItHint::CreateInsertion(End, "]"); 9723 } 9724 } 9725 9726 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9727 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9728 ExprResult &RHS, SourceLocation Loc, 9729 BinaryOperatorKind Opc) { 9730 // Check that left hand side is !something. 9731 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9732 if (!UO || UO->getOpcode() != UO_LNot) return; 9733 9734 // Only check if the right hand side is non-bool arithmetic type. 9735 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9736 9737 // Make sure that the something in !something is not bool. 9738 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9739 if (SubExpr->isKnownToHaveBooleanValue()) return; 9740 9741 // Emit warning. 9742 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9743 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9744 << Loc << IsBitwiseOp; 9745 9746 // First note suggest !(x < y) 9747 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9748 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9749 FirstClose = S.getLocForEndOfToken(FirstClose); 9750 if (FirstClose.isInvalid()) 9751 FirstOpen = SourceLocation(); 9752 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9753 << IsBitwiseOp 9754 << FixItHint::CreateInsertion(FirstOpen, "(") 9755 << FixItHint::CreateInsertion(FirstClose, ")"); 9756 9757 // Second note suggests (!x) < y 9758 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9759 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9760 SecondClose = S.getLocForEndOfToken(SecondClose); 9761 if (SecondClose.isInvalid()) 9762 SecondOpen = SourceLocation(); 9763 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9764 << FixItHint::CreateInsertion(SecondOpen, "(") 9765 << FixItHint::CreateInsertion(SecondClose, ")"); 9766 } 9767 9768 // Get the decl for a simple expression: a reference to a variable, 9769 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9770 static ValueDecl *getCompareDecl(Expr *E) { 9771 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9772 return DR->getDecl(); 9773 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9774 if (Ivar->isFreeIvar()) 9775 return Ivar->getDecl(); 9776 } 9777 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9778 if (Mem->isImplicitAccess()) 9779 return Mem->getMemberDecl(); 9780 } 9781 return nullptr; 9782 } 9783 9784 /// Diagnose some forms of syntactically-obvious tautological comparison. 9785 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9786 Expr *LHS, Expr *RHS, 9787 BinaryOperatorKind Opc) { 9788 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9789 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9790 9791 QualType LHSType = LHS->getType(); 9792 QualType RHSType = RHS->getType(); 9793 if (LHSType->hasFloatingRepresentation() || 9794 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9795 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9796 S.inTemplateInstantiation()) 9797 return; 9798 9799 // Comparisons between two array types are ill-formed for operator<=>, so 9800 // we shouldn't emit any additional warnings about it. 9801 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9802 return; 9803 9804 // For non-floating point types, check for self-comparisons of the form 9805 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9806 // often indicate logic errors in the program. 9807 // 9808 // NOTE: Don't warn about comparison expressions resulting from macro 9809 // expansion. Also don't warn about comparisons which are only self 9810 // comparisons within a template instantiation. The warnings should catch 9811 // obvious cases in the definition of the template anyways. The idea is to 9812 // warn when the typed comparison operator will always evaluate to the same 9813 // result. 9814 ValueDecl *DL = getCompareDecl(LHSStripped); 9815 ValueDecl *DR = getCompareDecl(RHSStripped); 9816 if (DL && DR && declaresSameEntity(DL, DR)) { 9817 StringRef Result; 9818 switch (Opc) { 9819 case BO_EQ: case BO_LE: case BO_GE: 9820 Result = "true"; 9821 break; 9822 case BO_NE: case BO_LT: case BO_GT: 9823 Result = "false"; 9824 break; 9825 case BO_Cmp: 9826 Result = "'std::strong_ordering::equal'"; 9827 break; 9828 default: 9829 break; 9830 } 9831 S.DiagRuntimeBehavior(Loc, nullptr, 9832 S.PDiag(diag::warn_comparison_always) 9833 << 0 /*self-comparison*/ << !Result.empty() 9834 << Result); 9835 } else if (DL && DR && 9836 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9837 !DL->isWeak() && !DR->isWeak()) { 9838 // What is it always going to evaluate to? 9839 StringRef Result; 9840 switch(Opc) { 9841 case BO_EQ: // e.g. array1 == array2 9842 Result = "false"; 9843 break; 9844 case BO_NE: // e.g. array1 != array2 9845 Result = "true"; 9846 break; 9847 default: // e.g. array1 <= array2 9848 // The best we can say is 'a constant' 9849 break; 9850 } 9851 S.DiagRuntimeBehavior(Loc, nullptr, 9852 S.PDiag(diag::warn_comparison_always) 9853 << 1 /*array comparison*/ 9854 << !Result.empty() << Result); 9855 } 9856 9857 if (isa<CastExpr>(LHSStripped)) 9858 LHSStripped = LHSStripped->IgnoreParenCasts(); 9859 if (isa<CastExpr>(RHSStripped)) 9860 RHSStripped = RHSStripped->IgnoreParenCasts(); 9861 9862 // Warn about comparisons against a string constant (unless the other 9863 // operand is null); the user probably wants strcmp. 9864 Expr *LiteralString = nullptr; 9865 Expr *LiteralStringStripped = nullptr; 9866 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9867 !RHSStripped->isNullPointerConstant(S.Context, 9868 Expr::NPC_ValueDependentIsNull)) { 9869 LiteralString = LHS; 9870 LiteralStringStripped = LHSStripped; 9871 } else if ((isa<StringLiteral>(RHSStripped) || 9872 isa<ObjCEncodeExpr>(RHSStripped)) && 9873 !LHSStripped->isNullPointerConstant(S.Context, 9874 Expr::NPC_ValueDependentIsNull)) { 9875 LiteralString = RHS; 9876 LiteralStringStripped = RHSStripped; 9877 } 9878 9879 if (LiteralString) { 9880 S.DiagRuntimeBehavior(Loc, nullptr, 9881 S.PDiag(diag::warn_stringcompare) 9882 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9883 << LiteralString->getSourceRange()); 9884 } 9885 } 9886 9887 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9888 switch (CK) { 9889 default: { 9890 #ifndef NDEBUG 9891 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9892 << "\n"; 9893 #endif 9894 llvm_unreachable("unhandled cast kind"); 9895 } 9896 case CK_UserDefinedConversion: 9897 return ICK_Identity; 9898 case CK_LValueToRValue: 9899 return ICK_Lvalue_To_Rvalue; 9900 case CK_ArrayToPointerDecay: 9901 return ICK_Array_To_Pointer; 9902 case CK_FunctionToPointerDecay: 9903 return ICK_Function_To_Pointer; 9904 case CK_IntegralCast: 9905 return ICK_Integral_Conversion; 9906 case CK_FloatingCast: 9907 return ICK_Floating_Conversion; 9908 case CK_IntegralToFloating: 9909 case CK_FloatingToIntegral: 9910 return ICK_Floating_Integral; 9911 case CK_IntegralComplexCast: 9912 case CK_FloatingComplexCast: 9913 case CK_FloatingComplexToIntegralComplex: 9914 case CK_IntegralComplexToFloatingComplex: 9915 return ICK_Complex_Conversion; 9916 case CK_FloatingComplexToReal: 9917 case CK_FloatingRealToComplex: 9918 case CK_IntegralComplexToReal: 9919 case CK_IntegralRealToComplex: 9920 return ICK_Complex_Real; 9921 } 9922 } 9923 9924 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9925 QualType FromType, 9926 SourceLocation Loc) { 9927 // Check for a narrowing implicit conversion. 9928 StandardConversionSequence SCS; 9929 SCS.setAsIdentityConversion(); 9930 SCS.setToType(0, FromType); 9931 SCS.setToType(1, ToType); 9932 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9933 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9934 9935 APValue PreNarrowingValue; 9936 QualType PreNarrowingType; 9937 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9938 PreNarrowingType, 9939 /*IgnoreFloatToIntegralConversion*/ true)) { 9940 case NK_Dependent_Narrowing: 9941 // Implicit conversion to a narrower type, but the expression is 9942 // value-dependent so we can't tell whether it's actually narrowing. 9943 case NK_Not_Narrowing: 9944 return false; 9945 9946 case NK_Constant_Narrowing: 9947 // Implicit conversion to a narrower type, and the value is not a constant 9948 // expression. 9949 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9950 << /*Constant*/ 1 9951 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9952 return true; 9953 9954 case NK_Variable_Narrowing: 9955 // Implicit conversion to a narrower type, and the value is not a constant 9956 // expression. 9957 case NK_Type_Narrowing: 9958 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9959 << /*Constant*/ 0 << FromType << ToType; 9960 // TODO: It's not a constant expression, but what if the user intended it 9961 // to be? Can we produce notes to help them figure out why it isn't? 9962 return true; 9963 } 9964 llvm_unreachable("unhandled case in switch"); 9965 } 9966 9967 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9968 ExprResult &LHS, 9969 ExprResult &RHS, 9970 SourceLocation Loc) { 9971 using CCT = ComparisonCategoryType; 9972 9973 QualType LHSType = LHS.get()->getType(); 9974 QualType RHSType = RHS.get()->getType(); 9975 // Dig out the original argument type and expression before implicit casts 9976 // were applied. These are the types/expressions we need to check the 9977 // [expr.spaceship] requirements against. 9978 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9979 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9980 QualType LHSStrippedType = LHSStripped.get()->getType(); 9981 QualType RHSStrippedType = RHSStripped.get()->getType(); 9982 9983 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9984 // other is not, the program is ill-formed. 9985 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9986 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9987 return QualType(); 9988 } 9989 9990 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9991 RHSStrippedType->isEnumeralType(); 9992 if (NumEnumArgs == 1) { 9993 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9994 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9995 if (OtherTy->hasFloatingRepresentation()) { 9996 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9997 return QualType(); 9998 } 9999 } 10000 if (NumEnumArgs == 2) { 10001 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10002 // type E, the operator yields the result of converting the operands 10003 // to the underlying type of E and applying <=> to the converted operands. 10004 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10005 S.InvalidOperands(Loc, LHS, RHS); 10006 return QualType(); 10007 } 10008 QualType IntType = 10009 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10010 assert(IntType->isArithmeticType()); 10011 10012 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10013 // promote the boolean type, and all other promotable integer types, to 10014 // avoid this. 10015 if (IntType->isPromotableIntegerType()) 10016 IntType = S.Context.getPromotedIntegerType(IntType); 10017 10018 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10019 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10020 LHSType = RHSType = IntType; 10021 } 10022 10023 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10024 // usual arithmetic conversions are applied to the operands. 10025 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10026 if (LHS.isInvalid() || RHS.isInvalid()) 10027 return QualType(); 10028 if (Type.isNull()) 10029 return S.InvalidOperands(Loc, LHS, RHS); 10030 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10031 10032 bool HasNarrowing = checkThreeWayNarrowingConversion( 10033 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10034 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10035 RHS.get()->getBeginLoc()); 10036 if (HasNarrowing) 10037 return QualType(); 10038 10039 assert(!Type.isNull() && "composite type for <=> has not been set"); 10040 10041 auto TypeKind = [&]() { 10042 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10043 if (CT->getElementType()->hasFloatingRepresentation()) 10044 return CCT::WeakEquality; 10045 return CCT::StrongEquality; 10046 } 10047 if (Type->isIntegralOrEnumerationType()) 10048 return CCT::StrongOrdering; 10049 if (Type->hasFloatingRepresentation()) 10050 return CCT::PartialOrdering; 10051 llvm_unreachable("other types are unimplemented"); 10052 }(); 10053 10054 return S.CheckComparisonCategoryType(TypeKind, Loc); 10055 } 10056 10057 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10058 ExprResult &RHS, 10059 SourceLocation Loc, 10060 BinaryOperatorKind Opc) { 10061 if (Opc == BO_Cmp) 10062 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10063 10064 // C99 6.5.8p3 / C99 6.5.9p4 10065 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10066 if (LHS.isInvalid() || RHS.isInvalid()) 10067 return QualType(); 10068 if (Type.isNull()) 10069 return S.InvalidOperands(Loc, LHS, RHS); 10070 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10071 10072 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10073 10074 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10075 return S.InvalidOperands(Loc, LHS, RHS); 10076 10077 // Check for comparisons of floating point operands using != and ==. 10078 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10079 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10080 10081 // The result of comparisons is 'bool' in C++, 'int' in C. 10082 return S.Context.getLogicalOperationType(); 10083 } 10084 10085 // C99 6.5.8, C++ [expr.rel] 10086 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10087 SourceLocation Loc, 10088 BinaryOperatorKind Opc) { 10089 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10090 bool IsThreeWay = Opc == BO_Cmp; 10091 auto IsAnyPointerType = [](ExprResult E) { 10092 QualType Ty = E.get()->getType(); 10093 return Ty->isPointerType() || Ty->isMemberPointerType(); 10094 }; 10095 10096 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10097 // type, array-to-pointer, ..., conversions are performed on both operands to 10098 // bring them to their composite type. 10099 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10100 // any type-related checks. 10101 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10102 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10103 if (LHS.isInvalid()) 10104 return QualType(); 10105 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10106 if (RHS.isInvalid()) 10107 return QualType(); 10108 } else { 10109 LHS = DefaultLvalueConversion(LHS.get()); 10110 if (LHS.isInvalid()) 10111 return QualType(); 10112 RHS = DefaultLvalueConversion(RHS.get()); 10113 if (RHS.isInvalid()) 10114 return QualType(); 10115 } 10116 10117 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10118 10119 // Handle vector comparisons separately. 10120 if (LHS.get()->getType()->isVectorType() || 10121 RHS.get()->getType()->isVectorType()) 10122 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10123 10124 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10125 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10126 10127 QualType LHSType = LHS.get()->getType(); 10128 QualType RHSType = RHS.get()->getType(); 10129 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10130 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10131 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10132 10133 const Expr::NullPointerConstantKind LHSNullKind = 10134 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10135 const Expr::NullPointerConstantKind RHSNullKind = 10136 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10137 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10138 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10139 10140 auto computeResultTy = [&]() { 10141 if (Opc != BO_Cmp) 10142 return Context.getLogicalOperationType(); 10143 assert(getLangOpts().CPlusPlus); 10144 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10145 10146 QualType CompositeTy = LHS.get()->getType(); 10147 assert(!CompositeTy->isReferenceType()); 10148 10149 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10150 return CheckComparisonCategoryType(Kind, Loc); 10151 }; 10152 10153 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10154 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10155 // result is of type std::strong_equality 10156 if (CompositeTy->isFunctionPointerType() || 10157 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10158 // FIXME: consider making the function pointer case produce 10159 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10160 // and direction polls 10161 return buildResultTy(ComparisonCategoryType::StrongEquality); 10162 10163 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10164 // pointer type, p <=> q is of type std::strong_ordering. 10165 if (CompositeTy->isPointerType()) { 10166 // P0946R0: Comparisons between a null pointer constant and an object 10167 // pointer result in std::strong_equality 10168 if (LHSIsNull != RHSIsNull) 10169 return buildResultTy(ComparisonCategoryType::StrongEquality); 10170 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10171 } 10172 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10173 // TODO: Extend support for operator<=> to ObjC types. 10174 return InvalidOperands(Loc, LHS, RHS); 10175 }; 10176 10177 10178 if (!IsRelational && LHSIsNull != RHSIsNull) { 10179 bool IsEquality = Opc == BO_EQ; 10180 if (RHSIsNull) 10181 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10182 RHS.get()->getSourceRange()); 10183 else 10184 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10185 LHS.get()->getSourceRange()); 10186 } 10187 10188 if ((LHSType->isIntegerType() && !LHSIsNull) || 10189 (RHSType->isIntegerType() && !RHSIsNull)) { 10190 // Skip normal pointer conversion checks in this case; we have better 10191 // diagnostics for this below. 10192 } else if (getLangOpts().CPlusPlus) { 10193 // Equality comparison of a function pointer to a void pointer is invalid, 10194 // but we allow it as an extension. 10195 // FIXME: If we really want to allow this, should it be part of composite 10196 // pointer type computation so it works in conditionals too? 10197 if (!IsRelational && 10198 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10199 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10200 // This is a gcc extension compatibility comparison. 10201 // In a SFINAE context, we treat this as a hard error to maintain 10202 // conformance with the C++ standard. 10203 diagnoseFunctionPointerToVoidComparison( 10204 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10205 10206 if (isSFINAEContext()) 10207 return QualType(); 10208 10209 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10210 return computeResultTy(); 10211 } 10212 10213 // C++ [expr.eq]p2: 10214 // If at least one operand is a pointer [...] bring them to their 10215 // composite pointer type. 10216 // C++ [expr.spaceship]p6 10217 // If at least one of the operands is of pointer type, [...] bring them 10218 // to their composite pointer type. 10219 // C++ [expr.rel]p2: 10220 // If both operands are pointers, [...] bring them to their composite 10221 // pointer type. 10222 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10223 (IsRelational ? 2 : 1) && 10224 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10225 RHSType->isObjCObjectPointerType()))) { 10226 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10227 return QualType(); 10228 return computeResultTy(); 10229 } 10230 } else if (LHSType->isPointerType() && 10231 RHSType->isPointerType()) { // C99 6.5.8p2 10232 // All of the following pointer-related warnings are GCC extensions, except 10233 // when handling null pointer constants. 10234 QualType LCanPointeeTy = 10235 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10236 QualType RCanPointeeTy = 10237 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10238 10239 // C99 6.5.9p2 and C99 6.5.8p2 10240 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10241 RCanPointeeTy.getUnqualifiedType())) { 10242 // Valid unless a relational comparison of function pointers 10243 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10244 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10245 << LHSType << RHSType << LHS.get()->getSourceRange() 10246 << RHS.get()->getSourceRange(); 10247 } 10248 } else if (!IsRelational && 10249 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10250 // Valid unless comparison between non-null pointer and function pointer 10251 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10252 && !LHSIsNull && !RHSIsNull) 10253 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10254 /*isError*/false); 10255 } else { 10256 // Invalid 10257 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10258 } 10259 if (LCanPointeeTy != RCanPointeeTy) { 10260 // Treat NULL constant as a special case in OpenCL. 10261 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10262 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10263 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10264 Diag(Loc, 10265 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10266 << LHSType << RHSType << 0 /* comparison */ 10267 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10268 } 10269 } 10270 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10271 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10272 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10273 : CK_BitCast; 10274 if (LHSIsNull && !RHSIsNull) 10275 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10276 else 10277 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10278 } 10279 return computeResultTy(); 10280 } 10281 10282 if (getLangOpts().CPlusPlus) { 10283 // C++ [expr.eq]p4: 10284 // Two operands of type std::nullptr_t or one operand of type 10285 // std::nullptr_t and the other a null pointer constant compare equal. 10286 if (!IsRelational && LHSIsNull && RHSIsNull) { 10287 if (LHSType->isNullPtrType()) { 10288 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10289 return computeResultTy(); 10290 } 10291 if (RHSType->isNullPtrType()) { 10292 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10293 return computeResultTy(); 10294 } 10295 } 10296 10297 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10298 // These aren't covered by the composite pointer type rules. 10299 if (!IsRelational && RHSType->isNullPtrType() && 10300 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10301 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10302 return computeResultTy(); 10303 } 10304 if (!IsRelational && LHSType->isNullPtrType() && 10305 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10306 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10307 return computeResultTy(); 10308 } 10309 10310 if (IsRelational && 10311 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10312 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10313 // HACK: Relational comparison of nullptr_t against a pointer type is 10314 // invalid per DR583, but we allow it within std::less<> and friends, 10315 // since otherwise common uses of it break. 10316 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10317 // friends to have std::nullptr_t overload candidates. 10318 DeclContext *DC = CurContext; 10319 if (isa<FunctionDecl>(DC)) 10320 DC = DC->getParent(); 10321 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10322 if (CTSD->isInStdNamespace() && 10323 llvm::StringSwitch<bool>(CTSD->getName()) 10324 .Cases("less", "less_equal", "greater", "greater_equal", true) 10325 .Default(false)) { 10326 if (RHSType->isNullPtrType()) 10327 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10328 else 10329 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10330 return computeResultTy(); 10331 } 10332 } 10333 } 10334 10335 // C++ [expr.eq]p2: 10336 // If at least one operand is a pointer to member, [...] bring them to 10337 // their composite pointer type. 10338 if (!IsRelational && 10339 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10340 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10341 return QualType(); 10342 else 10343 return computeResultTy(); 10344 } 10345 } 10346 10347 // Handle block pointer types. 10348 if (!IsRelational && LHSType->isBlockPointerType() && 10349 RHSType->isBlockPointerType()) { 10350 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10351 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10352 10353 if (!LHSIsNull && !RHSIsNull && 10354 !Context.typesAreCompatible(lpointee, rpointee)) { 10355 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10356 << LHSType << RHSType << LHS.get()->getSourceRange() 10357 << RHS.get()->getSourceRange(); 10358 } 10359 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10360 return computeResultTy(); 10361 } 10362 10363 // Allow block pointers to be compared with null pointer constants. 10364 if (!IsRelational 10365 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10366 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10367 if (!LHSIsNull && !RHSIsNull) { 10368 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10369 ->getPointeeType()->isVoidType()) 10370 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10371 ->getPointeeType()->isVoidType()))) 10372 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10373 << LHSType << RHSType << LHS.get()->getSourceRange() 10374 << RHS.get()->getSourceRange(); 10375 } 10376 if (LHSIsNull && !RHSIsNull) 10377 LHS = ImpCastExprToType(LHS.get(), RHSType, 10378 RHSType->isPointerType() ? CK_BitCast 10379 : CK_AnyPointerToBlockPointerCast); 10380 else 10381 RHS = ImpCastExprToType(RHS.get(), LHSType, 10382 LHSType->isPointerType() ? CK_BitCast 10383 : CK_AnyPointerToBlockPointerCast); 10384 return computeResultTy(); 10385 } 10386 10387 if (LHSType->isObjCObjectPointerType() || 10388 RHSType->isObjCObjectPointerType()) { 10389 const PointerType *LPT = LHSType->getAs<PointerType>(); 10390 const PointerType *RPT = RHSType->getAs<PointerType>(); 10391 if (LPT || RPT) { 10392 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10393 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10394 10395 if (!LPtrToVoid && !RPtrToVoid && 10396 !Context.typesAreCompatible(LHSType, RHSType)) { 10397 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10398 /*isError*/false); 10399 } 10400 if (LHSIsNull && !RHSIsNull) { 10401 Expr *E = LHS.get(); 10402 if (getLangOpts().ObjCAutoRefCount) 10403 CheckObjCConversion(SourceRange(), RHSType, E, 10404 CCK_ImplicitConversion); 10405 LHS = ImpCastExprToType(E, RHSType, 10406 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10407 } 10408 else { 10409 Expr *E = RHS.get(); 10410 if (getLangOpts().ObjCAutoRefCount) 10411 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10412 /*Diagnose=*/true, 10413 /*DiagnoseCFAudited=*/false, Opc); 10414 RHS = ImpCastExprToType(E, LHSType, 10415 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10416 } 10417 return computeResultTy(); 10418 } 10419 if (LHSType->isObjCObjectPointerType() && 10420 RHSType->isObjCObjectPointerType()) { 10421 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10422 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10423 /*isError*/false); 10424 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10425 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10426 10427 if (LHSIsNull && !RHSIsNull) 10428 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10429 else 10430 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10431 return computeResultTy(); 10432 } 10433 10434 if (!IsRelational && LHSType->isBlockPointerType() && 10435 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10436 LHS = ImpCastExprToType(LHS.get(), RHSType, 10437 CK_BlockPointerToObjCPointerCast); 10438 return computeResultTy(); 10439 } else if (!IsRelational && 10440 LHSType->isBlockCompatibleObjCPointerType(Context) && 10441 RHSType->isBlockPointerType()) { 10442 RHS = ImpCastExprToType(RHS.get(), LHSType, 10443 CK_BlockPointerToObjCPointerCast); 10444 return computeResultTy(); 10445 } 10446 } 10447 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10448 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10449 unsigned DiagID = 0; 10450 bool isError = false; 10451 if (LangOpts.DebuggerSupport) { 10452 // Under a debugger, allow the comparison of pointers to integers, 10453 // since users tend to want to compare addresses. 10454 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10455 (RHSIsNull && RHSType->isIntegerType())) { 10456 if (IsRelational) { 10457 isError = getLangOpts().CPlusPlus; 10458 DiagID = 10459 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10460 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10461 } 10462 } else if (getLangOpts().CPlusPlus) { 10463 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10464 isError = true; 10465 } else if (IsRelational) 10466 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10467 else 10468 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10469 10470 if (DiagID) { 10471 Diag(Loc, DiagID) 10472 << LHSType << RHSType << LHS.get()->getSourceRange() 10473 << RHS.get()->getSourceRange(); 10474 if (isError) 10475 return QualType(); 10476 } 10477 10478 if (LHSType->isIntegerType()) 10479 LHS = ImpCastExprToType(LHS.get(), RHSType, 10480 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10481 else 10482 RHS = ImpCastExprToType(RHS.get(), LHSType, 10483 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10484 return computeResultTy(); 10485 } 10486 10487 // Handle block pointers. 10488 if (!IsRelational && RHSIsNull 10489 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10490 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10491 return computeResultTy(); 10492 } 10493 if (!IsRelational && LHSIsNull 10494 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10495 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10496 return computeResultTy(); 10497 } 10498 10499 if (getLangOpts().OpenCLVersion >= 200) { 10500 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10501 return computeResultTy(); 10502 } 10503 10504 if (LHSIsNull && RHSType->isQueueT()) { 10505 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10506 return computeResultTy(); 10507 } 10508 10509 if (LHSType->isQueueT() && RHSIsNull) { 10510 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10511 return computeResultTy(); 10512 } 10513 } 10514 10515 return InvalidOperands(Loc, LHS, RHS); 10516 } 10517 10518 // Return a signed ext_vector_type that is of identical size and number of 10519 // elements. For floating point vectors, return an integer type of identical 10520 // size and number of elements. In the non ext_vector_type case, search from 10521 // the largest type to the smallest type to avoid cases where long long == long, 10522 // where long gets picked over long long. 10523 QualType Sema::GetSignedVectorType(QualType V) { 10524 const VectorType *VTy = V->getAs<VectorType>(); 10525 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10526 10527 if (isa<ExtVectorType>(VTy)) { 10528 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10529 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10530 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10531 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10532 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10533 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10534 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10535 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10536 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10537 "Unhandled vector element size in vector compare"); 10538 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10539 } 10540 10541 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10542 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10543 VectorType::GenericVector); 10544 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10545 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10546 VectorType::GenericVector); 10547 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10548 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10549 VectorType::GenericVector); 10550 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10551 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10552 VectorType::GenericVector); 10553 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10554 "Unhandled vector element size in vector compare"); 10555 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10556 VectorType::GenericVector); 10557 } 10558 10559 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10560 /// operates on extended vector types. Instead of producing an IntTy result, 10561 /// like a scalar comparison, a vector comparison produces a vector of integer 10562 /// types. 10563 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10564 SourceLocation Loc, 10565 BinaryOperatorKind Opc) { 10566 // Check to make sure we're operating on vectors of the same type and width, 10567 // Allowing one side to be a scalar of element type. 10568 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10569 /*AllowBothBool*/true, 10570 /*AllowBoolConversions*/getLangOpts().ZVector); 10571 if (vType.isNull()) 10572 return vType; 10573 10574 QualType LHSType = LHS.get()->getType(); 10575 10576 // If AltiVec, the comparison results in a numeric type, i.e. 10577 // bool for C++, int for C 10578 if (getLangOpts().AltiVec && 10579 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10580 return Context.getLogicalOperationType(); 10581 10582 // For non-floating point types, check for self-comparisons of the form 10583 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10584 // often indicate logic errors in the program. 10585 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10586 10587 // Check for comparisons of floating point operands using != and ==. 10588 if (BinaryOperator::isEqualityOp(Opc) && 10589 LHSType->hasFloatingRepresentation()) { 10590 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10591 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10592 } 10593 10594 // Return a signed type for the vector. 10595 return GetSignedVectorType(vType); 10596 } 10597 10598 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10599 SourceLocation Loc) { 10600 // Ensure that either both operands are of the same vector type, or 10601 // one operand is of a vector type and the other is of its element type. 10602 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10603 /*AllowBothBool*/true, 10604 /*AllowBoolConversions*/false); 10605 if (vType.isNull()) 10606 return InvalidOperands(Loc, LHS, RHS); 10607 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10608 vType->hasFloatingRepresentation()) 10609 return InvalidOperands(Loc, LHS, RHS); 10610 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10611 // usage of the logical operators && and || with vectors in C. This 10612 // check could be notionally dropped. 10613 if (!getLangOpts().CPlusPlus && 10614 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10615 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10616 10617 return GetSignedVectorType(LHS.get()->getType()); 10618 } 10619 10620 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10621 SourceLocation Loc, 10622 BinaryOperatorKind Opc) { 10623 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10624 10625 bool IsCompAssign = 10626 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10627 10628 if (LHS.get()->getType()->isVectorType() || 10629 RHS.get()->getType()->isVectorType()) { 10630 if (LHS.get()->getType()->hasIntegerRepresentation() && 10631 RHS.get()->getType()->hasIntegerRepresentation()) 10632 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10633 /*AllowBothBool*/true, 10634 /*AllowBoolConversions*/getLangOpts().ZVector); 10635 return InvalidOperands(Loc, LHS, RHS); 10636 } 10637 10638 if (Opc == BO_And) 10639 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10640 10641 ExprResult LHSResult = LHS, RHSResult = RHS; 10642 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10643 IsCompAssign); 10644 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10645 return QualType(); 10646 LHS = LHSResult.get(); 10647 RHS = RHSResult.get(); 10648 10649 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10650 return compType; 10651 return InvalidOperands(Loc, LHS, RHS); 10652 } 10653 10654 // C99 6.5.[13,14] 10655 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10656 SourceLocation Loc, 10657 BinaryOperatorKind Opc) { 10658 // Check vector operands differently. 10659 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10660 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10661 10662 // Diagnose cases where the user write a logical and/or but probably meant a 10663 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10664 // is a constant. 10665 if (LHS.get()->getType()->isIntegerType() && 10666 !LHS.get()->getType()->isBooleanType() && 10667 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10668 // Don't warn in macros or template instantiations. 10669 !Loc.isMacroID() && !inTemplateInstantiation()) { 10670 // If the RHS can be constant folded, and if it constant folds to something 10671 // that isn't 0 or 1 (which indicate a potential logical operation that 10672 // happened to fold to true/false) then warn. 10673 // Parens on the RHS are ignored. 10674 llvm::APSInt Result; 10675 if (RHS.get()->EvaluateAsInt(Result, Context)) 10676 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10677 !RHS.get()->getExprLoc().isMacroID()) || 10678 (Result != 0 && Result != 1)) { 10679 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10680 << RHS.get()->getSourceRange() 10681 << (Opc == BO_LAnd ? "&&" : "||"); 10682 // Suggest replacing the logical operator with the bitwise version 10683 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10684 << (Opc == BO_LAnd ? "&" : "|") 10685 << FixItHint::CreateReplacement(SourceRange( 10686 Loc, getLocForEndOfToken(Loc)), 10687 Opc == BO_LAnd ? "&" : "|"); 10688 if (Opc == BO_LAnd) 10689 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10690 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10691 << FixItHint::CreateRemoval( 10692 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10693 RHS.get()->getEndLoc())); 10694 } 10695 } 10696 10697 if (!Context.getLangOpts().CPlusPlus) { 10698 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10699 // not operate on the built-in scalar and vector float types. 10700 if (Context.getLangOpts().OpenCL && 10701 Context.getLangOpts().OpenCLVersion < 120) { 10702 if (LHS.get()->getType()->isFloatingType() || 10703 RHS.get()->getType()->isFloatingType()) 10704 return InvalidOperands(Loc, LHS, RHS); 10705 } 10706 10707 LHS = UsualUnaryConversions(LHS.get()); 10708 if (LHS.isInvalid()) 10709 return QualType(); 10710 10711 RHS = UsualUnaryConversions(RHS.get()); 10712 if (RHS.isInvalid()) 10713 return QualType(); 10714 10715 if (!LHS.get()->getType()->isScalarType() || 10716 !RHS.get()->getType()->isScalarType()) 10717 return InvalidOperands(Loc, LHS, RHS); 10718 10719 return Context.IntTy; 10720 } 10721 10722 // The following is safe because we only use this method for 10723 // non-overloadable operands. 10724 10725 // C++ [expr.log.and]p1 10726 // C++ [expr.log.or]p1 10727 // The operands are both contextually converted to type bool. 10728 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10729 if (LHSRes.isInvalid()) 10730 return InvalidOperands(Loc, LHS, RHS); 10731 LHS = LHSRes; 10732 10733 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10734 if (RHSRes.isInvalid()) 10735 return InvalidOperands(Loc, LHS, RHS); 10736 RHS = RHSRes; 10737 10738 // C++ [expr.log.and]p2 10739 // C++ [expr.log.or]p2 10740 // The result is a bool. 10741 return Context.BoolTy; 10742 } 10743 10744 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10745 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10746 if (!ME) return false; 10747 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10748 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10749 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10750 if (!Base) return false; 10751 return Base->getMethodDecl() != nullptr; 10752 } 10753 10754 /// Is the given expression (which must be 'const') a reference to a 10755 /// variable which was originally non-const, but which has become 10756 /// 'const' due to being captured within a block? 10757 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10758 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10759 assert(E->isLValue() && E->getType().isConstQualified()); 10760 E = E->IgnoreParens(); 10761 10762 // Must be a reference to a declaration from an enclosing scope. 10763 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10764 if (!DRE) return NCCK_None; 10765 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10766 10767 // The declaration must be a variable which is not declared 'const'. 10768 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10769 if (!var) return NCCK_None; 10770 if (var->getType().isConstQualified()) return NCCK_None; 10771 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10772 10773 // Decide whether the first capture was for a block or a lambda. 10774 DeclContext *DC = S.CurContext, *Prev = nullptr; 10775 // Decide whether the first capture was for a block or a lambda. 10776 while (DC) { 10777 // For init-capture, it is possible that the variable belongs to the 10778 // template pattern of the current context. 10779 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10780 if (var->isInitCapture() && 10781 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10782 break; 10783 if (DC == var->getDeclContext()) 10784 break; 10785 Prev = DC; 10786 DC = DC->getParent(); 10787 } 10788 // Unless we have an init-capture, we've gone one step too far. 10789 if (!var->isInitCapture()) 10790 DC = Prev; 10791 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10792 } 10793 10794 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10795 Ty = Ty.getNonReferenceType(); 10796 if (IsDereference && Ty->isPointerType()) 10797 Ty = Ty->getPointeeType(); 10798 return !Ty.isConstQualified(); 10799 } 10800 10801 // Update err_typecheck_assign_const and note_typecheck_assign_const 10802 // when this enum is changed. 10803 enum { 10804 ConstFunction, 10805 ConstVariable, 10806 ConstMember, 10807 ConstMethod, 10808 NestedConstMember, 10809 ConstUnknown, // Keep as last element 10810 }; 10811 10812 /// Emit the "read-only variable not assignable" error and print notes to give 10813 /// more information about why the variable is not assignable, such as pointing 10814 /// to the declaration of a const variable, showing that a method is const, or 10815 /// that the function is returning a const reference. 10816 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10817 SourceLocation Loc) { 10818 SourceRange ExprRange = E->getSourceRange(); 10819 10820 // Only emit one error on the first const found. All other consts will emit 10821 // a note to the error. 10822 bool DiagnosticEmitted = false; 10823 10824 // Track if the current expression is the result of a dereference, and if the 10825 // next checked expression is the result of a dereference. 10826 bool IsDereference = false; 10827 bool NextIsDereference = false; 10828 10829 // Loop to process MemberExpr chains. 10830 while (true) { 10831 IsDereference = NextIsDereference; 10832 10833 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10834 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10835 NextIsDereference = ME->isArrow(); 10836 const ValueDecl *VD = ME->getMemberDecl(); 10837 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10838 // Mutable fields can be modified even if the class is const. 10839 if (Field->isMutable()) { 10840 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10841 break; 10842 } 10843 10844 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10845 if (!DiagnosticEmitted) { 10846 S.Diag(Loc, diag::err_typecheck_assign_const) 10847 << ExprRange << ConstMember << false /*static*/ << Field 10848 << Field->getType(); 10849 DiagnosticEmitted = true; 10850 } 10851 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10852 << ConstMember << false /*static*/ << Field << Field->getType() 10853 << Field->getSourceRange(); 10854 } 10855 E = ME->getBase(); 10856 continue; 10857 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10858 if (VDecl->getType().isConstQualified()) { 10859 if (!DiagnosticEmitted) { 10860 S.Diag(Loc, diag::err_typecheck_assign_const) 10861 << ExprRange << ConstMember << true /*static*/ << VDecl 10862 << VDecl->getType(); 10863 DiagnosticEmitted = true; 10864 } 10865 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10866 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10867 << VDecl->getSourceRange(); 10868 } 10869 // Static fields do not inherit constness from parents. 10870 break; 10871 } 10872 break; // End MemberExpr 10873 } else if (const ArraySubscriptExpr *ASE = 10874 dyn_cast<ArraySubscriptExpr>(E)) { 10875 E = ASE->getBase()->IgnoreParenImpCasts(); 10876 continue; 10877 } else if (const ExtVectorElementExpr *EVE = 10878 dyn_cast<ExtVectorElementExpr>(E)) { 10879 E = EVE->getBase()->IgnoreParenImpCasts(); 10880 continue; 10881 } 10882 break; 10883 } 10884 10885 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10886 // Function calls 10887 const FunctionDecl *FD = CE->getDirectCallee(); 10888 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10889 if (!DiagnosticEmitted) { 10890 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10891 << ConstFunction << FD; 10892 DiagnosticEmitted = true; 10893 } 10894 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10895 diag::note_typecheck_assign_const) 10896 << ConstFunction << FD << FD->getReturnType() 10897 << FD->getReturnTypeSourceRange(); 10898 } 10899 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10900 // Point to variable declaration. 10901 if (const ValueDecl *VD = DRE->getDecl()) { 10902 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10903 if (!DiagnosticEmitted) { 10904 S.Diag(Loc, diag::err_typecheck_assign_const) 10905 << ExprRange << ConstVariable << VD << VD->getType(); 10906 DiagnosticEmitted = true; 10907 } 10908 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10909 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10910 } 10911 } 10912 } else if (isa<CXXThisExpr>(E)) { 10913 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10914 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10915 if (MD->isConst()) { 10916 if (!DiagnosticEmitted) { 10917 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10918 << ConstMethod << MD; 10919 DiagnosticEmitted = true; 10920 } 10921 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10922 << ConstMethod << MD << MD->getSourceRange(); 10923 } 10924 } 10925 } 10926 } 10927 10928 if (DiagnosticEmitted) 10929 return; 10930 10931 // Can't determine a more specific message, so display the generic error. 10932 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10933 } 10934 10935 enum OriginalExprKind { 10936 OEK_Variable, 10937 OEK_Member, 10938 OEK_LValue 10939 }; 10940 10941 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10942 const RecordType *Ty, 10943 SourceLocation Loc, SourceRange Range, 10944 OriginalExprKind OEK, 10945 bool &DiagnosticEmitted, 10946 bool IsNested = false) { 10947 // We walk the record hierarchy breadth-first to ensure that we print 10948 // diagnostics in field nesting order. 10949 // First, check every field for constness. 10950 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10951 if (Field->getType().isConstQualified()) { 10952 if (!DiagnosticEmitted) { 10953 S.Diag(Loc, diag::err_typecheck_assign_const) 10954 << Range << NestedConstMember << OEK << VD 10955 << IsNested << Field; 10956 DiagnosticEmitted = true; 10957 } 10958 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10959 << NestedConstMember << IsNested << Field 10960 << Field->getType() << Field->getSourceRange(); 10961 } 10962 } 10963 // Then, recurse. 10964 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10965 QualType FTy = Field->getType(); 10966 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10967 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10968 OEK, DiagnosticEmitted, true); 10969 } 10970 } 10971 10972 /// Emit an error for the case where a record we are trying to assign to has a 10973 /// const-qualified field somewhere in its hierarchy. 10974 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10975 SourceLocation Loc) { 10976 QualType Ty = E->getType(); 10977 assert(Ty->isRecordType() && "lvalue was not record?"); 10978 SourceRange Range = E->getSourceRange(); 10979 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10980 bool DiagEmitted = false; 10981 10982 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10983 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10984 Range, OEK_Member, DiagEmitted); 10985 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10986 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10987 Range, OEK_Variable, DiagEmitted); 10988 else 10989 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10990 Range, OEK_LValue, DiagEmitted); 10991 if (!DiagEmitted) 10992 DiagnoseConstAssignment(S, E, Loc); 10993 } 10994 10995 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10996 /// emit an error and return true. If so, return false. 10997 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10998 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10999 11000 S.CheckShadowingDeclModification(E, Loc); 11001 11002 SourceLocation OrigLoc = Loc; 11003 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11004 &Loc); 11005 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11006 IsLV = Expr::MLV_InvalidMessageExpression; 11007 if (IsLV == Expr::MLV_Valid) 11008 return false; 11009 11010 unsigned DiagID = 0; 11011 bool NeedType = false; 11012 switch (IsLV) { // C99 6.5.16p2 11013 case Expr::MLV_ConstQualified: 11014 // Use a specialized diagnostic when we're assigning to an object 11015 // from an enclosing function or block. 11016 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11017 if (NCCK == NCCK_Block) 11018 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11019 else 11020 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11021 break; 11022 } 11023 11024 // In ARC, use some specialized diagnostics for occasions where we 11025 // infer 'const'. These are always pseudo-strong variables. 11026 if (S.getLangOpts().ObjCAutoRefCount) { 11027 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11028 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11029 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11030 11031 // Use the normal diagnostic if it's pseudo-__strong but the 11032 // user actually wrote 'const'. 11033 if (var->isARCPseudoStrong() && 11034 (!var->getTypeSourceInfo() || 11035 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11036 // There are two pseudo-strong cases: 11037 // - self 11038 ObjCMethodDecl *method = S.getCurMethodDecl(); 11039 if (method && var == method->getSelfDecl()) 11040 DiagID = method->isClassMethod() 11041 ? diag::err_typecheck_arc_assign_self_class_method 11042 : diag::err_typecheck_arc_assign_self; 11043 11044 // - fast enumeration variables 11045 else 11046 DiagID = diag::err_typecheck_arr_assign_enumeration; 11047 11048 SourceRange Assign; 11049 if (Loc != OrigLoc) 11050 Assign = SourceRange(OrigLoc, OrigLoc); 11051 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11052 // We need to preserve the AST regardless, so migration tool 11053 // can do its job. 11054 return false; 11055 } 11056 } 11057 } 11058 11059 // If none of the special cases above are triggered, then this is a 11060 // simple const assignment. 11061 if (DiagID == 0) { 11062 DiagnoseConstAssignment(S, E, Loc); 11063 return true; 11064 } 11065 11066 break; 11067 case Expr::MLV_ConstAddrSpace: 11068 DiagnoseConstAssignment(S, E, Loc); 11069 return true; 11070 case Expr::MLV_ConstQualifiedField: 11071 DiagnoseRecursiveConstFields(S, E, Loc); 11072 return true; 11073 case Expr::MLV_ArrayType: 11074 case Expr::MLV_ArrayTemporary: 11075 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11076 NeedType = true; 11077 break; 11078 case Expr::MLV_NotObjectType: 11079 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11080 NeedType = true; 11081 break; 11082 case Expr::MLV_LValueCast: 11083 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11084 break; 11085 case Expr::MLV_Valid: 11086 llvm_unreachable("did not take early return for MLV_Valid"); 11087 case Expr::MLV_InvalidExpression: 11088 case Expr::MLV_MemberFunction: 11089 case Expr::MLV_ClassTemporary: 11090 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11091 break; 11092 case Expr::MLV_IncompleteType: 11093 case Expr::MLV_IncompleteVoidType: 11094 return S.RequireCompleteType(Loc, E->getType(), 11095 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11096 case Expr::MLV_DuplicateVectorComponents: 11097 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11098 break; 11099 case Expr::MLV_NoSetterProperty: 11100 llvm_unreachable("readonly properties should be processed differently"); 11101 case Expr::MLV_InvalidMessageExpression: 11102 DiagID = diag::err_readonly_message_assignment; 11103 break; 11104 case Expr::MLV_SubObjCPropertySetting: 11105 DiagID = diag::err_no_subobject_property_setting; 11106 break; 11107 } 11108 11109 SourceRange Assign; 11110 if (Loc != OrigLoc) 11111 Assign = SourceRange(OrigLoc, OrigLoc); 11112 if (NeedType) 11113 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11114 else 11115 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11116 return true; 11117 } 11118 11119 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11120 SourceLocation Loc, 11121 Sema &Sema) { 11122 if (Sema.inTemplateInstantiation()) 11123 return; 11124 if (Sema.isUnevaluatedContext()) 11125 return; 11126 if (Loc.isInvalid() || Loc.isMacroID()) 11127 return; 11128 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11129 return; 11130 11131 // C / C++ fields 11132 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11133 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11134 if (ML && MR) { 11135 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11136 return; 11137 const ValueDecl *LHSDecl = 11138 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11139 const ValueDecl *RHSDecl = 11140 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11141 if (LHSDecl != RHSDecl) 11142 return; 11143 if (LHSDecl->getType().isVolatileQualified()) 11144 return; 11145 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11146 if (RefTy->getPointeeType().isVolatileQualified()) 11147 return; 11148 11149 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11150 } 11151 11152 // Objective-C instance variables 11153 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11154 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11155 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11156 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11157 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11158 if (RL && RR && RL->getDecl() == RR->getDecl()) 11159 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11160 } 11161 } 11162 11163 // C99 6.5.16.1 11164 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11165 SourceLocation Loc, 11166 QualType CompoundType) { 11167 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11168 11169 // Verify that LHS is a modifiable lvalue, and emit error if not. 11170 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11171 return QualType(); 11172 11173 QualType LHSType = LHSExpr->getType(); 11174 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11175 CompoundType; 11176 // OpenCL v1.2 s6.1.1.1 p2: 11177 // The half data type can only be used to declare a pointer to a buffer that 11178 // contains half values 11179 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11180 LHSType->isHalfType()) { 11181 Diag(Loc, diag::err_opencl_half_load_store) << 1 11182 << LHSType.getUnqualifiedType(); 11183 return QualType(); 11184 } 11185 11186 AssignConvertType ConvTy; 11187 if (CompoundType.isNull()) { 11188 Expr *RHSCheck = RHS.get(); 11189 11190 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11191 11192 QualType LHSTy(LHSType); 11193 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11194 if (RHS.isInvalid()) 11195 return QualType(); 11196 // Special case of NSObject attributes on c-style pointer types. 11197 if (ConvTy == IncompatiblePointer && 11198 ((Context.isObjCNSObjectType(LHSType) && 11199 RHSType->isObjCObjectPointerType()) || 11200 (Context.isObjCNSObjectType(RHSType) && 11201 LHSType->isObjCObjectPointerType()))) 11202 ConvTy = Compatible; 11203 11204 if (ConvTy == Compatible && 11205 LHSType->isObjCObjectType()) 11206 Diag(Loc, diag::err_objc_object_assignment) 11207 << LHSType; 11208 11209 // If the RHS is a unary plus or minus, check to see if they = and + are 11210 // right next to each other. If so, the user may have typo'd "x =+ 4" 11211 // instead of "x += 4". 11212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11213 RHSCheck = ICE->getSubExpr(); 11214 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11215 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11216 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11217 // Only if the two operators are exactly adjacent. 11218 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11219 // And there is a space or other character before the subexpr of the 11220 // unary +/-. We don't want to warn on "x=-1". 11221 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11222 UO->getSubExpr()->getBeginLoc().isFileID()) { 11223 Diag(Loc, diag::warn_not_compound_assign) 11224 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11225 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11226 } 11227 } 11228 11229 if (ConvTy == Compatible) { 11230 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11231 // Warn about retain cycles where a block captures the LHS, but 11232 // not if the LHS is a simple variable into which the block is 11233 // being stored...unless that variable can be captured by reference! 11234 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11235 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11236 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11237 checkRetainCycles(LHSExpr, RHS.get()); 11238 } 11239 11240 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11241 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11242 // It is safe to assign a weak reference into a strong variable. 11243 // Although this code can still have problems: 11244 // id x = self.weakProp; 11245 // id y = self.weakProp; 11246 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11247 // paths through the function. This should be revisited if 11248 // -Wrepeated-use-of-weak is made flow-sensitive. 11249 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11250 // variable, which will be valid for the current autorelease scope. 11251 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11252 RHS.get()->getBeginLoc())) 11253 getCurFunction()->markSafeWeakUse(RHS.get()); 11254 11255 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11256 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11257 } 11258 } 11259 } else { 11260 // Compound assignment "x += y" 11261 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11262 } 11263 11264 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11265 RHS.get(), AA_Assigning)) 11266 return QualType(); 11267 11268 CheckForNullPointerDereference(*this, LHSExpr); 11269 11270 // C99 6.5.16p3: The type of an assignment expression is the type of the 11271 // left operand unless the left operand has qualified type, in which case 11272 // it is the unqualified version of the type of the left operand. 11273 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11274 // is converted to the type of the assignment expression (above). 11275 // C++ 5.17p1: the type of the assignment expression is that of its left 11276 // operand. 11277 return (getLangOpts().CPlusPlus 11278 ? LHSType : LHSType.getUnqualifiedType()); 11279 } 11280 11281 // Only ignore explicit casts to void. 11282 static bool IgnoreCommaOperand(const Expr *E) { 11283 E = E->IgnoreParens(); 11284 11285 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11286 if (CE->getCastKind() == CK_ToVoid) { 11287 return true; 11288 } 11289 11290 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11291 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11292 CE->getSubExpr()->getType()->isDependentType()) { 11293 return true; 11294 } 11295 } 11296 11297 return false; 11298 } 11299 11300 // Look for instances where it is likely the comma operator is confused with 11301 // another operator. There is a whitelist of acceptable expressions for the 11302 // left hand side of the comma operator, otherwise emit a warning. 11303 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11304 // No warnings in macros 11305 if (Loc.isMacroID()) 11306 return; 11307 11308 // Don't warn in template instantiations. 11309 if (inTemplateInstantiation()) 11310 return; 11311 11312 // Scope isn't fine-grained enough to whitelist the specific cases, so 11313 // instead, skip more than needed, then call back into here with the 11314 // CommaVisitor in SemaStmt.cpp. 11315 // The whitelisted locations are the initialization and increment portions 11316 // of a for loop. The additional checks are on the condition of 11317 // if statements, do/while loops, and for loops. 11318 // Differences in scope flags for C89 mode requires the extra logic. 11319 const unsigned ForIncrementFlags = 11320 getLangOpts().C99 || getLangOpts().CPlusPlus 11321 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11322 : Scope::ContinueScope | Scope::BreakScope; 11323 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11324 const unsigned ScopeFlags = getCurScope()->getFlags(); 11325 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11326 (ScopeFlags & ForInitFlags) == ForInitFlags) 11327 return; 11328 11329 // If there are multiple comma operators used together, get the RHS of the 11330 // of the comma operator as the LHS. 11331 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11332 if (BO->getOpcode() != BO_Comma) 11333 break; 11334 LHS = BO->getRHS(); 11335 } 11336 11337 // Only allow some expressions on LHS to not warn. 11338 if (IgnoreCommaOperand(LHS)) 11339 return; 11340 11341 Diag(Loc, diag::warn_comma_operator); 11342 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11343 << LHS->getSourceRange() 11344 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11345 LangOpts.CPlusPlus ? "static_cast<void>(" 11346 : "(void)(") 11347 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11348 ")"); 11349 } 11350 11351 // C99 6.5.17 11352 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11353 SourceLocation Loc) { 11354 LHS = S.CheckPlaceholderExpr(LHS.get()); 11355 RHS = S.CheckPlaceholderExpr(RHS.get()); 11356 if (LHS.isInvalid() || RHS.isInvalid()) 11357 return QualType(); 11358 11359 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11360 // operands, but not unary promotions. 11361 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11362 11363 // So we treat the LHS as a ignored value, and in C++ we allow the 11364 // containing site to determine what should be done with the RHS. 11365 LHS = S.IgnoredValueConversions(LHS.get()); 11366 if (LHS.isInvalid()) 11367 return QualType(); 11368 11369 S.DiagnoseUnusedExprResult(LHS.get()); 11370 11371 if (!S.getLangOpts().CPlusPlus) { 11372 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11373 if (RHS.isInvalid()) 11374 return QualType(); 11375 if (!RHS.get()->getType()->isVoidType()) 11376 S.RequireCompleteType(Loc, RHS.get()->getType(), 11377 diag::err_incomplete_type); 11378 } 11379 11380 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11381 S.DiagnoseCommaOperator(LHS.get(), Loc); 11382 11383 return RHS.get()->getType(); 11384 } 11385 11386 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11387 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11388 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11389 ExprValueKind &VK, 11390 ExprObjectKind &OK, 11391 SourceLocation OpLoc, 11392 bool IsInc, bool IsPrefix) { 11393 if (Op->isTypeDependent()) 11394 return S.Context.DependentTy; 11395 11396 QualType ResType = Op->getType(); 11397 // Atomic types can be used for increment / decrement where the non-atomic 11398 // versions can, so ignore the _Atomic() specifier for the purpose of 11399 // checking. 11400 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11401 ResType = ResAtomicType->getValueType(); 11402 11403 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11404 11405 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11406 // Decrement of bool is not allowed. 11407 if (!IsInc) { 11408 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11409 return QualType(); 11410 } 11411 // Increment of bool sets it to true, but is deprecated. 11412 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11413 : diag::warn_increment_bool) 11414 << Op->getSourceRange(); 11415 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11416 // Error on enum increments and decrements in C++ mode 11417 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11418 return QualType(); 11419 } else if (ResType->isRealType()) { 11420 // OK! 11421 } else if (ResType->isPointerType()) { 11422 // C99 6.5.2.4p2, 6.5.6p2 11423 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11424 return QualType(); 11425 } else if (ResType->isObjCObjectPointerType()) { 11426 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11427 // Otherwise, we just need a complete type. 11428 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11429 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11430 return QualType(); 11431 } else if (ResType->isAnyComplexType()) { 11432 // C99 does not support ++/-- on complex types, we allow as an extension. 11433 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11434 << ResType << Op->getSourceRange(); 11435 } else if (ResType->isPlaceholderType()) { 11436 ExprResult PR = S.CheckPlaceholderExpr(Op); 11437 if (PR.isInvalid()) return QualType(); 11438 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11439 IsInc, IsPrefix); 11440 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11441 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11442 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11443 (ResType->getAs<VectorType>()->getVectorKind() != 11444 VectorType::AltiVecBool)) { 11445 // The z vector extensions allow ++ and -- for non-bool vectors. 11446 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11447 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11448 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11449 } else { 11450 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11451 << ResType << int(IsInc) << Op->getSourceRange(); 11452 return QualType(); 11453 } 11454 // At this point, we know we have a real, complex or pointer type. 11455 // Now make sure the operand is a modifiable lvalue. 11456 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11457 return QualType(); 11458 // In C++, a prefix increment is the same type as the operand. Otherwise 11459 // (in C or with postfix), the increment is the unqualified type of the 11460 // operand. 11461 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11462 VK = VK_LValue; 11463 OK = Op->getObjectKind(); 11464 return ResType; 11465 } else { 11466 VK = VK_RValue; 11467 return ResType.getUnqualifiedType(); 11468 } 11469 } 11470 11471 11472 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11473 /// This routine allows us to typecheck complex/recursive expressions 11474 /// where the declaration is needed for type checking. We only need to 11475 /// handle cases when the expression references a function designator 11476 /// or is an lvalue. Here are some examples: 11477 /// - &(x) => x 11478 /// - &*****f => f for f a function designator. 11479 /// - &s.xx => s 11480 /// - &s.zz[1].yy -> s, if zz is an array 11481 /// - *(x + 1) -> x, if x is an array 11482 /// - &"123"[2] -> 0 11483 /// - & __real__ x -> x 11484 static ValueDecl *getPrimaryDecl(Expr *E) { 11485 switch (E->getStmtClass()) { 11486 case Stmt::DeclRefExprClass: 11487 return cast<DeclRefExpr>(E)->getDecl(); 11488 case Stmt::MemberExprClass: 11489 // If this is an arrow operator, the address is an offset from 11490 // the base's value, so the object the base refers to is 11491 // irrelevant. 11492 if (cast<MemberExpr>(E)->isArrow()) 11493 return nullptr; 11494 // Otherwise, the expression refers to a part of the base 11495 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11496 case Stmt::ArraySubscriptExprClass: { 11497 // FIXME: This code shouldn't be necessary! We should catch the implicit 11498 // promotion of register arrays earlier. 11499 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11500 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11501 if (ICE->getSubExpr()->getType()->isArrayType()) 11502 return getPrimaryDecl(ICE->getSubExpr()); 11503 } 11504 return nullptr; 11505 } 11506 case Stmt::UnaryOperatorClass: { 11507 UnaryOperator *UO = cast<UnaryOperator>(E); 11508 11509 switch(UO->getOpcode()) { 11510 case UO_Real: 11511 case UO_Imag: 11512 case UO_Extension: 11513 return getPrimaryDecl(UO->getSubExpr()); 11514 default: 11515 return nullptr; 11516 } 11517 } 11518 case Stmt::ParenExprClass: 11519 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11520 case Stmt::ImplicitCastExprClass: 11521 // If the result of an implicit cast is an l-value, we care about 11522 // the sub-expression; otherwise, the result here doesn't matter. 11523 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11524 default: 11525 return nullptr; 11526 } 11527 } 11528 11529 namespace { 11530 enum { 11531 AO_Bit_Field = 0, 11532 AO_Vector_Element = 1, 11533 AO_Property_Expansion = 2, 11534 AO_Register_Variable = 3, 11535 AO_No_Error = 4 11536 }; 11537 } 11538 /// Diagnose invalid operand for address of operations. 11539 /// 11540 /// \param Type The type of operand which cannot have its address taken. 11541 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11542 Expr *E, unsigned Type) { 11543 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11544 } 11545 11546 /// CheckAddressOfOperand - The operand of & must be either a function 11547 /// designator or an lvalue designating an object. If it is an lvalue, the 11548 /// object cannot be declared with storage class register or be a bit field. 11549 /// Note: The usual conversions are *not* applied to the operand of the & 11550 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11551 /// In C++, the operand might be an overloaded function name, in which case 11552 /// we allow the '&' but retain the overloaded-function type. 11553 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11554 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11555 if (PTy->getKind() == BuiltinType::Overload) { 11556 Expr *E = OrigOp.get()->IgnoreParens(); 11557 if (!isa<OverloadExpr>(E)) { 11558 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11559 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11560 << OrigOp.get()->getSourceRange(); 11561 return QualType(); 11562 } 11563 11564 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11565 if (isa<UnresolvedMemberExpr>(Ovl)) 11566 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11567 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11568 << OrigOp.get()->getSourceRange(); 11569 return QualType(); 11570 } 11571 11572 return Context.OverloadTy; 11573 } 11574 11575 if (PTy->getKind() == BuiltinType::UnknownAny) 11576 return Context.UnknownAnyTy; 11577 11578 if (PTy->getKind() == BuiltinType::BoundMember) { 11579 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11580 << OrigOp.get()->getSourceRange(); 11581 return QualType(); 11582 } 11583 11584 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11585 if (OrigOp.isInvalid()) return QualType(); 11586 } 11587 11588 if (OrigOp.get()->isTypeDependent()) 11589 return Context.DependentTy; 11590 11591 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11592 11593 // Make sure to ignore parentheses in subsequent checks 11594 Expr *op = OrigOp.get()->IgnoreParens(); 11595 11596 // In OpenCL captures for blocks called as lambda functions 11597 // are located in the private address space. Blocks used in 11598 // enqueue_kernel can be located in a different address space 11599 // depending on a vendor implementation. Thus preventing 11600 // taking an address of the capture to avoid invalid AS casts. 11601 if (LangOpts.OpenCL) { 11602 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11603 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11604 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11605 return QualType(); 11606 } 11607 } 11608 11609 if (getLangOpts().C99) { 11610 // Implement C99-only parts of addressof rules. 11611 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11612 if (uOp->getOpcode() == UO_Deref) 11613 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11614 // (assuming the deref expression is valid). 11615 return uOp->getSubExpr()->getType(); 11616 } 11617 // Technically, there should be a check for array subscript 11618 // expressions here, but the result of one is always an lvalue anyway. 11619 } 11620 ValueDecl *dcl = getPrimaryDecl(op); 11621 11622 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11623 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11624 op->getBeginLoc())) 11625 return QualType(); 11626 11627 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11628 unsigned AddressOfError = AO_No_Error; 11629 11630 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11631 bool sfinae = (bool)isSFINAEContext(); 11632 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11633 : diag::ext_typecheck_addrof_temporary) 11634 << op->getType() << op->getSourceRange(); 11635 if (sfinae) 11636 return QualType(); 11637 // Materialize the temporary as an lvalue so that we can take its address. 11638 OrigOp = op = 11639 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11640 } else if (isa<ObjCSelectorExpr>(op)) { 11641 return Context.getPointerType(op->getType()); 11642 } else if (lval == Expr::LV_MemberFunction) { 11643 // If it's an instance method, make a member pointer. 11644 // The expression must have exactly the form &A::foo. 11645 11646 // If the underlying expression isn't a decl ref, give up. 11647 if (!isa<DeclRefExpr>(op)) { 11648 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11649 << OrigOp.get()->getSourceRange(); 11650 return QualType(); 11651 } 11652 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11653 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11654 11655 // The id-expression was parenthesized. 11656 if (OrigOp.get() != DRE) { 11657 Diag(OpLoc, diag::err_parens_pointer_member_function) 11658 << OrigOp.get()->getSourceRange(); 11659 11660 // The method was named without a qualifier. 11661 } else if (!DRE->getQualifier()) { 11662 if (MD->getParent()->getName().empty()) 11663 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11664 << op->getSourceRange(); 11665 else { 11666 SmallString<32> Str; 11667 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11668 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11669 << op->getSourceRange() 11670 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11671 } 11672 } 11673 11674 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11675 if (isa<CXXDestructorDecl>(MD)) 11676 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11677 11678 QualType MPTy = Context.getMemberPointerType( 11679 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11680 // Under the MS ABI, lock down the inheritance model now. 11681 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11682 (void)isCompleteType(OpLoc, MPTy); 11683 return MPTy; 11684 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11685 // C99 6.5.3.2p1 11686 // The operand must be either an l-value or a function designator 11687 if (!op->getType()->isFunctionType()) { 11688 // Use a special diagnostic for loads from property references. 11689 if (isa<PseudoObjectExpr>(op)) { 11690 AddressOfError = AO_Property_Expansion; 11691 } else { 11692 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11693 << op->getType() << op->getSourceRange(); 11694 return QualType(); 11695 } 11696 } 11697 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11698 // The operand cannot be a bit-field 11699 AddressOfError = AO_Bit_Field; 11700 } else if (op->getObjectKind() == OK_VectorComponent) { 11701 // The operand cannot be an element of a vector 11702 AddressOfError = AO_Vector_Element; 11703 } else if (dcl) { // C99 6.5.3.2p1 11704 // We have an lvalue with a decl. Make sure the decl is not declared 11705 // with the register storage-class specifier. 11706 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11707 // in C++ it is not error to take address of a register 11708 // variable (c++03 7.1.1P3) 11709 if (vd->getStorageClass() == SC_Register && 11710 !getLangOpts().CPlusPlus) { 11711 AddressOfError = AO_Register_Variable; 11712 } 11713 } else if (isa<MSPropertyDecl>(dcl)) { 11714 AddressOfError = AO_Property_Expansion; 11715 } else if (isa<FunctionTemplateDecl>(dcl)) { 11716 return Context.OverloadTy; 11717 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11718 // Okay: we can take the address of a field. 11719 // Could be a pointer to member, though, if there is an explicit 11720 // scope qualifier for the class. 11721 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11722 DeclContext *Ctx = dcl->getDeclContext(); 11723 if (Ctx && Ctx->isRecord()) { 11724 if (dcl->getType()->isReferenceType()) { 11725 Diag(OpLoc, 11726 diag::err_cannot_form_pointer_to_member_of_reference_type) 11727 << dcl->getDeclName() << dcl->getType(); 11728 return QualType(); 11729 } 11730 11731 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11732 Ctx = Ctx->getParent(); 11733 11734 QualType MPTy = Context.getMemberPointerType( 11735 op->getType(), 11736 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11737 // Under the MS ABI, lock down the inheritance model now. 11738 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11739 (void)isCompleteType(OpLoc, MPTy); 11740 return MPTy; 11741 } 11742 } 11743 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11744 !isa<BindingDecl>(dcl)) 11745 llvm_unreachable("Unknown/unexpected decl type"); 11746 } 11747 11748 if (AddressOfError != AO_No_Error) { 11749 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11750 return QualType(); 11751 } 11752 11753 if (lval == Expr::LV_IncompleteVoidType) { 11754 // Taking the address of a void variable is technically illegal, but we 11755 // allow it in cases which are otherwise valid. 11756 // Example: "extern void x; void* y = &x;". 11757 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11758 } 11759 11760 // If the operand has type "type", the result has type "pointer to type". 11761 if (op->getType()->isObjCObjectType()) 11762 return Context.getObjCObjectPointerType(op->getType()); 11763 11764 CheckAddressOfPackedMember(op); 11765 11766 return Context.getPointerType(op->getType()); 11767 } 11768 11769 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11770 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11771 if (!DRE) 11772 return; 11773 const Decl *D = DRE->getDecl(); 11774 if (!D) 11775 return; 11776 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11777 if (!Param) 11778 return; 11779 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11780 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11781 return; 11782 if (FunctionScopeInfo *FD = S.getCurFunction()) 11783 if (!FD->ModifiedNonNullParams.count(Param)) 11784 FD->ModifiedNonNullParams.insert(Param); 11785 } 11786 11787 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11788 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11789 SourceLocation OpLoc) { 11790 if (Op->isTypeDependent()) 11791 return S.Context.DependentTy; 11792 11793 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11794 if (ConvResult.isInvalid()) 11795 return QualType(); 11796 Op = ConvResult.get(); 11797 QualType OpTy = Op->getType(); 11798 QualType Result; 11799 11800 if (isa<CXXReinterpretCastExpr>(Op)) { 11801 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11802 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11803 Op->getSourceRange()); 11804 } 11805 11806 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11807 { 11808 Result = PT->getPointeeType(); 11809 } 11810 else if (const ObjCObjectPointerType *OPT = 11811 OpTy->getAs<ObjCObjectPointerType>()) 11812 Result = OPT->getPointeeType(); 11813 else { 11814 ExprResult PR = S.CheckPlaceholderExpr(Op); 11815 if (PR.isInvalid()) return QualType(); 11816 if (PR.get() != Op) 11817 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11818 } 11819 11820 if (Result.isNull()) { 11821 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11822 << OpTy << Op->getSourceRange(); 11823 return QualType(); 11824 } 11825 11826 // Note that per both C89 and C99, indirection is always legal, even if Result 11827 // is an incomplete type or void. It would be possible to warn about 11828 // dereferencing a void pointer, but it's completely well-defined, and such a 11829 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11830 // for pointers to 'void' but is fine for any other pointer type: 11831 // 11832 // C++ [expr.unary.op]p1: 11833 // [...] the expression to which [the unary * operator] is applied shall 11834 // be a pointer to an object type, or a pointer to a function type 11835 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11836 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11837 << OpTy << Op->getSourceRange(); 11838 11839 // Dereferences are usually l-values... 11840 VK = VK_LValue; 11841 11842 // ...except that certain expressions are never l-values in C. 11843 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11844 VK = VK_RValue; 11845 11846 return Result; 11847 } 11848 11849 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11850 BinaryOperatorKind Opc; 11851 switch (Kind) { 11852 default: llvm_unreachable("Unknown binop!"); 11853 case tok::periodstar: Opc = BO_PtrMemD; break; 11854 case tok::arrowstar: Opc = BO_PtrMemI; break; 11855 case tok::star: Opc = BO_Mul; break; 11856 case tok::slash: Opc = BO_Div; break; 11857 case tok::percent: Opc = BO_Rem; break; 11858 case tok::plus: Opc = BO_Add; break; 11859 case tok::minus: Opc = BO_Sub; break; 11860 case tok::lessless: Opc = BO_Shl; break; 11861 case tok::greatergreater: Opc = BO_Shr; break; 11862 case tok::lessequal: Opc = BO_LE; break; 11863 case tok::less: Opc = BO_LT; break; 11864 case tok::greaterequal: Opc = BO_GE; break; 11865 case tok::greater: Opc = BO_GT; break; 11866 case tok::exclaimequal: Opc = BO_NE; break; 11867 case tok::equalequal: Opc = BO_EQ; break; 11868 case tok::spaceship: Opc = BO_Cmp; break; 11869 case tok::amp: Opc = BO_And; break; 11870 case tok::caret: Opc = BO_Xor; break; 11871 case tok::pipe: Opc = BO_Or; break; 11872 case tok::ampamp: Opc = BO_LAnd; break; 11873 case tok::pipepipe: Opc = BO_LOr; break; 11874 case tok::equal: Opc = BO_Assign; break; 11875 case tok::starequal: Opc = BO_MulAssign; break; 11876 case tok::slashequal: Opc = BO_DivAssign; break; 11877 case tok::percentequal: Opc = BO_RemAssign; break; 11878 case tok::plusequal: Opc = BO_AddAssign; break; 11879 case tok::minusequal: Opc = BO_SubAssign; break; 11880 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11881 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11882 case tok::ampequal: Opc = BO_AndAssign; break; 11883 case tok::caretequal: Opc = BO_XorAssign; break; 11884 case tok::pipeequal: Opc = BO_OrAssign; break; 11885 case tok::comma: Opc = BO_Comma; break; 11886 } 11887 return Opc; 11888 } 11889 11890 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11891 tok::TokenKind Kind) { 11892 UnaryOperatorKind Opc; 11893 switch (Kind) { 11894 default: llvm_unreachable("Unknown unary op!"); 11895 case tok::plusplus: Opc = UO_PreInc; break; 11896 case tok::minusminus: Opc = UO_PreDec; break; 11897 case tok::amp: Opc = UO_AddrOf; break; 11898 case tok::star: Opc = UO_Deref; break; 11899 case tok::plus: Opc = UO_Plus; break; 11900 case tok::minus: Opc = UO_Minus; break; 11901 case tok::tilde: Opc = UO_Not; break; 11902 case tok::exclaim: Opc = UO_LNot; break; 11903 case tok::kw___real: Opc = UO_Real; break; 11904 case tok::kw___imag: Opc = UO_Imag; break; 11905 case tok::kw___extension__: Opc = UO_Extension; break; 11906 } 11907 return Opc; 11908 } 11909 11910 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11911 /// This warning suppressed in the event of macro expansions. 11912 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11913 SourceLocation OpLoc, bool IsBuiltin) { 11914 if (S.inTemplateInstantiation()) 11915 return; 11916 if (S.isUnevaluatedContext()) 11917 return; 11918 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11919 return; 11920 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11921 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11922 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11923 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11924 if (!LHSDeclRef || !RHSDeclRef || 11925 LHSDeclRef->getLocation().isMacroID() || 11926 RHSDeclRef->getLocation().isMacroID()) 11927 return; 11928 const ValueDecl *LHSDecl = 11929 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11930 const ValueDecl *RHSDecl = 11931 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11932 if (LHSDecl != RHSDecl) 11933 return; 11934 if (LHSDecl->getType().isVolatileQualified()) 11935 return; 11936 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11937 if (RefTy->getPointeeType().isVolatileQualified()) 11938 return; 11939 11940 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11941 : diag::warn_self_assignment_overloaded) 11942 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11943 << RHSExpr->getSourceRange(); 11944 } 11945 11946 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11947 /// is usually indicative of introspection within the Objective-C pointer. 11948 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11949 SourceLocation OpLoc) { 11950 if (!S.getLangOpts().ObjC1) 11951 return; 11952 11953 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11954 const Expr *LHS = L.get(); 11955 const Expr *RHS = R.get(); 11956 11957 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11958 ObjCPointerExpr = LHS; 11959 OtherExpr = RHS; 11960 } 11961 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11962 ObjCPointerExpr = RHS; 11963 OtherExpr = LHS; 11964 } 11965 11966 // This warning is deliberately made very specific to reduce false 11967 // positives with logic that uses '&' for hashing. This logic mainly 11968 // looks for code trying to introspect into tagged pointers, which 11969 // code should generally never do. 11970 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11971 unsigned Diag = diag::warn_objc_pointer_masking; 11972 // Determine if we are introspecting the result of performSelectorXXX. 11973 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11974 // Special case messages to -performSelector and friends, which 11975 // can return non-pointer values boxed in a pointer value. 11976 // Some clients may wish to silence warnings in this subcase. 11977 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11978 Selector S = ME->getSelector(); 11979 StringRef SelArg0 = S.getNameForSlot(0); 11980 if (SelArg0.startswith("performSelector")) 11981 Diag = diag::warn_objc_pointer_masking_performSelector; 11982 } 11983 11984 S.Diag(OpLoc, Diag) 11985 << ObjCPointerExpr->getSourceRange(); 11986 } 11987 } 11988 11989 static NamedDecl *getDeclFromExpr(Expr *E) { 11990 if (!E) 11991 return nullptr; 11992 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11993 return DRE->getDecl(); 11994 if (auto *ME = dyn_cast<MemberExpr>(E)) 11995 return ME->getMemberDecl(); 11996 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11997 return IRE->getDecl(); 11998 return nullptr; 11999 } 12000 12001 // This helper function promotes a binary operator's operands (which are of a 12002 // half vector type) to a vector of floats and then truncates the result to 12003 // a vector of either half or short. 12004 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12005 BinaryOperatorKind Opc, QualType ResultTy, 12006 ExprValueKind VK, ExprObjectKind OK, 12007 bool IsCompAssign, SourceLocation OpLoc, 12008 FPOptions FPFeatures) { 12009 auto &Context = S.getASTContext(); 12010 assert((isVector(ResultTy, Context.HalfTy) || 12011 isVector(ResultTy, Context.ShortTy)) && 12012 "Result must be a vector of half or short"); 12013 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12014 isVector(RHS.get()->getType(), Context.HalfTy) && 12015 "both operands expected to be a half vector"); 12016 12017 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12018 QualType BinOpResTy = RHS.get()->getType(); 12019 12020 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12021 // change BinOpResTy to a vector of ints. 12022 if (isVector(ResultTy, Context.ShortTy)) 12023 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12024 12025 if (IsCompAssign) 12026 return new (Context) CompoundAssignOperator( 12027 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12028 OpLoc, FPFeatures); 12029 12030 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12031 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12032 VK, OK, OpLoc, FPFeatures); 12033 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12034 } 12035 12036 static std::pair<ExprResult, ExprResult> 12037 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12038 Expr *RHSExpr) { 12039 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12040 if (!S.getLangOpts().CPlusPlus) { 12041 // C cannot handle TypoExpr nodes on either side of a binop because it 12042 // doesn't handle dependent types properly, so make sure any TypoExprs have 12043 // been dealt with before checking the operands. 12044 LHS = S.CorrectDelayedTyposInExpr(LHS); 12045 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12046 if (Opc != BO_Assign) 12047 return ExprResult(E); 12048 // Avoid correcting the RHS to the same Expr as the LHS. 12049 Decl *D = getDeclFromExpr(E); 12050 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12051 }); 12052 } 12053 return std::make_pair(LHS, RHS); 12054 } 12055 12056 /// Returns true if conversion between vectors of halfs and vectors of floats 12057 /// is needed. 12058 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12059 QualType SrcType) { 12060 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12061 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12062 isVector(SrcType, Ctx.HalfTy); 12063 } 12064 12065 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12066 /// operator @p Opc at location @c TokLoc. This routine only supports 12067 /// built-in operations; ActOnBinOp handles overloaded operators. 12068 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12069 BinaryOperatorKind Opc, 12070 Expr *LHSExpr, Expr *RHSExpr) { 12071 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12072 // The syntax only allows initializer lists on the RHS of assignment, 12073 // so we don't need to worry about accepting invalid code for 12074 // non-assignment operators. 12075 // C++11 5.17p9: 12076 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12077 // of x = {} is x = T(). 12078 InitializationKind Kind = InitializationKind::CreateDirectList( 12079 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12080 InitializedEntity Entity = 12081 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12082 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12083 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12084 if (Init.isInvalid()) 12085 return Init; 12086 RHSExpr = Init.get(); 12087 } 12088 12089 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12090 QualType ResultTy; // Result type of the binary operator. 12091 // The following two variables are used for compound assignment operators 12092 QualType CompLHSTy; // Type of LHS after promotions for computation 12093 QualType CompResultTy; // Type of computation result 12094 ExprValueKind VK = VK_RValue; 12095 ExprObjectKind OK = OK_Ordinary; 12096 bool ConvertHalfVec = false; 12097 12098 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12099 if (!LHS.isUsable() || !RHS.isUsable()) 12100 return ExprError(); 12101 12102 if (getLangOpts().OpenCL) { 12103 QualType LHSTy = LHSExpr->getType(); 12104 QualType RHSTy = RHSExpr->getType(); 12105 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12106 // the ATOMIC_VAR_INIT macro. 12107 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12108 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12109 if (BO_Assign == Opc) 12110 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12111 else 12112 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12113 return ExprError(); 12114 } 12115 12116 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12117 // only with a builtin functions and therefore should be disallowed here. 12118 if (LHSTy->isImageType() || RHSTy->isImageType() || 12119 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12120 LHSTy->isPipeType() || RHSTy->isPipeType() || 12121 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12122 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12123 return ExprError(); 12124 } 12125 } 12126 12127 switch (Opc) { 12128 case BO_Assign: 12129 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12130 if (getLangOpts().CPlusPlus && 12131 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12132 VK = LHS.get()->getValueKind(); 12133 OK = LHS.get()->getObjectKind(); 12134 } 12135 if (!ResultTy.isNull()) { 12136 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12137 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12138 } 12139 RecordModifiableNonNullParam(*this, LHS.get()); 12140 break; 12141 case BO_PtrMemD: 12142 case BO_PtrMemI: 12143 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12144 Opc == BO_PtrMemI); 12145 break; 12146 case BO_Mul: 12147 case BO_Div: 12148 ConvertHalfVec = true; 12149 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12150 Opc == BO_Div); 12151 break; 12152 case BO_Rem: 12153 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12154 break; 12155 case BO_Add: 12156 ConvertHalfVec = true; 12157 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12158 break; 12159 case BO_Sub: 12160 ConvertHalfVec = true; 12161 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12162 break; 12163 case BO_Shl: 12164 case BO_Shr: 12165 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12166 break; 12167 case BO_LE: 12168 case BO_LT: 12169 case BO_GE: 12170 case BO_GT: 12171 ConvertHalfVec = true; 12172 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12173 break; 12174 case BO_EQ: 12175 case BO_NE: 12176 ConvertHalfVec = true; 12177 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12178 break; 12179 case BO_Cmp: 12180 ConvertHalfVec = true; 12181 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12182 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12183 break; 12184 case BO_And: 12185 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12186 LLVM_FALLTHROUGH; 12187 case BO_Xor: 12188 case BO_Or: 12189 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12190 break; 12191 case BO_LAnd: 12192 case BO_LOr: 12193 ConvertHalfVec = true; 12194 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12195 break; 12196 case BO_MulAssign: 12197 case BO_DivAssign: 12198 ConvertHalfVec = true; 12199 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12200 Opc == BO_DivAssign); 12201 CompLHSTy = CompResultTy; 12202 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12203 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12204 break; 12205 case BO_RemAssign: 12206 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12207 CompLHSTy = CompResultTy; 12208 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12209 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12210 break; 12211 case BO_AddAssign: 12212 ConvertHalfVec = true; 12213 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12214 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12215 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12216 break; 12217 case BO_SubAssign: 12218 ConvertHalfVec = true; 12219 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12220 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12221 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12222 break; 12223 case BO_ShlAssign: 12224 case BO_ShrAssign: 12225 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12226 CompLHSTy = CompResultTy; 12227 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12228 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12229 break; 12230 case BO_AndAssign: 12231 case BO_OrAssign: // fallthrough 12232 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12233 LLVM_FALLTHROUGH; 12234 case BO_XorAssign: 12235 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12236 CompLHSTy = CompResultTy; 12237 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12238 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12239 break; 12240 case BO_Comma: 12241 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12242 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12243 VK = RHS.get()->getValueKind(); 12244 OK = RHS.get()->getObjectKind(); 12245 } 12246 break; 12247 } 12248 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12249 return ExprError(); 12250 12251 // Some of the binary operations require promoting operands of half vector to 12252 // float vectors and truncating the result back to half vector. For now, we do 12253 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12254 // arm64). 12255 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12256 isVector(LHS.get()->getType(), Context.HalfTy) && 12257 "both sides are half vectors or neither sides are"); 12258 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12259 LHS.get()->getType()); 12260 12261 // Check for array bounds violations for both sides of the BinaryOperator 12262 CheckArrayAccess(LHS.get()); 12263 CheckArrayAccess(RHS.get()); 12264 12265 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12266 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12267 &Context.Idents.get("object_setClass"), 12268 SourceLocation(), LookupOrdinaryName); 12269 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12270 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12271 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12272 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12273 "object_setClass(") 12274 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12275 ",") 12276 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12277 } 12278 else 12279 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12280 } 12281 else if (const ObjCIvarRefExpr *OIRE = 12282 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12283 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12284 12285 // Opc is not a compound assignment if CompResultTy is null. 12286 if (CompResultTy.isNull()) { 12287 if (ConvertHalfVec) 12288 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12289 OpLoc, FPFeatures); 12290 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12291 OK, OpLoc, FPFeatures); 12292 } 12293 12294 // Handle compound assignments. 12295 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12296 OK_ObjCProperty) { 12297 VK = VK_LValue; 12298 OK = LHS.get()->getObjectKind(); 12299 } 12300 12301 if (ConvertHalfVec) 12302 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12303 OpLoc, FPFeatures); 12304 12305 return new (Context) CompoundAssignOperator( 12306 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12307 OpLoc, FPFeatures); 12308 } 12309 12310 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12311 /// operators are mixed in a way that suggests that the programmer forgot that 12312 /// comparison operators have higher precedence. The most typical example of 12313 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12314 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12315 SourceLocation OpLoc, Expr *LHSExpr, 12316 Expr *RHSExpr) { 12317 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12318 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12319 12320 // Check that one of the sides is a comparison operator and the other isn't. 12321 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12322 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12323 if (isLeftComp == isRightComp) 12324 return; 12325 12326 // Bitwise operations are sometimes used as eager logical ops. 12327 // Don't diagnose this. 12328 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12329 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12330 if (isLeftBitwise || isRightBitwise) 12331 return; 12332 12333 SourceRange DiagRange = isLeftComp 12334 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12335 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12336 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12337 SourceRange ParensRange = 12338 isLeftComp 12339 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12340 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12341 12342 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12343 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12344 SuggestParentheses(Self, OpLoc, 12345 Self.PDiag(diag::note_precedence_silence) << OpStr, 12346 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12347 SuggestParentheses(Self, OpLoc, 12348 Self.PDiag(diag::note_precedence_bitwise_first) 12349 << BinaryOperator::getOpcodeStr(Opc), 12350 ParensRange); 12351 } 12352 12353 /// It accepts a '&&' expr that is inside a '||' one. 12354 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12355 /// in parentheses. 12356 static void 12357 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12358 BinaryOperator *Bop) { 12359 assert(Bop->getOpcode() == BO_LAnd); 12360 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12361 << Bop->getSourceRange() << OpLoc; 12362 SuggestParentheses(Self, Bop->getOperatorLoc(), 12363 Self.PDiag(diag::note_precedence_silence) 12364 << Bop->getOpcodeStr(), 12365 Bop->getSourceRange()); 12366 } 12367 12368 /// Returns true if the given expression can be evaluated as a constant 12369 /// 'true'. 12370 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12371 bool Res; 12372 return !E->isValueDependent() && 12373 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12374 } 12375 12376 /// Returns true if the given expression can be evaluated as a constant 12377 /// 'false'. 12378 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12379 bool Res; 12380 return !E->isValueDependent() && 12381 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12382 } 12383 12384 /// Look for '&&' in the left hand of a '||' expr. 12385 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12386 Expr *LHSExpr, Expr *RHSExpr) { 12387 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12388 if (Bop->getOpcode() == BO_LAnd) { 12389 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12390 if (EvaluatesAsFalse(S, RHSExpr)) 12391 return; 12392 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12393 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12394 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12395 } else if (Bop->getOpcode() == BO_LOr) { 12396 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12397 // If it's "a || b && 1 || c" we didn't warn earlier for 12398 // "a || b && 1", but warn now. 12399 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12400 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12401 } 12402 } 12403 } 12404 } 12405 12406 /// Look for '&&' in the right hand of a '||' expr. 12407 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12408 Expr *LHSExpr, Expr *RHSExpr) { 12409 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12410 if (Bop->getOpcode() == BO_LAnd) { 12411 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12412 if (EvaluatesAsFalse(S, LHSExpr)) 12413 return; 12414 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12415 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12416 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12417 } 12418 } 12419 } 12420 12421 /// Look for bitwise op in the left or right hand of a bitwise op with 12422 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12423 /// the '&' expression in parentheses. 12424 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12425 SourceLocation OpLoc, Expr *SubExpr) { 12426 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12427 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12428 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12429 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12430 << Bop->getSourceRange() << OpLoc; 12431 SuggestParentheses(S, Bop->getOperatorLoc(), 12432 S.PDiag(diag::note_precedence_silence) 12433 << Bop->getOpcodeStr(), 12434 Bop->getSourceRange()); 12435 } 12436 } 12437 } 12438 12439 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12440 Expr *SubExpr, StringRef Shift) { 12441 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12442 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12443 StringRef Op = Bop->getOpcodeStr(); 12444 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12445 << Bop->getSourceRange() << OpLoc << Shift << Op; 12446 SuggestParentheses(S, Bop->getOperatorLoc(), 12447 S.PDiag(diag::note_precedence_silence) << Op, 12448 Bop->getSourceRange()); 12449 } 12450 } 12451 } 12452 12453 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12454 Expr *LHSExpr, Expr *RHSExpr) { 12455 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12456 if (!OCE) 12457 return; 12458 12459 FunctionDecl *FD = OCE->getDirectCallee(); 12460 if (!FD || !FD->isOverloadedOperator()) 12461 return; 12462 12463 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12464 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12465 return; 12466 12467 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12468 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12469 << (Kind == OO_LessLess); 12470 SuggestParentheses(S, OCE->getOperatorLoc(), 12471 S.PDiag(diag::note_precedence_silence) 12472 << (Kind == OO_LessLess ? "<<" : ">>"), 12473 OCE->getSourceRange()); 12474 SuggestParentheses( 12475 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12476 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12477 } 12478 12479 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12480 /// precedence. 12481 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12482 SourceLocation OpLoc, Expr *LHSExpr, 12483 Expr *RHSExpr){ 12484 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12485 if (BinaryOperator::isBitwiseOp(Opc)) 12486 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12487 12488 // Diagnose "arg1 & arg2 | arg3" 12489 if ((Opc == BO_Or || Opc == BO_Xor) && 12490 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12491 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12492 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12493 } 12494 12495 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12496 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12497 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12498 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12499 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12500 } 12501 12502 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12503 || Opc == BO_Shr) { 12504 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12505 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12506 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12507 } 12508 12509 // Warn on overloaded shift operators and comparisons, such as: 12510 // cout << 5 == 4; 12511 if (BinaryOperator::isComparisonOp(Opc)) 12512 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12513 } 12514 12515 // Binary Operators. 'Tok' is the token for the operator. 12516 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12517 tok::TokenKind Kind, 12518 Expr *LHSExpr, Expr *RHSExpr) { 12519 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12520 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12521 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12522 12523 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12524 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12525 12526 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12527 } 12528 12529 /// Build an overloaded binary operator expression in the given scope. 12530 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12531 BinaryOperatorKind Opc, 12532 Expr *LHS, Expr *RHS) { 12533 switch (Opc) { 12534 case BO_Assign: 12535 case BO_DivAssign: 12536 case BO_RemAssign: 12537 case BO_SubAssign: 12538 case BO_AndAssign: 12539 case BO_OrAssign: 12540 case BO_XorAssign: 12541 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12542 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12543 break; 12544 default: 12545 break; 12546 } 12547 12548 // Find all of the overloaded operators visible from this 12549 // point. We perform both an operator-name lookup from the local 12550 // scope and an argument-dependent lookup based on the types of 12551 // the arguments. 12552 UnresolvedSet<16> Functions; 12553 OverloadedOperatorKind OverOp 12554 = BinaryOperator::getOverloadedOperator(Opc); 12555 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12556 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12557 RHS->getType(), Functions); 12558 12559 // Build the (potentially-overloaded, potentially-dependent) 12560 // binary operation. 12561 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12562 } 12563 12564 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12565 BinaryOperatorKind Opc, 12566 Expr *LHSExpr, Expr *RHSExpr) { 12567 ExprResult LHS, RHS; 12568 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12569 if (!LHS.isUsable() || !RHS.isUsable()) 12570 return ExprError(); 12571 LHSExpr = LHS.get(); 12572 RHSExpr = RHS.get(); 12573 12574 // We want to end up calling one of checkPseudoObjectAssignment 12575 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12576 // both expressions are overloadable or either is type-dependent), 12577 // or CreateBuiltinBinOp (in any other case). We also want to get 12578 // any placeholder types out of the way. 12579 12580 // Handle pseudo-objects in the LHS. 12581 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12582 // Assignments with a pseudo-object l-value need special analysis. 12583 if (pty->getKind() == BuiltinType::PseudoObject && 12584 BinaryOperator::isAssignmentOp(Opc)) 12585 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12586 12587 // Don't resolve overloads if the other type is overloadable. 12588 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12589 // We can't actually test that if we still have a placeholder, 12590 // though. Fortunately, none of the exceptions we see in that 12591 // code below are valid when the LHS is an overload set. Note 12592 // that an overload set can be dependently-typed, but it never 12593 // instantiates to having an overloadable type. 12594 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12595 if (resolvedRHS.isInvalid()) return ExprError(); 12596 RHSExpr = resolvedRHS.get(); 12597 12598 if (RHSExpr->isTypeDependent() || 12599 RHSExpr->getType()->isOverloadableType()) 12600 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12601 } 12602 12603 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12604 // template, diagnose the missing 'template' keyword instead of diagnosing 12605 // an invalid use of a bound member function. 12606 // 12607 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12608 // to C++1z [over.over]/1.4, but we already checked for that case above. 12609 if (Opc == BO_LT && inTemplateInstantiation() && 12610 (pty->getKind() == BuiltinType::BoundMember || 12611 pty->getKind() == BuiltinType::Overload)) { 12612 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12613 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12614 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12615 return isa<FunctionTemplateDecl>(ND); 12616 })) { 12617 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12618 : OE->getNameLoc(), 12619 diag::err_template_kw_missing) 12620 << OE->getName().getAsString() << ""; 12621 return ExprError(); 12622 } 12623 } 12624 12625 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12626 if (LHS.isInvalid()) return ExprError(); 12627 LHSExpr = LHS.get(); 12628 } 12629 12630 // Handle pseudo-objects in the RHS. 12631 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12632 // An overload in the RHS can potentially be resolved by the type 12633 // being assigned to. 12634 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12635 if (getLangOpts().CPlusPlus && 12636 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12637 LHSExpr->getType()->isOverloadableType())) 12638 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12639 12640 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12641 } 12642 12643 // Don't resolve overloads if the other type is overloadable. 12644 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12645 LHSExpr->getType()->isOverloadableType()) 12646 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12647 12648 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12649 if (!resolvedRHS.isUsable()) return ExprError(); 12650 RHSExpr = resolvedRHS.get(); 12651 } 12652 12653 if (getLangOpts().CPlusPlus) { 12654 // If either expression is type-dependent, always build an 12655 // overloaded op. 12656 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12657 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12658 12659 // Otherwise, build an overloaded op if either expression has an 12660 // overloadable type. 12661 if (LHSExpr->getType()->isOverloadableType() || 12662 RHSExpr->getType()->isOverloadableType()) 12663 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12664 } 12665 12666 // Build a built-in binary operation. 12667 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12668 } 12669 12670 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12671 if (T.isNull() || T->isDependentType()) 12672 return false; 12673 12674 if (!T->isPromotableIntegerType()) 12675 return true; 12676 12677 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12678 } 12679 12680 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12681 UnaryOperatorKind Opc, 12682 Expr *InputExpr) { 12683 ExprResult Input = InputExpr; 12684 ExprValueKind VK = VK_RValue; 12685 ExprObjectKind OK = OK_Ordinary; 12686 QualType resultType; 12687 bool CanOverflow = false; 12688 12689 bool ConvertHalfVec = false; 12690 if (getLangOpts().OpenCL) { 12691 QualType Ty = InputExpr->getType(); 12692 // The only legal unary operation for atomics is '&'. 12693 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12694 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12695 // only with a builtin functions and therefore should be disallowed here. 12696 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12697 || Ty->isBlockPointerType())) { 12698 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12699 << InputExpr->getType() 12700 << Input.get()->getSourceRange()); 12701 } 12702 } 12703 switch (Opc) { 12704 case UO_PreInc: 12705 case UO_PreDec: 12706 case UO_PostInc: 12707 case UO_PostDec: 12708 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12709 OpLoc, 12710 Opc == UO_PreInc || 12711 Opc == UO_PostInc, 12712 Opc == UO_PreInc || 12713 Opc == UO_PreDec); 12714 CanOverflow = isOverflowingIntegerType(Context, resultType); 12715 break; 12716 case UO_AddrOf: 12717 resultType = CheckAddressOfOperand(Input, OpLoc); 12718 RecordModifiableNonNullParam(*this, InputExpr); 12719 break; 12720 case UO_Deref: { 12721 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12722 if (Input.isInvalid()) return ExprError(); 12723 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12724 break; 12725 } 12726 case UO_Plus: 12727 case UO_Minus: 12728 CanOverflow = Opc == UO_Minus && 12729 isOverflowingIntegerType(Context, Input.get()->getType()); 12730 Input = UsualUnaryConversions(Input.get()); 12731 if (Input.isInvalid()) return ExprError(); 12732 // Unary plus and minus require promoting an operand of half vector to a 12733 // float vector and truncating the result back to a half vector. For now, we 12734 // do this only when HalfArgsAndReturns is set (that is, when the target is 12735 // arm or arm64). 12736 ConvertHalfVec = 12737 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12738 12739 // If the operand is a half vector, promote it to a float vector. 12740 if (ConvertHalfVec) 12741 Input = convertVector(Input.get(), Context.FloatTy, *this); 12742 resultType = Input.get()->getType(); 12743 if (resultType->isDependentType()) 12744 break; 12745 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12746 break; 12747 else if (resultType->isVectorType() && 12748 // The z vector extensions don't allow + or - with bool vectors. 12749 (!Context.getLangOpts().ZVector || 12750 resultType->getAs<VectorType>()->getVectorKind() != 12751 VectorType::AltiVecBool)) 12752 break; 12753 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12754 Opc == UO_Plus && 12755 resultType->isPointerType()) 12756 break; 12757 12758 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12759 << resultType << Input.get()->getSourceRange()); 12760 12761 case UO_Not: // bitwise complement 12762 Input = UsualUnaryConversions(Input.get()); 12763 if (Input.isInvalid()) 12764 return ExprError(); 12765 resultType = Input.get()->getType(); 12766 12767 if (resultType->isDependentType()) 12768 break; 12769 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12770 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12771 // C99 does not support '~' for complex conjugation. 12772 Diag(OpLoc, diag::ext_integer_complement_complex) 12773 << resultType << Input.get()->getSourceRange(); 12774 else if (resultType->hasIntegerRepresentation()) 12775 break; 12776 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12777 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12778 // on vector float types. 12779 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12780 if (!T->isIntegerType()) 12781 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12782 << resultType << Input.get()->getSourceRange()); 12783 } else { 12784 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12785 << resultType << Input.get()->getSourceRange()); 12786 } 12787 break; 12788 12789 case UO_LNot: // logical negation 12790 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12791 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12792 if (Input.isInvalid()) return ExprError(); 12793 resultType = Input.get()->getType(); 12794 12795 // Though we still have to promote half FP to float... 12796 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12797 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12798 resultType = Context.FloatTy; 12799 } 12800 12801 if (resultType->isDependentType()) 12802 break; 12803 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12804 // C99 6.5.3.3p1: ok, fallthrough; 12805 if (Context.getLangOpts().CPlusPlus) { 12806 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12807 // operand contextually converted to bool. 12808 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12809 ScalarTypeToBooleanCastKind(resultType)); 12810 } else if (Context.getLangOpts().OpenCL && 12811 Context.getLangOpts().OpenCLVersion < 120) { 12812 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12813 // operate on scalar float types. 12814 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12815 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12816 << resultType << Input.get()->getSourceRange()); 12817 } 12818 } else if (resultType->isExtVectorType()) { 12819 if (Context.getLangOpts().OpenCL && 12820 Context.getLangOpts().OpenCLVersion < 120) { 12821 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12822 // operate on vector float types. 12823 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12824 if (!T->isIntegerType()) 12825 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12826 << resultType << Input.get()->getSourceRange()); 12827 } 12828 // Vector logical not returns the signed variant of the operand type. 12829 resultType = GetSignedVectorType(resultType); 12830 break; 12831 } else { 12832 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12833 // type in C++. We should allow that here too. 12834 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12835 << resultType << Input.get()->getSourceRange()); 12836 } 12837 12838 // LNot always has type int. C99 6.5.3.3p5. 12839 // In C++, it's bool. C++ 5.3.1p8 12840 resultType = Context.getLogicalOperationType(); 12841 break; 12842 case UO_Real: 12843 case UO_Imag: 12844 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12845 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12846 // complex l-values to ordinary l-values and all other values to r-values. 12847 if (Input.isInvalid()) return ExprError(); 12848 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12849 if (Input.get()->getValueKind() != VK_RValue && 12850 Input.get()->getObjectKind() == OK_Ordinary) 12851 VK = Input.get()->getValueKind(); 12852 } else if (!getLangOpts().CPlusPlus) { 12853 // In C, a volatile scalar is read by __imag. In C++, it is not. 12854 Input = DefaultLvalueConversion(Input.get()); 12855 } 12856 break; 12857 case UO_Extension: 12858 resultType = Input.get()->getType(); 12859 VK = Input.get()->getValueKind(); 12860 OK = Input.get()->getObjectKind(); 12861 break; 12862 case UO_Coawait: 12863 // It's unnecessary to represent the pass-through operator co_await in the 12864 // AST; just return the input expression instead. 12865 assert(!Input.get()->getType()->isDependentType() && 12866 "the co_await expression must be non-dependant before " 12867 "building operator co_await"); 12868 return Input; 12869 } 12870 if (resultType.isNull() || Input.isInvalid()) 12871 return ExprError(); 12872 12873 // Check for array bounds violations in the operand of the UnaryOperator, 12874 // except for the '*' and '&' operators that have to be handled specially 12875 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12876 // that are explicitly defined as valid by the standard). 12877 if (Opc != UO_AddrOf && Opc != UO_Deref) 12878 CheckArrayAccess(Input.get()); 12879 12880 auto *UO = new (Context) 12881 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12882 // Convert the result back to a half vector. 12883 if (ConvertHalfVec) 12884 return convertVector(UO, Context.HalfTy, *this); 12885 return UO; 12886 } 12887 12888 /// Determine whether the given expression is a qualified member 12889 /// access expression, of a form that could be turned into a pointer to member 12890 /// with the address-of operator. 12891 bool Sema::isQualifiedMemberAccess(Expr *E) { 12892 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12893 if (!DRE->getQualifier()) 12894 return false; 12895 12896 ValueDecl *VD = DRE->getDecl(); 12897 if (!VD->isCXXClassMember()) 12898 return false; 12899 12900 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12901 return true; 12902 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12903 return Method->isInstance(); 12904 12905 return false; 12906 } 12907 12908 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12909 if (!ULE->getQualifier()) 12910 return false; 12911 12912 for (NamedDecl *D : ULE->decls()) { 12913 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12914 if (Method->isInstance()) 12915 return true; 12916 } else { 12917 // Overload set does not contain methods. 12918 break; 12919 } 12920 } 12921 12922 return false; 12923 } 12924 12925 return false; 12926 } 12927 12928 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12929 UnaryOperatorKind Opc, Expr *Input) { 12930 // First things first: handle placeholders so that the 12931 // overloaded-operator check considers the right type. 12932 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12933 // Increment and decrement of pseudo-object references. 12934 if (pty->getKind() == BuiltinType::PseudoObject && 12935 UnaryOperator::isIncrementDecrementOp(Opc)) 12936 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12937 12938 // extension is always a builtin operator. 12939 if (Opc == UO_Extension) 12940 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12941 12942 // & gets special logic for several kinds of placeholder. 12943 // The builtin code knows what to do. 12944 if (Opc == UO_AddrOf && 12945 (pty->getKind() == BuiltinType::Overload || 12946 pty->getKind() == BuiltinType::UnknownAny || 12947 pty->getKind() == BuiltinType::BoundMember)) 12948 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12949 12950 // Anything else needs to be handled now. 12951 ExprResult Result = CheckPlaceholderExpr(Input); 12952 if (Result.isInvalid()) return ExprError(); 12953 Input = Result.get(); 12954 } 12955 12956 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12957 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12958 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12959 // Find all of the overloaded operators visible from this 12960 // point. We perform both an operator-name lookup from the local 12961 // scope and an argument-dependent lookup based on the types of 12962 // the arguments. 12963 UnresolvedSet<16> Functions; 12964 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12965 if (S && OverOp != OO_None) 12966 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12967 Functions); 12968 12969 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12970 } 12971 12972 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12973 } 12974 12975 // Unary Operators. 'Tok' is the token for the operator. 12976 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12977 tok::TokenKind Op, Expr *Input) { 12978 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12979 } 12980 12981 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12982 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12983 LabelDecl *TheDecl) { 12984 TheDecl->markUsed(Context); 12985 // Create the AST node. The address of a label always has type 'void*'. 12986 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12987 Context.getPointerType(Context.VoidTy)); 12988 } 12989 12990 /// Given the last statement in a statement-expression, check whether 12991 /// the result is a producing expression (like a call to an 12992 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12993 /// release out of the full-expression. Otherwise, return null. 12994 /// Cannot fail. 12995 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12996 // Should always be wrapped with one of these. 12997 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12998 if (!cleanups) return nullptr; 12999 13000 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 13001 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 13002 return nullptr; 13003 13004 // Splice out the cast. This shouldn't modify any interesting 13005 // features of the statement. 13006 Expr *producer = cast->getSubExpr(); 13007 assert(producer->getType() == cast->getType()); 13008 assert(producer->getValueKind() == cast->getValueKind()); 13009 cleanups->setSubExpr(producer); 13010 return cleanups; 13011 } 13012 13013 void Sema::ActOnStartStmtExpr() { 13014 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13015 } 13016 13017 void Sema::ActOnStmtExprError() { 13018 // Note that function is also called by TreeTransform when leaving a 13019 // StmtExpr scope without rebuilding anything. 13020 13021 DiscardCleanupsInEvaluationContext(); 13022 PopExpressionEvaluationContext(); 13023 } 13024 13025 ExprResult 13026 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13027 SourceLocation RPLoc) { // "({..})" 13028 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13029 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13030 13031 if (hasAnyUnrecoverableErrorsInThisFunction()) 13032 DiscardCleanupsInEvaluationContext(); 13033 assert(!Cleanup.exprNeedsCleanups() && 13034 "cleanups within StmtExpr not correctly bound!"); 13035 PopExpressionEvaluationContext(); 13036 13037 // FIXME: there are a variety of strange constraints to enforce here, for 13038 // example, it is not possible to goto into a stmt expression apparently. 13039 // More semantic analysis is needed. 13040 13041 // If there are sub-stmts in the compound stmt, take the type of the last one 13042 // as the type of the stmtexpr. 13043 QualType Ty = Context.VoidTy; 13044 bool StmtExprMayBindToTemp = false; 13045 if (!Compound->body_empty()) { 13046 Stmt *LastStmt = Compound->body_back(); 13047 LabelStmt *LastLabelStmt = nullptr; 13048 // If LastStmt is a label, skip down through into the body. 13049 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 13050 LastLabelStmt = Label; 13051 LastStmt = Label->getSubStmt(); 13052 } 13053 13054 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 13055 // Do function/array conversion on the last expression, but not 13056 // lvalue-to-rvalue. However, initialize an unqualified type. 13057 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 13058 if (LastExpr.isInvalid()) 13059 return ExprError(); 13060 Ty = LastExpr.get()->getType().getUnqualifiedType(); 13061 13062 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 13063 // In ARC, if the final expression ends in a consume, splice 13064 // the consume out and bind it later. In the alternate case 13065 // (when dealing with a retainable type), the result 13066 // initialization will create a produce. In both cases the 13067 // result will be +1, and we'll need to balance that out with 13068 // a bind. 13069 if (Expr *rebuiltLastStmt 13070 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 13071 LastExpr = rebuiltLastStmt; 13072 } else { 13073 LastExpr = PerformCopyInitialization( 13074 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 13075 SourceLocation(), LastExpr); 13076 } 13077 13078 if (LastExpr.isInvalid()) 13079 return ExprError(); 13080 if (LastExpr.get() != nullptr) { 13081 if (!LastLabelStmt) 13082 Compound->setLastStmt(LastExpr.get()); 13083 else 13084 LastLabelStmt->setSubStmt(LastExpr.get()); 13085 StmtExprMayBindToTemp = true; 13086 } 13087 } 13088 } 13089 } 13090 13091 // FIXME: Check that expression type is complete/non-abstract; statement 13092 // expressions are not lvalues. 13093 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13094 if (StmtExprMayBindToTemp) 13095 return MaybeBindToTemporary(ResStmtExpr); 13096 return ResStmtExpr; 13097 } 13098 13099 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13100 TypeSourceInfo *TInfo, 13101 ArrayRef<OffsetOfComponent> Components, 13102 SourceLocation RParenLoc) { 13103 QualType ArgTy = TInfo->getType(); 13104 bool Dependent = ArgTy->isDependentType(); 13105 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13106 13107 // We must have at least one component that refers to the type, and the first 13108 // one is known to be a field designator. Verify that the ArgTy represents 13109 // a struct/union/class. 13110 if (!Dependent && !ArgTy->isRecordType()) 13111 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13112 << ArgTy << TypeRange); 13113 13114 // Type must be complete per C99 7.17p3 because a declaring a variable 13115 // with an incomplete type would be ill-formed. 13116 if (!Dependent 13117 && RequireCompleteType(BuiltinLoc, ArgTy, 13118 diag::err_offsetof_incomplete_type, TypeRange)) 13119 return ExprError(); 13120 13121 bool DidWarnAboutNonPOD = false; 13122 QualType CurrentType = ArgTy; 13123 SmallVector<OffsetOfNode, 4> Comps; 13124 SmallVector<Expr*, 4> Exprs; 13125 for (const OffsetOfComponent &OC : Components) { 13126 if (OC.isBrackets) { 13127 // Offset of an array sub-field. TODO: Should we allow vector elements? 13128 if (!CurrentType->isDependentType()) { 13129 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13130 if(!AT) 13131 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13132 << CurrentType); 13133 CurrentType = AT->getElementType(); 13134 } else 13135 CurrentType = Context.DependentTy; 13136 13137 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13138 if (IdxRval.isInvalid()) 13139 return ExprError(); 13140 Expr *Idx = IdxRval.get(); 13141 13142 // The expression must be an integral expression. 13143 // FIXME: An integral constant expression? 13144 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13145 !Idx->getType()->isIntegerType()) 13146 return ExprError( 13147 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13148 << Idx->getSourceRange()); 13149 13150 // Record this array index. 13151 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13152 Exprs.push_back(Idx); 13153 continue; 13154 } 13155 13156 // Offset of a field. 13157 if (CurrentType->isDependentType()) { 13158 // We have the offset of a field, but we can't look into the dependent 13159 // type. Just record the identifier of the field. 13160 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13161 CurrentType = Context.DependentTy; 13162 continue; 13163 } 13164 13165 // We need to have a complete type to look into. 13166 if (RequireCompleteType(OC.LocStart, CurrentType, 13167 diag::err_offsetof_incomplete_type)) 13168 return ExprError(); 13169 13170 // Look for the designated field. 13171 const RecordType *RC = CurrentType->getAs<RecordType>(); 13172 if (!RC) 13173 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13174 << CurrentType); 13175 RecordDecl *RD = RC->getDecl(); 13176 13177 // C++ [lib.support.types]p5: 13178 // The macro offsetof accepts a restricted set of type arguments in this 13179 // International Standard. type shall be a POD structure or a POD union 13180 // (clause 9). 13181 // C++11 [support.types]p4: 13182 // If type is not a standard-layout class (Clause 9), the results are 13183 // undefined. 13184 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13185 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13186 unsigned DiagID = 13187 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13188 : diag::ext_offsetof_non_pod_type; 13189 13190 if (!IsSafe && !DidWarnAboutNonPOD && 13191 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13192 PDiag(DiagID) 13193 << SourceRange(Components[0].LocStart, OC.LocEnd) 13194 << CurrentType)) 13195 DidWarnAboutNonPOD = true; 13196 } 13197 13198 // Look for the field. 13199 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13200 LookupQualifiedName(R, RD); 13201 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13202 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13203 if (!MemberDecl) { 13204 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13205 MemberDecl = IndirectMemberDecl->getAnonField(); 13206 } 13207 13208 if (!MemberDecl) 13209 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13210 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13211 OC.LocEnd)); 13212 13213 // C99 7.17p3: 13214 // (If the specified member is a bit-field, the behavior is undefined.) 13215 // 13216 // We diagnose this as an error. 13217 if (MemberDecl->isBitField()) { 13218 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13219 << MemberDecl->getDeclName() 13220 << SourceRange(BuiltinLoc, RParenLoc); 13221 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13222 return ExprError(); 13223 } 13224 13225 RecordDecl *Parent = MemberDecl->getParent(); 13226 if (IndirectMemberDecl) 13227 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13228 13229 // If the member was found in a base class, introduce OffsetOfNodes for 13230 // the base class indirections. 13231 CXXBasePaths Paths; 13232 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13233 Paths)) { 13234 if (Paths.getDetectedVirtual()) { 13235 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13236 << MemberDecl->getDeclName() 13237 << SourceRange(BuiltinLoc, RParenLoc); 13238 return ExprError(); 13239 } 13240 13241 CXXBasePath &Path = Paths.front(); 13242 for (const CXXBasePathElement &B : Path) 13243 Comps.push_back(OffsetOfNode(B.Base)); 13244 } 13245 13246 if (IndirectMemberDecl) { 13247 for (auto *FI : IndirectMemberDecl->chain()) { 13248 assert(isa<FieldDecl>(FI)); 13249 Comps.push_back(OffsetOfNode(OC.LocStart, 13250 cast<FieldDecl>(FI), OC.LocEnd)); 13251 } 13252 } else 13253 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13254 13255 CurrentType = MemberDecl->getType().getNonReferenceType(); 13256 } 13257 13258 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13259 Comps, Exprs, RParenLoc); 13260 } 13261 13262 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13263 SourceLocation BuiltinLoc, 13264 SourceLocation TypeLoc, 13265 ParsedType ParsedArgTy, 13266 ArrayRef<OffsetOfComponent> Components, 13267 SourceLocation RParenLoc) { 13268 13269 TypeSourceInfo *ArgTInfo; 13270 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13271 if (ArgTy.isNull()) 13272 return ExprError(); 13273 13274 if (!ArgTInfo) 13275 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13276 13277 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13278 } 13279 13280 13281 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13282 Expr *CondExpr, 13283 Expr *LHSExpr, Expr *RHSExpr, 13284 SourceLocation RPLoc) { 13285 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13286 13287 ExprValueKind VK = VK_RValue; 13288 ExprObjectKind OK = OK_Ordinary; 13289 QualType resType; 13290 bool ValueDependent = false; 13291 bool CondIsTrue = false; 13292 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13293 resType = Context.DependentTy; 13294 ValueDependent = true; 13295 } else { 13296 // The conditional expression is required to be a constant expression. 13297 llvm::APSInt condEval(32); 13298 ExprResult CondICE 13299 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13300 diag::err_typecheck_choose_expr_requires_constant, false); 13301 if (CondICE.isInvalid()) 13302 return ExprError(); 13303 CondExpr = CondICE.get(); 13304 CondIsTrue = condEval.getZExtValue(); 13305 13306 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13307 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13308 13309 resType = ActiveExpr->getType(); 13310 ValueDependent = ActiveExpr->isValueDependent(); 13311 VK = ActiveExpr->getValueKind(); 13312 OK = ActiveExpr->getObjectKind(); 13313 } 13314 13315 return new (Context) 13316 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13317 CondIsTrue, resType->isDependentType(), ValueDependent); 13318 } 13319 13320 //===----------------------------------------------------------------------===// 13321 // Clang Extensions. 13322 //===----------------------------------------------------------------------===// 13323 13324 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13325 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13326 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13327 13328 if (LangOpts.CPlusPlus) { 13329 Decl *ManglingContextDecl; 13330 if (MangleNumberingContext *MCtx = 13331 getCurrentMangleNumberContext(Block->getDeclContext(), 13332 ManglingContextDecl)) { 13333 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13334 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13335 } 13336 } 13337 13338 PushBlockScope(CurScope, Block); 13339 CurContext->addDecl(Block); 13340 if (CurScope) 13341 PushDeclContext(CurScope, Block); 13342 else 13343 CurContext = Block; 13344 13345 getCurBlock()->HasImplicitReturnType = true; 13346 13347 // Enter a new evaluation context to insulate the block from any 13348 // cleanups from the enclosing full-expression. 13349 PushExpressionEvaluationContext( 13350 ExpressionEvaluationContext::PotentiallyEvaluated); 13351 } 13352 13353 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13354 Scope *CurScope) { 13355 assert(ParamInfo.getIdentifier() == nullptr && 13356 "block-id should have no identifier!"); 13357 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13358 BlockScopeInfo *CurBlock = getCurBlock(); 13359 13360 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13361 QualType T = Sig->getType(); 13362 13363 // FIXME: We should allow unexpanded parameter packs here, but that would, 13364 // in turn, make the block expression contain unexpanded parameter packs. 13365 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13366 // Drop the parameters. 13367 FunctionProtoType::ExtProtoInfo EPI; 13368 EPI.HasTrailingReturn = false; 13369 EPI.TypeQuals |= DeclSpec::TQ_const; 13370 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13371 Sig = Context.getTrivialTypeSourceInfo(T); 13372 } 13373 13374 // GetTypeForDeclarator always produces a function type for a block 13375 // literal signature. Furthermore, it is always a FunctionProtoType 13376 // unless the function was written with a typedef. 13377 assert(T->isFunctionType() && 13378 "GetTypeForDeclarator made a non-function block signature"); 13379 13380 // Look for an explicit signature in that function type. 13381 FunctionProtoTypeLoc ExplicitSignature; 13382 13383 if ((ExplicitSignature = 13384 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13385 13386 // Check whether that explicit signature was synthesized by 13387 // GetTypeForDeclarator. If so, don't save that as part of the 13388 // written signature. 13389 if (ExplicitSignature.getLocalRangeBegin() == 13390 ExplicitSignature.getLocalRangeEnd()) { 13391 // This would be much cheaper if we stored TypeLocs instead of 13392 // TypeSourceInfos. 13393 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13394 unsigned Size = Result.getFullDataSize(); 13395 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13396 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13397 13398 ExplicitSignature = FunctionProtoTypeLoc(); 13399 } 13400 } 13401 13402 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13403 CurBlock->FunctionType = T; 13404 13405 const FunctionType *Fn = T->getAs<FunctionType>(); 13406 QualType RetTy = Fn->getReturnType(); 13407 bool isVariadic = 13408 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13409 13410 CurBlock->TheDecl->setIsVariadic(isVariadic); 13411 13412 // Context.DependentTy is used as a placeholder for a missing block 13413 // return type. TODO: what should we do with declarators like: 13414 // ^ * { ... } 13415 // If the answer is "apply template argument deduction".... 13416 if (RetTy != Context.DependentTy) { 13417 CurBlock->ReturnType = RetTy; 13418 CurBlock->TheDecl->setBlockMissingReturnType(false); 13419 CurBlock->HasImplicitReturnType = false; 13420 } 13421 13422 // Push block parameters from the declarator if we had them. 13423 SmallVector<ParmVarDecl*, 8> Params; 13424 if (ExplicitSignature) { 13425 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13426 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13427 if (Param->getIdentifier() == nullptr && 13428 !Param->isImplicit() && 13429 !Param->isInvalidDecl() && 13430 !getLangOpts().CPlusPlus) 13431 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13432 Params.push_back(Param); 13433 } 13434 13435 // Fake up parameter variables if we have a typedef, like 13436 // ^ fntype { ... } 13437 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13438 for (const auto &I : Fn->param_types()) { 13439 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13440 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13441 Params.push_back(Param); 13442 } 13443 } 13444 13445 // Set the parameters on the block decl. 13446 if (!Params.empty()) { 13447 CurBlock->TheDecl->setParams(Params); 13448 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13449 /*CheckParameterNames=*/false); 13450 } 13451 13452 // Finally we can process decl attributes. 13453 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13454 13455 // Put the parameter variables in scope. 13456 for (auto AI : CurBlock->TheDecl->parameters()) { 13457 AI->setOwningFunction(CurBlock->TheDecl); 13458 13459 // If this has an identifier, add it to the scope stack. 13460 if (AI->getIdentifier()) { 13461 CheckShadow(CurBlock->TheScope, AI); 13462 13463 PushOnScopeChains(AI, CurBlock->TheScope); 13464 } 13465 } 13466 } 13467 13468 /// ActOnBlockError - If there is an error parsing a block, this callback 13469 /// is invoked to pop the information about the block from the action impl. 13470 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13471 // Leave the expression-evaluation context. 13472 DiscardCleanupsInEvaluationContext(); 13473 PopExpressionEvaluationContext(); 13474 13475 // Pop off CurBlock, handle nested blocks. 13476 PopDeclContext(); 13477 PopFunctionScopeInfo(); 13478 } 13479 13480 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13481 /// literal was successfully completed. ^(int x){...} 13482 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13483 Stmt *Body, Scope *CurScope) { 13484 // If blocks are disabled, emit an error. 13485 if (!LangOpts.Blocks) 13486 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13487 13488 // Leave the expression-evaluation context. 13489 if (hasAnyUnrecoverableErrorsInThisFunction()) 13490 DiscardCleanupsInEvaluationContext(); 13491 assert(!Cleanup.exprNeedsCleanups() && 13492 "cleanups within block not correctly bound!"); 13493 PopExpressionEvaluationContext(); 13494 13495 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13496 BlockDecl *BD = BSI->TheDecl; 13497 13498 if (BSI->HasImplicitReturnType) 13499 deduceClosureReturnType(*BSI); 13500 13501 PopDeclContext(); 13502 13503 QualType RetTy = Context.VoidTy; 13504 if (!BSI->ReturnType.isNull()) 13505 RetTy = BSI->ReturnType; 13506 13507 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13508 QualType BlockTy; 13509 13510 // Set the captured variables on the block. 13511 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13512 SmallVector<BlockDecl::Capture, 4> Captures; 13513 for (Capture &Cap : BSI->Captures) { 13514 if (Cap.isThisCapture()) 13515 continue; 13516 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13517 Cap.isNested(), Cap.getInitExpr()); 13518 Captures.push_back(NewCap); 13519 } 13520 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13521 13522 // If the user wrote a function type in some form, try to use that. 13523 if (!BSI->FunctionType.isNull()) { 13524 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13525 13526 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13527 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13528 13529 // Turn protoless block types into nullary block types. 13530 if (isa<FunctionNoProtoType>(FTy)) { 13531 FunctionProtoType::ExtProtoInfo EPI; 13532 EPI.ExtInfo = Ext; 13533 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13534 13535 // Otherwise, if we don't need to change anything about the function type, 13536 // preserve its sugar structure. 13537 } else if (FTy->getReturnType() == RetTy && 13538 (!NoReturn || FTy->getNoReturnAttr())) { 13539 BlockTy = BSI->FunctionType; 13540 13541 // Otherwise, make the minimal modifications to the function type. 13542 } else { 13543 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13544 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13545 EPI.TypeQuals = 0; // FIXME: silently? 13546 EPI.ExtInfo = Ext; 13547 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13548 } 13549 13550 // If we don't have a function type, just build one from nothing. 13551 } else { 13552 FunctionProtoType::ExtProtoInfo EPI; 13553 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13554 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13555 } 13556 13557 DiagnoseUnusedParameters(BD->parameters()); 13558 BlockTy = Context.getBlockPointerType(BlockTy); 13559 13560 // If needed, diagnose invalid gotos and switches in the block. 13561 if (getCurFunction()->NeedsScopeChecking() && 13562 !PP.isCodeCompletionEnabled()) 13563 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13564 13565 BD->setBody(cast<CompoundStmt>(Body)); 13566 13567 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13568 DiagnoseUnguardedAvailabilityViolations(BD); 13569 13570 // Try to apply the named return value optimization. We have to check again 13571 // if we can do this, though, because blocks keep return statements around 13572 // to deduce an implicit return type. 13573 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13574 !BD->isDependentContext()) 13575 computeNRVO(Body, BSI); 13576 13577 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13578 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13579 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13580 13581 // If the block isn't obviously global, i.e. it captures anything at 13582 // all, then we need to do a few things in the surrounding context: 13583 if (Result->getBlockDecl()->hasCaptures()) { 13584 // First, this expression has a new cleanup object. 13585 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13586 Cleanup.setExprNeedsCleanups(true); 13587 13588 // It also gets a branch-protected scope if any of the captured 13589 // variables needs destruction. 13590 for (const auto &CI : Result->getBlockDecl()->captures()) { 13591 const VarDecl *var = CI.getVariable(); 13592 if (var->getType().isDestructedType() != QualType::DK_none) { 13593 setFunctionHasBranchProtectedScope(); 13594 break; 13595 } 13596 } 13597 } 13598 13599 if (getCurFunction()) 13600 getCurFunction()->addBlock(BD); 13601 13602 return Result; 13603 } 13604 13605 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13606 SourceLocation RPLoc) { 13607 TypeSourceInfo *TInfo; 13608 GetTypeFromParser(Ty, &TInfo); 13609 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13610 } 13611 13612 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13613 Expr *E, TypeSourceInfo *TInfo, 13614 SourceLocation RPLoc) { 13615 Expr *OrigExpr = E; 13616 bool IsMS = false; 13617 13618 // CUDA device code does not support varargs. 13619 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13620 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13621 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13622 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13623 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13624 } 13625 } 13626 13627 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13628 // as Microsoft ABI on an actual Microsoft platform, where 13629 // __builtin_ms_va_list and __builtin_va_list are the same.) 13630 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13631 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13632 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13633 if (Context.hasSameType(MSVaListType, E->getType())) { 13634 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13635 return ExprError(); 13636 IsMS = true; 13637 } 13638 } 13639 13640 // Get the va_list type 13641 QualType VaListType = Context.getBuiltinVaListType(); 13642 if (!IsMS) { 13643 if (VaListType->isArrayType()) { 13644 // Deal with implicit array decay; for example, on x86-64, 13645 // va_list is an array, but it's supposed to decay to 13646 // a pointer for va_arg. 13647 VaListType = Context.getArrayDecayedType(VaListType); 13648 // Make sure the input expression also decays appropriately. 13649 ExprResult Result = UsualUnaryConversions(E); 13650 if (Result.isInvalid()) 13651 return ExprError(); 13652 E = Result.get(); 13653 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13654 // If va_list is a record type and we are compiling in C++ mode, 13655 // check the argument using reference binding. 13656 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13657 Context, Context.getLValueReferenceType(VaListType), false); 13658 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13659 if (Init.isInvalid()) 13660 return ExprError(); 13661 E = Init.getAs<Expr>(); 13662 } else { 13663 // Otherwise, the va_list argument must be an l-value because 13664 // it is modified by va_arg. 13665 if (!E->isTypeDependent() && 13666 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13667 return ExprError(); 13668 } 13669 } 13670 13671 if (!IsMS && !E->isTypeDependent() && 13672 !Context.hasSameType(VaListType, E->getType())) 13673 return ExprError( 13674 Diag(E->getBeginLoc(), 13675 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13676 << OrigExpr->getType() << E->getSourceRange()); 13677 13678 if (!TInfo->getType()->isDependentType()) { 13679 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13680 diag::err_second_parameter_to_va_arg_incomplete, 13681 TInfo->getTypeLoc())) 13682 return ExprError(); 13683 13684 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13685 TInfo->getType(), 13686 diag::err_second_parameter_to_va_arg_abstract, 13687 TInfo->getTypeLoc())) 13688 return ExprError(); 13689 13690 if (!TInfo->getType().isPODType(Context)) { 13691 Diag(TInfo->getTypeLoc().getBeginLoc(), 13692 TInfo->getType()->isObjCLifetimeType() 13693 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13694 : diag::warn_second_parameter_to_va_arg_not_pod) 13695 << TInfo->getType() 13696 << TInfo->getTypeLoc().getSourceRange(); 13697 } 13698 13699 // Check for va_arg where arguments of the given type will be promoted 13700 // (i.e. this va_arg is guaranteed to have undefined behavior). 13701 QualType PromoteType; 13702 if (TInfo->getType()->isPromotableIntegerType()) { 13703 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13704 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13705 PromoteType = QualType(); 13706 } 13707 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13708 PromoteType = Context.DoubleTy; 13709 if (!PromoteType.isNull()) 13710 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13711 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13712 << TInfo->getType() 13713 << PromoteType 13714 << TInfo->getTypeLoc().getSourceRange()); 13715 } 13716 13717 QualType T = TInfo->getType().getNonLValueExprType(Context); 13718 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13719 } 13720 13721 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13722 // The type of __null will be int or long, depending on the size of 13723 // pointers on the target. 13724 QualType Ty; 13725 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13726 if (pw == Context.getTargetInfo().getIntWidth()) 13727 Ty = Context.IntTy; 13728 else if (pw == Context.getTargetInfo().getLongWidth()) 13729 Ty = Context.LongTy; 13730 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13731 Ty = Context.LongLongTy; 13732 else { 13733 llvm_unreachable("I don't know size of pointer!"); 13734 } 13735 13736 return new (Context) GNUNullExpr(Ty, TokenLoc); 13737 } 13738 13739 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13740 bool Diagnose) { 13741 if (!getLangOpts().ObjC1) 13742 return false; 13743 13744 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13745 if (!PT) 13746 return false; 13747 13748 if (!PT->isObjCIdType()) { 13749 // Check if the destination is the 'NSString' interface. 13750 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13751 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13752 return false; 13753 } 13754 13755 // Ignore any parens, implicit casts (should only be 13756 // array-to-pointer decays), and not-so-opaque values. The last is 13757 // important for making this trigger for property assignments. 13758 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13759 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13760 if (OV->getSourceExpr()) 13761 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13762 13763 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13764 if (!SL || !SL->isAscii()) 13765 return false; 13766 if (Diagnose) { 13767 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13768 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13769 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13770 } 13771 return true; 13772 } 13773 13774 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13775 const Expr *SrcExpr) { 13776 if (!DstType->isFunctionPointerType() || 13777 !SrcExpr->getType()->isFunctionType()) 13778 return false; 13779 13780 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13781 if (!DRE) 13782 return false; 13783 13784 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13785 if (!FD) 13786 return false; 13787 13788 return !S.checkAddressOfFunctionIsAvailable(FD, 13789 /*Complain=*/true, 13790 SrcExpr->getBeginLoc()); 13791 } 13792 13793 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13794 SourceLocation Loc, 13795 QualType DstType, QualType SrcType, 13796 Expr *SrcExpr, AssignmentAction Action, 13797 bool *Complained) { 13798 if (Complained) 13799 *Complained = false; 13800 13801 // Decode the result (notice that AST's are still created for extensions). 13802 bool CheckInferredResultType = false; 13803 bool isInvalid = false; 13804 unsigned DiagKind = 0; 13805 FixItHint Hint; 13806 ConversionFixItGenerator ConvHints; 13807 bool MayHaveConvFixit = false; 13808 bool MayHaveFunctionDiff = false; 13809 const ObjCInterfaceDecl *IFace = nullptr; 13810 const ObjCProtocolDecl *PDecl = nullptr; 13811 13812 switch (ConvTy) { 13813 case Compatible: 13814 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13815 return false; 13816 13817 case PointerToInt: 13818 DiagKind = diag::ext_typecheck_convert_pointer_int; 13819 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13820 MayHaveConvFixit = true; 13821 break; 13822 case IntToPointer: 13823 DiagKind = diag::ext_typecheck_convert_int_pointer; 13824 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13825 MayHaveConvFixit = true; 13826 break; 13827 case IncompatiblePointer: 13828 if (Action == AA_Passing_CFAudited) 13829 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13830 else if (SrcType->isFunctionPointerType() && 13831 DstType->isFunctionPointerType()) 13832 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13833 else 13834 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13835 13836 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13837 SrcType->isObjCObjectPointerType(); 13838 if (Hint.isNull() && !CheckInferredResultType) { 13839 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13840 } 13841 else if (CheckInferredResultType) { 13842 SrcType = SrcType.getUnqualifiedType(); 13843 DstType = DstType.getUnqualifiedType(); 13844 } 13845 MayHaveConvFixit = true; 13846 break; 13847 case IncompatiblePointerSign: 13848 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13849 break; 13850 case FunctionVoidPointer: 13851 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13852 break; 13853 case IncompatiblePointerDiscardsQualifiers: { 13854 // Perform array-to-pointer decay if necessary. 13855 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13856 13857 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13858 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13859 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13860 DiagKind = diag::err_typecheck_incompatible_address_space; 13861 break; 13862 13863 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13864 DiagKind = diag::err_typecheck_incompatible_ownership; 13865 break; 13866 } 13867 13868 llvm_unreachable("unknown error case for discarding qualifiers!"); 13869 // fallthrough 13870 } 13871 case CompatiblePointerDiscardsQualifiers: 13872 // If the qualifiers lost were because we were applying the 13873 // (deprecated) C++ conversion from a string literal to a char* 13874 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13875 // Ideally, this check would be performed in 13876 // checkPointerTypesForAssignment. However, that would require a 13877 // bit of refactoring (so that the second argument is an 13878 // expression, rather than a type), which should be done as part 13879 // of a larger effort to fix checkPointerTypesForAssignment for 13880 // C++ semantics. 13881 if (getLangOpts().CPlusPlus && 13882 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13883 return false; 13884 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13885 break; 13886 case IncompatibleNestedPointerQualifiers: 13887 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13888 break; 13889 case IntToBlockPointer: 13890 DiagKind = diag::err_int_to_block_pointer; 13891 break; 13892 case IncompatibleBlockPointer: 13893 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13894 break; 13895 case IncompatibleObjCQualifiedId: { 13896 if (SrcType->isObjCQualifiedIdType()) { 13897 const ObjCObjectPointerType *srcOPT = 13898 SrcType->getAs<ObjCObjectPointerType>(); 13899 for (auto *srcProto : srcOPT->quals()) { 13900 PDecl = srcProto; 13901 break; 13902 } 13903 if (const ObjCInterfaceType *IFaceT = 13904 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13905 IFace = IFaceT->getDecl(); 13906 } 13907 else if (DstType->isObjCQualifiedIdType()) { 13908 const ObjCObjectPointerType *dstOPT = 13909 DstType->getAs<ObjCObjectPointerType>(); 13910 for (auto *dstProto : dstOPT->quals()) { 13911 PDecl = dstProto; 13912 break; 13913 } 13914 if (const ObjCInterfaceType *IFaceT = 13915 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13916 IFace = IFaceT->getDecl(); 13917 } 13918 DiagKind = diag::warn_incompatible_qualified_id; 13919 break; 13920 } 13921 case IncompatibleVectors: 13922 DiagKind = diag::warn_incompatible_vectors; 13923 break; 13924 case IncompatibleObjCWeakRef: 13925 DiagKind = diag::err_arc_weak_unavailable_assign; 13926 break; 13927 case Incompatible: 13928 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13929 if (Complained) 13930 *Complained = true; 13931 return true; 13932 } 13933 13934 DiagKind = diag::err_typecheck_convert_incompatible; 13935 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13936 MayHaveConvFixit = true; 13937 isInvalid = true; 13938 MayHaveFunctionDiff = true; 13939 break; 13940 } 13941 13942 QualType FirstType, SecondType; 13943 switch (Action) { 13944 case AA_Assigning: 13945 case AA_Initializing: 13946 // The destination type comes first. 13947 FirstType = DstType; 13948 SecondType = SrcType; 13949 break; 13950 13951 case AA_Returning: 13952 case AA_Passing: 13953 case AA_Passing_CFAudited: 13954 case AA_Converting: 13955 case AA_Sending: 13956 case AA_Casting: 13957 // The source type comes first. 13958 FirstType = SrcType; 13959 SecondType = DstType; 13960 break; 13961 } 13962 13963 PartialDiagnostic FDiag = PDiag(DiagKind); 13964 if (Action == AA_Passing_CFAudited) 13965 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13966 else 13967 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13968 13969 // If we can fix the conversion, suggest the FixIts. 13970 assert(ConvHints.isNull() || Hint.isNull()); 13971 if (!ConvHints.isNull()) { 13972 for (FixItHint &H : ConvHints.Hints) 13973 FDiag << H; 13974 } else { 13975 FDiag << Hint; 13976 } 13977 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13978 13979 if (MayHaveFunctionDiff) 13980 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13981 13982 Diag(Loc, FDiag); 13983 if (DiagKind == diag::warn_incompatible_qualified_id && 13984 PDecl && IFace && !IFace->hasDefinition()) 13985 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13986 << IFace << PDecl; 13987 13988 if (SecondType == Context.OverloadTy) 13989 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13990 FirstType, /*TakingAddress=*/true); 13991 13992 if (CheckInferredResultType) 13993 EmitRelatedResultTypeNote(SrcExpr); 13994 13995 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13996 EmitRelatedResultTypeNoteForReturn(DstType); 13997 13998 if (Complained) 13999 *Complained = true; 14000 return isInvalid; 14001 } 14002 14003 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14004 llvm::APSInt *Result) { 14005 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14006 public: 14007 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14008 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14009 } 14010 } Diagnoser; 14011 14012 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14013 } 14014 14015 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14016 llvm::APSInt *Result, 14017 unsigned DiagID, 14018 bool AllowFold) { 14019 class IDDiagnoser : public VerifyICEDiagnoser { 14020 unsigned DiagID; 14021 14022 public: 14023 IDDiagnoser(unsigned DiagID) 14024 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14025 14026 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14027 S.Diag(Loc, DiagID) << SR; 14028 } 14029 } Diagnoser(DiagID); 14030 14031 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14032 } 14033 14034 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14035 SourceRange SR) { 14036 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14037 } 14038 14039 ExprResult 14040 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14041 VerifyICEDiagnoser &Diagnoser, 14042 bool AllowFold) { 14043 SourceLocation DiagLoc = E->getBeginLoc(); 14044 14045 if (getLangOpts().CPlusPlus11) { 14046 // C++11 [expr.const]p5: 14047 // If an expression of literal class type is used in a context where an 14048 // integral constant expression is required, then that class type shall 14049 // have a single non-explicit conversion function to an integral or 14050 // unscoped enumeration type 14051 ExprResult Converted; 14052 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14053 public: 14054 CXX11ConvertDiagnoser(bool Silent) 14055 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14056 Silent, true) {} 14057 14058 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14059 QualType T) override { 14060 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14061 } 14062 14063 SemaDiagnosticBuilder diagnoseIncomplete( 14064 Sema &S, SourceLocation Loc, QualType T) override { 14065 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14066 } 14067 14068 SemaDiagnosticBuilder diagnoseExplicitConv( 14069 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14070 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14071 } 14072 14073 SemaDiagnosticBuilder noteExplicitConv( 14074 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14075 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14076 << ConvTy->isEnumeralType() << ConvTy; 14077 } 14078 14079 SemaDiagnosticBuilder diagnoseAmbiguous( 14080 Sema &S, SourceLocation Loc, QualType T) override { 14081 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14082 } 14083 14084 SemaDiagnosticBuilder noteAmbiguous( 14085 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14086 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14087 << ConvTy->isEnumeralType() << ConvTy; 14088 } 14089 14090 SemaDiagnosticBuilder diagnoseConversion( 14091 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14092 llvm_unreachable("conversion functions are permitted"); 14093 } 14094 } ConvertDiagnoser(Diagnoser.Suppress); 14095 14096 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14097 ConvertDiagnoser); 14098 if (Converted.isInvalid()) 14099 return Converted; 14100 E = Converted.get(); 14101 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14102 return ExprError(); 14103 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14104 // An ICE must be of integral or unscoped enumeration type. 14105 if (!Diagnoser.Suppress) 14106 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14107 return ExprError(); 14108 } 14109 14110 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14111 // in the non-ICE case. 14112 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14113 if (Result) 14114 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14115 return E; 14116 } 14117 14118 Expr::EvalResult EvalResult; 14119 SmallVector<PartialDiagnosticAt, 8> Notes; 14120 EvalResult.Diag = &Notes; 14121 14122 // Try to evaluate the expression, and produce diagnostics explaining why it's 14123 // not a constant expression as a side-effect. 14124 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14125 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14126 14127 // In C++11, we can rely on diagnostics being produced for any expression 14128 // which is not a constant expression. If no diagnostics were produced, then 14129 // this is a constant expression. 14130 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14131 if (Result) 14132 *Result = EvalResult.Val.getInt(); 14133 return E; 14134 } 14135 14136 // If our only note is the usual "invalid subexpression" note, just point 14137 // the caret at its location rather than producing an essentially 14138 // redundant note. 14139 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14140 diag::note_invalid_subexpr_in_const_expr) { 14141 DiagLoc = Notes[0].first; 14142 Notes.clear(); 14143 } 14144 14145 if (!Folded || !AllowFold) { 14146 if (!Diagnoser.Suppress) { 14147 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14148 for (const PartialDiagnosticAt &Note : Notes) 14149 Diag(Note.first, Note.second); 14150 } 14151 14152 return ExprError(); 14153 } 14154 14155 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14156 for (const PartialDiagnosticAt &Note : Notes) 14157 Diag(Note.first, Note.second); 14158 14159 if (Result) 14160 *Result = EvalResult.Val.getInt(); 14161 return E; 14162 } 14163 14164 namespace { 14165 // Handle the case where we conclude a expression which we speculatively 14166 // considered to be unevaluated is actually evaluated. 14167 class TransformToPE : public TreeTransform<TransformToPE> { 14168 typedef TreeTransform<TransformToPE> BaseTransform; 14169 14170 public: 14171 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14172 14173 // Make sure we redo semantic analysis 14174 bool AlwaysRebuild() { return true; } 14175 14176 // Make sure we handle LabelStmts correctly. 14177 // FIXME: This does the right thing, but maybe we need a more general 14178 // fix to TreeTransform? 14179 StmtResult TransformLabelStmt(LabelStmt *S) { 14180 S->getDecl()->setStmt(nullptr); 14181 return BaseTransform::TransformLabelStmt(S); 14182 } 14183 14184 // We need to special-case DeclRefExprs referring to FieldDecls which 14185 // are not part of a member pointer formation; normal TreeTransforming 14186 // doesn't catch this case because of the way we represent them in the AST. 14187 // FIXME: This is a bit ugly; is it really the best way to handle this 14188 // case? 14189 // 14190 // Error on DeclRefExprs referring to FieldDecls. 14191 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14192 if (isa<FieldDecl>(E->getDecl()) && 14193 !SemaRef.isUnevaluatedContext()) 14194 return SemaRef.Diag(E->getLocation(), 14195 diag::err_invalid_non_static_member_use) 14196 << E->getDecl() << E->getSourceRange(); 14197 14198 return BaseTransform::TransformDeclRefExpr(E); 14199 } 14200 14201 // Exception: filter out member pointer formation 14202 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14203 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14204 return E; 14205 14206 return BaseTransform::TransformUnaryOperator(E); 14207 } 14208 14209 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14210 // Lambdas never need to be transformed. 14211 return E; 14212 } 14213 }; 14214 } 14215 14216 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14217 assert(isUnevaluatedContext() && 14218 "Should only transform unevaluated expressions"); 14219 ExprEvalContexts.back().Context = 14220 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14221 if (isUnevaluatedContext()) 14222 return E; 14223 return TransformToPE(*this).TransformExpr(E); 14224 } 14225 14226 void 14227 Sema::PushExpressionEvaluationContext( 14228 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14229 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14230 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14231 LambdaContextDecl, ExprContext); 14232 Cleanup.reset(); 14233 if (!MaybeODRUseExprs.empty()) 14234 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14235 } 14236 14237 void 14238 Sema::PushExpressionEvaluationContext( 14239 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14240 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14241 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14242 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14243 } 14244 14245 void Sema::PopExpressionEvaluationContext() { 14246 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14247 unsigned NumTypos = Rec.NumTypos; 14248 14249 if (!Rec.Lambdas.empty()) { 14250 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14251 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14252 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14253 unsigned D; 14254 if (Rec.isUnevaluated()) { 14255 // C++11 [expr.prim.lambda]p2: 14256 // A lambda-expression shall not appear in an unevaluated operand 14257 // (Clause 5). 14258 D = diag::err_lambda_unevaluated_operand; 14259 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14260 // C++1y [expr.const]p2: 14261 // A conditional-expression e is a core constant expression unless the 14262 // evaluation of e, following the rules of the abstract machine, would 14263 // evaluate [...] a lambda-expression. 14264 D = diag::err_lambda_in_constant_expression; 14265 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14266 // C++17 [expr.prim.lamda]p2: 14267 // A lambda-expression shall not appear [...] in a template-argument. 14268 D = diag::err_lambda_in_invalid_context; 14269 } else 14270 llvm_unreachable("Couldn't infer lambda error message."); 14271 14272 for (const auto *L : Rec.Lambdas) 14273 Diag(L->getBeginLoc(), D); 14274 } else { 14275 // Mark the capture expressions odr-used. This was deferred 14276 // during lambda expression creation. 14277 for (auto *Lambda : Rec.Lambdas) { 14278 for (auto *C : Lambda->capture_inits()) 14279 MarkDeclarationsReferencedInExpr(C); 14280 } 14281 } 14282 } 14283 14284 // When are coming out of an unevaluated context, clear out any 14285 // temporaries that we may have created as part of the evaluation of 14286 // the expression in that context: they aren't relevant because they 14287 // will never be constructed. 14288 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14289 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14290 ExprCleanupObjects.end()); 14291 Cleanup = Rec.ParentCleanup; 14292 CleanupVarDeclMarking(); 14293 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14294 // Otherwise, merge the contexts together. 14295 } else { 14296 Cleanup.mergeFrom(Rec.ParentCleanup); 14297 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14298 Rec.SavedMaybeODRUseExprs.end()); 14299 } 14300 14301 // Pop the current expression evaluation context off the stack. 14302 ExprEvalContexts.pop_back(); 14303 14304 if (!ExprEvalContexts.empty()) 14305 ExprEvalContexts.back().NumTypos += NumTypos; 14306 else 14307 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14308 "last ExpressionEvaluationContextRecord"); 14309 } 14310 14311 void Sema::DiscardCleanupsInEvaluationContext() { 14312 ExprCleanupObjects.erase( 14313 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14314 ExprCleanupObjects.end()); 14315 Cleanup.reset(); 14316 MaybeODRUseExprs.clear(); 14317 } 14318 14319 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14320 if (!E->getType()->isVariablyModifiedType()) 14321 return E; 14322 return TransformToPotentiallyEvaluated(E); 14323 } 14324 14325 /// Are we within a context in which some evaluation could be performed (be it 14326 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14327 /// captured by C++'s idea of an "unevaluated context". 14328 static bool isEvaluatableContext(Sema &SemaRef) { 14329 switch (SemaRef.ExprEvalContexts.back().Context) { 14330 case Sema::ExpressionEvaluationContext::Unevaluated: 14331 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14332 // Expressions in this context are never evaluated. 14333 return false; 14334 14335 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14336 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14337 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14338 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14339 // Expressions in this context could be evaluated. 14340 return true; 14341 14342 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14343 // Referenced declarations will only be used if the construct in the 14344 // containing expression is used, at which point we'll be given another 14345 // turn to mark them. 14346 return false; 14347 } 14348 llvm_unreachable("Invalid context"); 14349 } 14350 14351 /// Are we within a context in which references to resolved functions or to 14352 /// variables result in odr-use? 14353 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14354 // An expression in a template is not really an expression until it's been 14355 // instantiated, so it doesn't trigger odr-use. 14356 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14357 return false; 14358 14359 switch (SemaRef.ExprEvalContexts.back().Context) { 14360 case Sema::ExpressionEvaluationContext::Unevaluated: 14361 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14362 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14363 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14364 return false; 14365 14366 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14367 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14368 return true; 14369 14370 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14371 return false; 14372 } 14373 llvm_unreachable("Invalid context"); 14374 } 14375 14376 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14377 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14378 return Func->isConstexpr() && 14379 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14380 } 14381 14382 /// Mark a function referenced, and check whether it is odr-used 14383 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14384 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14385 bool MightBeOdrUse) { 14386 assert(Func && "No function?"); 14387 14388 Func->setReferenced(); 14389 14390 // C++11 [basic.def.odr]p3: 14391 // A function whose name appears as a potentially-evaluated expression is 14392 // odr-used if it is the unique lookup result or the selected member of a 14393 // set of overloaded functions [...]. 14394 // 14395 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14396 // can just check that here. 14397 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14398 14399 // Determine whether we require a function definition to exist, per 14400 // C++11 [temp.inst]p3: 14401 // Unless a function template specialization has been explicitly 14402 // instantiated or explicitly specialized, the function template 14403 // specialization is implicitly instantiated when the specialization is 14404 // referenced in a context that requires a function definition to exist. 14405 // 14406 // That is either when this is an odr-use, or when a usage of a constexpr 14407 // function occurs within an evaluatable context. 14408 bool NeedDefinition = 14409 OdrUse || (isEvaluatableContext(*this) && 14410 isImplicitlyDefinableConstexprFunction(Func)); 14411 14412 // C++14 [temp.expl.spec]p6: 14413 // If a template [...] is explicitly specialized then that specialization 14414 // shall be declared before the first use of that specialization that would 14415 // cause an implicit instantiation to take place, in every translation unit 14416 // in which such a use occurs 14417 if (NeedDefinition && 14418 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14419 Func->getMemberSpecializationInfo())) 14420 checkSpecializationVisibility(Loc, Func); 14421 14422 // C++14 [except.spec]p17: 14423 // An exception-specification is considered to be needed when: 14424 // - the function is odr-used or, if it appears in an unevaluated operand, 14425 // would be odr-used if the expression were potentially-evaluated; 14426 // 14427 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14428 // function is a pure virtual function we're calling, and in that case the 14429 // function was selected by overload resolution and we need to resolve its 14430 // exception specification for a different reason. 14431 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14432 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14433 ResolveExceptionSpec(Loc, FPT); 14434 14435 // If we don't need to mark the function as used, and we don't need to 14436 // try to provide a definition, there's nothing more to do. 14437 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14438 (!NeedDefinition || Func->getBody())) 14439 return; 14440 14441 // Note that this declaration has been used. 14442 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14443 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14444 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14445 if (Constructor->isDefaultConstructor()) { 14446 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14447 return; 14448 DefineImplicitDefaultConstructor(Loc, Constructor); 14449 } else if (Constructor->isCopyConstructor()) { 14450 DefineImplicitCopyConstructor(Loc, Constructor); 14451 } else if (Constructor->isMoveConstructor()) { 14452 DefineImplicitMoveConstructor(Loc, Constructor); 14453 } 14454 } else if (Constructor->getInheritedConstructor()) { 14455 DefineInheritingConstructor(Loc, Constructor); 14456 } 14457 } else if (CXXDestructorDecl *Destructor = 14458 dyn_cast<CXXDestructorDecl>(Func)) { 14459 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14460 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14461 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14462 return; 14463 DefineImplicitDestructor(Loc, Destructor); 14464 } 14465 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14466 MarkVTableUsed(Loc, Destructor->getParent()); 14467 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14468 if (MethodDecl->isOverloadedOperator() && 14469 MethodDecl->getOverloadedOperator() == OO_Equal) { 14470 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14471 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14472 if (MethodDecl->isCopyAssignmentOperator()) 14473 DefineImplicitCopyAssignment(Loc, MethodDecl); 14474 else if (MethodDecl->isMoveAssignmentOperator()) 14475 DefineImplicitMoveAssignment(Loc, MethodDecl); 14476 } 14477 } else if (isa<CXXConversionDecl>(MethodDecl) && 14478 MethodDecl->getParent()->isLambda()) { 14479 CXXConversionDecl *Conversion = 14480 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14481 if (Conversion->isLambdaToBlockPointerConversion()) 14482 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14483 else 14484 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14485 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14486 MarkVTableUsed(Loc, MethodDecl->getParent()); 14487 } 14488 14489 // Recursive functions should be marked when used from another function. 14490 // FIXME: Is this really right? 14491 if (CurContext == Func) return; 14492 14493 // Implicit instantiation of function templates and member functions of 14494 // class templates. 14495 if (Func->isImplicitlyInstantiable()) { 14496 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14497 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14498 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14499 if (FirstInstantiation) { 14500 PointOfInstantiation = Loc; 14501 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14502 } else if (TSK != TSK_ImplicitInstantiation) { 14503 // Use the point of use as the point of instantiation, instead of the 14504 // point of explicit instantiation (which we track as the actual point of 14505 // instantiation). This gives better backtraces in diagnostics. 14506 PointOfInstantiation = Loc; 14507 } 14508 14509 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14510 Func->isConstexpr()) { 14511 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14512 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14513 CodeSynthesisContexts.size()) 14514 PendingLocalImplicitInstantiations.push_back( 14515 std::make_pair(Func, PointOfInstantiation)); 14516 else if (Func->isConstexpr()) 14517 // Do not defer instantiations of constexpr functions, to avoid the 14518 // expression evaluator needing to call back into Sema if it sees a 14519 // call to such a function. 14520 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14521 else { 14522 Func->setInstantiationIsPending(true); 14523 PendingInstantiations.push_back(std::make_pair(Func, 14524 PointOfInstantiation)); 14525 // Notify the consumer that a function was implicitly instantiated. 14526 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14527 } 14528 } 14529 } else { 14530 // Walk redefinitions, as some of them may be instantiable. 14531 for (auto i : Func->redecls()) { 14532 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14533 MarkFunctionReferenced(Loc, i, OdrUse); 14534 } 14535 } 14536 14537 if (!OdrUse) return; 14538 14539 // Keep track of used but undefined functions. 14540 if (!Func->isDefined()) { 14541 if (mightHaveNonExternalLinkage(Func)) 14542 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14543 else if (Func->getMostRecentDecl()->isInlined() && 14544 !LangOpts.GNUInline && 14545 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14546 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14547 else if (isExternalWithNoLinkageType(Func)) 14548 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14549 } 14550 14551 Func->markUsed(Context); 14552 } 14553 14554 static void 14555 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14556 ValueDecl *var, DeclContext *DC) { 14557 DeclContext *VarDC = var->getDeclContext(); 14558 14559 // If the parameter still belongs to the translation unit, then 14560 // we're actually just using one parameter in the declaration of 14561 // the next. 14562 if (isa<ParmVarDecl>(var) && 14563 isa<TranslationUnitDecl>(VarDC)) 14564 return; 14565 14566 // For C code, don't diagnose about capture if we're not actually in code 14567 // right now; it's impossible to write a non-constant expression outside of 14568 // function context, so we'll get other (more useful) diagnostics later. 14569 // 14570 // For C++, things get a bit more nasty... it would be nice to suppress this 14571 // diagnostic for certain cases like using a local variable in an array bound 14572 // for a member of a local class, but the correct predicate is not obvious. 14573 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14574 return; 14575 14576 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14577 unsigned ContextKind = 3; // unknown 14578 if (isa<CXXMethodDecl>(VarDC) && 14579 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14580 ContextKind = 2; 14581 } else if (isa<FunctionDecl>(VarDC)) { 14582 ContextKind = 0; 14583 } else if (isa<BlockDecl>(VarDC)) { 14584 ContextKind = 1; 14585 } 14586 14587 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14588 << var << ValueKind << ContextKind << VarDC; 14589 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14590 << var; 14591 14592 // FIXME: Add additional diagnostic info about class etc. which prevents 14593 // capture. 14594 } 14595 14596 14597 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14598 bool &SubCapturesAreNested, 14599 QualType &CaptureType, 14600 QualType &DeclRefType) { 14601 // Check whether we've already captured it. 14602 if (CSI->CaptureMap.count(Var)) { 14603 // If we found a capture, any subcaptures are nested. 14604 SubCapturesAreNested = true; 14605 14606 // Retrieve the capture type for this variable. 14607 CaptureType = CSI->getCapture(Var).getCaptureType(); 14608 14609 // Compute the type of an expression that refers to this variable. 14610 DeclRefType = CaptureType.getNonReferenceType(); 14611 14612 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14613 // are mutable in the sense that user can change their value - they are 14614 // private instances of the captured declarations. 14615 const Capture &Cap = CSI->getCapture(Var); 14616 if (Cap.isCopyCapture() && 14617 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14618 !(isa<CapturedRegionScopeInfo>(CSI) && 14619 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14620 DeclRefType.addConst(); 14621 return true; 14622 } 14623 return false; 14624 } 14625 14626 // Only block literals, captured statements, and lambda expressions can 14627 // capture; other scopes don't work. 14628 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14629 SourceLocation Loc, 14630 const bool Diagnose, Sema &S) { 14631 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14632 return getLambdaAwareParentOfDeclContext(DC); 14633 else if (Var->hasLocalStorage()) { 14634 if (Diagnose) 14635 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14636 } 14637 return nullptr; 14638 } 14639 14640 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14641 // certain types of variables (unnamed, variably modified types etc.) 14642 // so check for eligibility. 14643 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14644 SourceLocation Loc, 14645 const bool Diagnose, Sema &S) { 14646 14647 bool IsBlock = isa<BlockScopeInfo>(CSI); 14648 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14649 14650 // Lambdas are not allowed to capture unnamed variables 14651 // (e.g. anonymous unions). 14652 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14653 // assuming that's the intent. 14654 if (IsLambda && !Var->getDeclName()) { 14655 if (Diagnose) { 14656 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14657 S.Diag(Var->getLocation(), diag::note_declared_at); 14658 } 14659 return false; 14660 } 14661 14662 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14663 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14664 if (Diagnose) { 14665 S.Diag(Loc, diag::err_ref_vm_type); 14666 S.Diag(Var->getLocation(), diag::note_previous_decl) 14667 << Var->getDeclName(); 14668 } 14669 return false; 14670 } 14671 // Prohibit structs with flexible array members too. 14672 // We cannot capture what is in the tail end of the struct. 14673 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14674 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14675 if (Diagnose) { 14676 if (IsBlock) 14677 S.Diag(Loc, diag::err_ref_flexarray_type); 14678 else 14679 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14680 << Var->getDeclName(); 14681 S.Diag(Var->getLocation(), diag::note_previous_decl) 14682 << Var->getDeclName(); 14683 } 14684 return false; 14685 } 14686 } 14687 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14688 // Lambdas and captured statements are not allowed to capture __block 14689 // variables; they don't support the expected semantics. 14690 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14691 if (Diagnose) { 14692 S.Diag(Loc, diag::err_capture_block_variable) 14693 << Var->getDeclName() << !IsLambda; 14694 S.Diag(Var->getLocation(), diag::note_previous_decl) 14695 << Var->getDeclName(); 14696 } 14697 return false; 14698 } 14699 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14700 if (S.getLangOpts().OpenCL && IsBlock && 14701 Var->getType()->isBlockPointerType()) { 14702 if (Diagnose) 14703 S.Diag(Loc, diag::err_opencl_block_ref_block); 14704 return false; 14705 } 14706 14707 return true; 14708 } 14709 14710 // Returns true if the capture by block was successful. 14711 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14712 SourceLocation Loc, 14713 const bool BuildAndDiagnose, 14714 QualType &CaptureType, 14715 QualType &DeclRefType, 14716 const bool Nested, 14717 Sema &S) { 14718 Expr *CopyExpr = nullptr; 14719 bool ByRef = false; 14720 14721 // Blocks are not allowed to capture arrays, excepting OpenCL. 14722 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 14723 // (decayed to pointers). 14724 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 14725 if (BuildAndDiagnose) { 14726 S.Diag(Loc, diag::err_ref_array_type); 14727 S.Diag(Var->getLocation(), diag::note_previous_decl) 14728 << Var->getDeclName(); 14729 } 14730 return false; 14731 } 14732 14733 // Forbid the block-capture of autoreleasing variables. 14734 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14735 if (BuildAndDiagnose) { 14736 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14737 << /*block*/ 0; 14738 S.Diag(Var->getLocation(), diag::note_previous_decl) 14739 << Var->getDeclName(); 14740 } 14741 return false; 14742 } 14743 14744 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14745 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14746 // This function finds out whether there is an AttributedType of kind 14747 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14748 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14749 // rather than being added implicitly by the compiler. 14750 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14751 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14752 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14753 return true; 14754 14755 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14756 Ty = AttrTy->getModifiedType(); 14757 } 14758 14759 return false; 14760 }; 14761 14762 QualType PointeeTy = PT->getPointeeType(); 14763 14764 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14765 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14766 !IsObjCOwnershipAttributedType(PointeeTy)) { 14767 if (BuildAndDiagnose) { 14768 SourceLocation VarLoc = Var->getLocation(); 14769 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14770 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14771 } 14772 } 14773 } 14774 14775 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14776 if (HasBlocksAttr || CaptureType->isReferenceType() || 14777 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14778 // Block capture by reference does not change the capture or 14779 // declaration reference types. 14780 ByRef = true; 14781 } else { 14782 // Block capture by copy introduces 'const'. 14783 CaptureType = CaptureType.getNonReferenceType().withConst(); 14784 DeclRefType = CaptureType; 14785 14786 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14787 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14788 // The capture logic needs the destructor, so make sure we mark it. 14789 // Usually this is unnecessary because most local variables have 14790 // their destructors marked at declaration time, but parameters are 14791 // an exception because it's technically only the call site that 14792 // actually requires the destructor. 14793 if (isa<ParmVarDecl>(Var)) 14794 S.FinalizeVarWithDestructor(Var, Record); 14795 14796 // Enter a new evaluation context to insulate the copy 14797 // full-expression. 14798 EnterExpressionEvaluationContext scope( 14799 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14800 14801 // According to the blocks spec, the capture of a variable from 14802 // the stack requires a const copy constructor. This is not true 14803 // of the copy/move done to move a __block variable to the heap. 14804 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14805 DeclRefType.withConst(), 14806 VK_LValue, Loc); 14807 14808 ExprResult Result 14809 = S.PerformCopyInitialization( 14810 InitializedEntity::InitializeBlock(Var->getLocation(), 14811 CaptureType, false), 14812 Loc, DeclRef); 14813 14814 // Build a full-expression copy expression if initialization 14815 // succeeded and used a non-trivial constructor. Recover from 14816 // errors by pretending that the copy isn't necessary. 14817 if (!Result.isInvalid() && 14818 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14819 ->isTrivial()) { 14820 Result = S.MaybeCreateExprWithCleanups(Result); 14821 CopyExpr = Result.get(); 14822 } 14823 } 14824 } 14825 } 14826 14827 // Actually capture the variable. 14828 if (BuildAndDiagnose) 14829 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14830 SourceLocation(), CaptureType, CopyExpr); 14831 14832 return true; 14833 14834 } 14835 14836 14837 /// Capture the given variable in the captured region. 14838 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14839 VarDecl *Var, 14840 SourceLocation Loc, 14841 const bool BuildAndDiagnose, 14842 QualType &CaptureType, 14843 QualType &DeclRefType, 14844 const bool RefersToCapturedVariable, 14845 Sema &S) { 14846 // By default, capture variables by reference. 14847 bool ByRef = true; 14848 // Using an LValue reference type is consistent with Lambdas (see below). 14849 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14850 if (S.isOpenMPCapturedDecl(Var)) { 14851 bool HasConst = DeclRefType.isConstQualified(); 14852 DeclRefType = DeclRefType.getUnqualifiedType(); 14853 // Don't lose diagnostics about assignments to const. 14854 if (HasConst) 14855 DeclRefType.addConst(); 14856 } 14857 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14858 } 14859 14860 if (ByRef) 14861 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14862 else 14863 CaptureType = DeclRefType; 14864 14865 Expr *CopyExpr = nullptr; 14866 if (BuildAndDiagnose) { 14867 // The current implementation assumes that all variables are captured 14868 // by references. Since there is no capture by copy, no expression 14869 // evaluation will be needed. 14870 RecordDecl *RD = RSI->TheRecordDecl; 14871 14872 FieldDecl *Field 14873 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14874 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14875 nullptr, false, ICIS_NoInit); 14876 Field->setImplicit(true); 14877 Field->setAccess(AS_private); 14878 RD->addDecl(Field); 14879 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14880 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14881 14882 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14883 DeclRefType, VK_LValue, Loc); 14884 Var->setReferenced(true); 14885 Var->markUsed(S.Context); 14886 } 14887 14888 // Actually capture the variable. 14889 if (BuildAndDiagnose) 14890 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14891 SourceLocation(), CaptureType, CopyExpr); 14892 14893 14894 return true; 14895 } 14896 14897 /// Create a field within the lambda class for the variable 14898 /// being captured. 14899 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14900 QualType FieldType, QualType DeclRefType, 14901 SourceLocation Loc, 14902 bool RefersToCapturedVariable) { 14903 CXXRecordDecl *Lambda = LSI->Lambda; 14904 14905 // Build the non-static data member. 14906 FieldDecl *Field 14907 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14908 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14909 nullptr, false, ICIS_NoInit); 14910 Field->setImplicit(true); 14911 Field->setAccess(AS_private); 14912 Lambda->addDecl(Field); 14913 } 14914 14915 /// Capture the given variable in the lambda. 14916 static bool captureInLambda(LambdaScopeInfo *LSI, 14917 VarDecl *Var, 14918 SourceLocation Loc, 14919 const bool BuildAndDiagnose, 14920 QualType &CaptureType, 14921 QualType &DeclRefType, 14922 const bool RefersToCapturedVariable, 14923 const Sema::TryCaptureKind Kind, 14924 SourceLocation EllipsisLoc, 14925 const bool IsTopScope, 14926 Sema &S) { 14927 14928 // Determine whether we are capturing by reference or by value. 14929 bool ByRef = false; 14930 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14931 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14932 } else { 14933 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14934 } 14935 14936 // Compute the type of the field that will capture this variable. 14937 if (ByRef) { 14938 // C++11 [expr.prim.lambda]p15: 14939 // An entity is captured by reference if it is implicitly or 14940 // explicitly captured but not captured by copy. It is 14941 // unspecified whether additional unnamed non-static data 14942 // members are declared in the closure type for entities 14943 // captured by reference. 14944 // 14945 // FIXME: It is not clear whether we want to build an lvalue reference 14946 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14947 // to do the former, while EDG does the latter. Core issue 1249 will 14948 // clarify, but for now we follow GCC because it's a more permissive and 14949 // easily defensible position. 14950 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14951 } else { 14952 // C++11 [expr.prim.lambda]p14: 14953 // For each entity captured by copy, an unnamed non-static 14954 // data member is declared in the closure type. The 14955 // declaration order of these members is unspecified. The type 14956 // of such a data member is the type of the corresponding 14957 // captured entity if the entity is not a reference to an 14958 // object, or the referenced type otherwise. [Note: If the 14959 // captured entity is a reference to a function, the 14960 // corresponding data member is also a reference to a 14961 // function. - end note ] 14962 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14963 if (!RefType->getPointeeType()->isFunctionType()) 14964 CaptureType = RefType->getPointeeType(); 14965 } 14966 14967 // Forbid the lambda copy-capture of autoreleasing variables. 14968 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14969 if (BuildAndDiagnose) { 14970 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14971 S.Diag(Var->getLocation(), diag::note_previous_decl) 14972 << Var->getDeclName(); 14973 } 14974 return false; 14975 } 14976 14977 // Make sure that by-copy captures are of a complete and non-abstract type. 14978 if (BuildAndDiagnose) { 14979 if (!CaptureType->isDependentType() && 14980 S.RequireCompleteType(Loc, CaptureType, 14981 diag::err_capture_of_incomplete_type, 14982 Var->getDeclName())) 14983 return false; 14984 14985 if (S.RequireNonAbstractType(Loc, CaptureType, 14986 diag::err_capture_of_abstract_type)) 14987 return false; 14988 } 14989 } 14990 14991 // Capture this variable in the lambda. 14992 if (BuildAndDiagnose) 14993 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14994 RefersToCapturedVariable); 14995 14996 // Compute the type of a reference to this captured variable. 14997 if (ByRef) 14998 DeclRefType = CaptureType.getNonReferenceType(); 14999 else { 15000 // C++ [expr.prim.lambda]p5: 15001 // The closure type for a lambda-expression has a public inline 15002 // function call operator [...]. This function call operator is 15003 // declared const (9.3.1) if and only if the lambda-expression's 15004 // parameter-declaration-clause is not followed by mutable. 15005 DeclRefType = CaptureType.getNonReferenceType(); 15006 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15007 DeclRefType.addConst(); 15008 } 15009 15010 // Add the capture. 15011 if (BuildAndDiagnose) 15012 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15013 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15014 15015 return true; 15016 } 15017 15018 bool Sema::tryCaptureVariable( 15019 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15020 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15021 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15022 // An init-capture is notionally from the context surrounding its 15023 // declaration, but its parent DC is the lambda class. 15024 DeclContext *VarDC = Var->getDeclContext(); 15025 if (Var->isInitCapture()) 15026 VarDC = VarDC->getParent(); 15027 15028 DeclContext *DC = CurContext; 15029 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15030 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15031 // We need to sync up the Declaration Context with the 15032 // FunctionScopeIndexToStopAt 15033 if (FunctionScopeIndexToStopAt) { 15034 unsigned FSIndex = FunctionScopes.size() - 1; 15035 while (FSIndex != MaxFunctionScopesIndex) { 15036 DC = getLambdaAwareParentOfDeclContext(DC); 15037 --FSIndex; 15038 } 15039 } 15040 15041 15042 // If the variable is declared in the current context, there is no need to 15043 // capture it. 15044 if (VarDC == DC) return true; 15045 15046 // Capture global variables if it is required to use private copy of this 15047 // variable. 15048 bool IsGlobal = !Var->hasLocalStorage(); 15049 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15050 return true; 15051 Var = Var->getCanonicalDecl(); 15052 15053 // Walk up the stack to determine whether we can capture the variable, 15054 // performing the "simple" checks that don't depend on type. We stop when 15055 // we've either hit the declared scope of the variable or find an existing 15056 // capture of that variable. We start from the innermost capturing-entity 15057 // (the DC) and ensure that all intervening capturing-entities 15058 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15059 // declcontext can either capture the variable or have already captured 15060 // the variable. 15061 CaptureType = Var->getType(); 15062 DeclRefType = CaptureType.getNonReferenceType(); 15063 bool Nested = false; 15064 bool Explicit = (Kind != TryCapture_Implicit); 15065 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15066 do { 15067 // Only block literals, captured statements, and lambda expressions can 15068 // capture; other scopes don't work. 15069 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15070 ExprLoc, 15071 BuildAndDiagnose, 15072 *this); 15073 // We need to check for the parent *first* because, if we *have* 15074 // private-captured a global variable, we need to recursively capture it in 15075 // intermediate blocks, lambdas, etc. 15076 if (!ParentDC) { 15077 if (IsGlobal) { 15078 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15079 break; 15080 } 15081 return true; 15082 } 15083 15084 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15085 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15086 15087 15088 // Check whether we've already captured it. 15089 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15090 DeclRefType)) { 15091 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15092 break; 15093 } 15094 // If we are instantiating a generic lambda call operator body, 15095 // we do not want to capture new variables. What was captured 15096 // during either a lambdas transformation or initial parsing 15097 // should be used. 15098 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15099 if (BuildAndDiagnose) { 15100 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15101 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15102 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15103 Diag(Var->getLocation(), diag::note_previous_decl) 15104 << Var->getDeclName(); 15105 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15106 } else 15107 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15108 } 15109 return true; 15110 } 15111 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15112 // certain types of variables (unnamed, variably modified types etc.) 15113 // so check for eligibility. 15114 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15115 return true; 15116 15117 // Try to capture variable-length arrays types. 15118 if (Var->getType()->isVariablyModifiedType()) { 15119 // We're going to walk down into the type and look for VLA 15120 // expressions. 15121 QualType QTy = Var->getType(); 15122 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15123 QTy = PVD->getOriginalType(); 15124 captureVariablyModifiedType(Context, QTy, CSI); 15125 } 15126 15127 if (getLangOpts().OpenMP) { 15128 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15129 // OpenMP private variables should not be captured in outer scope, so 15130 // just break here. Similarly, global variables that are captured in a 15131 // target region should not be captured outside the scope of the region. 15132 if (RSI->CapRegionKind == CR_OpenMP) { 15133 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15134 auto IsTargetCap = !IsOpenMPPrivateDecl && 15135 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15136 // When we detect target captures we are looking from inside the 15137 // target region, therefore we need to propagate the capture from the 15138 // enclosing region. Therefore, the capture is not initially nested. 15139 if (IsTargetCap) 15140 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15141 15142 if (IsTargetCap || IsOpenMPPrivateDecl) { 15143 Nested = !IsTargetCap; 15144 DeclRefType = DeclRefType.getUnqualifiedType(); 15145 CaptureType = Context.getLValueReferenceType(DeclRefType); 15146 break; 15147 } 15148 } 15149 } 15150 } 15151 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15152 // No capture-default, and this is not an explicit capture 15153 // so cannot capture this variable. 15154 if (BuildAndDiagnose) { 15155 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15156 Diag(Var->getLocation(), diag::note_previous_decl) 15157 << Var->getDeclName(); 15158 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15159 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15160 diag::note_lambda_decl); 15161 // FIXME: If we error out because an outer lambda can not implicitly 15162 // capture a variable that an inner lambda explicitly captures, we 15163 // should have the inner lambda do the explicit capture - because 15164 // it makes for cleaner diagnostics later. This would purely be done 15165 // so that the diagnostic does not misleadingly claim that a variable 15166 // can not be captured by a lambda implicitly even though it is captured 15167 // explicitly. Suggestion: 15168 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15169 // at the function head 15170 // - cache the StartingDeclContext - this must be a lambda 15171 // - captureInLambda in the innermost lambda the variable. 15172 } 15173 return true; 15174 } 15175 15176 FunctionScopesIndex--; 15177 DC = ParentDC; 15178 Explicit = false; 15179 } while (!VarDC->Equals(DC)); 15180 15181 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15182 // computing the type of the capture at each step, checking type-specific 15183 // requirements, and adding captures if requested. 15184 // If the variable had already been captured previously, we start capturing 15185 // at the lambda nested within that one. 15186 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15187 ++I) { 15188 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15189 15190 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15191 if (!captureInBlock(BSI, Var, ExprLoc, 15192 BuildAndDiagnose, CaptureType, 15193 DeclRefType, Nested, *this)) 15194 return true; 15195 Nested = true; 15196 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15197 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15198 BuildAndDiagnose, CaptureType, 15199 DeclRefType, Nested, *this)) 15200 return true; 15201 Nested = true; 15202 } else { 15203 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15204 if (!captureInLambda(LSI, Var, ExprLoc, 15205 BuildAndDiagnose, CaptureType, 15206 DeclRefType, Nested, Kind, EllipsisLoc, 15207 /*IsTopScope*/I == N - 1, *this)) 15208 return true; 15209 Nested = true; 15210 } 15211 } 15212 return false; 15213 } 15214 15215 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15216 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15217 QualType CaptureType; 15218 QualType DeclRefType; 15219 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15220 /*BuildAndDiagnose=*/true, CaptureType, 15221 DeclRefType, nullptr); 15222 } 15223 15224 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15225 QualType CaptureType; 15226 QualType DeclRefType; 15227 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15228 /*BuildAndDiagnose=*/false, CaptureType, 15229 DeclRefType, nullptr); 15230 } 15231 15232 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15233 QualType CaptureType; 15234 QualType DeclRefType; 15235 15236 // Determine whether we can capture this variable. 15237 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15238 /*BuildAndDiagnose=*/false, CaptureType, 15239 DeclRefType, nullptr)) 15240 return QualType(); 15241 15242 return DeclRefType; 15243 } 15244 15245 15246 15247 // If either the type of the variable or the initializer is dependent, 15248 // return false. Otherwise, determine whether the variable is a constant 15249 // expression. Use this if you need to know if a variable that might or 15250 // might not be dependent is truly a constant expression. 15251 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15252 ASTContext &Context) { 15253 15254 if (Var->getType()->isDependentType()) 15255 return false; 15256 const VarDecl *DefVD = nullptr; 15257 Var->getAnyInitializer(DefVD); 15258 if (!DefVD) 15259 return false; 15260 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15261 Expr *Init = cast<Expr>(Eval->Value); 15262 if (Init->isValueDependent()) 15263 return false; 15264 return IsVariableAConstantExpression(Var, Context); 15265 } 15266 15267 15268 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15269 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15270 // an object that satisfies the requirements for appearing in a 15271 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15272 // is immediately applied." This function handles the lvalue-to-rvalue 15273 // conversion part. 15274 MaybeODRUseExprs.erase(E->IgnoreParens()); 15275 15276 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15277 // to a variable that is a constant expression, and if so, identify it as 15278 // a reference to a variable that does not involve an odr-use of that 15279 // variable. 15280 if (LambdaScopeInfo *LSI = getCurLambda()) { 15281 Expr *SansParensExpr = E->IgnoreParens(); 15282 VarDecl *Var = nullptr; 15283 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15284 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15285 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15286 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15287 15288 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15289 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15290 } 15291 } 15292 15293 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15294 Res = CorrectDelayedTyposInExpr(Res); 15295 15296 if (!Res.isUsable()) 15297 return Res; 15298 15299 // If a constant-expression is a reference to a variable where we delay 15300 // deciding whether it is an odr-use, just assume we will apply the 15301 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15302 // (a non-type template argument), we have special handling anyway. 15303 UpdateMarkingForLValueToRValue(Res.get()); 15304 return Res; 15305 } 15306 15307 void Sema::CleanupVarDeclMarking() { 15308 for (Expr *E : MaybeODRUseExprs) { 15309 VarDecl *Var; 15310 SourceLocation Loc; 15311 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15312 Var = cast<VarDecl>(DRE->getDecl()); 15313 Loc = DRE->getLocation(); 15314 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15315 Var = cast<VarDecl>(ME->getMemberDecl()); 15316 Loc = ME->getMemberLoc(); 15317 } else { 15318 llvm_unreachable("Unexpected expression"); 15319 } 15320 15321 MarkVarDeclODRUsed(Var, Loc, *this, 15322 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15323 } 15324 15325 MaybeODRUseExprs.clear(); 15326 } 15327 15328 15329 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15330 VarDecl *Var, Expr *E) { 15331 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15332 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15333 Var->setReferenced(); 15334 15335 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15336 15337 bool OdrUseContext = isOdrUseContext(SemaRef); 15338 bool UsableInConstantExpr = 15339 Var->isUsableInConstantExpressions(SemaRef.Context); 15340 bool NeedDefinition = 15341 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15342 15343 VarTemplateSpecializationDecl *VarSpec = 15344 dyn_cast<VarTemplateSpecializationDecl>(Var); 15345 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15346 "Can't instantiate a partial template specialization."); 15347 15348 // If this might be a member specialization of a static data member, check 15349 // the specialization is visible. We already did the checks for variable 15350 // template specializations when we created them. 15351 if (NeedDefinition && TSK != TSK_Undeclared && 15352 !isa<VarTemplateSpecializationDecl>(Var)) 15353 SemaRef.checkSpecializationVisibility(Loc, Var); 15354 15355 // Perform implicit instantiation of static data members, static data member 15356 // templates of class templates, and variable template specializations. Delay 15357 // instantiations of variable templates, except for those that could be used 15358 // in a constant expression. 15359 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15360 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15361 // instantiation declaration if a variable is usable in a constant 15362 // expression (among other cases). 15363 bool TryInstantiating = 15364 TSK == TSK_ImplicitInstantiation || 15365 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15366 15367 if (TryInstantiating) { 15368 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15369 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15370 if (FirstInstantiation) { 15371 PointOfInstantiation = Loc; 15372 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15373 } 15374 15375 bool InstantiationDependent = false; 15376 bool IsNonDependent = 15377 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15378 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15379 : true; 15380 15381 // Do not instantiate specializations that are still type-dependent. 15382 if (IsNonDependent) { 15383 if (UsableInConstantExpr) { 15384 // Do not defer instantiations of variables that could be used in a 15385 // constant expression. 15386 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15387 } else if (FirstInstantiation || 15388 isa<VarTemplateSpecializationDecl>(Var)) { 15389 // FIXME: For a specialization of a variable template, we don't 15390 // distinguish between "declaration and type implicitly instantiated" 15391 // and "implicit instantiation of definition requested", so we have 15392 // no direct way to avoid enqueueing the pending instantiation 15393 // multiple times. 15394 SemaRef.PendingInstantiations 15395 .push_back(std::make_pair(Var, PointOfInstantiation)); 15396 } 15397 } 15398 } 15399 } 15400 15401 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15402 // the requirements for appearing in a constant expression (5.19) and, if 15403 // it is an object, the lvalue-to-rvalue conversion (4.1) 15404 // is immediately applied." We check the first part here, and 15405 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15406 // Note that we use the C++11 definition everywhere because nothing in 15407 // C++03 depends on whether we get the C++03 version correct. The second 15408 // part does not apply to references, since they are not objects. 15409 if (OdrUseContext && E && 15410 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15411 // A reference initialized by a constant expression can never be 15412 // odr-used, so simply ignore it. 15413 if (!Var->getType()->isReferenceType() || 15414 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15415 SemaRef.MaybeODRUseExprs.insert(E); 15416 } else if (OdrUseContext) { 15417 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15418 /*MaxFunctionScopeIndex ptr*/ nullptr); 15419 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15420 // If this is a dependent context, we don't need to mark variables as 15421 // odr-used, but we may still need to track them for lambda capture. 15422 // FIXME: Do we also need to do this inside dependent typeid expressions 15423 // (which are modeled as unevaluated at this point)? 15424 const bool RefersToEnclosingScope = 15425 (SemaRef.CurContext != Var->getDeclContext() && 15426 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15427 if (RefersToEnclosingScope) { 15428 LambdaScopeInfo *const LSI = 15429 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15430 if (LSI && (!LSI->CallOperator || 15431 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15432 // If a variable could potentially be odr-used, defer marking it so 15433 // until we finish analyzing the full expression for any 15434 // lvalue-to-rvalue 15435 // or discarded value conversions that would obviate odr-use. 15436 // Add it to the list of potential captures that will be analyzed 15437 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15438 // unless the variable is a reference that was initialized by a constant 15439 // expression (this will never need to be captured or odr-used). 15440 assert(E && "Capture variable should be used in an expression."); 15441 if (!Var->getType()->isReferenceType() || 15442 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15443 LSI->addPotentialCapture(E->IgnoreParens()); 15444 } 15445 } 15446 } 15447 } 15448 15449 /// Mark a variable referenced, and check whether it is odr-used 15450 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15451 /// used directly for normal expressions referring to VarDecl. 15452 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15453 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15454 } 15455 15456 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15457 Decl *D, Expr *E, bool MightBeOdrUse) { 15458 if (SemaRef.isInOpenMPDeclareTargetContext()) 15459 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15460 15461 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15462 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15463 return; 15464 } 15465 15466 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15467 15468 // If this is a call to a method via a cast, also mark the method in the 15469 // derived class used in case codegen can devirtualize the call. 15470 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15471 if (!ME) 15472 return; 15473 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15474 if (!MD) 15475 return; 15476 // Only attempt to devirtualize if this is truly a virtual call. 15477 bool IsVirtualCall = MD->isVirtual() && 15478 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15479 if (!IsVirtualCall) 15480 return; 15481 15482 // If it's possible to devirtualize the call, mark the called function 15483 // referenced. 15484 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15485 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15486 if (DM) 15487 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15488 } 15489 15490 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15491 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15492 // TODO: update this with DR# once a defect report is filed. 15493 // C++11 defect. The address of a pure member should not be an ODR use, even 15494 // if it's a qualified reference. 15495 bool OdrUse = true; 15496 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15497 if (Method->isVirtual() && 15498 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15499 OdrUse = false; 15500 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15501 } 15502 15503 /// Perform reference-marking and odr-use handling for a MemberExpr. 15504 void Sema::MarkMemberReferenced(MemberExpr *E) { 15505 // C++11 [basic.def.odr]p2: 15506 // A non-overloaded function whose name appears as a potentially-evaluated 15507 // expression or a member of a set of candidate functions, if selected by 15508 // overload resolution when referred to from a potentially-evaluated 15509 // expression, is odr-used, unless it is a pure virtual function and its 15510 // name is not explicitly qualified. 15511 bool MightBeOdrUse = true; 15512 if (E->performsVirtualDispatch(getLangOpts())) { 15513 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15514 if (Method->isPure()) 15515 MightBeOdrUse = false; 15516 } 15517 SourceLocation Loc = 15518 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15519 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15520 } 15521 15522 /// Perform marking for a reference to an arbitrary declaration. It 15523 /// marks the declaration referenced, and performs odr-use checking for 15524 /// functions and variables. This method should not be used when building a 15525 /// normal expression which refers to a variable. 15526 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15527 bool MightBeOdrUse) { 15528 if (MightBeOdrUse) { 15529 if (auto *VD = dyn_cast<VarDecl>(D)) { 15530 MarkVariableReferenced(Loc, VD); 15531 return; 15532 } 15533 } 15534 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15535 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15536 return; 15537 } 15538 D->setReferenced(); 15539 } 15540 15541 namespace { 15542 // Mark all of the declarations used by a type as referenced. 15543 // FIXME: Not fully implemented yet! We need to have a better understanding 15544 // of when we're entering a context we should not recurse into. 15545 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15546 // TreeTransforms rebuilding the type in a new context. Rather than 15547 // duplicating the TreeTransform logic, we should consider reusing it here. 15548 // Currently that causes problems when rebuilding LambdaExprs. 15549 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15550 Sema &S; 15551 SourceLocation Loc; 15552 15553 public: 15554 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15555 15556 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15557 15558 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15559 }; 15560 } 15561 15562 bool MarkReferencedDecls::TraverseTemplateArgument( 15563 const TemplateArgument &Arg) { 15564 { 15565 // A non-type template argument is a constant-evaluated context. 15566 EnterExpressionEvaluationContext Evaluated( 15567 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15568 if (Arg.getKind() == TemplateArgument::Declaration) { 15569 if (Decl *D = Arg.getAsDecl()) 15570 S.MarkAnyDeclReferenced(Loc, D, true); 15571 } else if (Arg.getKind() == TemplateArgument::Expression) { 15572 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15573 } 15574 } 15575 15576 return Inherited::TraverseTemplateArgument(Arg); 15577 } 15578 15579 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15580 MarkReferencedDecls Marker(*this, Loc); 15581 Marker.TraverseType(T); 15582 } 15583 15584 namespace { 15585 /// Helper class that marks all of the declarations referenced by 15586 /// potentially-evaluated subexpressions as "referenced". 15587 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15588 Sema &S; 15589 bool SkipLocalVariables; 15590 15591 public: 15592 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15593 15594 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15595 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15596 15597 void VisitDeclRefExpr(DeclRefExpr *E) { 15598 // If we were asked not to visit local variables, don't. 15599 if (SkipLocalVariables) { 15600 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15601 if (VD->hasLocalStorage()) 15602 return; 15603 } 15604 15605 S.MarkDeclRefReferenced(E); 15606 } 15607 15608 void VisitMemberExpr(MemberExpr *E) { 15609 S.MarkMemberReferenced(E); 15610 Inherited::VisitMemberExpr(E); 15611 } 15612 15613 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15614 S.MarkFunctionReferenced( 15615 E->getBeginLoc(), 15616 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15617 Visit(E->getSubExpr()); 15618 } 15619 15620 void VisitCXXNewExpr(CXXNewExpr *E) { 15621 if (E->getOperatorNew()) 15622 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15623 if (E->getOperatorDelete()) 15624 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15625 Inherited::VisitCXXNewExpr(E); 15626 } 15627 15628 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15629 if (E->getOperatorDelete()) 15630 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15631 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15632 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15633 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15634 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15635 } 15636 15637 Inherited::VisitCXXDeleteExpr(E); 15638 } 15639 15640 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15641 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15642 Inherited::VisitCXXConstructExpr(E); 15643 } 15644 15645 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15646 Visit(E->getExpr()); 15647 } 15648 15649 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15650 Inherited::VisitImplicitCastExpr(E); 15651 15652 if (E->getCastKind() == CK_LValueToRValue) 15653 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15654 } 15655 }; 15656 } 15657 15658 /// Mark any declarations that appear within this expression or any 15659 /// potentially-evaluated subexpressions as "referenced". 15660 /// 15661 /// \param SkipLocalVariables If true, don't mark local variables as 15662 /// 'referenced'. 15663 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15664 bool SkipLocalVariables) { 15665 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15666 } 15667 15668 /// Emit a diagnostic that describes an effect on the run-time behavior 15669 /// of the program being compiled. 15670 /// 15671 /// This routine emits the given diagnostic when the code currently being 15672 /// type-checked is "potentially evaluated", meaning that there is a 15673 /// possibility that the code will actually be executable. Code in sizeof() 15674 /// expressions, code used only during overload resolution, etc., are not 15675 /// potentially evaluated. This routine will suppress such diagnostics or, 15676 /// in the absolutely nutty case of potentially potentially evaluated 15677 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15678 /// later. 15679 /// 15680 /// This routine should be used for all diagnostics that describe the run-time 15681 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15682 /// Failure to do so will likely result in spurious diagnostics or failures 15683 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15684 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15685 const PartialDiagnostic &PD) { 15686 switch (ExprEvalContexts.back().Context) { 15687 case ExpressionEvaluationContext::Unevaluated: 15688 case ExpressionEvaluationContext::UnevaluatedList: 15689 case ExpressionEvaluationContext::UnevaluatedAbstract: 15690 case ExpressionEvaluationContext::DiscardedStatement: 15691 // The argument will never be evaluated, so don't complain. 15692 break; 15693 15694 case ExpressionEvaluationContext::ConstantEvaluated: 15695 // Relevant diagnostics should be produced by constant evaluation. 15696 break; 15697 15698 case ExpressionEvaluationContext::PotentiallyEvaluated: 15699 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15700 if (Statement && getCurFunctionOrMethodDecl()) { 15701 FunctionScopes.back()->PossiblyUnreachableDiags. 15702 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15703 return true; 15704 } 15705 15706 // The initializer of a constexpr variable or of the first declaration of a 15707 // static data member is not syntactically a constant evaluated constant, 15708 // but nonetheless is always required to be a constant expression, so we 15709 // can skip diagnosing. 15710 // FIXME: Using the mangling context here is a hack. 15711 if (auto *VD = dyn_cast_or_null<VarDecl>( 15712 ExprEvalContexts.back().ManglingContextDecl)) { 15713 if (VD->isConstexpr() || 15714 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15715 break; 15716 // FIXME: For any other kind of variable, we should build a CFG for its 15717 // initializer and check whether the context in question is reachable. 15718 } 15719 15720 Diag(Loc, PD); 15721 return true; 15722 } 15723 15724 return false; 15725 } 15726 15727 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15728 CallExpr *CE, FunctionDecl *FD) { 15729 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15730 return false; 15731 15732 // If we're inside a decltype's expression, don't check for a valid return 15733 // type or construct temporaries until we know whether this is the last call. 15734 if (ExprEvalContexts.back().ExprContext == 15735 ExpressionEvaluationContextRecord::EK_Decltype) { 15736 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15737 return false; 15738 } 15739 15740 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15741 FunctionDecl *FD; 15742 CallExpr *CE; 15743 15744 public: 15745 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15746 : FD(FD), CE(CE) { } 15747 15748 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15749 if (!FD) { 15750 S.Diag(Loc, diag::err_call_incomplete_return) 15751 << T << CE->getSourceRange(); 15752 return; 15753 } 15754 15755 S.Diag(Loc, diag::err_call_function_incomplete_return) 15756 << CE->getSourceRange() << FD->getDeclName() << T; 15757 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15758 << FD->getDeclName(); 15759 } 15760 } Diagnoser(FD, CE); 15761 15762 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15763 return true; 15764 15765 return false; 15766 } 15767 15768 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15769 // will prevent this condition from triggering, which is what we want. 15770 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15771 SourceLocation Loc; 15772 15773 unsigned diagnostic = diag::warn_condition_is_assignment; 15774 bool IsOrAssign = false; 15775 15776 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15777 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15778 return; 15779 15780 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15781 15782 // Greylist some idioms by putting them into a warning subcategory. 15783 if (ObjCMessageExpr *ME 15784 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15785 Selector Sel = ME->getSelector(); 15786 15787 // self = [<foo> init...] 15788 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15789 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15790 15791 // <foo> = [<bar> nextObject] 15792 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15793 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15794 } 15795 15796 Loc = Op->getOperatorLoc(); 15797 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15798 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15799 return; 15800 15801 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15802 Loc = Op->getOperatorLoc(); 15803 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15804 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15805 else { 15806 // Not an assignment. 15807 return; 15808 } 15809 15810 Diag(Loc, diagnostic) << E->getSourceRange(); 15811 15812 SourceLocation Open = E->getBeginLoc(); 15813 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15814 Diag(Loc, diag::note_condition_assign_silence) 15815 << FixItHint::CreateInsertion(Open, "(") 15816 << FixItHint::CreateInsertion(Close, ")"); 15817 15818 if (IsOrAssign) 15819 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15820 << FixItHint::CreateReplacement(Loc, "!="); 15821 else 15822 Diag(Loc, diag::note_condition_assign_to_comparison) 15823 << FixItHint::CreateReplacement(Loc, "=="); 15824 } 15825 15826 /// Redundant parentheses over an equality comparison can indicate 15827 /// that the user intended an assignment used as condition. 15828 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15829 // Don't warn if the parens came from a macro. 15830 SourceLocation parenLoc = ParenE->getBeginLoc(); 15831 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15832 return; 15833 // Don't warn for dependent expressions. 15834 if (ParenE->isTypeDependent()) 15835 return; 15836 15837 Expr *E = ParenE->IgnoreParens(); 15838 15839 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15840 if (opE->getOpcode() == BO_EQ && 15841 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15842 == Expr::MLV_Valid) { 15843 SourceLocation Loc = opE->getOperatorLoc(); 15844 15845 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15846 SourceRange ParenERange = ParenE->getSourceRange(); 15847 Diag(Loc, diag::note_equality_comparison_silence) 15848 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15849 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15850 Diag(Loc, diag::note_equality_comparison_to_assign) 15851 << FixItHint::CreateReplacement(Loc, "="); 15852 } 15853 } 15854 15855 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15856 bool IsConstexpr) { 15857 DiagnoseAssignmentAsCondition(E); 15858 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15859 DiagnoseEqualityWithExtraParens(parenE); 15860 15861 ExprResult result = CheckPlaceholderExpr(E); 15862 if (result.isInvalid()) return ExprError(); 15863 E = result.get(); 15864 15865 if (!E->isTypeDependent()) { 15866 if (getLangOpts().CPlusPlus) 15867 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15868 15869 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15870 if (ERes.isInvalid()) 15871 return ExprError(); 15872 E = ERes.get(); 15873 15874 QualType T = E->getType(); 15875 if (!T->isScalarType()) { // C99 6.8.4.1p1 15876 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15877 << T << E->getSourceRange(); 15878 return ExprError(); 15879 } 15880 CheckBoolLikeConversion(E, Loc); 15881 } 15882 15883 return E; 15884 } 15885 15886 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15887 Expr *SubExpr, ConditionKind CK) { 15888 // Empty conditions are valid in for-statements. 15889 if (!SubExpr) 15890 return ConditionResult(); 15891 15892 ExprResult Cond; 15893 switch (CK) { 15894 case ConditionKind::Boolean: 15895 Cond = CheckBooleanCondition(Loc, SubExpr); 15896 break; 15897 15898 case ConditionKind::ConstexprIf: 15899 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15900 break; 15901 15902 case ConditionKind::Switch: 15903 Cond = CheckSwitchCondition(Loc, SubExpr); 15904 break; 15905 } 15906 if (Cond.isInvalid()) 15907 return ConditionError(); 15908 15909 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15910 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15911 if (!FullExpr.get()) 15912 return ConditionError(); 15913 15914 return ConditionResult(*this, nullptr, FullExpr, 15915 CK == ConditionKind::ConstexprIf); 15916 } 15917 15918 namespace { 15919 /// A visitor for rebuilding a call to an __unknown_any expression 15920 /// to have an appropriate type. 15921 struct RebuildUnknownAnyFunction 15922 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15923 15924 Sema &S; 15925 15926 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15927 15928 ExprResult VisitStmt(Stmt *S) { 15929 llvm_unreachable("unexpected statement!"); 15930 } 15931 15932 ExprResult VisitExpr(Expr *E) { 15933 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15934 << E->getSourceRange(); 15935 return ExprError(); 15936 } 15937 15938 /// Rebuild an expression which simply semantically wraps another 15939 /// expression which it shares the type and value kind of. 15940 template <class T> ExprResult rebuildSugarExpr(T *E) { 15941 ExprResult SubResult = Visit(E->getSubExpr()); 15942 if (SubResult.isInvalid()) return ExprError(); 15943 15944 Expr *SubExpr = SubResult.get(); 15945 E->setSubExpr(SubExpr); 15946 E->setType(SubExpr->getType()); 15947 E->setValueKind(SubExpr->getValueKind()); 15948 assert(E->getObjectKind() == OK_Ordinary); 15949 return E; 15950 } 15951 15952 ExprResult VisitParenExpr(ParenExpr *E) { 15953 return rebuildSugarExpr(E); 15954 } 15955 15956 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15957 return rebuildSugarExpr(E); 15958 } 15959 15960 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15961 ExprResult SubResult = Visit(E->getSubExpr()); 15962 if (SubResult.isInvalid()) return ExprError(); 15963 15964 Expr *SubExpr = SubResult.get(); 15965 E->setSubExpr(SubExpr); 15966 E->setType(S.Context.getPointerType(SubExpr->getType())); 15967 assert(E->getValueKind() == VK_RValue); 15968 assert(E->getObjectKind() == OK_Ordinary); 15969 return E; 15970 } 15971 15972 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15973 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15974 15975 E->setType(VD->getType()); 15976 15977 assert(E->getValueKind() == VK_RValue); 15978 if (S.getLangOpts().CPlusPlus && 15979 !(isa<CXXMethodDecl>(VD) && 15980 cast<CXXMethodDecl>(VD)->isInstance())) 15981 E->setValueKind(VK_LValue); 15982 15983 return E; 15984 } 15985 15986 ExprResult VisitMemberExpr(MemberExpr *E) { 15987 return resolveDecl(E, E->getMemberDecl()); 15988 } 15989 15990 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15991 return resolveDecl(E, E->getDecl()); 15992 } 15993 }; 15994 } 15995 15996 /// Given a function expression of unknown-any type, try to rebuild it 15997 /// to have a function type. 15998 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15999 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16000 if (Result.isInvalid()) return ExprError(); 16001 return S.DefaultFunctionArrayConversion(Result.get()); 16002 } 16003 16004 namespace { 16005 /// A visitor for rebuilding an expression of type __unknown_anytype 16006 /// into one which resolves the type directly on the referring 16007 /// expression. Strict preservation of the original source 16008 /// structure is not a goal. 16009 struct RebuildUnknownAnyExpr 16010 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16011 16012 Sema &S; 16013 16014 /// The current destination type. 16015 QualType DestType; 16016 16017 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16018 : S(S), DestType(CastType) {} 16019 16020 ExprResult VisitStmt(Stmt *S) { 16021 llvm_unreachable("unexpected statement!"); 16022 } 16023 16024 ExprResult VisitExpr(Expr *E) { 16025 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16026 << E->getSourceRange(); 16027 return ExprError(); 16028 } 16029 16030 ExprResult VisitCallExpr(CallExpr *E); 16031 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16032 16033 /// Rebuild an expression which simply semantically wraps another 16034 /// expression which it shares the type and value kind of. 16035 template <class T> ExprResult rebuildSugarExpr(T *E) { 16036 ExprResult SubResult = Visit(E->getSubExpr()); 16037 if (SubResult.isInvalid()) return ExprError(); 16038 Expr *SubExpr = SubResult.get(); 16039 E->setSubExpr(SubExpr); 16040 E->setType(SubExpr->getType()); 16041 E->setValueKind(SubExpr->getValueKind()); 16042 assert(E->getObjectKind() == OK_Ordinary); 16043 return E; 16044 } 16045 16046 ExprResult VisitParenExpr(ParenExpr *E) { 16047 return rebuildSugarExpr(E); 16048 } 16049 16050 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16051 return rebuildSugarExpr(E); 16052 } 16053 16054 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16055 const PointerType *Ptr = DestType->getAs<PointerType>(); 16056 if (!Ptr) { 16057 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16058 << E->getSourceRange(); 16059 return ExprError(); 16060 } 16061 16062 if (isa<CallExpr>(E->getSubExpr())) { 16063 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16064 << E->getSourceRange(); 16065 return ExprError(); 16066 } 16067 16068 assert(E->getValueKind() == VK_RValue); 16069 assert(E->getObjectKind() == OK_Ordinary); 16070 E->setType(DestType); 16071 16072 // Build the sub-expression as if it were an object of the pointee type. 16073 DestType = Ptr->getPointeeType(); 16074 ExprResult SubResult = Visit(E->getSubExpr()); 16075 if (SubResult.isInvalid()) return ExprError(); 16076 E->setSubExpr(SubResult.get()); 16077 return E; 16078 } 16079 16080 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16081 16082 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16083 16084 ExprResult VisitMemberExpr(MemberExpr *E) { 16085 return resolveDecl(E, E->getMemberDecl()); 16086 } 16087 16088 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16089 return resolveDecl(E, E->getDecl()); 16090 } 16091 }; 16092 } 16093 16094 /// Rebuilds a call expression which yielded __unknown_anytype. 16095 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16096 Expr *CalleeExpr = E->getCallee(); 16097 16098 enum FnKind { 16099 FK_MemberFunction, 16100 FK_FunctionPointer, 16101 FK_BlockPointer 16102 }; 16103 16104 FnKind Kind; 16105 QualType CalleeType = CalleeExpr->getType(); 16106 if (CalleeType == S.Context.BoundMemberTy) { 16107 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16108 Kind = FK_MemberFunction; 16109 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16110 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16111 CalleeType = Ptr->getPointeeType(); 16112 Kind = FK_FunctionPointer; 16113 } else { 16114 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16115 Kind = FK_BlockPointer; 16116 } 16117 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16118 16119 // Verify that this is a legal result type of a function. 16120 if (DestType->isArrayType() || DestType->isFunctionType()) { 16121 unsigned diagID = diag::err_func_returning_array_function; 16122 if (Kind == FK_BlockPointer) 16123 diagID = diag::err_block_returning_array_function; 16124 16125 S.Diag(E->getExprLoc(), diagID) 16126 << DestType->isFunctionType() << DestType; 16127 return ExprError(); 16128 } 16129 16130 // Otherwise, go ahead and set DestType as the call's result. 16131 E->setType(DestType.getNonLValueExprType(S.Context)); 16132 E->setValueKind(Expr::getValueKindForType(DestType)); 16133 assert(E->getObjectKind() == OK_Ordinary); 16134 16135 // Rebuild the function type, replacing the result type with DestType. 16136 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16137 if (Proto) { 16138 // __unknown_anytype(...) is a special case used by the debugger when 16139 // it has no idea what a function's signature is. 16140 // 16141 // We want to build this call essentially under the K&R 16142 // unprototyped rules, but making a FunctionNoProtoType in C++ 16143 // would foul up all sorts of assumptions. However, we cannot 16144 // simply pass all arguments as variadic arguments, nor can we 16145 // portably just call the function under a non-variadic type; see 16146 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16147 // However, it turns out that in practice it is generally safe to 16148 // call a function declared as "A foo(B,C,D);" under the prototype 16149 // "A foo(B,C,D,...);". The only known exception is with the 16150 // Windows ABI, where any variadic function is implicitly cdecl 16151 // regardless of its normal CC. Therefore we change the parameter 16152 // types to match the types of the arguments. 16153 // 16154 // This is a hack, but it is far superior to moving the 16155 // corresponding target-specific code from IR-gen to Sema/AST. 16156 16157 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16158 SmallVector<QualType, 8> ArgTypes; 16159 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16160 ArgTypes.reserve(E->getNumArgs()); 16161 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16162 Expr *Arg = E->getArg(i); 16163 QualType ArgType = Arg->getType(); 16164 if (E->isLValue()) { 16165 ArgType = S.Context.getLValueReferenceType(ArgType); 16166 } else if (E->isXValue()) { 16167 ArgType = S.Context.getRValueReferenceType(ArgType); 16168 } 16169 ArgTypes.push_back(ArgType); 16170 } 16171 ParamTypes = ArgTypes; 16172 } 16173 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16174 Proto->getExtProtoInfo()); 16175 } else { 16176 DestType = S.Context.getFunctionNoProtoType(DestType, 16177 FnType->getExtInfo()); 16178 } 16179 16180 // Rebuild the appropriate pointer-to-function type. 16181 switch (Kind) { 16182 case FK_MemberFunction: 16183 // Nothing to do. 16184 break; 16185 16186 case FK_FunctionPointer: 16187 DestType = S.Context.getPointerType(DestType); 16188 break; 16189 16190 case FK_BlockPointer: 16191 DestType = S.Context.getBlockPointerType(DestType); 16192 break; 16193 } 16194 16195 // Finally, we can recurse. 16196 ExprResult CalleeResult = Visit(CalleeExpr); 16197 if (!CalleeResult.isUsable()) return ExprError(); 16198 E->setCallee(CalleeResult.get()); 16199 16200 // Bind a temporary if necessary. 16201 return S.MaybeBindToTemporary(E); 16202 } 16203 16204 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16205 // Verify that this is a legal result type of a call. 16206 if (DestType->isArrayType() || DestType->isFunctionType()) { 16207 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16208 << DestType->isFunctionType() << DestType; 16209 return ExprError(); 16210 } 16211 16212 // Rewrite the method result type if available. 16213 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16214 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16215 Method->setReturnType(DestType); 16216 } 16217 16218 // Change the type of the message. 16219 E->setType(DestType.getNonReferenceType()); 16220 E->setValueKind(Expr::getValueKindForType(DestType)); 16221 16222 return S.MaybeBindToTemporary(E); 16223 } 16224 16225 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16226 // The only case we should ever see here is a function-to-pointer decay. 16227 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16228 assert(E->getValueKind() == VK_RValue); 16229 assert(E->getObjectKind() == OK_Ordinary); 16230 16231 E->setType(DestType); 16232 16233 // Rebuild the sub-expression as the pointee (function) type. 16234 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16235 16236 ExprResult Result = Visit(E->getSubExpr()); 16237 if (!Result.isUsable()) return ExprError(); 16238 16239 E->setSubExpr(Result.get()); 16240 return E; 16241 } else if (E->getCastKind() == CK_LValueToRValue) { 16242 assert(E->getValueKind() == VK_RValue); 16243 assert(E->getObjectKind() == OK_Ordinary); 16244 16245 assert(isa<BlockPointerType>(E->getType())); 16246 16247 E->setType(DestType); 16248 16249 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16250 DestType = S.Context.getLValueReferenceType(DestType); 16251 16252 ExprResult Result = Visit(E->getSubExpr()); 16253 if (!Result.isUsable()) return ExprError(); 16254 16255 E->setSubExpr(Result.get()); 16256 return E; 16257 } else { 16258 llvm_unreachable("Unhandled cast type!"); 16259 } 16260 } 16261 16262 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16263 ExprValueKind ValueKind = VK_LValue; 16264 QualType Type = DestType; 16265 16266 // We know how to make this work for certain kinds of decls: 16267 16268 // - functions 16269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16270 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16271 DestType = Ptr->getPointeeType(); 16272 ExprResult Result = resolveDecl(E, VD); 16273 if (Result.isInvalid()) return ExprError(); 16274 return S.ImpCastExprToType(Result.get(), Type, 16275 CK_FunctionToPointerDecay, VK_RValue); 16276 } 16277 16278 if (!Type->isFunctionType()) { 16279 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16280 << VD << E->getSourceRange(); 16281 return ExprError(); 16282 } 16283 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16284 // We must match the FunctionDecl's type to the hack introduced in 16285 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16286 // type. See the lengthy commentary in that routine. 16287 QualType FDT = FD->getType(); 16288 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16289 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16290 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16291 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16292 SourceLocation Loc = FD->getLocation(); 16293 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16294 FD->getDeclContext(), 16295 Loc, Loc, FD->getNameInfo().getName(), 16296 DestType, FD->getTypeSourceInfo(), 16297 SC_None, false/*isInlineSpecified*/, 16298 FD->hasPrototype(), 16299 false/*isConstexprSpecified*/); 16300 16301 if (FD->getQualifier()) 16302 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16303 16304 SmallVector<ParmVarDecl*, 16> Params; 16305 for (const auto &AI : FT->param_types()) { 16306 ParmVarDecl *Param = 16307 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16308 Param->setScopeInfo(0, Params.size()); 16309 Params.push_back(Param); 16310 } 16311 NewFD->setParams(Params); 16312 DRE->setDecl(NewFD); 16313 VD = DRE->getDecl(); 16314 } 16315 } 16316 16317 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16318 if (MD->isInstance()) { 16319 ValueKind = VK_RValue; 16320 Type = S.Context.BoundMemberTy; 16321 } 16322 16323 // Function references aren't l-values in C. 16324 if (!S.getLangOpts().CPlusPlus) 16325 ValueKind = VK_RValue; 16326 16327 // - variables 16328 } else if (isa<VarDecl>(VD)) { 16329 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16330 Type = RefTy->getPointeeType(); 16331 } else if (Type->isFunctionType()) { 16332 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16333 << VD << E->getSourceRange(); 16334 return ExprError(); 16335 } 16336 16337 // - nothing else 16338 } else { 16339 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16340 << VD << E->getSourceRange(); 16341 return ExprError(); 16342 } 16343 16344 // Modifying the declaration like this is friendly to IR-gen but 16345 // also really dangerous. 16346 VD->setType(DestType); 16347 E->setType(Type); 16348 E->setValueKind(ValueKind); 16349 return E; 16350 } 16351 16352 /// Check a cast of an unknown-any type. We intentionally only 16353 /// trigger this for C-style casts. 16354 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16355 Expr *CastExpr, CastKind &CastKind, 16356 ExprValueKind &VK, CXXCastPath &Path) { 16357 // The type we're casting to must be either void or complete. 16358 if (!CastType->isVoidType() && 16359 RequireCompleteType(TypeRange.getBegin(), CastType, 16360 diag::err_typecheck_cast_to_incomplete)) 16361 return ExprError(); 16362 16363 // Rewrite the casted expression from scratch. 16364 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16365 if (!result.isUsable()) return ExprError(); 16366 16367 CastExpr = result.get(); 16368 VK = CastExpr->getValueKind(); 16369 CastKind = CK_NoOp; 16370 16371 return CastExpr; 16372 } 16373 16374 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16375 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16376 } 16377 16378 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16379 Expr *arg, QualType ¶mType) { 16380 // If the syntactic form of the argument is not an explicit cast of 16381 // any sort, just do default argument promotion. 16382 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16383 if (!castArg) { 16384 ExprResult result = DefaultArgumentPromotion(arg); 16385 if (result.isInvalid()) return ExprError(); 16386 paramType = result.get()->getType(); 16387 return result; 16388 } 16389 16390 // Otherwise, use the type that was written in the explicit cast. 16391 assert(!arg->hasPlaceholderType()); 16392 paramType = castArg->getTypeAsWritten(); 16393 16394 // Copy-initialize a parameter of that type. 16395 InitializedEntity entity = 16396 InitializedEntity::InitializeParameter(Context, paramType, 16397 /*consumed*/ false); 16398 return PerformCopyInitialization(entity, callLoc, arg); 16399 } 16400 16401 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16402 Expr *orig = E; 16403 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16404 while (true) { 16405 E = E->IgnoreParenImpCasts(); 16406 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16407 E = call->getCallee(); 16408 diagID = diag::err_uncasted_call_of_unknown_any; 16409 } else { 16410 break; 16411 } 16412 } 16413 16414 SourceLocation loc; 16415 NamedDecl *d; 16416 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16417 loc = ref->getLocation(); 16418 d = ref->getDecl(); 16419 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16420 loc = mem->getMemberLoc(); 16421 d = mem->getMemberDecl(); 16422 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16423 diagID = diag::err_uncasted_call_of_unknown_any; 16424 loc = msg->getSelectorStartLoc(); 16425 d = msg->getMethodDecl(); 16426 if (!d) { 16427 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16428 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16429 << orig->getSourceRange(); 16430 return ExprError(); 16431 } 16432 } else { 16433 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16434 << E->getSourceRange(); 16435 return ExprError(); 16436 } 16437 16438 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16439 16440 // Never recoverable. 16441 return ExprError(); 16442 } 16443 16444 /// Check for operands with placeholder types and complain if found. 16445 /// Returns ExprError() if there was an error and no recovery was possible. 16446 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16447 if (!getLangOpts().CPlusPlus) { 16448 // C cannot handle TypoExpr nodes on either side of a binop because it 16449 // doesn't handle dependent types properly, so make sure any TypoExprs have 16450 // been dealt with before checking the operands. 16451 ExprResult Result = CorrectDelayedTyposInExpr(E); 16452 if (!Result.isUsable()) return ExprError(); 16453 E = Result.get(); 16454 } 16455 16456 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16457 if (!placeholderType) return E; 16458 16459 switch (placeholderType->getKind()) { 16460 16461 // Overloaded expressions. 16462 case BuiltinType::Overload: { 16463 // Try to resolve a single function template specialization. 16464 // This is obligatory. 16465 ExprResult Result = E; 16466 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16467 return Result; 16468 16469 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16470 // leaves Result unchanged on failure. 16471 Result = E; 16472 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16473 return Result; 16474 16475 // If that failed, try to recover with a call. 16476 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16477 /*complain*/ true); 16478 return Result; 16479 } 16480 16481 // Bound member functions. 16482 case BuiltinType::BoundMember: { 16483 ExprResult result = E; 16484 const Expr *BME = E->IgnoreParens(); 16485 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16486 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16487 if (isa<CXXPseudoDestructorExpr>(BME)) { 16488 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16489 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16490 if (ME->getMemberNameInfo().getName().getNameKind() == 16491 DeclarationName::CXXDestructorName) 16492 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16493 } 16494 tryToRecoverWithCall(result, PD, 16495 /*complain*/ true); 16496 return result; 16497 } 16498 16499 // ARC unbridged casts. 16500 case BuiltinType::ARCUnbridgedCast: { 16501 Expr *realCast = stripARCUnbridgedCast(E); 16502 diagnoseARCUnbridgedCast(realCast); 16503 return realCast; 16504 } 16505 16506 // Expressions of unknown type. 16507 case BuiltinType::UnknownAny: 16508 return diagnoseUnknownAnyExpr(*this, E); 16509 16510 // Pseudo-objects. 16511 case BuiltinType::PseudoObject: 16512 return checkPseudoObjectRValue(E); 16513 16514 case BuiltinType::BuiltinFn: { 16515 // Accept __noop without parens by implicitly converting it to a call expr. 16516 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16517 if (DRE) { 16518 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16519 if (FD->getBuiltinID() == Builtin::BI__noop) { 16520 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16521 CK_BuiltinFnToFnPtr).get(); 16522 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16523 VK_RValue, SourceLocation()); 16524 } 16525 } 16526 16527 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16528 return ExprError(); 16529 } 16530 16531 // Expressions of unknown type. 16532 case BuiltinType::OMPArraySection: 16533 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16534 return ExprError(); 16535 16536 // Everything else should be impossible. 16537 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16538 case BuiltinType::Id: 16539 #include "clang/Basic/OpenCLImageTypes.def" 16540 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16541 #define PLACEHOLDER_TYPE(Id, SingletonId) 16542 #include "clang/AST/BuiltinTypes.def" 16543 break; 16544 } 16545 16546 llvm_unreachable("invalid placeholder type!"); 16547 } 16548 16549 bool Sema::CheckCaseExpression(Expr *E) { 16550 if (E->isTypeDependent()) 16551 return true; 16552 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16553 return E->getType()->isIntegralOrEnumerationType(); 16554 return false; 16555 } 16556 16557 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16558 ExprResult 16559 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16560 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16561 "Unknown Objective-C Boolean value!"); 16562 QualType BoolT = Context.ObjCBuiltinBoolTy; 16563 if (!Context.getBOOLDecl()) { 16564 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16565 Sema::LookupOrdinaryName); 16566 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16567 NamedDecl *ND = Result.getFoundDecl(); 16568 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16569 Context.setBOOLDecl(TD); 16570 } 16571 } 16572 if (Context.getBOOLDecl()) 16573 BoolT = Context.getBOOLType(); 16574 return new (Context) 16575 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16576 } 16577 16578 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16579 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16580 SourceLocation RParen) { 16581 16582 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16583 16584 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16585 [&](const AvailabilitySpec &Spec) { 16586 return Spec.getPlatform() == Platform; 16587 }); 16588 16589 VersionTuple Version; 16590 if (Spec != AvailSpecs.end()) 16591 Version = Spec->getVersion(); 16592 16593 // The use of `@available` in the enclosing function should be analyzed to 16594 // warn when it's used inappropriately (i.e. not if(@available)). 16595 if (getCurFunctionOrMethodDecl()) 16596 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16597 else if (getCurBlock() || getCurLambda()) 16598 getCurFunction()->HasPotentialAvailabilityViolations = true; 16599 16600 return new (Context) 16601 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16602 } 16603