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 // See if this is an aligned allocation/deallocation function that is 71 // unavailable. 72 if (TreatUnavailableAsInvalid && 73 isUnavailableAlignedAllocationFunction(*FD)) 74 return false; 75 } 76 77 // See if this function is unavailable. 78 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 79 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 80 return false; 81 82 return true; 83 } 84 85 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 86 // Warn if this is used but marked unused. 87 if (const auto *A = D->getAttr<UnusedAttr>()) { 88 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 89 // should diagnose them. 90 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 91 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 92 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 93 if (DC && !DC->hasAttr<UnusedAttr>()) 94 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 95 } 96 } 97 } 98 99 /// Emit a note explaining that this function is deleted. 100 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 101 assert(Decl->isDeleted()); 102 103 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 104 105 if (Method && Method->isDeleted() && Method->isDefaulted()) { 106 // If the method was explicitly defaulted, point at that declaration. 107 if (!Method->isImplicit()) 108 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 109 110 // Try to diagnose why this special member function was implicitly 111 // deleted. This might fail, if that reason no longer applies. 112 CXXSpecialMember CSM = getSpecialMember(Method); 113 if (CSM != CXXInvalid) 114 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 115 116 return; 117 } 118 119 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 120 if (Ctor && Ctor->isInheritingConstructor()) 121 return NoteDeletedInheritingConstructor(Ctor); 122 123 Diag(Decl->getLocation(), diag::note_availability_specified_here) 124 << Decl << 1; 125 } 126 127 /// Determine whether a FunctionDecl was ever declared with an 128 /// explicit storage class. 129 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 130 for (auto I : D->redecls()) { 131 if (I->getStorageClass() != SC_None) 132 return true; 133 } 134 return false; 135 } 136 137 /// Check whether we're in an extern inline function and referring to a 138 /// variable or function with internal linkage (C11 6.7.4p3). 139 /// 140 /// This is only a warning because we used to silently accept this code, but 141 /// in many cases it will not behave correctly. This is not enabled in C++ mode 142 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 143 /// and so while there may still be user mistakes, most of the time we can't 144 /// prove that there are errors. 145 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 146 const NamedDecl *D, 147 SourceLocation Loc) { 148 // This is disabled under C++; there are too many ways for this to fire in 149 // contexts where the warning is a false positive, or where it is technically 150 // correct but benign. 151 if (S.getLangOpts().CPlusPlus) 152 return; 153 154 // Check if this is an inlined function or method. 155 FunctionDecl *Current = S.getCurFunctionDecl(); 156 if (!Current) 157 return; 158 if (!Current->isInlined()) 159 return; 160 if (!Current->isExternallyVisible()) 161 return; 162 163 // Check if the decl has internal linkage. 164 if (D->getFormalLinkage() != InternalLinkage) 165 return; 166 167 // Downgrade from ExtWarn to Extension if 168 // (1) the supposedly external inline function is in the main file, 169 // and probably won't be included anywhere else. 170 // (2) the thing we're referencing is a pure function. 171 // (3) the thing we're referencing is another inline function. 172 // This last can give us false negatives, but it's better than warning on 173 // wrappers for simple C library functions. 174 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 175 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 176 if (!DowngradeWarning && UsedFn) 177 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 178 179 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 180 : diag::ext_internal_in_extern_inline) 181 << /*IsVar=*/!UsedFn << D; 182 183 S.MaybeSuggestAddingStaticToDecl(Current); 184 185 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 186 << D; 187 } 188 189 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 190 const FunctionDecl *First = Cur->getFirstDecl(); 191 192 // Suggest "static" on the function, if possible. 193 if (!hasAnyExplicitStorageClass(First)) { 194 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 195 Diag(DeclBegin, diag::note_convert_inline_to_static) 196 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 197 } 198 } 199 200 /// Determine whether the use of this declaration is valid, and 201 /// emit any corresponding diagnostics. 202 /// 203 /// This routine diagnoses various problems with referencing 204 /// declarations that can occur when using a declaration. For example, 205 /// it might warn if a deprecated or unavailable declaration is being 206 /// used, or produce an error (and return true) if a C++0x deleted 207 /// function is being used. 208 /// 209 /// \returns true if there was an error (this declaration cannot be 210 /// referenced), false otherwise. 211 /// 212 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 213 const ObjCInterfaceDecl *UnknownObjCClass, 214 bool ObjCPropertyAccess, 215 bool AvoidPartialAvailabilityChecks, 216 ObjCInterfaceDecl *ClassReceiver) { 217 SourceLocation Loc = Locs.front(); 218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 219 // If there were any diagnostics suppressed by template argument deduction, 220 // emit them now. 221 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 222 if (Pos != SuppressedDiagnostics.end()) { 223 for (const PartialDiagnosticAt &Suppressed : Pos->second) 224 Diag(Suppressed.first, Suppressed.second); 225 226 // Clear out the list of suppressed diagnostics, so that we don't emit 227 // them again for this specialization. However, we don't obsolete this 228 // entry from the table, because we want to avoid ever emitting these 229 // diagnostics again. 230 Pos->second.clear(); 231 } 232 233 // C++ [basic.start.main]p3: 234 // The function 'main' shall not be used within a program. 235 if (cast<FunctionDecl>(D)->isMain()) 236 Diag(Loc, diag::ext_main_used); 237 238 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 239 } 240 241 // See if this is an auto-typed variable whose initializer we are parsing. 242 if (ParsingInitForAutoVars.count(D)) { 243 if (isa<BindingDecl>(D)) { 244 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 245 << D->getDeclName(); 246 } else { 247 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 248 << D->getDeclName() << cast<VarDecl>(D)->getType(); 249 } 250 return true; 251 } 252 253 // See if this is a deleted function. 254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 255 if (FD->isDeleted()) { 256 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 257 if (Ctor && Ctor->isInheritingConstructor()) 258 Diag(Loc, diag::err_deleted_inherited_ctor_use) 259 << Ctor->getParent() 260 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 261 else 262 Diag(Loc, diag::err_deleted_function_use); 263 NoteDeletedFunction(FD); 264 return true; 265 } 266 267 // If the function has a deduced return type, and we can't deduce it, 268 // then we can't use it either. 269 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 270 DeduceReturnType(FD, Loc)) 271 return true; 272 273 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 274 return true; 275 } 276 277 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 278 // Lambdas are only default-constructible or assignable in C++2a onwards. 279 if (MD->getParent()->isLambda() && 280 ((isa<CXXConstructorDecl>(MD) && 281 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 282 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 283 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 284 << !isa<CXXConstructorDecl>(MD); 285 } 286 } 287 288 auto getReferencedObjCProp = [](const NamedDecl *D) -> 289 const ObjCPropertyDecl * { 290 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 291 return MD->findPropertyDecl(); 292 return nullptr; 293 }; 294 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 295 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 296 return true; 297 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 298 return true; 299 } 300 301 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 302 // Only the variables omp_in and omp_out are allowed in the combiner. 303 // Only the variables omp_priv and omp_orig are allowed in the 304 // initializer-clause. 305 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 306 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 307 isa<VarDecl>(D)) { 308 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 309 << getCurFunction()->HasOMPDeclareReductionCombiner; 310 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 311 return true; 312 } 313 314 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 315 AvoidPartialAvailabilityChecks, ClassReceiver); 316 317 DiagnoseUnusedOfDecl(*this, D, Loc); 318 319 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 320 321 return false; 322 } 323 324 /// Retrieve the message suffix that should be added to a 325 /// diagnostic complaining about the given function being deleted or 326 /// unavailable. 327 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 328 std::string Message; 329 if (FD->getAvailability(&Message)) 330 return ": " + Message; 331 332 return std::string(); 333 } 334 335 /// DiagnoseSentinelCalls - This routine checks whether a call or 336 /// message-send is to a declaration with the sentinel attribute, and 337 /// if so, it checks that the requirements of the sentinel are 338 /// satisfied. 339 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 340 ArrayRef<Expr *> Args) { 341 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 342 if (!attr) 343 return; 344 345 // The number of formal parameters of the declaration. 346 unsigned numFormalParams; 347 348 // The kind of declaration. This is also an index into a %select in 349 // the diagnostic. 350 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 351 352 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 353 numFormalParams = MD->param_size(); 354 calleeType = CT_Method; 355 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 356 numFormalParams = FD->param_size(); 357 calleeType = CT_Function; 358 } else if (isa<VarDecl>(D)) { 359 QualType type = cast<ValueDecl>(D)->getType(); 360 const FunctionType *fn = nullptr; 361 if (const PointerType *ptr = type->getAs<PointerType>()) { 362 fn = ptr->getPointeeType()->getAs<FunctionType>(); 363 if (!fn) return; 364 calleeType = CT_Function; 365 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 366 fn = ptr->getPointeeType()->castAs<FunctionType>(); 367 calleeType = CT_Block; 368 } else { 369 return; 370 } 371 372 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 373 numFormalParams = proto->getNumParams(); 374 } else { 375 numFormalParams = 0; 376 } 377 } else { 378 return; 379 } 380 381 // "nullPos" is the number of formal parameters at the end which 382 // effectively count as part of the variadic arguments. This is 383 // useful if you would prefer to not have *any* formal parameters, 384 // but the language forces you to have at least one. 385 unsigned nullPos = attr->getNullPos(); 386 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 387 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 388 389 // The number of arguments which should follow the sentinel. 390 unsigned numArgsAfterSentinel = attr->getSentinel(); 391 392 // If there aren't enough arguments for all the formal parameters, 393 // the sentinel, and the args after the sentinel, complain. 394 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 395 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 396 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 397 return; 398 } 399 400 // Otherwise, find the sentinel expression. 401 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 402 if (!sentinelExpr) return; 403 if (sentinelExpr->isValueDependent()) return; 404 if (Context.isSentinelNullExpr(sentinelExpr)) return; 405 406 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 407 // or 'NULL' if those are actually defined in the context. Only use 408 // 'nil' for ObjC methods, where it's much more likely that the 409 // variadic arguments form a list of object pointers. 410 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 411 std::string NullValue; 412 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 413 NullValue = "nil"; 414 else if (getLangOpts().CPlusPlus11) 415 NullValue = "nullptr"; 416 else if (PP.isMacroDefined("NULL")) 417 NullValue = "NULL"; 418 else 419 NullValue = "(void*) 0"; 420 421 if (MissingNilLoc.isInvalid()) 422 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 423 else 424 Diag(MissingNilLoc, diag::warn_missing_sentinel) 425 << int(calleeType) 426 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 427 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 428 } 429 430 SourceRange Sema::getExprRange(Expr *E) const { 431 return E ? E->getSourceRange() : SourceRange(); 432 } 433 434 //===----------------------------------------------------------------------===// 435 // Standard Promotions and Conversions 436 //===----------------------------------------------------------------------===// 437 438 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 439 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 440 // Handle any placeholder expressions which made it here. 441 if (E->getType()->isPlaceholderType()) { 442 ExprResult result = CheckPlaceholderExpr(E); 443 if (result.isInvalid()) return ExprError(); 444 E = result.get(); 445 } 446 447 QualType Ty = E->getType(); 448 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 449 450 if (Ty->isFunctionType()) { 451 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 452 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 453 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 454 return ExprError(); 455 456 E = ImpCastExprToType(E, Context.getPointerType(Ty), 457 CK_FunctionToPointerDecay).get(); 458 } else if (Ty->isArrayType()) { 459 // In C90 mode, arrays only promote to pointers if the array expression is 460 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 461 // type 'array of type' is converted to an expression that has type 'pointer 462 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 463 // that has type 'array of type' ...". The relevant change is "an lvalue" 464 // (C90) to "an expression" (C99). 465 // 466 // C++ 4.2p1: 467 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 468 // T" can be converted to an rvalue of type "pointer to T". 469 // 470 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 471 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 472 CK_ArrayToPointerDecay).get(); 473 } 474 return E; 475 } 476 477 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 478 // Check to see if we are dereferencing a null pointer. If so, 479 // and if not volatile-qualified, this is undefined behavior that the 480 // optimizer will delete, so warn about it. People sometimes try to use this 481 // to get a deterministic trap and are surprised by clang's behavior. This 482 // only handles the pattern "*null", which is a very syntactic check. 483 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 484 if (UO->getOpcode() == UO_Deref && 485 UO->getSubExpr()->IgnoreParenCasts()-> 486 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 487 !UO->getType().isVolatileQualified()) { 488 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 489 S.PDiag(diag::warn_indirection_through_null) 490 << UO->getSubExpr()->getSourceRange()); 491 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 492 S.PDiag(diag::note_indirection_through_null)); 493 } 494 } 495 496 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 497 SourceLocation AssignLoc, 498 const Expr* RHS) { 499 const ObjCIvarDecl *IV = OIRE->getDecl(); 500 if (!IV) 501 return; 502 503 DeclarationName MemberName = IV->getDeclName(); 504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 505 if (!Member || !Member->isStr("isa")) 506 return; 507 508 const Expr *Base = OIRE->getBase(); 509 QualType BaseType = Base->getType(); 510 if (OIRE->isArrow()) 511 BaseType = BaseType->getPointeeType(); 512 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 513 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 514 ObjCInterfaceDecl *ClassDeclared = nullptr; 515 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 516 if (!ClassDeclared->getSuperClass() 517 && (*ClassDeclared->ivar_begin()) == IV) { 518 if (RHS) { 519 NamedDecl *ObjectSetClass = 520 S.LookupSingleName(S.TUScope, 521 &S.Context.Idents.get("object_setClass"), 522 SourceLocation(), S.LookupOrdinaryName); 523 if (ObjectSetClass) { 524 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 525 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 526 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 527 "object_setClass(") 528 << FixItHint::CreateReplacement( 529 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 530 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 531 } 532 else 533 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 534 } else { 535 NamedDecl *ObjectGetClass = 536 S.LookupSingleName(S.TUScope, 537 &S.Context.Idents.get("object_getClass"), 538 SourceLocation(), S.LookupOrdinaryName); 539 if (ObjectGetClass) 540 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 541 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 542 "object_getClass(") 543 << FixItHint::CreateReplacement( 544 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 545 else 546 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 547 } 548 S.Diag(IV->getLocation(), diag::note_ivar_decl); 549 } 550 } 551 } 552 553 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 554 // Handle any placeholder expressions which made it here. 555 if (E->getType()->isPlaceholderType()) { 556 ExprResult result = CheckPlaceholderExpr(E); 557 if (result.isInvalid()) return ExprError(); 558 E = result.get(); 559 } 560 561 // C++ [conv.lval]p1: 562 // A glvalue of a non-function, non-array type T can be 563 // converted to a prvalue. 564 if (!E->isGLValue()) return E; 565 566 QualType T = E->getType(); 567 assert(!T.isNull() && "r-value conversion on typeless expression?"); 568 569 // We don't want to throw lvalue-to-rvalue casts on top of 570 // expressions of certain types in C++. 571 if (getLangOpts().CPlusPlus && 572 (E->getType() == Context.OverloadTy || 573 T->isDependentType() || 574 T->isRecordType())) 575 return E; 576 577 // The C standard is actually really unclear on this point, and 578 // DR106 tells us what the result should be but not why. It's 579 // generally best to say that void types just doesn't undergo 580 // lvalue-to-rvalue at all. Note that expressions of unqualified 581 // 'void' type are never l-values, but qualified void can be. 582 if (T->isVoidType()) 583 return E; 584 585 // OpenCL usually rejects direct accesses to values of 'half' type. 586 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 587 T->isHalfType()) { 588 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 589 << 0 << T; 590 return ExprError(); 591 } 592 593 CheckForNullPointerDereference(*this, E); 594 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 595 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 596 &Context.Idents.get("object_getClass"), 597 SourceLocation(), LookupOrdinaryName); 598 if (ObjectGetClass) 599 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 600 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 601 << FixItHint::CreateReplacement( 602 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 603 else 604 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 605 } 606 else if (const ObjCIvarRefExpr *OIRE = 607 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 608 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 609 610 // C++ [conv.lval]p1: 611 // [...] If T is a non-class type, the type of the prvalue is the 612 // cv-unqualified version of T. Otherwise, the type of the 613 // rvalue is T. 614 // 615 // C99 6.3.2.1p2: 616 // If the lvalue has qualified type, the value has the unqualified 617 // version of the type of the lvalue; otherwise, the value has the 618 // type of the lvalue. 619 if (T.hasQualifiers()) 620 T = T.getUnqualifiedType(); 621 622 // Under the MS ABI, lock down the inheritance model now. 623 if (T->isMemberPointerType() && 624 Context.getTargetInfo().getCXXABI().isMicrosoft()) 625 (void)isCompleteType(E->getExprLoc(), T); 626 627 UpdateMarkingForLValueToRValue(E); 628 629 // Loading a __weak object implicitly retains the value, so we need a cleanup to 630 // balance that. 631 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 632 Cleanup.setExprNeedsCleanups(true); 633 634 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 635 nullptr, VK_RValue); 636 637 // C11 6.3.2.1p2: 638 // ... if the lvalue has atomic type, the value has the non-atomic version 639 // of the type of the lvalue ... 640 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 641 T = Atomic->getValueType().getUnqualifiedType(); 642 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 643 nullptr, VK_RValue); 644 } 645 646 return Res; 647 } 648 649 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 650 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 651 if (Res.isInvalid()) 652 return ExprError(); 653 Res = DefaultLvalueConversion(Res.get()); 654 if (Res.isInvalid()) 655 return ExprError(); 656 return Res; 657 } 658 659 /// CallExprUnaryConversions - a special case of an unary conversion 660 /// performed on a function designator of a call expression. 661 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 662 QualType Ty = E->getType(); 663 ExprResult Res = E; 664 // Only do implicit cast for a function type, but not for a pointer 665 // to function type. 666 if (Ty->isFunctionType()) { 667 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 668 CK_FunctionToPointerDecay).get(); 669 if (Res.isInvalid()) 670 return ExprError(); 671 } 672 Res = DefaultLvalueConversion(Res.get()); 673 if (Res.isInvalid()) 674 return ExprError(); 675 return Res.get(); 676 } 677 678 /// UsualUnaryConversions - Performs various conversions that are common to most 679 /// operators (C99 6.3). The conversions of array and function types are 680 /// sometimes suppressed. For example, the array->pointer conversion doesn't 681 /// apply if the array is an argument to the sizeof or address (&) operators. 682 /// In these instances, this routine should *not* be called. 683 ExprResult Sema::UsualUnaryConversions(Expr *E) { 684 // First, convert to an r-value. 685 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 686 if (Res.isInvalid()) 687 return ExprError(); 688 E = Res.get(); 689 690 QualType Ty = E->getType(); 691 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 692 693 // Half FP have to be promoted to float unless it is natively supported 694 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 695 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 696 697 // Try to perform integral promotions if the object has a theoretically 698 // promotable type. 699 if (Ty->isIntegralOrUnscopedEnumerationType()) { 700 // C99 6.3.1.1p2: 701 // 702 // The following may be used in an expression wherever an int or 703 // unsigned int may be used: 704 // - an object or expression with an integer type whose integer 705 // conversion rank is less than or equal to the rank of int 706 // and unsigned int. 707 // - A bit-field of type _Bool, int, signed int, or unsigned int. 708 // 709 // If an int can represent all values of the original type, the 710 // value is converted to an int; otherwise, it is converted to an 711 // unsigned int. These are called the integer promotions. All 712 // other types are unchanged by the integer promotions. 713 714 QualType PTy = Context.isPromotableBitField(E); 715 if (!PTy.isNull()) { 716 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 717 return E; 718 } 719 if (Ty->isPromotableIntegerType()) { 720 QualType PT = Context.getPromotedIntegerType(Ty); 721 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 722 return E; 723 } 724 } 725 return E; 726 } 727 728 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 729 /// do not have a prototype. Arguments that have type float or __fp16 730 /// are promoted to double. All other argument types are converted by 731 /// UsualUnaryConversions(). 732 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 733 QualType Ty = E->getType(); 734 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 735 736 ExprResult Res = UsualUnaryConversions(E); 737 if (Res.isInvalid()) 738 return ExprError(); 739 E = Res.get(); 740 741 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 742 // promote to double. 743 // Note that default argument promotion applies only to float (and 744 // half/fp16); it does not apply to _Float16. 745 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 746 if (BTy && (BTy->getKind() == BuiltinType::Half || 747 BTy->getKind() == BuiltinType::Float)) { 748 if (getLangOpts().OpenCL && 749 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 750 if (BTy->getKind() == BuiltinType::Half) { 751 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 752 } 753 } else { 754 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 755 } 756 } 757 758 // C++ performs lvalue-to-rvalue conversion as a default argument 759 // promotion, even on class types, but note: 760 // C++11 [conv.lval]p2: 761 // When an lvalue-to-rvalue conversion occurs in an unevaluated 762 // operand or a subexpression thereof the value contained in the 763 // referenced object is not accessed. Otherwise, if the glvalue 764 // has a class type, the conversion copy-initializes a temporary 765 // of type T from the glvalue and the result of the conversion 766 // is a prvalue for the temporary. 767 // FIXME: add some way to gate this entire thing for correctness in 768 // potentially potentially evaluated contexts. 769 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 770 ExprResult Temp = PerformCopyInitialization( 771 InitializedEntity::InitializeTemporary(E->getType()), 772 E->getExprLoc(), E); 773 if (Temp.isInvalid()) 774 return ExprError(); 775 E = Temp.get(); 776 } 777 778 return E; 779 } 780 781 /// Determine the degree of POD-ness for an expression. 782 /// Incomplete types are considered POD, since this check can be performed 783 /// when we're in an unevaluated context. 784 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 785 if (Ty->isIncompleteType()) { 786 // C++11 [expr.call]p7: 787 // After these conversions, if the argument does not have arithmetic, 788 // enumeration, pointer, pointer to member, or class type, the program 789 // is ill-formed. 790 // 791 // Since we've already performed array-to-pointer and function-to-pointer 792 // decay, the only such type in C++ is cv void. This also handles 793 // initializer lists as variadic arguments. 794 if (Ty->isVoidType()) 795 return VAK_Invalid; 796 797 if (Ty->isObjCObjectType()) 798 return VAK_Invalid; 799 return VAK_Valid; 800 } 801 802 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 803 return VAK_Invalid; 804 805 if (Ty.isCXX98PODType(Context)) 806 return VAK_Valid; 807 808 // C++11 [expr.call]p7: 809 // Passing a potentially-evaluated argument of class type (Clause 9) 810 // having a non-trivial copy constructor, a non-trivial move constructor, 811 // or a non-trivial destructor, with no corresponding parameter, 812 // is conditionally-supported with implementation-defined semantics. 813 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 814 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 815 if (!Record->hasNonTrivialCopyConstructor() && 816 !Record->hasNonTrivialMoveConstructor() && 817 !Record->hasNonTrivialDestructor()) 818 return VAK_ValidInCXX11; 819 820 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 821 return VAK_Valid; 822 823 if (Ty->isObjCObjectType()) 824 return VAK_Invalid; 825 826 if (getLangOpts().MSVCCompat) 827 return VAK_MSVCUndefined; 828 829 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 830 // permitted to reject them. We should consider doing so. 831 return VAK_Undefined; 832 } 833 834 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 835 // Don't allow one to pass an Objective-C interface to a vararg. 836 const QualType &Ty = E->getType(); 837 VarArgKind VAK = isValidVarArgType(Ty); 838 839 // Complain about passing non-POD types through varargs. 840 switch (VAK) { 841 case VAK_ValidInCXX11: 842 DiagRuntimeBehavior( 843 E->getBeginLoc(), nullptr, 844 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 845 LLVM_FALLTHROUGH; 846 case VAK_Valid: 847 if (Ty->isRecordType()) { 848 // This is unlikely to be what the user intended. If the class has a 849 // 'c_str' member function, the user probably meant to call that. 850 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 851 PDiag(diag::warn_pass_class_arg_to_vararg) 852 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 853 } 854 break; 855 856 case VAK_Undefined: 857 case VAK_MSVCUndefined: 858 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 859 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 860 << getLangOpts().CPlusPlus11 << Ty << CT); 861 break; 862 863 case VAK_Invalid: 864 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 865 Diag(E->getBeginLoc(), 866 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 867 << Ty << CT; 868 else if (Ty->isObjCObjectType()) 869 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 870 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 871 << Ty << CT); 872 else 873 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 874 << isa<InitListExpr>(E) << Ty << CT; 875 break; 876 } 877 } 878 879 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 880 /// will create a trap if the resulting type is not a POD type. 881 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 882 FunctionDecl *FDecl) { 883 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 884 // Strip the unbridged-cast placeholder expression off, if applicable. 885 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 886 (CT == VariadicMethod || 887 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 888 E = stripARCUnbridgedCast(E); 889 890 // Otherwise, do normal placeholder checking. 891 } else { 892 ExprResult ExprRes = CheckPlaceholderExpr(E); 893 if (ExprRes.isInvalid()) 894 return ExprError(); 895 E = ExprRes.get(); 896 } 897 } 898 899 ExprResult ExprRes = DefaultArgumentPromotion(E); 900 if (ExprRes.isInvalid()) 901 return ExprError(); 902 E = ExprRes.get(); 903 904 // Diagnostics regarding non-POD argument types are 905 // emitted along with format string checking in Sema::CheckFunctionCall(). 906 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 907 // Turn this into a trap. 908 CXXScopeSpec SS; 909 SourceLocation TemplateKWLoc; 910 UnqualifiedId Name; 911 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 912 E->getBeginLoc()); 913 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 914 Name, true, false); 915 if (TrapFn.isInvalid()) 916 return ExprError(); 917 918 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 919 None, E->getEndLoc()); 920 if (Call.isInvalid()) 921 return ExprError(); 922 923 ExprResult Comma = 924 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 925 if (Comma.isInvalid()) 926 return ExprError(); 927 return Comma.get(); 928 } 929 930 if (!getLangOpts().CPlusPlus && 931 RequireCompleteType(E->getExprLoc(), E->getType(), 932 diag::err_call_incomplete_argument)) 933 return ExprError(); 934 935 return E; 936 } 937 938 /// Converts an integer to complex float type. Helper function of 939 /// UsualArithmeticConversions() 940 /// 941 /// \return false if the integer expression is an integer type and is 942 /// successfully converted to the complex type. 943 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 944 ExprResult &ComplexExpr, 945 QualType IntTy, 946 QualType ComplexTy, 947 bool SkipCast) { 948 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 949 if (SkipCast) return false; 950 if (IntTy->isIntegerType()) { 951 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 952 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 953 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 954 CK_FloatingRealToComplex); 955 } else { 956 assert(IntTy->isComplexIntegerType()); 957 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 958 CK_IntegralComplexToFloatingComplex); 959 } 960 return false; 961 } 962 963 /// Handle arithmetic conversion with complex types. Helper function of 964 /// UsualArithmeticConversions() 965 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 966 ExprResult &RHS, QualType LHSType, 967 QualType RHSType, 968 bool IsCompAssign) { 969 // if we have an integer operand, the result is the complex type. 970 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 971 /*skipCast*/false)) 972 return LHSType; 973 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 974 /*skipCast*/IsCompAssign)) 975 return RHSType; 976 977 // This handles complex/complex, complex/float, or float/complex. 978 // When both operands are complex, the shorter operand is converted to the 979 // type of the longer, and that is the type of the result. This corresponds 980 // to what is done when combining two real floating-point operands. 981 // The fun begins when size promotion occur across type domains. 982 // From H&S 6.3.4: When one operand is complex and the other is a real 983 // floating-point type, the less precise type is converted, within it's 984 // real or complex domain, to the precision of the other type. For example, 985 // when combining a "long double" with a "double _Complex", the 986 // "double _Complex" is promoted to "long double _Complex". 987 988 // Compute the rank of the two types, regardless of whether they are complex. 989 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 990 991 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 992 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 993 QualType LHSElementType = 994 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 995 QualType RHSElementType = 996 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 997 998 QualType ResultType = S.Context.getComplexType(LHSElementType); 999 if (Order < 0) { 1000 // Promote the precision of the LHS if not an assignment. 1001 ResultType = S.Context.getComplexType(RHSElementType); 1002 if (!IsCompAssign) { 1003 if (LHSComplexType) 1004 LHS = 1005 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1006 else 1007 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1008 } 1009 } else if (Order > 0) { 1010 // Promote the precision of the RHS. 1011 if (RHSComplexType) 1012 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1013 else 1014 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1015 } 1016 return ResultType; 1017 } 1018 1019 /// Handle arithmetic conversion from integer to float. Helper function 1020 /// of UsualArithmeticConversions() 1021 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1022 ExprResult &IntExpr, 1023 QualType FloatTy, QualType IntTy, 1024 bool ConvertFloat, bool ConvertInt) { 1025 if (IntTy->isIntegerType()) { 1026 if (ConvertInt) 1027 // Convert intExpr to the lhs floating point type. 1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1029 CK_IntegralToFloating); 1030 return FloatTy; 1031 } 1032 1033 // Convert both sides to the appropriate complex float. 1034 assert(IntTy->isComplexIntegerType()); 1035 QualType result = S.Context.getComplexType(FloatTy); 1036 1037 // _Complex int -> _Complex float 1038 if (ConvertInt) 1039 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1040 CK_IntegralComplexToFloatingComplex); 1041 1042 // float -> _Complex float 1043 if (ConvertFloat) 1044 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1045 CK_FloatingRealToComplex); 1046 1047 return result; 1048 } 1049 1050 /// Handle arithmethic conversion with floating point types. Helper 1051 /// function of UsualArithmeticConversions() 1052 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1053 ExprResult &RHS, QualType LHSType, 1054 QualType RHSType, bool IsCompAssign) { 1055 bool LHSFloat = LHSType->isRealFloatingType(); 1056 bool RHSFloat = RHSType->isRealFloatingType(); 1057 1058 // If we have two real floating types, convert the smaller operand 1059 // to the bigger result. 1060 if (LHSFloat && RHSFloat) { 1061 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1062 if (order > 0) { 1063 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1064 return LHSType; 1065 } 1066 1067 assert(order < 0 && "illegal float comparison"); 1068 if (!IsCompAssign) 1069 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1070 return RHSType; 1071 } 1072 1073 if (LHSFloat) { 1074 // Half FP has to be promoted to float unless it is natively supported 1075 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1076 LHSType = S.Context.FloatTy; 1077 1078 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1079 /*convertFloat=*/!IsCompAssign, 1080 /*convertInt=*/ true); 1081 } 1082 assert(RHSFloat); 1083 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1084 /*convertInt=*/ true, 1085 /*convertFloat=*/!IsCompAssign); 1086 } 1087 1088 /// Diagnose attempts to convert between __float128 and long double if 1089 /// there is no support for such conversion. Helper function of 1090 /// UsualArithmeticConversions(). 1091 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1092 QualType RHSType) { 1093 /* No issue converting if at least one of the types is not a floating point 1094 type or the two types have the same rank. 1095 */ 1096 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1097 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1098 return false; 1099 1100 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1101 "The remaining types must be floating point types."); 1102 1103 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1104 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1105 1106 QualType LHSElemType = LHSComplex ? 1107 LHSComplex->getElementType() : LHSType; 1108 QualType RHSElemType = RHSComplex ? 1109 RHSComplex->getElementType() : RHSType; 1110 1111 // No issue if the two types have the same representation 1112 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1113 &S.Context.getFloatTypeSemantics(RHSElemType)) 1114 return false; 1115 1116 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1117 RHSElemType == S.Context.LongDoubleTy); 1118 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1119 RHSElemType == S.Context.Float128Ty); 1120 1121 // We've handled the situation where __float128 and long double have the same 1122 // representation. We allow all conversions for all possible long double types 1123 // except PPC's double double. 1124 return Float128AndLongDouble && 1125 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1126 &llvm::APFloat::PPCDoubleDouble()); 1127 } 1128 1129 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1130 1131 namespace { 1132 /// These helper callbacks are placed in an anonymous namespace to 1133 /// permit their use as function template parameters. 1134 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1135 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1136 } 1137 1138 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1139 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1140 CK_IntegralComplexCast); 1141 } 1142 } 1143 1144 /// Handle integer arithmetic conversions. Helper function of 1145 /// UsualArithmeticConversions() 1146 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1147 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1148 ExprResult &RHS, QualType LHSType, 1149 QualType RHSType, bool IsCompAssign) { 1150 // The rules for this case are in C99 6.3.1.8 1151 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1152 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1153 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1154 if (LHSSigned == RHSSigned) { 1155 // Same signedness; use the higher-ranked type 1156 if (order >= 0) { 1157 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1158 return LHSType; 1159 } else if (!IsCompAssign) 1160 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1161 return RHSType; 1162 } else if (order != (LHSSigned ? 1 : -1)) { 1163 // The unsigned type has greater than or equal rank to the 1164 // signed type, so use the unsigned type 1165 if (RHSSigned) { 1166 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1167 return LHSType; 1168 } else if (!IsCompAssign) 1169 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1170 return RHSType; 1171 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1172 // The two types are different widths; if we are here, that 1173 // means the signed type is larger than the unsigned type, so 1174 // use the signed type. 1175 if (LHSSigned) { 1176 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1177 return LHSType; 1178 } else if (!IsCompAssign) 1179 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1180 return RHSType; 1181 } else { 1182 // The signed type is higher-ranked than the unsigned type, 1183 // but isn't actually any bigger (like unsigned int and long 1184 // on most 32-bit systems). Use the unsigned type corresponding 1185 // to the signed type. 1186 QualType result = 1187 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1188 RHS = (*doRHSCast)(S, RHS.get(), result); 1189 if (!IsCompAssign) 1190 LHS = (*doLHSCast)(S, LHS.get(), result); 1191 return result; 1192 } 1193 } 1194 1195 /// Handle conversions with GCC complex int extension. Helper function 1196 /// of UsualArithmeticConversions() 1197 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1198 ExprResult &RHS, QualType LHSType, 1199 QualType RHSType, 1200 bool IsCompAssign) { 1201 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1202 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1203 1204 if (LHSComplexInt && RHSComplexInt) { 1205 QualType LHSEltType = LHSComplexInt->getElementType(); 1206 QualType RHSEltType = RHSComplexInt->getElementType(); 1207 QualType ScalarType = 1208 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1209 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1210 1211 return S.Context.getComplexType(ScalarType); 1212 } 1213 1214 if (LHSComplexInt) { 1215 QualType LHSEltType = LHSComplexInt->getElementType(); 1216 QualType ScalarType = 1217 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1218 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1219 QualType ComplexType = S.Context.getComplexType(ScalarType); 1220 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1221 CK_IntegralRealToComplex); 1222 1223 return ComplexType; 1224 } 1225 1226 assert(RHSComplexInt); 1227 1228 QualType RHSEltType = RHSComplexInt->getElementType(); 1229 QualType ScalarType = 1230 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1231 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1232 QualType ComplexType = S.Context.getComplexType(ScalarType); 1233 1234 if (!IsCompAssign) 1235 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1236 CK_IntegralRealToComplex); 1237 return ComplexType; 1238 } 1239 1240 /// UsualArithmeticConversions - Performs various conversions that are common to 1241 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1242 /// routine returns the first non-arithmetic type found. The client is 1243 /// responsible for emitting appropriate error diagnostics. 1244 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1245 bool IsCompAssign) { 1246 if (!IsCompAssign) { 1247 LHS = UsualUnaryConversions(LHS.get()); 1248 if (LHS.isInvalid()) 1249 return QualType(); 1250 } 1251 1252 RHS = UsualUnaryConversions(RHS.get()); 1253 if (RHS.isInvalid()) 1254 return QualType(); 1255 1256 // For conversion purposes, we ignore any qualifiers. 1257 // For example, "const float" and "float" are equivalent. 1258 QualType LHSType = 1259 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1260 QualType RHSType = 1261 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1262 1263 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1264 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1265 LHSType = AtomicLHS->getValueType(); 1266 1267 // If both types are identical, no conversion is needed. 1268 if (LHSType == RHSType) 1269 return LHSType; 1270 1271 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1272 // The caller can deal with this (e.g. pointer + int). 1273 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1274 return QualType(); 1275 1276 // Apply unary and bitfield promotions to the LHS's type. 1277 QualType LHSUnpromotedType = LHSType; 1278 if (LHSType->isPromotableIntegerType()) 1279 LHSType = Context.getPromotedIntegerType(LHSType); 1280 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1281 if (!LHSBitfieldPromoteTy.isNull()) 1282 LHSType = LHSBitfieldPromoteTy; 1283 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1284 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1285 1286 // If both types are identical, no conversion is needed. 1287 if (LHSType == RHSType) 1288 return LHSType; 1289 1290 // At this point, we have two different arithmetic types. 1291 1292 // Diagnose attempts to convert between __float128 and long double where 1293 // such conversions currently can't be handled. 1294 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1295 return QualType(); 1296 1297 // Handle complex types first (C99 6.3.1.8p1). 1298 if (LHSType->isComplexType() || RHSType->isComplexType()) 1299 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1300 IsCompAssign); 1301 1302 // Now handle "real" floating types (i.e. float, double, long double). 1303 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1304 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1305 IsCompAssign); 1306 1307 // Handle GCC complex int extension. 1308 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1309 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1310 IsCompAssign); 1311 1312 // Finally, we have two differing integer types. 1313 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1314 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1315 } 1316 1317 1318 //===----------------------------------------------------------------------===// 1319 // Semantic Analysis for various Expression Types 1320 //===----------------------------------------------------------------------===// 1321 1322 1323 ExprResult 1324 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1325 SourceLocation DefaultLoc, 1326 SourceLocation RParenLoc, 1327 Expr *ControllingExpr, 1328 ArrayRef<ParsedType> ArgTypes, 1329 ArrayRef<Expr *> ArgExprs) { 1330 unsigned NumAssocs = ArgTypes.size(); 1331 assert(NumAssocs == ArgExprs.size()); 1332 1333 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1334 for (unsigned i = 0; i < NumAssocs; ++i) { 1335 if (ArgTypes[i]) 1336 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1337 else 1338 Types[i] = nullptr; 1339 } 1340 1341 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1342 ControllingExpr, 1343 llvm::makeArrayRef(Types, NumAssocs), 1344 ArgExprs); 1345 delete [] Types; 1346 return ER; 1347 } 1348 1349 ExprResult 1350 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1351 SourceLocation DefaultLoc, 1352 SourceLocation RParenLoc, 1353 Expr *ControllingExpr, 1354 ArrayRef<TypeSourceInfo *> Types, 1355 ArrayRef<Expr *> Exprs) { 1356 unsigned NumAssocs = Types.size(); 1357 assert(NumAssocs == Exprs.size()); 1358 1359 // Decay and strip qualifiers for the controlling expression type, and handle 1360 // placeholder type replacement. See committee discussion from WG14 DR423. 1361 { 1362 EnterExpressionEvaluationContext Unevaluated( 1363 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1364 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1365 if (R.isInvalid()) 1366 return ExprError(); 1367 ControllingExpr = R.get(); 1368 } 1369 1370 // The controlling expression is an unevaluated operand, so side effects are 1371 // likely unintended. 1372 if (!inTemplateInstantiation() && 1373 ControllingExpr->HasSideEffects(Context, false)) 1374 Diag(ControllingExpr->getExprLoc(), 1375 diag::warn_side_effects_unevaluated_context); 1376 1377 bool TypeErrorFound = false, 1378 IsResultDependent = ControllingExpr->isTypeDependent(), 1379 ContainsUnexpandedParameterPack 1380 = ControllingExpr->containsUnexpandedParameterPack(); 1381 1382 for (unsigned i = 0; i < NumAssocs; ++i) { 1383 if (Exprs[i]->containsUnexpandedParameterPack()) 1384 ContainsUnexpandedParameterPack = true; 1385 1386 if (Types[i]) { 1387 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1388 ContainsUnexpandedParameterPack = true; 1389 1390 if (Types[i]->getType()->isDependentType()) { 1391 IsResultDependent = true; 1392 } else { 1393 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1394 // complete object type other than a variably modified type." 1395 unsigned D = 0; 1396 if (Types[i]->getType()->isIncompleteType()) 1397 D = diag::err_assoc_type_incomplete; 1398 else if (!Types[i]->getType()->isObjectType()) 1399 D = diag::err_assoc_type_nonobject; 1400 else if (Types[i]->getType()->isVariablyModifiedType()) 1401 D = diag::err_assoc_type_variably_modified; 1402 1403 if (D != 0) { 1404 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1405 << Types[i]->getTypeLoc().getSourceRange() 1406 << Types[i]->getType(); 1407 TypeErrorFound = true; 1408 } 1409 1410 // C11 6.5.1.1p2 "No two generic associations in the same generic 1411 // selection shall specify compatible types." 1412 for (unsigned j = i+1; j < NumAssocs; ++j) 1413 if (Types[j] && !Types[j]->getType()->isDependentType() && 1414 Context.typesAreCompatible(Types[i]->getType(), 1415 Types[j]->getType())) { 1416 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1417 diag::err_assoc_compatible_types) 1418 << Types[j]->getTypeLoc().getSourceRange() 1419 << Types[j]->getType() 1420 << Types[i]->getType(); 1421 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1422 diag::note_compat_assoc) 1423 << Types[i]->getTypeLoc().getSourceRange() 1424 << Types[i]->getType(); 1425 TypeErrorFound = true; 1426 } 1427 } 1428 } 1429 } 1430 if (TypeErrorFound) 1431 return ExprError(); 1432 1433 // If we determined that the generic selection is result-dependent, don't 1434 // try to compute the result expression. 1435 if (IsResultDependent) 1436 return new (Context) GenericSelectionExpr( 1437 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1438 ContainsUnexpandedParameterPack); 1439 1440 SmallVector<unsigned, 1> CompatIndices; 1441 unsigned DefaultIndex = -1U; 1442 for (unsigned i = 0; i < NumAssocs; ++i) { 1443 if (!Types[i]) 1444 DefaultIndex = i; 1445 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1446 Types[i]->getType())) 1447 CompatIndices.push_back(i); 1448 } 1449 1450 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1451 // type compatible with at most one of the types named in its generic 1452 // association list." 1453 if (CompatIndices.size() > 1) { 1454 // We strip parens here because the controlling expression is typically 1455 // parenthesized in macro definitions. 1456 ControllingExpr = ControllingExpr->IgnoreParens(); 1457 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1458 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1459 << (unsigned)CompatIndices.size(); 1460 for (unsigned I : CompatIndices) { 1461 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1462 diag::note_compat_assoc) 1463 << Types[I]->getTypeLoc().getSourceRange() 1464 << Types[I]->getType(); 1465 } 1466 return ExprError(); 1467 } 1468 1469 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1470 // its controlling expression shall have type compatible with exactly one of 1471 // the types named in its generic association list." 1472 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1473 // We strip parens here because the controlling expression is typically 1474 // parenthesized in macro definitions. 1475 ControllingExpr = ControllingExpr->IgnoreParens(); 1476 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1477 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1478 return ExprError(); 1479 } 1480 1481 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1482 // type name that is compatible with the type of the controlling expression, 1483 // then the result expression of the generic selection is the expression 1484 // in that generic association. Otherwise, the result expression of the 1485 // generic selection is the expression in the default generic association." 1486 unsigned ResultIndex = 1487 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1488 1489 return new (Context) GenericSelectionExpr( 1490 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1491 ContainsUnexpandedParameterPack, ResultIndex); 1492 } 1493 1494 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1495 /// location of the token and the offset of the ud-suffix within it. 1496 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1497 unsigned Offset) { 1498 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1499 S.getLangOpts()); 1500 } 1501 1502 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1503 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1504 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1505 IdentifierInfo *UDSuffix, 1506 SourceLocation UDSuffixLoc, 1507 ArrayRef<Expr*> Args, 1508 SourceLocation LitEndLoc) { 1509 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1510 1511 QualType ArgTy[2]; 1512 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1513 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1514 if (ArgTy[ArgIdx]->isArrayType()) 1515 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1516 } 1517 1518 DeclarationName OpName = 1519 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1520 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1521 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1522 1523 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1524 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1525 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1526 /*AllowStringTemplate*/ false, 1527 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1528 return ExprError(); 1529 1530 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1531 } 1532 1533 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1534 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1535 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1536 /// multiple tokens. However, the common case is that StringToks points to one 1537 /// string. 1538 /// 1539 ExprResult 1540 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1541 assert(!StringToks.empty() && "Must have at least one string!"); 1542 1543 StringLiteralParser Literal(StringToks, PP); 1544 if (Literal.hadError) 1545 return ExprError(); 1546 1547 SmallVector<SourceLocation, 4> StringTokLocs; 1548 for (const Token &Tok : StringToks) 1549 StringTokLocs.push_back(Tok.getLocation()); 1550 1551 QualType CharTy = Context.CharTy; 1552 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1553 if (Literal.isWide()) { 1554 CharTy = Context.getWideCharType(); 1555 Kind = StringLiteral::Wide; 1556 } else if (Literal.isUTF8()) { 1557 if (getLangOpts().Char8) 1558 CharTy = Context.Char8Ty; 1559 Kind = StringLiteral::UTF8; 1560 } else if (Literal.isUTF16()) { 1561 CharTy = Context.Char16Ty; 1562 Kind = StringLiteral::UTF16; 1563 } else if (Literal.isUTF32()) { 1564 CharTy = Context.Char32Ty; 1565 Kind = StringLiteral::UTF32; 1566 } else if (Literal.isPascal()) { 1567 CharTy = Context.UnsignedCharTy; 1568 } 1569 1570 // Warn on initializing an array of char from a u8 string literal; this 1571 // becomes ill-formed in C++2a. 1572 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1573 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1574 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1575 1576 // Create removals for all 'u8' prefixes in the string literal(s). This 1577 // ensures C++2a compatibility (but may change the program behavior when 1578 // built by non-Clang compilers for which the execution character set is 1579 // not always UTF-8). 1580 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1581 SourceLocation RemovalDiagLoc; 1582 for (const Token &Tok : StringToks) { 1583 if (Tok.getKind() == tok::utf8_string_literal) { 1584 if (RemovalDiagLoc.isInvalid()) 1585 RemovalDiagLoc = Tok.getLocation(); 1586 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1587 Tok.getLocation(), 1588 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1589 getSourceManager(), getLangOpts()))); 1590 } 1591 } 1592 Diag(RemovalDiagLoc, RemovalDiag); 1593 } 1594 1595 1596 QualType CharTyConst = CharTy; 1597 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1598 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1599 CharTyConst.addConst(); 1600 1601 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1602 1603 // Get an array type for the string, according to C99 6.4.5. This includes 1604 // the nul terminator character as well as the string length for pascal 1605 // strings. 1606 QualType StrTy = Context.getConstantArrayType( 1607 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1608 ArrayType::Normal, 0); 1609 1610 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1611 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1612 Kind, Literal.Pascal, StrTy, 1613 &StringTokLocs[0], 1614 StringTokLocs.size()); 1615 if (Literal.getUDSuffix().empty()) 1616 return Lit; 1617 1618 // We're building a user-defined literal. 1619 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1620 SourceLocation UDSuffixLoc = 1621 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1622 Literal.getUDSuffixOffset()); 1623 1624 // Make sure we're allowed user-defined literals here. 1625 if (!UDLScope) 1626 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1627 1628 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1629 // operator "" X (str, len) 1630 QualType SizeType = Context.getSizeType(); 1631 1632 DeclarationName OpName = 1633 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1634 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1635 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1636 1637 QualType ArgTy[] = { 1638 Context.getArrayDecayedType(StrTy), SizeType 1639 }; 1640 1641 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1642 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1643 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1644 /*AllowStringTemplate*/ true, 1645 /*DiagnoseMissing*/ true)) { 1646 1647 case LOLR_Cooked: { 1648 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1649 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1650 StringTokLocs[0]); 1651 Expr *Args[] = { Lit, LenArg }; 1652 1653 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1654 } 1655 1656 case LOLR_StringTemplate: { 1657 TemplateArgumentListInfo ExplicitArgs; 1658 1659 unsigned CharBits = Context.getIntWidth(CharTy); 1660 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1661 llvm::APSInt Value(CharBits, CharIsUnsigned); 1662 1663 TemplateArgument TypeArg(CharTy); 1664 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1665 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1666 1667 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1668 Value = Lit->getCodeUnit(I); 1669 TemplateArgument Arg(Context, Value, CharTy); 1670 TemplateArgumentLocInfo ArgInfo; 1671 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1672 } 1673 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1674 &ExplicitArgs); 1675 } 1676 case LOLR_Raw: 1677 case LOLR_Template: 1678 case LOLR_ErrorNoDiagnostic: 1679 llvm_unreachable("unexpected literal operator lookup result"); 1680 case LOLR_Error: 1681 return ExprError(); 1682 } 1683 llvm_unreachable("unexpected literal operator lookup result"); 1684 } 1685 1686 ExprResult 1687 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1688 SourceLocation Loc, 1689 const CXXScopeSpec *SS) { 1690 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1691 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1692 } 1693 1694 /// BuildDeclRefExpr - Build an expression that references a 1695 /// declaration that does not require a closure capture. 1696 ExprResult 1697 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1698 const DeclarationNameInfo &NameInfo, 1699 const CXXScopeSpec *SS, NamedDecl *FoundD, 1700 const TemplateArgumentListInfo *TemplateArgs) { 1701 bool RefersToCapturedVariable = 1702 isa<VarDecl>(D) && 1703 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1704 1705 DeclRefExpr *E; 1706 if (isa<VarTemplateSpecializationDecl>(D)) { 1707 VarTemplateSpecializationDecl *VarSpec = 1708 cast<VarTemplateSpecializationDecl>(D); 1709 1710 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1711 : NestedNameSpecifierLoc(), 1712 VarSpec->getTemplateKeywordLoc(), D, 1713 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1714 FoundD, TemplateArgs); 1715 } else { 1716 assert(!TemplateArgs && "No template arguments for non-variable" 1717 " template specialization references"); 1718 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1719 : NestedNameSpecifierLoc(), 1720 SourceLocation(), D, RefersToCapturedVariable, 1721 NameInfo, Ty, VK, FoundD); 1722 } 1723 1724 MarkDeclRefReferenced(E); 1725 1726 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1727 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1728 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1729 getCurFunction()->recordUseOfWeak(E); 1730 1731 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1732 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1733 FD = IFD->getAnonField(); 1734 if (FD) { 1735 UnusedPrivateFields.remove(FD); 1736 // Just in case we're building an illegal pointer-to-member. 1737 if (FD->isBitField()) 1738 E->setObjectKind(OK_BitField); 1739 } 1740 1741 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1742 // designates a bit-field. 1743 if (auto *BD = dyn_cast<BindingDecl>(D)) 1744 if (auto *BE = BD->getBinding()) 1745 E->setObjectKind(BE->getObjectKind()); 1746 1747 return E; 1748 } 1749 1750 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1751 /// possibly a list of template arguments. 1752 /// 1753 /// If this produces template arguments, it is permitted to call 1754 /// DecomposeTemplateName. 1755 /// 1756 /// This actually loses a lot of source location information for 1757 /// non-standard name kinds; we should consider preserving that in 1758 /// some way. 1759 void 1760 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1761 TemplateArgumentListInfo &Buffer, 1762 DeclarationNameInfo &NameInfo, 1763 const TemplateArgumentListInfo *&TemplateArgs) { 1764 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1765 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1766 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1767 1768 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1769 Id.TemplateId->NumArgs); 1770 translateTemplateArguments(TemplateArgsPtr, Buffer); 1771 1772 TemplateName TName = Id.TemplateId->Template.get(); 1773 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1774 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1775 TemplateArgs = &Buffer; 1776 } else { 1777 NameInfo = GetNameFromUnqualifiedId(Id); 1778 TemplateArgs = nullptr; 1779 } 1780 } 1781 1782 static void emitEmptyLookupTypoDiagnostic( 1783 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1784 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1785 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1786 DeclContext *Ctx = 1787 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1788 if (!TC) { 1789 // Emit a special diagnostic for failed member lookups. 1790 // FIXME: computing the declaration context might fail here (?) 1791 if (Ctx) 1792 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1793 << SS.getRange(); 1794 else 1795 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1796 return; 1797 } 1798 1799 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1800 bool DroppedSpecifier = 1801 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1802 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1803 ? diag::note_implicit_param_decl 1804 : diag::note_previous_decl; 1805 if (!Ctx) 1806 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1807 SemaRef.PDiag(NoteID)); 1808 else 1809 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1810 << Typo << Ctx << DroppedSpecifier 1811 << SS.getRange(), 1812 SemaRef.PDiag(NoteID)); 1813 } 1814 1815 /// Diagnose an empty lookup. 1816 /// 1817 /// \return false if new lookup candidates were found 1818 bool 1819 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1820 std::unique_ptr<CorrectionCandidateCallback> CCC, 1821 TemplateArgumentListInfo *ExplicitTemplateArgs, 1822 ArrayRef<Expr *> Args, TypoExpr **Out) { 1823 DeclarationName Name = R.getLookupName(); 1824 1825 unsigned diagnostic = diag::err_undeclared_var_use; 1826 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1827 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1828 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1829 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1830 diagnostic = diag::err_undeclared_use; 1831 diagnostic_suggest = diag::err_undeclared_use_suggest; 1832 } 1833 1834 // If the original lookup was an unqualified lookup, fake an 1835 // unqualified lookup. This is useful when (for example) the 1836 // original lookup would not have found something because it was a 1837 // dependent name. 1838 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1839 while (DC) { 1840 if (isa<CXXRecordDecl>(DC)) { 1841 LookupQualifiedName(R, DC); 1842 1843 if (!R.empty()) { 1844 // Don't give errors about ambiguities in this lookup. 1845 R.suppressDiagnostics(); 1846 1847 // During a default argument instantiation the CurContext points 1848 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1849 // function parameter list, hence add an explicit check. 1850 bool isDefaultArgument = 1851 !CodeSynthesisContexts.empty() && 1852 CodeSynthesisContexts.back().Kind == 1853 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1854 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1855 bool isInstance = CurMethod && 1856 CurMethod->isInstance() && 1857 DC == CurMethod->getParent() && !isDefaultArgument; 1858 1859 // Give a code modification hint to insert 'this->'. 1860 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1861 // Actually quite difficult! 1862 if (getLangOpts().MSVCCompat) 1863 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1864 if (isInstance) { 1865 Diag(R.getNameLoc(), diagnostic) << Name 1866 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1867 CheckCXXThisCapture(R.getNameLoc()); 1868 } else { 1869 Diag(R.getNameLoc(), diagnostic) << Name; 1870 } 1871 1872 // Do we really want to note all of these? 1873 for (NamedDecl *D : R) 1874 Diag(D->getLocation(), diag::note_dependent_var_use); 1875 1876 // Return true if we are inside a default argument instantiation 1877 // and the found name refers to an instance member function, otherwise 1878 // the function calling DiagnoseEmptyLookup will try to create an 1879 // implicit member call and this is wrong for default argument. 1880 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1881 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1882 return true; 1883 } 1884 1885 // Tell the callee to try to recover. 1886 return false; 1887 } 1888 1889 R.clear(); 1890 } 1891 1892 // In Microsoft mode, if we are performing lookup from within a friend 1893 // function definition declared at class scope then we must set 1894 // DC to the lexical parent to be able to search into the parent 1895 // class. 1896 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1897 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1898 DC->getLexicalParent()->isRecord()) 1899 DC = DC->getLexicalParent(); 1900 else 1901 DC = DC->getParent(); 1902 } 1903 1904 // We didn't find anything, so try to correct for a typo. 1905 TypoCorrection Corrected; 1906 if (S && Out) { 1907 SourceLocation TypoLoc = R.getNameLoc(); 1908 assert(!ExplicitTemplateArgs && 1909 "Diagnosing an empty lookup with explicit template args!"); 1910 *Out = CorrectTypoDelayed( 1911 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1912 [=](const TypoCorrection &TC) { 1913 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1914 diagnostic, diagnostic_suggest); 1915 }, 1916 nullptr, CTK_ErrorRecovery); 1917 if (*Out) 1918 return true; 1919 } else if (S && (Corrected = 1920 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1921 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1922 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1923 bool DroppedSpecifier = 1924 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1925 R.setLookupName(Corrected.getCorrection()); 1926 1927 bool AcceptableWithRecovery = false; 1928 bool AcceptableWithoutRecovery = false; 1929 NamedDecl *ND = Corrected.getFoundDecl(); 1930 if (ND) { 1931 if (Corrected.isOverloaded()) { 1932 OverloadCandidateSet OCS(R.getNameLoc(), 1933 OverloadCandidateSet::CSK_Normal); 1934 OverloadCandidateSet::iterator Best; 1935 for (NamedDecl *CD : Corrected) { 1936 if (FunctionTemplateDecl *FTD = 1937 dyn_cast<FunctionTemplateDecl>(CD)) 1938 AddTemplateOverloadCandidate( 1939 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1940 Args, OCS); 1941 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1942 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1943 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1944 Args, OCS); 1945 } 1946 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1947 case OR_Success: 1948 ND = Best->FoundDecl; 1949 Corrected.setCorrectionDecl(ND); 1950 break; 1951 default: 1952 // FIXME: Arbitrarily pick the first declaration for the note. 1953 Corrected.setCorrectionDecl(ND); 1954 break; 1955 } 1956 } 1957 R.addDecl(ND); 1958 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1959 CXXRecordDecl *Record = nullptr; 1960 if (Corrected.getCorrectionSpecifier()) { 1961 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1962 Record = Ty->getAsCXXRecordDecl(); 1963 } 1964 if (!Record) 1965 Record = cast<CXXRecordDecl>( 1966 ND->getDeclContext()->getRedeclContext()); 1967 R.setNamingClass(Record); 1968 } 1969 1970 auto *UnderlyingND = ND->getUnderlyingDecl(); 1971 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1972 isa<FunctionTemplateDecl>(UnderlyingND); 1973 // FIXME: If we ended up with a typo for a type name or 1974 // Objective-C class name, we're in trouble because the parser 1975 // is in the wrong place to recover. Suggest the typo 1976 // correction, but don't make it a fix-it since we're not going 1977 // to recover well anyway. 1978 AcceptableWithoutRecovery = 1979 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1980 } else { 1981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1982 // because we aren't able to recover. 1983 AcceptableWithoutRecovery = true; 1984 } 1985 1986 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1987 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1988 ? diag::note_implicit_param_decl 1989 : diag::note_previous_decl; 1990 if (SS.isEmpty()) 1991 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1992 PDiag(NoteID), AcceptableWithRecovery); 1993 else 1994 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1995 << Name << computeDeclContext(SS, false) 1996 << DroppedSpecifier << SS.getRange(), 1997 PDiag(NoteID), AcceptableWithRecovery); 1998 1999 // Tell the callee whether to try to recover. 2000 return !AcceptableWithRecovery; 2001 } 2002 } 2003 R.clear(); 2004 2005 // Emit a special diagnostic for failed member lookups. 2006 // FIXME: computing the declaration context might fail here (?) 2007 if (!SS.isEmpty()) { 2008 Diag(R.getNameLoc(), diag::err_no_member) 2009 << Name << computeDeclContext(SS, false) 2010 << SS.getRange(); 2011 return true; 2012 } 2013 2014 // Give up, we can't recover. 2015 Diag(R.getNameLoc(), diagnostic) << Name; 2016 return true; 2017 } 2018 2019 /// In Microsoft mode, if we are inside a template class whose parent class has 2020 /// dependent base classes, and we can't resolve an unqualified identifier, then 2021 /// assume the identifier is a member of a dependent base class. We can only 2022 /// recover successfully in static methods, instance methods, and other contexts 2023 /// where 'this' is available. This doesn't precisely match MSVC's 2024 /// instantiation model, but it's close enough. 2025 static Expr * 2026 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2027 DeclarationNameInfo &NameInfo, 2028 SourceLocation TemplateKWLoc, 2029 const TemplateArgumentListInfo *TemplateArgs) { 2030 // Only try to recover from lookup into dependent bases in static methods or 2031 // contexts where 'this' is available. 2032 QualType ThisType = S.getCurrentThisType(); 2033 const CXXRecordDecl *RD = nullptr; 2034 if (!ThisType.isNull()) 2035 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2036 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2037 RD = MD->getParent(); 2038 if (!RD || !RD->hasAnyDependentBases()) 2039 return nullptr; 2040 2041 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2042 // is available, suggest inserting 'this->' as a fixit. 2043 SourceLocation Loc = NameInfo.getLoc(); 2044 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2045 DB << NameInfo.getName() << RD; 2046 2047 if (!ThisType.isNull()) { 2048 DB << FixItHint::CreateInsertion(Loc, "this->"); 2049 return CXXDependentScopeMemberExpr::Create( 2050 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2051 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2052 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2053 } 2054 2055 // Synthesize a fake NNS that points to the derived class. This will 2056 // perform name lookup during template instantiation. 2057 CXXScopeSpec SS; 2058 auto *NNS = 2059 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2060 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2061 return DependentScopeDeclRefExpr::Create( 2062 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2063 TemplateArgs); 2064 } 2065 2066 ExprResult 2067 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2068 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2069 bool HasTrailingLParen, bool IsAddressOfOperand, 2070 std::unique_ptr<CorrectionCandidateCallback> CCC, 2071 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2072 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2073 "cannot be direct & operand and have a trailing lparen"); 2074 if (SS.isInvalid()) 2075 return ExprError(); 2076 2077 TemplateArgumentListInfo TemplateArgsBuffer; 2078 2079 // Decompose the UnqualifiedId into the following data. 2080 DeclarationNameInfo NameInfo; 2081 const TemplateArgumentListInfo *TemplateArgs; 2082 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2083 2084 DeclarationName Name = NameInfo.getName(); 2085 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2086 SourceLocation NameLoc = NameInfo.getLoc(); 2087 2088 if (II && II->isEditorPlaceholder()) { 2089 // FIXME: When typed placeholders are supported we can create a typed 2090 // placeholder expression node. 2091 return ExprError(); 2092 } 2093 2094 // C++ [temp.dep.expr]p3: 2095 // An id-expression is type-dependent if it contains: 2096 // -- an identifier that was declared with a dependent type, 2097 // (note: handled after lookup) 2098 // -- a template-id that is dependent, 2099 // (note: handled in BuildTemplateIdExpr) 2100 // -- a conversion-function-id that specifies a dependent type, 2101 // -- a nested-name-specifier that contains a class-name that 2102 // names a dependent type. 2103 // Determine whether this is a member of an unknown specialization; 2104 // we need to handle these differently. 2105 bool DependentID = false; 2106 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2107 Name.getCXXNameType()->isDependentType()) { 2108 DependentID = true; 2109 } else if (SS.isSet()) { 2110 if (DeclContext *DC = computeDeclContext(SS, false)) { 2111 if (RequireCompleteDeclContext(SS, DC)) 2112 return ExprError(); 2113 } else { 2114 DependentID = true; 2115 } 2116 } 2117 2118 if (DependentID) 2119 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2120 IsAddressOfOperand, TemplateArgs); 2121 2122 // Perform the required lookup. 2123 LookupResult R(*this, NameInfo, 2124 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2125 ? LookupObjCImplicitSelfParam 2126 : LookupOrdinaryName); 2127 if (TemplateKWLoc.isValid() || TemplateArgs) { 2128 // Lookup the template name again to correctly establish the context in 2129 // which it was found. This is really unfortunate as we already did the 2130 // lookup to determine that it was a template name in the first place. If 2131 // this becomes a performance hit, we can work harder to preserve those 2132 // results until we get here but it's likely not worth it. 2133 bool MemberOfUnknownSpecialization; 2134 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2135 MemberOfUnknownSpecialization, TemplateKWLoc)) 2136 return ExprError(); 2137 2138 if (MemberOfUnknownSpecialization || 2139 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2140 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2141 IsAddressOfOperand, TemplateArgs); 2142 } else { 2143 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2144 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2145 2146 // If the result might be in a dependent base class, this is a dependent 2147 // id-expression. 2148 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2149 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2150 IsAddressOfOperand, TemplateArgs); 2151 2152 // If this reference is in an Objective-C method, then we need to do 2153 // some special Objective-C lookup, too. 2154 if (IvarLookupFollowUp) { 2155 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2156 if (E.isInvalid()) 2157 return ExprError(); 2158 2159 if (Expr *Ex = E.getAs<Expr>()) 2160 return Ex; 2161 } 2162 } 2163 2164 if (R.isAmbiguous()) 2165 return ExprError(); 2166 2167 // This could be an implicitly declared function reference (legal in C90, 2168 // extension in C99, forbidden in C++). 2169 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2170 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2171 if (D) R.addDecl(D); 2172 } 2173 2174 // Determine whether this name might be a candidate for 2175 // argument-dependent lookup. 2176 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2177 2178 if (R.empty() && !ADL) { 2179 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2180 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2181 TemplateKWLoc, TemplateArgs)) 2182 return E; 2183 } 2184 2185 // Don't diagnose an empty lookup for inline assembly. 2186 if (IsInlineAsmIdentifier) 2187 return ExprError(); 2188 2189 // If this name wasn't predeclared and if this is not a function 2190 // call, diagnose the problem. 2191 TypoExpr *TE = nullptr; 2192 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2193 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2194 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2195 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2196 "Typo correction callback misconfigured"); 2197 if (CCC) { 2198 // Make sure the callback knows what the typo being diagnosed is. 2199 CCC->setTypoName(II); 2200 if (SS.isValid()) 2201 CCC->setTypoNNS(SS.getScopeRep()); 2202 } 2203 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2204 // a template name, but we happen to have always already looked up the name 2205 // before we get here if it must be a template name. 2206 if (DiagnoseEmptyLookup(S, SS, R, 2207 CCC ? std::move(CCC) : std::move(DefaultValidator), 2208 nullptr, None, &TE)) { 2209 if (TE && KeywordReplacement) { 2210 auto &State = getTypoExprState(TE); 2211 auto BestTC = State.Consumer->getNextCorrection(); 2212 if (BestTC.isKeyword()) { 2213 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2214 if (State.DiagHandler) 2215 State.DiagHandler(BestTC); 2216 KeywordReplacement->startToken(); 2217 KeywordReplacement->setKind(II->getTokenID()); 2218 KeywordReplacement->setIdentifierInfo(II); 2219 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2220 // Clean up the state associated with the TypoExpr, since it has 2221 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2222 clearDelayedTypo(TE); 2223 // Signal that a correction to a keyword was performed by returning a 2224 // valid-but-null ExprResult. 2225 return (Expr*)nullptr; 2226 } 2227 State.Consumer->resetCorrectionStream(); 2228 } 2229 return TE ? TE : ExprError(); 2230 } 2231 2232 assert(!R.empty() && 2233 "DiagnoseEmptyLookup returned false but added no results"); 2234 2235 // If we found an Objective-C instance variable, let 2236 // LookupInObjCMethod build the appropriate expression to 2237 // reference the ivar. 2238 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2239 R.clear(); 2240 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2241 // In a hopelessly buggy code, Objective-C instance variable 2242 // lookup fails and no expression will be built to reference it. 2243 if (!E.isInvalid() && !E.get()) 2244 return ExprError(); 2245 return E; 2246 } 2247 } 2248 2249 // This is guaranteed from this point on. 2250 assert(!R.empty() || ADL); 2251 2252 // Check whether this might be a C++ implicit instance member access. 2253 // C++ [class.mfct.non-static]p3: 2254 // When an id-expression that is not part of a class member access 2255 // syntax and not used to form a pointer to member is used in the 2256 // body of a non-static member function of class X, if name lookup 2257 // resolves the name in the id-expression to a non-static non-type 2258 // member of some class C, the id-expression is transformed into a 2259 // class member access expression using (*this) as the 2260 // postfix-expression to the left of the . operator. 2261 // 2262 // But we don't actually need to do this for '&' operands if R 2263 // resolved to a function or overloaded function set, because the 2264 // expression is ill-formed if it actually works out to be a 2265 // non-static member function: 2266 // 2267 // C++ [expr.ref]p4: 2268 // Otherwise, if E1.E2 refers to a non-static member function. . . 2269 // [t]he expression can be used only as the left-hand operand of a 2270 // member function call. 2271 // 2272 // There are other safeguards against such uses, but it's important 2273 // to get this right here so that we don't end up making a 2274 // spuriously dependent expression if we're inside a dependent 2275 // instance method. 2276 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2277 bool MightBeImplicitMember; 2278 if (!IsAddressOfOperand) 2279 MightBeImplicitMember = true; 2280 else if (!SS.isEmpty()) 2281 MightBeImplicitMember = false; 2282 else if (R.isOverloadedResult()) 2283 MightBeImplicitMember = false; 2284 else if (R.isUnresolvableResult()) 2285 MightBeImplicitMember = true; 2286 else 2287 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2288 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2289 isa<MSPropertyDecl>(R.getFoundDecl()); 2290 2291 if (MightBeImplicitMember) 2292 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2293 R, TemplateArgs, S); 2294 } 2295 2296 if (TemplateArgs || TemplateKWLoc.isValid()) { 2297 2298 // In C++1y, if this is a variable template id, then check it 2299 // in BuildTemplateIdExpr(). 2300 // The single lookup result must be a variable template declaration. 2301 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2302 Id.TemplateId->Kind == TNK_Var_template) { 2303 assert(R.getAsSingle<VarTemplateDecl>() && 2304 "There should only be one declaration found."); 2305 } 2306 2307 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2308 } 2309 2310 return BuildDeclarationNameExpr(SS, R, ADL); 2311 } 2312 2313 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2314 /// declaration name, generally during template instantiation. 2315 /// There's a large number of things which don't need to be done along 2316 /// this path. 2317 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2318 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2319 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2320 DeclContext *DC = computeDeclContext(SS, false); 2321 if (!DC) 2322 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2323 NameInfo, /*TemplateArgs=*/nullptr); 2324 2325 if (RequireCompleteDeclContext(SS, DC)) 2326 return ExprError(); 2327 2328 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2329 LookupQualifiedName(R, DC); 2330 2331 if (R.isAmbiguous()) 2332 return ExprError(); 2333 2334 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2335 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2336 NameInfo, /*TemplateArgs=*/nullptr); 2337 2338 if (R.empty()) { 2339 Diag(NameInfo.getLoc(), diag::err_no_member) 2340 << NameInfo.getName() << DC << SS.getRange(); 2341 return ExprError(); 2342 } 2343 2344 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2345 // Diagnose a missing typename if this resolved unambiguously to a type in 2346 // a dependent context. If we can recover with a type, downgrade this to 2347 // a warning in Microsoft compatibility mode. 2348 unsigned DiagID = diag::err_typename_missing; 2349 if (RecoveryTSI && getLangOpts().MSVCCompat) 2350 DiagID = diag::ext_typename_missing; 2351 SourceLocation Loc = SS.getBeginLoc(); 2352 auto D = Diag(Loc, DiagID); 2353 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2354 << SourceRange(Loc, NameInfo.getEndLoc()); 2355 2356 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2357 // context. 2358 if (!RecoveryTSI) 2359 return ExprError(); 2360 2361 // Only issue the fixit if we're prepared to recover. 2362 D << FixItHint::CreateInsertion(Loc, "typename "); 2363 2364 // Recover by pretending this was an elaborated type. 2365 QualType Ty = Context.getTypeDeclType(TD); 2366 TypeLocBuilder TLB; 2367 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2368 2369 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2370 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2371 QTL.setElaboratedKeywordLoc(SourceLocation()); 2372 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2373 2374 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2375 2376 return ExprEmpty(); 2377 } 2378 2379 // Defend against this resolving to an implicit member access. We usually 2380 // won't get here if this might be a legitimate a class member (we end up in 2381 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2382 // a pointer-to-member or in an unevaluated context in C++11. 2383 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2384 return BuildPossibleImplicitMemberExpr(SS, 2385 /*TemplateKWLoc=*/SourceLocation(), 2386 R, /*TemplateArgs=*/nullptr, S); 2387 2388 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2389 } 2390 2391 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2392 /// detected that we're currently inside an ObjC method. Perform some 2393 /// additional lookup. 2394 /// 2395 /// Ideally, most of this would be done by lookup, but there's 2396 /// actually quite a lot of extra work involved. 2397 /// 2398 /// Returns a null sentinel to indicate trivial success. 2399 ExprResult 2400 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2401 IdentifierInfo *II, bool AllowBuiltinCreation) { 2402 SourceLocation Loc = Lookup.getNameLoc(); 2403 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2404 2405 // Check for error condition which is already reported. 2406 if (!CurMethod) 2407 return ExprError(); 2408 2409 // There are two cases to handle here. 1) scoped lookup could have failed, 2410 // in which case we should look for an ivar. 2) scoped lookup could have 2411 // found a decl, but that decl is outside the current instance method (i.e. 2412 // a global variable). In these two cases, we do a lookup for an ivar with 2413 // this name, if the lookup sucedes, we replace it our current decl. 2414 2415 // If we're in a class method, we don't normally want to look for 2416 // ivars. But if we don't find anything else, and there's an 2417 // ivar, that's an error. 2418 bool IsClassMethod = CurMethod->isClassMethod(); 2419 2420 bool LookForIvars; 2421 if (Lookup.empty()) 2422 LookForIvars = true; 2423 else if (IsClassMethod) 2424 LookForIvars = false; 2425 else 2426 LookForIvars = (Lookup.isSingleResult() && 2427 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2428 ObjCInterfaceDecl *IFace = nullptr; 2429 if (LookForIvars) { 2430 IFace = CurMethod->getClassInterface(); 2431 ObjCInterfaceDecl *ClassDeclared; 2432 ObjCIvarDecl *IV = nullptr; 2433 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2434 // Diagnose using an ivar in a class method. 2435 if (IsClassMethod) 2436 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2437 << IV->getDeclName()); 2438 2439 // If we're referencing an invalid decl, just return this as a silent 2440 // error node. The error diagnostic was already emitted on the decl. 2441 if (IV->isInvalidDecl()) 2442 return ExprError(); 2443 2444 // Check if referencing a field with __attribute__((deprecated)). 2445 if (DiagnoseUseOfDecl(IV, Loc)) 2446 return ExprError(); 2447 2448 // Diagnose the use of an ivar outside of the declaring class. 2449 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2450 !declaresSameEntity(ClassDeclared, IFace) && 2451 !getLangOpts().DebuggerSupport) 2452 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2453 2454 // FIXME: This should use a new expr for a direct reference, don't 2455 // turn this into Self->ivar, just return a BareIVarExpr or something. 2456 IdentifierInfo &II = Context.Idents.get("self"); 2457 UnqualifiedId SelfName; 2458 SelfName.setIdentifier(&II, SourceLocation()); 2459 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2460 CXXScopeSpec SelfScopeSpec; 2461 SourceLocation TemplateKWLoc; 2462 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2463 SelfName, false, false); 2464 if (SelfExpr.isInvalid()) 2465 return ExprError(); 2466 2467 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2468 if (SelfExpr.isInvalid()) 2469 return ExprError(); 2470 2471 MarkAnyDeclReferenced(Loc, IV, true); 2472 2473 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2474 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2475 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2476 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2477 2478 ObjCIvarRefExpr *Result = new (Context) 2479 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2480 IV->getLocation(), SelfExpr.get(), true, true); 2481 2482 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2483 if (!isUnevaluatedContext() && 2484 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2485 getCurFunction()->recordUseOfWeak(Result); 2486 } 2487 if (getLangOpts().ObjCAutoRefCount) { 2488 if (CurContext->isClosure()) 2489 Diag(Loc, diag::warn_implicitly_retains_self) 2490 << FixItHint::CreateInsertion(Loc, "self->"); 2491 } 2492 2493 return Result; 2494 } 2495 } else if (CurMethod->isInstanceMethod()) { 2496 // We should warn if a local variable hides an ivar. 2497 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2498 ObjCInterfaceDecl *ClassDeclared; 2499 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2500 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2501 declaresSameEntity(IFace, ClassDeclared)) 2502 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2503 } 2504 } 2505 } else if (Lookup.isSingleResult() && 2506 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2507 // If accessing a stand-alone ivar in a class method, this is an error. 2508 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2509 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2510 << IV->getDeclName()); 2511 } 2512 2513 if (Lookup.empty() && II && AllowBuiltinCreation) { 2514 // FIXME. Consolidate this with similar code in LookupName. 2515 if (unsigned BuiltinID = II->getBuiltinID()) { 2516 if (!(getLangOpts().CPlusPlus && 2517 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2518 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2519 S, Lookup.isForRedeclaration(), 2520 Lookup.getNameLoc()); 2521 if (D) Lookup.addDecl(D); 2522 } 2523 } 2524 } 2525 // Sentinel value saying that we didn't do anything special. 2526 return ExprResult((Expr *)nullptr); 2527 } 2528 2529 /// Cast a base object to a member's actual type. 2530 /// 2531 /// Logically this happens in three phases: 2532 /// 2533 /// * First we cast from the base type to the naming class. 2534 /// The naming class is the class into which we were looking 2535 /// when we found the member; it's the qualifier type if a 2536 /// qualifier was provided, and otherwise it's the base type. 2537 /// 2538 /// * Next we cast from the naming class to the declaring class. 2539 /// If the member we found was brought into a class's scope by 2540 /// a using declaration, this is that class; otherwise it's 2541 /// the class declaring the member. 2542 /// 2543 /// * Finally we cast from the declaring class to the "true" 2544 /// declaring class of the member. This conversion does not 2545 /// obey access control. 2546 ExprResult 2547 Sema::PerformObjectMemberConversion(Expr *From, 2548 NestedNameSpecifier *Qualifier, 2549 NamedDecl *FoundDecl, 2550 NamedDecl *Member) { 2551 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2552 if (!RD) 2553 return From; 2554 2555 QualType DestRecordType; 2556 QualType DestType; 2557 QualType FromRecordType; 2558 QualType FromType = From->getType(); 2559 bool PointerConversions = false; 2560 if (isa<FieldDecl>(Member)) { 2561 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2562 2563 if (FromType->getAs<PointerType>()) { 2564 DestType = Context.getPointerType(DestRecordType); 2565 FromRecordType = FromType->getPointeeType(); 2566 PointerConversions = true; 2567 } else { 2568 DestType = DestRecordType; 2569 FromRecordType = FromType; 2570 } 2571 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2572 if (Method->isStatic()) 2573 return From; 2574 2575 DestType = Method->getThisType(); 2576 DestRecordType = DestType->getPointeeType(); 2577 2578 if (FromType->getAs<PointerType>()) { 2579 FromRecordType = FromType->getPointeeType(); 2580 PointerConversions = true; 2581 } else { 2582 FromRecordType = FromType; 2583 DestType = DestRecordType; 2584 } 2585 } else { 2586 // No conversion necessary. 2587 return From; 2588 } 2589 2590 if (DestType->isDependentType() || FromType->isDependentType()) 2591 return From; 2592 2593 // If the unqualified types are the same, no conversion is necessary. 2594 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2595 return From; 2596 2597 SourceRange FromRange = From->getSourceRange(); 2598 SourceLocation FromLoc = FromRange.getBegin(); 2599 2600 ExprValueKind VK = From->getValueKind(); 2601 2602 // C++ [class.member.lookup]p8: 2603 // [...] Ambiguities can often be resolved by qualifying a name with its 2604 // class name. 2605 // 2606 // If the member was a qualified name and the qualified referred to a 2607 // specific base subobject type, we'll cast to that intermediate type 2608 // first and then to the object in which the member is declared. That allows 2609 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2610 // 2611 // class Base { public: int x; }; 2612 // class Derived1 : public Base { }; 2613 // class Derived2 : public Base { }; 2614 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2615 // 2616 // void VeryDerived::f() { 2617 // x = 17; // error: ambiguous base subobjects 2618 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2619 // } 2620 if (Qualifier && Qualifier->getAsType()) { 2621 QualType QType = QualType(Qualifier->getAsType(), 0); 2622 assert(QType->isRecordType() && "lookup done with non-record type"); 2623 2624 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2625 2626 // In C++98, the qualifier type doesn't actually have to be a base 2627 // type of the object type, in which case we just ignore it. 2628 // Otherwise build the appropriate casts. 2629 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2630 CXXCastPath BasePath; 2631 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2632 FromLoc, FromRange, &BasePath)) 2633 return ExprError(); 2634 2635 if (PointerConversions) 2636 QType = Context.getPointerType(QType); 2637 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2638 VK, &BasePath).get(); 2639 2640 FromType = QType; 2641 FromRecordType = QRecordType; 2642 2643 // If the qualifier type was the same as the destination type, 2644 // we're done. 2645 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2646 return From; 2647 } 2648 } 2649 2650 bool IgnoreAccess = false; 2651 2652 // If we actually found the member through a using declaration, cast 2653 // down to the using declaration's type. 2654 // 2655 // Pointer equality is fine here because only one declaration of a 2656 // class ever has member declarations. 2657 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2658 assert(isa<UsingShadowDecl>(FoundDecl)); 2659 QualType URecordType = Context.getTypeDeclType( 2660 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2661 2662 // We only need to do this if the naming-class to declaring-class 2663 // conversion is non-trivial. 2664 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2665 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2666 CXXCastPath BasePath; 2667 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2668 FromLoc, FromRange, &BasePath)) 2669 return ExprError(); 2670 2671 QualType UType = URecordType; 2672 if (PointerConversions) 2673 UType = Context.getPointerType(UType); 2674 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2675 VK, &BasePath).get(); 2676 FromType = UType; 2677 FromRecordType = URecordType; 2678 } 2679 2680 // We don't do access control for the conversion from the 2681 // declaring class to the true declaring class. 2682 IgnoreAccess = true; 2683 } 2684 2685 CXXCastPath BasePath; 2686 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2687 FromLoc, FromRange, &BasePath, 2688 IgnoreAccess)) 2689 return ExprError(); 2690 2691 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2692 VK, &BasePath); 2693 } 2694 2695 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2696 const LookupResult &R, 2697 bool HasTrailingLParen) { 2698 // Only when used directly as the postfix-expression of a call. 2699 if (!HasTrailingLParen) 2700 return false; 2701 2702 // Never if a scope specifier was provided. 2703 if (SS.isSet()) 2704 return false; 2705 2706 // Only in C++ or ObjC++. 2707 if (!getLangOpts().CPlusPlus) 2708 return false; 2709 2710 // Turn off ADL when we find certain kinds of declarations during 2711 // normal lookup: 2712 for (NamedDecl *D : R) { 2713 // C++0x [basic.lookup.argdep]p3: 2714 // -- a declaration of a class member 2715 // Since using decls preserve this property, we check this on the 2716 // original decl. 2717 if (D->isCXXClassMember()) 2718 return false; 2719 2720 // C++0x [basic.lookup.argdep]p3: 2721 // -- a block-scope function declaration that is not a 2722 // using-declaration 2723 // NOTE: we also trigger this for function templates (in fact, we 2724 // don't check the decl type at all, since all other decl types 2725 // turn off ADL anyway). 2726 if (isa<UsingShadowDecl>(D)) 2727 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2728 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2729 return false; 2730 2731 // C++0x [basic.lookup.argdep]p3: 2732 // -- a declaration that is neither a function or a function 2733 // template 2734 // And also for builtin functions. 2735 if (isa<FunctionDecl>(D)) { 2736 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2737 2738 // But also builtin functions. 2739 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2740 return false; 2741 } else if (!isa<FunctionTemplateDecl>(D)) 2742 return false; 2743 } 2744 2745 return true; 2746 } 2747 2748 2749 /// Diagnoses obvious problems with the use of the given declaration 2750 /// as an expression. This is only actually called for lookups that 2751 /// were not overloaded, and it doesn't promise that the declaration 2752 /// will in fact be used. 2753 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2754 if (D->isInvalidDecl()) 2755 return true; 2756 2757 if (isa<TypedefNameDecl>(D)) { 2758 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2759 return true; 2760 } 2761 2762 if (isa<ObjCInterfaceDecl>(D)) { 2763 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2764 return true; 2765 } 2766 2767 if (isa<NamespaceDecl>(D)) { 2768 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2769 return true; 2770 } 2771 2772 return false; 2773 } 2774 2775 // Certain multiversion types should be treated as overloaded even when there is 2776 // only one result. 2777 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2778 assert(R.isSingleResult() && "Expected only a single result"); 2779 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2780 return FD && 2781 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2782 } 2783 2784 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2785 LookupResult &R, bool NeedsADL, 2786 bool AcceptInvalidDecl) { 2787 // If this is a single, fully-resolved result and we don't need ADL, 2788 // just build an ordinary singleton decl ref. 2789 if (!NeedsADL && R.isSingleResult() && 2790 !R.getAsSingle<FunctionTemplateDecl>() && 2791 !ShouldLookupResultBeMultiVersionOverload(R)) 2792 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2793 R.getRepresentativeDecl(), nullptr, 2794 AcceptInvalidDecl); 2795 2796 // We only need to check the declaration if there's exactly one 2797 // result, because in the overloaded case the results can only be 2798 // functions and function templates. 2799 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2800 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2801 return ExprError(); 2802 2803 // Otherwise, just build an unresolved lookup expression. Suppress 2804 // any lookup-related diagnostics; we'll hash these out later, when 2805 // we've picked a target. 2806 R.suppressDiagnostics(); 2807 2808 UnresolvedLookupExpr *ULE 2809 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2810 SS.getWithLocInContext(Context), 2811 R.getLookupNameInfo(), 2812 NeedsADL, R.isOverloadedResult(), 2813 R.begin(), R.end()); 2814 2815 return ULE; 2816 } 2817 2818 static void 2819 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2820 ValueDecl *var, DeclContext *DC); 2821 2822 /// Complete semantic analysis for a reference to the given declaration. 2823 ExprResult Sema::BuildDeclarationNameExpr( 2824 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2825 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2826 bool AcceptInvalidDecl) { 2827 assert(D && "Cannot refer to a NULL declaration"); 2828 assert(!isa<FunctionTemplateDecl>(D) && 2829 "Cannot refer unambiguously to a function template"); 2830 2831 SourceLocation Loc = NameInfo.getLoc(); 2832 if (CheckDeclInExpr(*this, Loc, D)) 2833 return ExprError(); 2834 2835 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2836 // Specifically diagnose references to class templates that are missing 2837 // a template argument list. 2838 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2839 return ExprError(); 2840 } 2841 2842 // Make sure that we're referring to a value. 2843 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2844 if (!VD) { 2845 Diag(Loc, diag::err_ref_non_value) 2846 << D << SS.getRange(); 2847 Diag(D->getLocation(), diag::note_declared_at); 2848 return ExprError(); 2849 } 2850 2851 // Check whether this declaration can be used. Note that we suppress 2852 // this check when we're going to perform argument-dependent lookup 2853 // on this function name, because this might not be the function 2854 // that overload resolution actually selects. 2855 if (DiagnoseUseOfDecl(VD, Loc)) 2856 return ExprError(); 2857 2858 // Only create DeclRefExpr's for valid Decl's. 2859 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2860 return ExprError(); 2861 2862 // Handle members of anonymous structs and unions. If we got here, 2863 // and the reference is to a class member indirect field, then this 2864 // must be the subject of a pointer-to-member expression. 2865 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2866 if (!indirectField->isCXXClassMember()) 2867 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2868 indirectField); 2869 2870 { 2871 QualType type = VD->getType(); 2872 if (type.isNull()) 2873 return ExprError(); 2874 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2875 // C++ [except.spec]p17: 2876 // An exception-specification is considered to be needed when: 2877 // - in an expression, the function is the unique lookup result or 2878 // the selected member of a set of overloaded functions. 2879 ResolveExceptionSpec(Loc, FPT); 2880 type = VD->getType(); 2881 } 2882 ExprValueKind valueKind = VK_RValue; 2883 2884 switch (D->getKind()) { 2885 // Ignore all the non-ValueDecl kinds. 2886 #define ABSTRACT_DECL(kind) 2887 #define VALUE(type, base) 2888 #define DECL(type, base) \ 2889 case Decl::type: 2890 #include "clang/AST/DeclNodes.inc" 2891 llvm_unreachable("invalid value decl kind"); 2892 2893 // These shouldn't make it here. 2894 case Decl::ObjCAtDefsField: 2895 case Decl::ObjCIvar: 2896 llvm_unreachable("forming non-member reference to ivar?"); 2897 2898 // Enum constants are always r-values and never references. 2899 // Unresolved using declarations are dependent. 2900 case Decl::EnumConstant: 2901 case Decl::UnresolvedUsingValue: 2902 case Decl::OMPDeclareReduction: 2903 valueKind = VK_RValue; 2904 break; 2905 2906 // Fields and indirect fields that got here must be for 2907 // pointer-to-member expressions; we just call them l-values for 2908 // internal consistency, because this subexpression doesn't really 2909 // exist in the high-level semantics. 2910 case Decl::Field: 2911 case Decl::IndirectField: 2912 assert(getLangOpts().CPlusPlus && 2913 "building reference to field in C?"); 2914 2915 // These can't have reference type in well-formed programs, but 2916 // for internal consistency we do this anyway. 2917 type = type.getNonReferenceType(); 2918 valueKind = VK_LValue; 2919 break; 2920 2921 // Non-type template parameters are either l-values or r-values 2922 // depending on the type. 2923 case Decl::NonTypeTemplateParm: { 2924 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2925 type = reftype->getPointeeType(); 2926 valueKind = VK_LValue; // even if the parameter is an r-value reference 2927 break; 2928 } 2929 2930 // For non-references, we need to strip qualifiers just in case 2931 // the template parameter was declared as 'const int' or whatever. 2932 valueKind = VK_RValue; 2933 type = type.getUnqualifiedType(); 2934 break; 2935 } 2936 2937 case Decl::Var: 2938 case Decl::VarTemplateSpecialization: 2939 case Decl::VarTemplatePartialSpecialization: 2940 case Decl::Decomposition: 2941 case Decl::OMPCapturedExpr: 2942 // In C, "extern void blah;" is valid and is an r-value. 2943 if (!getLangOpts().CPlusPlus && 2944 !type.hasQualifiers() && 2945 type->isVoidType()) { 2946 valueKind = VK_RValue; 2947 break; 2948 } 2949 LLVM_FALLTHROUGH; 2950 2951 case Decl::ImplicitParam: 2952 case Decl::ParmVar: { 2953 // These are always l-values. 2954 valueKind = VK_LValue; 2955 type = type.getNonReferenceType(); 2956 2957 // FIXME: Does the addition of const really only apply in 2958 // potentially-evaluated contexts? Since the variable isn't actually 2959 // captured in an unevaluated context, it seems that the answer is no. 2960 if (!isUnevaluatedContext()) { 2961 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2962 if (!CapturedType.isNull()) 2963 type = CapturedType; 2964 } 2965 2966 break; 2967 } 2968 2969 case Decl::Binding: { 2970 // These are always lvalues. 2971 valueKind = VK_LValue; 2972 type = type.getNonReferenceType(); 2973 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2974 // decides how that's supposed to work. 2975 auto *BD = cast<BindingDecl>(VD); 2976 if (BD->getDeclContext()->isFunctionOrMethod() && 2977 BD->getDeclContext() != CurContext) 2978 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2979 break; 2980 } 2981 2982 case Decl::Function: { 2983 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2984 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2985 type = Context.BuiltinFnTy; 2986 valueKind = VK_RValue; 2987 break; 2988 } 2989 } 2990 2991 const FunctionType *fty = type->castAs<FunctionType>(); 2992 2993 // If we're referring to a function with an __unknown_anytype 2994 // result type, make the entire expression __unknown_anytype. 2995 if (fty->getReturnType() == Context.UnknownAnyTy) { 2996 type = Context.UnknownAnyTy; 2997 valueKind = VK_RValue; 2998 break; 2999 } 3000 3001 // Functions are l-values in C++. 3002 if (getLangOpts().CPlusPlus) { 3003 valueKind = VK_LValue; 3004 break; 3005 } 3006 3007 // C99 DR 316 says that, if a function type comes from a 3008 // function definition (without a prototype), that type is only 3009 // used for checking compatibility. Therefore, when referencing 3010 // the function, we pretend that we don't have the full function 3011 // type. 3012 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3013 isa<FunctionProtoType>(fty)) 3014 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3015 fty->getExtInfo()); 3016 3017 // Functions are r-values in C. 3018 valueKind = VK_RValue; 3019 break; 3020 } 3021 3022 case Decl::CXXDeductionGuide: 3023 llvm_unreachable("building reference to deduction guide"); 3024 3025 case Decl::MSProperty: 3026 valueKind = VK_LValue; 3027 break; 3028 3029 case Decl::CXXMethod: 3030 // If we're referring to a method with an __unknown_anytype 3031 // result type, make the entire expression __unknown_anytype. 3032 // This should only be possible with a type written directly. 3033 if (const FunctionProtoType *proto 3034 = dyn_cast<FunctionProtoType>(VD->getType())) 3035 if (proto->getReturnType() == Context.UnknownAnyTy) { 3036 type = Context.UnknownAnyTy; 3037 valueKind = VK_RValue; 3038 break; 3039 } 3040 3041 // C++ methods are l-values if static, r-values if non-static. 3042 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3043 valueKind = VK_LValue; 3044 break; 3045 } 3046 LLVM_FALLTHROUGH; 3047 3048 case Decl::CXXConversion: 3049 case Decl::CXXDestructor: 3050 case Decl::CXXConstructor: 3051 valueKind = VK_RValue; 3052 break; 3053 } 3054 3055 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3056 TemplateArgs); 3057 } 3058 } 3059 3060 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3061 SmallString<32> &Target) { 3062 Target.resize(CharByteWidth * (Source.size() + 1)); 3063 char *ResultPtr = &Target[0]; 3064 const llvm::UTF8 *ErrorPtr; 3065 bool success = 3066 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3067 (void)success; 3068 assert(success); 3069 Target.resize(ResultPtr - &Target[0]); 3070 } 3071 3072 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3073 PredefinedExpr::IdentKind IK) { 3074 // Pick the current block, lambda, captured statement or function. 3075 Decl *currentDecl = nullptr; 3076 if (const BlockScopeInfo *BSI = getCurBlock()) 3077 currentDecl = BSI->TheDecl; 3078 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3079 currentDecl = LSI->CallOperator; 3080 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3081 currentDecl = CSI->TheCapturedDecl; 3082 else 3083 currentDecl = getCurFunctionOrMethodDecl(); 3084 3085 if (!currentDecl) { 3086 Diag(Loc, diag::ext_predef_outside_function); 3087 currentDecl = Context.getTranslationUnitDecl(); 3088 } 3089 3090 QualType ResTy; 3091 StringLiteral *SL = nullptr; 3092 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3093 ResTy = Context.DependentTy; 3094 else { 3095 // Pre-defined identifiers are of type char[x], where x is the length of 3096 // the string. 3097 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3098 unsigned Length = Str.length(); 3099 3100 llvm::APInt LengthI(32, Length + 1); 3101 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3102 ResTy = 3103 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3104 SmallString<32> RawChars; 3105 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3106 Str, RawChars); 3107 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3108 /*IndexTypeQuals*/ 0); 3109 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3110 /*Pascal*/ false, ResTy, Loc); 3111 } else { 3112 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3113 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3114 /*IndexTypeQuals*/ 0); 3115 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3116 /*Pascal*/ false, ResTy, Loc); 3117 } 3118 } 3119 3120 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3121 } 3122 3123 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3124 PredefinedExpr::IdentKind IK; 3125 3126 switch (Kind) { 3127 default: llvm_unreachable("Unknown simple primary expr!"); 3128 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3129 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3130 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3131 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3132 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3133 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3134 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3135 } 3136 3137 return BuildPredefinedExpr(Loc, IK); 3138 } 3139 3140 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3141 SmallString<16> CharBuffer; 3142 bool Invalid = false; 3143 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3144 if (Invalid) 3145 return ExprError(); 3146 3147 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3148 PP, Tok.getKind()); 3149 if (Literal.hadError()) 3150 return ExprError(); 3151 3152 QualType Ty; 3153 if (Literal.isWide()) 3154 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3155 else if (Literal.isUTF8() && getLangOpts().Char8) 3156 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3157 else if (Literal.isUTF16()) 3158 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3159 else if (Literal.isUTF32()) 3160 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3161 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3162 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3163 else 3164 Ty = Context.CharTy; // 'x' -> char in C++ 3165 3166 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3167 if (Literal.isWide()) 3168 Kind = CharacterLiteral::Wide; 3169 else if (Literal.isUTF16()) 3170 Kind = CharacterLiteral::UTF16; 3171 else if (Literal.isUTF32()) 3172 Kind = CharacterLiteral::UTF32; 3173 else if (Literal.isUTF8()) 3174 Kind = CharacterLiteral::UTF8; 3175 3176 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3177 Tok.getLocation()); 3178 3179 if (Literal.getUDSuffix().empty()) 3180 return Lit; 3181 3182 // We're building a user-defined literal. 3183 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3184 SourceLocation UDSuffixLoc = 3185 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3186 3187 // Make sure we're allowed user-defined literals here. 3188 if (!UDLScope) 3189 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3190 3191 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3192 // operator "" X (ch) 3193 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3194 Lit, Tok.getLocation()); 3195 } 3196 3197 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3198 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3199 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3200 Context.IntTy, Loc); 3201 } 3202 3203 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3204 QualType Ty, SourceLocation Loc) { 3205 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3206 3207 using llvm::APFloat; 3208 APFloat Val(Format); 3209 3210 APFloat::opStatus result = Literal.GetFloatValue(Val); 3211 3212 // Overflow is always an error, but underflow is only an error if 3213 // we underflowed to zero (APFloat reports denormals as underflow). 3214 if ((result & APFloat::opOverflow) || 3215 ((result & APFloat::opUnderflow) && Val.isZero())) { 3216 unsigned diagnostic; 3217 SmallString<20> buffer; 3218 if (result & APFloat::opOverflow) { 3219 diagnostic = diag::warn_float_overflow; 3220 APFloat::getLargest(Format).toString(buffer); 3221 } else { 3222 diagnostic = diag::warn_float_underflow; 3223 APFloat::getSmallest(Format).toString(buffer); 3224 } 3225 3226 S.Diag(Loc, diagnostic) 3227 << Ty 3228 << StringRef(buffer.data(), buffer.size()); 3229 } 3230 3231 bool isExact = (result == APFloat::opOK); 3232 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3233 } 3234 3235 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3236 assert(E && "Invalid expression"); 3237 3238 if (E->isValueDependent()) 3239 return false; 3240 3241 QualType QT = E->getType(); 3242 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3243 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3244 return true; 3245 } 3246 3247 llvm::APSInt ValueAPS; 3248 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3249 3250 if (R.isInvalid()) 3251 return true; 3252 3253 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3254 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3255 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3256 << ValueAPS.toString(10) << ValueIsPositive; 3257 return true; 3258 } 3259 3260 return false; 3261 } 3262 3263 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3264 // Fast path for a single digit (which is quite common). A single digit 3265 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3266 if (Tok.getLength() == 1) { 3267 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3268 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3269 } 3270 3271 SmallString<128> SpellingBuffer; 3272 // NumericLiteralParser wants to overread by one character. Add padding to 3273 // the buffer in case the token is copied to the buffer. If getSpelling() 3274 // returns a StringRef to the memory buffer, it should have a null char at 3275 // the EOF, so it is also safe. 3276 SpellingBuffer.resize(Tok.getLength() + 1); 3277 3278 // Get the spelling of the token, which eliminates trigraphs, etc. 3279 bool Invalid = false; 3280 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3281 if (Invalid) 3282 return ExprError(); 3283 3284 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3285 if (Literal.hadError) 3286 return ExprError(); 3287 3288 if (Literal.hasUDSuffix()) { 3289 // We're building a user-defined literal. 3290 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3291 SourceLocation UDSuffixLoc = 3292 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3293 3294 // Make sure we're allowed user-defined literals here. 3295 if (!UDLScope) 3296 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3297 3298 QualType CookedTy; 3299 if (Literal.isFloatingLiteral()) { 3300 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3301 // long double, the literal is treated as a call of the form 3302 // operator "" X (f L) 3303 CookedTy = Context.LongDoubleTy; 3304 } else { 3305 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3306 // unsigned long long, the literal is treated as a call of the form 3307 // operator "" X (n ULL) 3308 CookedTy = Context.UnsignedLongLongTy; 3309 } 3310 3311 DeclarationName OpName = 3312 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3313 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3314 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3315 3316 SourceLocation TokLoc = Tok.getLocation(); 3317 3318 // Perform literal operator lookup to determine if we're building a raw 3319 // literal or a cooked one. 3320 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3321 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3322 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3323 /*AllowStringTemplate*/ false, 3324 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3325 case LOLR_ErrorNoDiagnostic: 3326 // Lookup failure for imaginary constants isn't fatal, there's still the 3327 // GNU extension producing _Complex types. 3328 break; 3329 case LOLR_Error: 3330 return ExprError(); 3331 case LOLR_Cooked: { 3332 Expr *Lit; 3333 if (Literal.isFloatingLiteral()) { 3334 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3335 } else { 3336 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3337 if (Literal.GetIntegerValue(ResultVal)) 3338 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3339 << /* Unsigned */ 1; 3340 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3341 Tok.getLocation()); 3342 } 3343 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3344 } 3345 3346 case LOLR_Raw: { 3347 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3348 // literal is treated as a call of the form 3349 // operator "" X ("n") 3350 unsigned Length = Literal.getUDSuffixOffset(); 3351 QualType StrTy = Context.getConstantArrayType( 3352 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3353 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3354 Expr *Lit = StringLiteral::Create( 3355 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3356 /*Pascal*/false, StrTy, &TokLoc, 1); 3357 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3358 } 3359 3360 case LOLR_Template: { 3361 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3362 // template), L is treated as a call fo the form 3363 // operator "" X <'c1', 'c2', ... 'ck'>() 3364 // where n is the source character sequence c1 c2 ... ck. 3365 TemplateArgumentListInfo ExplicitArgs; 3366 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3367 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3368 llvm::APSInt Value(CharBits, CharIsUnsigned); 3369 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3370 Value = TokSpelling[I]; 3371 TemplateArgument Arg(Context, Value, Context.CharTy); 3372 TemplateArgumentLocInfo ArgInfo; 3373 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3374 } 3375 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3376 &ExplicitArgs); 3377 } 3378 case LOLR_StringTemplate: 3379 llvm_unreachable("unexpected literal operator lookup result"); 3380 } 3381 } 3382 3383 Expr *Res; 3384 3385 if (Literal.isFixedPointLiteral()) { 3386 QualType Ty; 3387 3388 if (Literal.isAccum) { 3389 if (Literal.isHalf) { 3390 Ty = Context.ShortAccumTy; 3391 } else if (Literal.isLong) { 3392 Ty = Context.LongAccumTy; 3393 } else { 3394 Ty = Context.AccumTy; 3395 } 3396 } else if (Literal.isFract) { 3397 if (Literal.isHalf) { 3398 Ty = Context.ShortFractTy; 3399 } else if (Literal.isLong) { 3400 Ty = Context.LongFractTy; 3401 } else { 3402 Ty = Context.FractTy; 3403 } 3404 } 3405 3406 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3407 3408 bool isSigned = !Literal.isUnsigned; 3409 unsigned scale = Context.getFixedPointScale(Ty); 3410 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3411 3412 llvm::APInt Val(bit_width, 0, isSigned); 3413 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3414 bool ValIsZero = Val.isNullValue() && !Overflowed; 3415 3416 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3417 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3418 // Clause 6.4.4 - The value of a constant shall be in the range of 3419 // representable values for its type, with exception for constants of a 3420 // fract type with a value of exactly 1; such a constant shall denote 3421 // the maximal value for the type. 3422 --Val; 3423 else if (Val.ugt(MaxVal) || Overflowed) 3424 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3425 3426 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3427 Tok.getLocation(), scale); 3428 } else if (Literal.isFloatingLiteral()) { 3429 QualType Ty; 3430 if (Literal.isHalf){ 3431 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3432 Ty = Context.HalfTy; 3433 else { 3434 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3435 return ExprError(); 3436 } 3437 } else if (Literal.isFloat) 3438 Ty = Context.FloatTy; 3439 else if (Literal.isLong) 3440 Ty = Context.LongDoubleTy; 3441 else if (Literal.isFloat16) 3442 Ty = Context.Float16Ty; 3443 else if (Literal.isFloat128) 3444 Ty = Context.Float128Ty; 3445 else 3446 Ty = Context.DoubleTy; 3447 3448 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3449 3450 if (Ty == Context.DoubleTy) { 3451 if (getLangOpts().SinglePrecisionConstants) { 3452 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3453 if (BTy->getKind() != BuiltinType::Float) { 3454 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3455 } 3456 } else if (getLangOpts().OpenCL && 3457 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3458 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3459 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3460 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3461 } 3462 } 3463 } else if (!Literal.isIntegerLiteral()) { 3464 return ExprError(); 3465 } else { 3466 QualType Ty; 3467 3468 // 'long long' is a C99 or C++11 feature. 3469 if (!getLangOpts().C99 && Literal.isLongLong) { 3470 if (getLangOpts().CPlusPlus) 3471 Diag(Tok.getLocation(), 3472 getLangOpts().CPlusPlus11 ? 3473 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3474 else 3475 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3476 } 3477 3478 // Get the value in the widest-possible width. 3479 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3480 llvm::APInt ResultVal(MaxWidth, 0); 3481 3482 if (Literal.GetIntegerValue(ResultVal)) { 3483 // If this value didn't fit into uintmax_t, error and force to ull. 3484 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3485 << /* Unsigned */ 1; 3486 Ty = Context.UnsignedLongLongTy; 3487 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3488 "long long is not intmax_t?"); 3489 } else { 3490 // If this value fits into a ULL, try to figure out what else it fits into 3491 // according to the rules of C99 6.4.4.1p5. 3492 3493 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3494 // be an unsigned int. 3495 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3496 3497 // Check from smallest to largest, picking the smallest type we can. 3498 unsigned Width = 0; 3499 3500 // Microsoft specific integer suffixes are explicitly sized. 3501 if (Literal.MicrosoftInteger) { 3502 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3503 Width = 8; 3504 Ty = Context.CharTy; 3505 } else { 3506 Width = Literal.MicrosoftInteger; 3507 Ty = Context.getIntTypeForBitwidth(Width, 3508 /*Signed=*/!Literal.isUnsigned); 3509 } 3510 } 3511 3512 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3513 // Are int/unsigned possibilities? 3514 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3515 3516 // Does it fit in a unsigned int? 3517 if (ResultVal.isIntN(IntSize)) { 3518 // Does it fit in a signed int? 3519 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3520 Ty = Context.IntTy; 3521 else if (AllowUnsigned) 3522 Ty = Context.UnsignedIntTy; 3523 Width = IntSize; 3524 } 3525 } 3526 3527 // Are long/unsigned long possibilities? 3528 if (Ty.isNull() && !Literal.isLongLong) { 3529 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3530 3531 // Does it fit in a unsigned long? 3532 if (ResultVal.isIntN(LongSize)) { 3533 // Does it fit in a signed long? 3534 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3535 Ty = Context.LongTy; 3536 else if (AllowUnsigned) 3537 Ty = Context.UnsignedLongTy; 3538 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3539 // is compatible. 3540 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3541 const unsigned LongLongSize = 3542 Context.getTargetInfo().getLongLongWidth(); 3543 Diag(Tok.getLocation(), 3544 getLangOpts().CPlusPlus 3545 ? Literal.isLong 3546 ? diag::warn_old_implicitly_unsigned_long_cxx 3547 : /*C++98 UB*/ diag:: 3548 ext_old_implicitly_unsigned_long_cxx 3549 : diag::warn_old_implicitly_unsigned_long) 3550 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3551 : /*will be ill-formed*/ 1); 3552 Ty = Context.UnsignedLongTy; 3553 } 3554 Width = LongSize; 3555 } 3556 } 3557 3558 // Check long long if needed. 3559 if (Ty.isNull()) { 3560 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3561 3562 // Does it fit in a unsigned long long? 3563 if (ResultVal.isIntN(LongLongSize)) { 3564 // Does it fit in a signed long long? 3565 // To be compatible with MSVC, hex integer literals ending with the 3566 // LL or i64 suffix are always signed in Microsoft mode. 3567 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3568 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3569 Ty = Context.LongLongTy; 3570 else if (AllowUnsigned) 3571 Ty = Context.UnsignedLongLongTy; 3572 Width = LongLongSize; 3573 } 3574 } 3575 3576 // If we still couldn't decide a type, we probably have something that 3577 // does not fit in a signed long long, but has no U suffix. 3578 if (Ty.isNull()) { 3579 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3580 Ty = Context.UnsignedLongLongTy; 3581 Width = Context.getTargetInfo().getLongLongWidth(); 3582 } 3583 3584 if (ResultVal.getBitWidth() != Width) 3585 ResultVal = ResultVal.trunc(Width); 3586 } 3587 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3588 } 3589 3590 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3591 if (Literal.isImaginary) { 3592 Res = new (Context) ImaginaryLiteral(Res, 3593 Context.getComplexType(Res->getType())); 3594 3595 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3596 } 3597 return Res; 3598 } 3599 3600 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3601 assert(E && "ActOnParenExpr() missing expr"); 3602 return new (Context) ParenExpr(L, R, E); 3603 } 3604 3605 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3606 SourceLocation Loc, 3607 SourceRange ArgRange) { 3608 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3609 // scalar or vector data type argument..." 3610 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3611 // type (C99 6.2.5p18) or void. 3612 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3613 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3614 << T << ArgRange; 3615 return true; 3616 } 3617 3618 assert((T->isVoidType() || !T->isIncompleteType()) && 3619 "Scalar types should always be complete"); 3620 return false; 3621 } 3622 3623 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3624 SourceLocation Loc, 3625 SourceRange ArgRange, 3626 UnaryExprOrTypeTrait TraitKind) { 3627 // Invalid types must be hard errors for SFINAE in C++. 3628 if (S.LangOpts.CPlusPlus) 3629 return true; 3630 3631 // C99 6.5.3.4p1: 3632 if (T->isFunctionType() && 3633 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3634 TraitKind == UETT_PreferredAlignOf)) { 3635 // sizeof(function)/alignof(function) is allowed as an extension. 3636 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3637 << TraitKind << ArgRange; 3638 return false; 3639 } 3640 3641 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3642 // this is an error (OpenCL v1.1 s6.3.k) 3643 if (T->isVoidType()) { 3644 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3645 : diag::ext_sizeof_alignof_void_type; 3646 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3647 return false; 3648 } 3649 3650 return true; 3651 } 3652 3653 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3654 SourceLocation Loc, 3655 SourceRange ArgRange, 3656 UnaryExprOrTypeTrait TraitKind) { 3657 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3658 // runtime doesn't allow it. 3659 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3660 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3661 << T << (TraitKind == UETT_SizeOf) 3662 << ArgRange; 3663 return true; 3664 } 3665 3666 return false; 3667 } 3668 3669 /// Check whether E is a pointer from a decayed array type (the decayed 3670 /// pointer type is equal to T) and emit a warning if it is. 3671 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3672 Expr *E) { 3673 // Don't warn if the operation changed the type. 3674 if (T != E->getType()) 3675 return; 3676 3677 // Now look for array decays. 3678 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3679 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3680 return; 3681 3682 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3683 << ICE->getType() 3684 << ICE->getSubExpr()->getType(); 3685 } 3686 3687 /// Check the constraints on expression operands to unary type expression 3688 /// and type traits. 3689 /// 3690 /// Completes any types necessary and validates the constraints on the operand 3691 /// expression. The logic mostly mirrors the type-based overload, but may modify 3692 /// the expression as it completes the type for that expression through template 3693 /// instantiation, etc. 3694 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3695 UnaryExprOrTypeTrait ExprKind) { 3696 QualType ExprTy = E->getType(); 3697 assert(!ExprTy->isReferenceType()); 3698 3699 if (ExprKind == UETT_VecStep) 3700 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3701 E->getSourceRange()); 3702 3703 // Whitelist some types as extensions 3704 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3705 E->getSourceRange(), ExprKind)) 3706 return false; 3707 3708 // 'alignof' applied to an expression only requires the base element type of 3709 // the expression to be complete. 'sizeof' requires the expression's type to 3710 // be complete (and will attempt to complete it if it's an array of unknown 3711 // bound). 3712 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3713 if (RequireCompleteType(E->getExprLoc(), 3714 Context.getBaseElementType(E->getType()), 3715 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3716 E->getSourceRange())) 3717 return true; 3718 } else { 3719 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3720 ExprKind, E->getSourceRange())) 3721 return true; 3722 } 3723 3724 // Completing the expression's type may have changed it. 3725 ExprTy = E->getType(); 3726 assert(!ExprTy->isReferenceType()); 3727 3728 if (ExprTy->isFunctionType()) { 3729 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3730 << ExprKind << E->getSourceRange(); 3731 return true; 3732 } 3733 3734 // The operand for sizeof and alignof is in an unevaluated expression context, 3735 // so side effects could result in unintended consequences. 3736 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3737 ExprKind == UETT_PreferredAlignOf) && 3738 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3739 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3740 3741 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3742 E->getSourceRange(), ExprKind)) 3743 return true; 3744 3745 if (ExprKind == UETT_SizeOf) { 3746 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3747 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3748 QualType OType = PVD->getOriginalType(); 3749 QualType Type = PVD->getType(); 3750 if (Type->isPointerType() && OType->isArrayType()) { 3751 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3752 << Type << OType; 3753 Diag(PVD->getLocation(), diag::note_declared_at); 3754 } 3755 } 3756 } 3757 3758 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3759 // decays into a pointer and returns an unintended result. This is most 3760 // likely a typo for "sizeof(array) op x". 3761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3762 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3763 BO->getLHS()); 3764 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3765 BO->getRHS()); 3766 } 3767 } 3768 3769 return false; 3770 } 3771 3772 /// Check the constraints on operands to unary expression and type 3773 /// traits. 3774 /// 3775 /// This will complete any types necessary, and validate the various constraints 3776 /// on those operands. 3777 /// 3778 /// The UsualUnaryConversions() function is *not* called by this routine. 3779 /// C99 6.3.2.1p[2-4] all state: 3780 /// Except when it is the operand of the sizeof operator ... 3781 /// 3782 /// C++ [expr.sizeof]p4 3783 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3784 /// standard conversions are not applied to the operand of sizeof. 3785 /// 3786 /// This policy is followed for all of the unary trait expressions. 3787 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3788 SourceLocation OpLoc, 3789 SourceRange ExprRange, 3790 UnaryExprOrTypeTrait ExprKind) { 3791 if (ExprType->isDependentType()) 3792 return false; 3793 3794 // C++ [expr.sizeof]p2: 3795 // When applied to a reference or a reference type, the result 3796 // is the size of the referenced type. 3797 // C++11 [expr.alignof]p3: 3798 // When alignof is applied to a reference type, the result 3799 // shall be the alignment of the referenced type. 3800 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3801 ExprType = Ref->getPointeeType(); 3802 3803 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3804 // When alignof or _Alignof is applied to an array type, the result 3805 // is the alignment of the element type. 3806 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3807 ExprKind == UETT_OpenMPRequiredSimdAlign) 3808 ExprType = Context.getBaseElementType(ExprType); 3809 3810 if (ExprKind == UETT_VecStep) 3811 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3812 3813 // Whitelist some types as extensions 3814 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3815 ExprKind)) 3816 return false; 3817 3818 if (RequireCompleteType(OpLoc, ExprType, 3819 diag::err_sizeof_alignof_incomplete_type, 3820 ExprKind, ExprRange)) 3821 return true; 3822 3823 if (ExprType->isFunctionType()) { 3824 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3825 << ExprKind << ExprRange; 3826 return true; 3827 } 3828 3829 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3830 ExprKind)) 3831 return true; 3832 3833 return false; 3834 } 3835 3836 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3837 E = E->IgnoreParens(); 3838 3839 // Cannot know anything else if the expression is dependent. 3840 if (E->isTypeDependent()) 3841 return false; 3842 3843 if (E->getObjectKind() == OK_BitField) { 3844 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3845 << 1 << E->getSourceRange(); 3846 return true; 3847 } 3848 3849 ValueDecl *D = nullptr; 3850 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3851 D = DRE->getDecl(); 3852 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3853 D = ME->getMemberDecl(); 3854 } 3855 3856 // If it's a field, require the containing struct to have a 3857 // complete definition so that we can compute the layout. 3858 // 3859 // This can happen in C++11 onwards, either by naming the member 3860 // in a way that is not transformed into a member access expression 3861 // (in an unevaluated operand, for instance), or by naming the member 3862 // in a trailing-return-type. 3863 // 3864 // For the record, since __alignof__ on expressions is a GCC 3865 // extension, GCC seems to permit this but always gives the 3866 // nonsensical answer 0. 3867 // 3868 // We don't really need the layout here --- we could instead just 3869 // directly check for all the appropriate alignment-lowing 3870 // attributes --- but that would require duplicating a lot of 3871 // logic that just isn't worth duplicating for such a marginal 3872 // use-case. 3873 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3874 // Fast path this check, since we at least know the record has a 3875 // definition if we can find a member of it. 3876 if (!FD->getParent()->isCompleteDefinition()) { 3877 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3878 << E->getSourceRange(); 3879 return true; 3880 } 3881 3882 // Otherwise, if it's a field, and the field doesn't have 3883 // reference type, then it must have a complete type (or be a 3884 // flexible array member, which we explicitly want to 3885 // white-list anyway), which makes the following checks trivial. 3886 if (!FD->getType()->isReferenceType()) 3887 return false; 3888 } 3889 3890 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3891 } 3892 3893 bool Sema::CheckVecStepExpr(Expr *E) { 3894 E = E->IgnoreParens(); 3895 3896 // Cannot know anything else if the expression is dependent. 3897 if (E->isTypeDependent()) 3898 return false; 3899 3900 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3901 } 3902 3903 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3904 CapturingScopeInfo *CSI) { 3905 assert(T->isVariablyModifiedType()); 3906 assert(CSI != nullptr); 3907 3908 // We're going to walk down into the type and look for VLA expressions. 3909 do { 3910 const Type *Ty = T.getTypePtr(); 3911 switch (Ty->getTypeClass()) { 3912 #define TYPE(Class, Base) 3913 #define ABSTRACT_TYPE(Class, Base) 3914 #define NON_CANONICAL_TYPE(Class, Base) 3915 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3916 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3917 #include "clang/AST/TypeNodes.def" 3918 T = QualType(); 3919 break; 3920 // These types are never variably-modified. 3921 case Type::Builtin: 3922 case Type::Complex: 3923 case Type::Vector: 3924 case Type::ExtVector: 3925 case Type::Record: 3926 case Type::Enum: 3927 case Type::Elaborated: 3928 case Type::TemplateSpecialization: 3929 case Type::ObjCObject: 3930 case Type::ObjCInterface: 3931 case Type::ObjCObjectPointer: 3932 case Type::ObjCTypeParam: 3933 case Type::Pipe: 3934 llvm_unreachable("type class is never variably-modified!"); 3935 case Type::Adjusted: 3936 T = cast<AdjustedType>(Ty)->getOriginalType(); 3937 break; 3938 case Type::Decayed: 3939 T = cast<DecayedType>(Ty)->getPointeeType(); 3940 break; 3941 case Type::Pointer: 3942 T = cast<PointerType>(Ty)->getPointeeType(); 3943 break; 3944 case Type::BlockPointer: 3945 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3946 break; 3947 case Type::LValueReference: 3948 case Type::RValueReference: 3949 T = cast<ReferenceType>(Ty)->getPointeeType(); 3950 break; 3951 case Type::MemberPointer: 3952 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3953 break; 3954 case Type::ConstantArray: 3955 case Type::IncompleteArray: 3956 // Losing element qualification here is fine. 3957 T = cast<ArrayType>(Ty)->getElementType(); 3958 break; 3959 case Type::VariableArray: { 3960 // Losing element qualification here is fine. 3961 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3962 3963 // Unknown size indication requires no size computation. 3964 // Otherwise, evaluate and record it. 3965 if (auto Size = VAT->getSizeExpr()) { 3966 if (!CSI->isVLATypeCaptured(VAT)) { 3967 RecordDecl *CapRecord = nullptr; 3968 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3969 CapRecord = LSI->Lambda; 3970 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3971 CapRecord = CRSI->TheRecordDecl; 3972 } 3973 if (CapRecord) { 3974 auto ExprLoc = Size->getExprLoc(); 3975 auto SizeType = Context.getSizeType(); 3976 // Build the non-static data member. 3977 auto Field = 3978 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3979 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3980 /*BW*/ nullptr, /*Mutable*/ false, 3981 /*InitStyle*/ ICIS_NoInit); 3982 Field->setImplicit(true); 3983 Field->setAccess(AS_private); 3984 Field->setCapturedVLAType(VAT); 3985 CapRecord->addDecl(Field); 3986 3987 CSI->addVLATypeCapture(ExprLoc, SizeType); 3988 } 3989 } 3990 } 3991 T = VAT->getElementType(); 3992 break; 3993 } 3994 case Type::FunctionProto: 3995 case Type::FunctionNoProto: 3996 T = cast<FunctionType>(Ty)->getReturnType(); 3997 break; 3998 case Type::Paren: 3999 case Type::TypeOf: 4000 case Type::UnaryTransform: 4001 case Type::Attributed: 4002 case Type::SubstTemplateTypeParm: 4003 case Type::PackExpansion: 4004 // Keep walking after single level desugaring. 4005 T = T.getSingleStepDesugaredType(Context); 4006 break; 4007 case Type::Typedef: 4008 T = cast<TypedefType>(Ty)->desugar(); 4009 break; 4010 case Type::Decltype: 4011 T = cast<DecltypeType>(Ty)->desugar(); 4012 break; 4013 case Type::Auto: 4014 case Type::DeducedTemplateSpecialization: 4015 T = cast<DeducedType>(Ty)->getDeducedType(); 4016 break; 4017 case Type::TypeOfExpr: 4018 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4019 break; 4020 case Type::Atomic: 4021 T = cast<AtomicType>(Ty)->getValueType(); 4022 break; 4023 } 4024 } while (!T.isNull() && T->isVariablyModifiedType()); 4025 } 4026 4027 /// Build a sizeof or alignof expression given a type operand. 4028 ExprResult 4029 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4030 SourceLocation OpLoc, 4031 UnaryExprOrTypeTrait ExprKind, 4032 SourceRange R) { 4033 if (!TInfo) 4034 return ExprError(); 4035 4036 QualType T = TInfo->getType(); 4037 4038 if (!T->isDependentType() && 4039 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4040 return ExprError(); 4041 4042 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4043 if (auto *TT = T->getAs<TypedefType>()) { 4044 for (auto I = FunctionScopes.rbegin(), 4045 E = std::prev(FunctionScopes.rend()); 4046 I != E; ++I) { 4047 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4048 if (CSI == nullptr) 4049 break; 4050 DeclContext *DC = nullptr; 4051 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4052 DC = LSI->CallOperator; 4053 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4054 DC = CRSI->TheCapturedDecl; 4055 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4056 DC = BSI->TheDecl; 4057 if (DC) { 4058 if (DC->containsDecl(TT->getDecl())) 4059 break; 4060 captureVariablyModifiedType(Context, T, CSI); 4061 } 4062 } 4063 } 4064 } 4065 4066 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4067 return new (Context) UnaryExprOrTypeTraitExpr( 4068 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4069 } 4070 4071 /// Build a sizeof or alignof expression given an expression 4072 /// operand. 4073 ExprResult 4074 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4075 UnaryExprOrTypeTrait ExprKind) { 4076 ExprResult PE = CheckPlaceholderExpr(E); 4077 if (PE.isInvalid()) 4078 return ExprError(); 4079 4080 E = PE.get(); 4081 4082 // Verify that the operand is valid. 4083 bool isInvalid = false; 4084 if (E->isTypeDependent()) { 4085 // Delay type-checking for type-dependent expressions. 4086 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4087 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4088 } else if (ExprKind == UETT_VecStep) { 4089 isInvalid = CheckVecStepExpr(E); 4090 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4091 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4092 isInvalid = true; 4093 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4094 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4095 isInvalid = true; 4096 } else { 4097 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4098 } 4099 4100 if (isInvalid) 4101 return ExprError(); 4102 4103 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4104 PE = TransformToPotentiallyEvaluated(E); 4105 if (PE.isInvalid()) return ExprError(); 4106 E = PE.get(); 4107 } 4108 4109 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4110 return new (Context) UnaryExprOrTypeTraitExpr( 4111 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4112 } 4113 4114 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4115 /// expr and the same for @c alignof and @c __alignof 4116 /// Note that the ArgRange is invalid if isType is false. 4117 ExprResult 4118 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4119 UnaryExprOrTypeTrait ExprKind, bool IsType, 4120 void *TyOrEx, SourceRange ArgRange) { 4121 // If error parsing type, ignore. 4122 if (!TyOrEx) return ExprError(); 4123 4124 if (IsType) { 4125 TypeSourceInfo *TInfo; 4126 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4127 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4128 } 4129 4130 Expr *ArgEx = (Expr *)TyOrEx; 4131 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4132 return Result; 4133 } 4134 4135 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4136 bool IsReal) { 4137 if (V.get()->isTypeDependent()) 4138 return S.Context.DependentTy; 4139 4140 // _Real and _Imag are only l-values for normal l-values. 4141 if (V.get()->getObjectKind() != OK_Ordinary) { 4142 V = S.DefaultLvalueConversion(V.get()); 4143 if (V.isInvalid()) 4144 return QualType(); 4145 } 4146 4147 // These operators return the element type of a complex type. 4148 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4149 return CT->getElementType(); 4150 4151 // Otherwise they pass through real integer and floating point types here. 4152 if (V.get()->getType()->isArithmeticType()) 4153 return V.get()->getType(); 4154 4155 // Test for placeholders. 4156 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4157 if (PR.isInvalid()) return QualType(); 4158 if (PR.get() != V.get()) { 4159 V = PR; 4160 return CheckRealImagOperand(S, V, Loc, IsReal); 4161 } 4162 4163 // Reject anything else. 4164 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4165 << (IsReal ? "__real" : "__imag"); 4166 return QualType(); 4167 } 4168 4169 4170 4171 ExprResult 4172 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4173 tok::TokenKind Kind, Expr *Input) { 4174 UnaryOperatorKind Opc; 4175 switch (Kind) { 4176 default: llvm_unreachable("Unknown unary op!"); 4177 case tok::plusplus: Opc = UO_PostInc; break; 4178 case tok::minusminus: Opc = UO_PostDec; break; 4179 } 4180 4181 // Since this might is a postfix expression, get rid of ParenListExprs. 4182 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4183 if (Result.isInvalid()) return ExprError(); 4184 Input = Result.get(); 4185 4186 return BuildUnaryOp(S, OpLoc, Opc, Input); 4187 } 4188 4189 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4190 /// 4191 /// \return true on error 4192 static bool checkArithmeticOnObjCPointer(Sema &S, 4193 SourceLocation opLoc, 4194 Expr *op) { 4195 assert(op->getType()->isObjCObjectPointerType()); 4196 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4197 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4198 return false; 4199 4200 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4201 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4202 << op->getSourceRange(); 4203 return true; 4204 } 4205 4206 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4207 auto *BaseNoParens = Base->IgnoreParens(); 4208 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4209 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4210 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4211 } 4212 4213 ExprResult 4214 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4215 Expr *idx, SourceLocation rbLoc) { 4216 if (base && !base->getType().isNull() && 4217 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4218 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4219 /*Length=*/nullptr, rbLoc); 4220 4221 // Since this might be a postfix expression, get rid of ParenListExprs. 4222 if (isa<ParenListExpr>(base)) { 4223 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4224 if (result.isInvalid()) return ExprError(); 4225 base = result.get(); 4226 } 4227 4228 // Handle any non-overload placeholder types in the base and index 4229 // expressions. We can't handle overloads here because the other 4230 // operand might be an overloadable type, in which case the overload 4231 // resolution for the operator overload should get the first crack 4232 // at the overload. 4233 bool IsMSPropertySubscript = false; 4234 if (base->getType()->isNonOverloadPlaceholderType()) { 4235 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4236 if (!IsMSPropertySubscript) { 4237 ExprResult result = CheckPlaceholderExpr(base); 4238 if (result.isInvalid()) 4239 return ExprError(); 4240 base = result.get(); 4241 } 4242 } 4243 if (idx->getType()->isNonOverloadPlaceholderType()) { 4244 ExprResult result = CheckPlaceholderExpr(idx); 4245 if (result.isInvalid()) return ExprError(); 4246 idx = result.get(); 4247 } 4248 4249 // Build an unanalyzed expression if either operand is type-dependent. 4250 if (getLangOpts().CPlusPlus && 4251 (base->isTypeDependent() || idx->isTypeDependent())) { 4252 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4253 VK_LValue, OK_Ordinary, rbLoc); 4254 } 4255 4256 // MSDN, property (C++) 4257 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4258 // This attribute can also be used in the declaration of an empty array in a 4259 // class or structure definition. For example: 4260 // __declspec(property(get=GetX, put=PutX)) int x[]; 4261 // The above statement indicates that x[] can be used with one or more array 4262 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4263 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4264 if (IsMSPropertySubscript) { 4265 // Build MS property subscript expression if base is MS property reference 4266 // or MS property subscript. 4267 return new (Context) MSPropertySubscriptExpr( 4268 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4269 } 4270 4271 // Use C++ overloaded-operator rules if either operand has record 4272 // type. The spec says to do this if either type is *overloadable*, 4273 // but enum types can't declare subscript operators or conversion 4274 // operators, so there's nothing interesting for overload resolution 4275 // to do if there aren't any record types involved. 4276 // 4277 // ObjC pointers have their own subscripting logic that is not tied 4278 // to overload resolution and so should not take this path. 4279 if (getLangOpts().CPlusPlus && 4280 (base->getType()->isRecordType() || 4281 (!base->getType()->isObjCObjectPointerType() && 4282 idx->getType()->isRecordType()))) { 4283 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4284 } 4285 4286 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4287 4288 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4289 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4290 4291 return Res; 4292 } 4293 4294 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4295 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4296 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4297 4298 // For expressions like `&(*s).b`, the base is recorded and what should be 4299 // checked. 4300 const MemberExpr *Member = nullptr; 4301 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4302 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4303 4304 LastRecord.PossibleDerefs.erase(StrippedExpr); 4305 } 4306 4307 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4308 QualType ResultTy = E->getType(); 4309 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4310 4311 // Bail if the element is an array since it is not memory access. 4312 if (isa<ArrayType>(ResultTy)) 4313 return; 4314 4315 if (ResultTy->hasAttr(attr::NoDeref)) { 4316 LastRecord.PossibleDerefs.insert(E); 4317 return; 4318 } 4319 4320 // Check if the base type is a pointer to a member access of a struct 4321 // marked with noderef. 4322 const Expr *Base = E->getBase(); 4323 QualType BaseTy = Base->getType(); 4324 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4325 // Not a pointer access 4326 return; 4327 4328 const MemberExpr *Member = nullptr; 4329 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4330 Member->isArrow()) 4331 Base = Member->getBase(); 4332 4333 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4334 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4335 LastRecord.PossibleDerefs.insert(E); 4336 } 4337 } 4338 4339 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4340 Expr *LowerBound, 4341 SourceLocation ColonLoc, Expr *Length, 4342 SourceLocation RBLoc) { 4343 if (Base->getType()->isPlaceholderType() && 4344 !Base->getType()->isSpecificPlaceholderType( 4345 BuiltinType::OMPArraySection)) { 4346 ExprResult Result = CheckPlaceholderExpr(Base); 4347 if (Result.isInvalid()) 4348 return ExprError(); 4349 Base = Result.get(); 4350 } 4351 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4352 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4353 if (Result.isInvalid()) 4354 return ExprError(); 4355 Result = DefaultLvalueConversion(Result.get()); 4356 if (Result.isInvalid()) 4357 return ExprError(); 4358 LowerBound = Result.get(); 4359 } 4360 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4361 ExprResult Result = CheckPlaceholderExpr(Length); 4362 if (Result.isInvalid()) 4363 return ExprError(); 4364 Result = DefaultLvalueConversion(Result.get()); 4365 if (Result.isInvalid()) 4366 return ExprError(); 4367 Length = Result.get(); 4368 } 4369 4370 // Build an unanalyzed expression if either operand is type-dependent. 4371 if (Base->isTypeDependent() || 4372 (LowerBound && 4373 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4374 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4375 return new (Context) 4376 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4377 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4378 } 4379 4380 // Perform default conversions. 4381 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4382 QualType ResultTy; 4383 if (OriginalTy->isAnyPointerType()) { 4384 ResultTy = OriginalTy->getPointeeType(); 4385 } else if (OriginalTy->isArrayType()) { 4386 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4387 } else { 4388 return ExprError( 4389 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4390 << Base->getSourceRange()); 4391 } 4392 // C99 6.5.2.1p1 4393 if (LowerBound) { 4394 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4395 LowerBound); 4396 if (Res.isInvalid()) 4397 return ExprError(Diag(LowerBound->getExprLoc(), 4398 diag::err_omp_typecheck_section_not_integer) 4399 << 0 << LowerBound->getSourceRange()); 4400 LowerBound = Res.get(); 4401 4402 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4403 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4404 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4405 << 0 << LowerBound->getSourceRange(); 4406 } 4407 if (Length) { 4408 auto Res = 4409 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4410 if (Res.isInvalid()) 4411 return ExprError(Diag(Length->getExprLoc(), 4412 diag::err_omp_typecheck_section_not_integer) 4413 << 1 << Length->getSourceRange()); 4414 Length = Res.get(); 4415 4416 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4417 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4418 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4419 << 1 << Length->getSourceRange(); 4420 } 4421 4422 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4423 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4424 // type. Note that functions are not objects, and that (in C99 parlance) 4425 // incomplete types are not object types. 4426 if (ResultTy->isFunctionType()) { 4427 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4428 << ResultTy << Base->getSourceRange(); 4429 return ExprError(); 4430 } 4431 4432 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4433 diag::err_omp_section_incomplete_type, Base)) 4434 return ExprError(); 4435 4436 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4437 Expr::EvalResult Result; 4438 if (LowerBound->EvaluateAsInt(Result, Context)) { 4439 // OpenMP 4.5, [2.4 Array Sections] 4440 // The array section must be a subset of the original array. 4441 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4442 if (LowerBoundValue.isNegative()) { 4443 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4444 << LowerBound->getSourceRange(); 4445 return ExprError(); 4446 } 4447 } 4448 } 4449 4450 if (Length) { 4451 Expr::EvalResult Result; 4452 if (Length->EvaluateAsInt(Result, Context)) { 4453 // OpenMP 4.5, [2.4 Array Sections] 4454 // The length must evaluate to non-negative integers. 4455 llvm::APSInt LengthValue = Result.Val.getInt(); 4456 if (LengthValue.isNegative()) { 4457 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4458 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4459 << Length->getSourceRange(); 4460 return ExprError(); 4461 } 4462 } 4463 } else if (ColonLoc.isValid() && 4464 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4465 !OriginalTy->isVariableArrayType()))) { 4466 // OpenMP 4.5, [2.4 Array Sections] 4467 // When the size of the array dimension is not known, the length must be 4468 // specified explicitly. 4469 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4470 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4471 return ExprError(); 4472 } 4473 4474 if (!Base->getType()->isSpecificPlaceholderType( 4475 BuiltinType::OMPArraySection)) { 4476 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4477 if (Result.isInvalid()) 4478 return ExprError(); 4479 Base = Result.get(); 4480 } 4481 return new (Context) 4482 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4483 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4484 } 4485 4486 ExprResult 4487 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4488 Expr *Idx, SourceLocation RLoc) { 4489 Expr *LHSExp = Base; 4490 Expr *RHSExp = Idx; 4491 4492 ExprValueKind VK = VK_LValue; 4493 ExprObjectKind OK = OK_Ordinary; 4494 4495 // Per C++ core issue 1213, the result is an xvalue if either operand is 4496 // a non-lvalue array, and an lvalue otherwise. 4497 if (getLangOpts().CPlusPlus11) { 4498 for (auto *Op : {LHSExp, RHSExp}) { 4499 Op = Op->IgnoreImplicit(); 4500 if (Op->getType()->isArrayType() && !Op->isLValue()) 4501 VK = VK_XValue; 4502 } 4503 } 4504 4505 // Perform default conversions. 4506 if (!LHSExp->getType()->getAs<VectorType>()) { 4507 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4508 if (Result.isInvalid()) 4509 return ExprError(); 4510 LHSExp = Result.get(); 4511 } 4512 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4513 if (Result.isInvalid()) 4514 return ExprError(); 4515 RHSExp = Result.get(); 4516 4517 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4518 4519 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4520 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4521 // in the subscript position. As a result, we need to derive the array base 4522 // and index from the expression types. 4523 Expr *BaseExpr, *IndexExpr; 4524 QualType ResultType; 4525 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4526 BaseExpr = LHSExp; 4527 IndexExpr = RHSExp; 4528 ResultType = Context.DependentTy; 4529 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4530 BaseExpr = LHSExp; 4531 IndexExpr = RHSExp; 4532 ResultType = PTy->getPointeeType(); 4533 } else if (const ObjCObjectPointerType *PTy = 4534 LHSTy->getAs<ObjCObjectPointerType>()) { 4535 BaseExpr = LHSExp; 4536 IndexExpr = RHSExp; 4537 4538 // Use custom logic if this should be the pseudo-object subscript 4539 // expression. 4540 if (!LangOpts.isSubscriptPointerArithmetic()) 4541 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4542 nullptr); 4543 4544 ResultType = PTy->getPointeeType(); 4545 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4546 // Handle the uncommon case of "123[Ptr]". 4547 BaseExpr = RHSExp; 4548 IndexExpr = LHSExp; 4549 ResultType = PTy->getPointeeType(); 4550 } else if (const ObjCObjectPointerType *PTy = 4551 RHSTy->getAs<ObjCObjectPointerType>()) { 4552 // Handle the uncommon case of "123[Ptr]". 4553 BaseExpr = RHSExp; 4554 IndexExpr = LHSExp; 4555 ResultType = PTy->getPointeeType(); 4556 if (!LangOpts.isSubscriptPointerArithmetic()) { 4557 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4558 << ResultType << BaseExpr->getSourceRange(); 4559 return ExprError(); 4560 } 4561 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4562 BaseExpr = LHSExp; // vectors: V[123] 4563 IndexExpr = RHSExp; 4564 // We apply C++ DR1213 to vector subscripting too. 4565 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4566 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4567 if (Materialized.isInvalid()) 4568 return ExprError(); 4569 LHSExp = Materialized.get(); 4570 } 4571 VK = LHSExp->getValueKind(); 4572 if (VK != VK_RValue) 4573 OK = OK_VectorComponent; 4574 4575 ResultType = VTy->getElementType(); 4576 QualType BaseType = BaseExpr->getType(); 4577 Qualifiers BaseQuals = BaseType.getQualifiers(); 4578 Qualifiers MemberQuals = ResultType.getQualifiers(); 4579 Qualifiers Combined = BaseQuals + MemberQuals; 4580 if (Combined != MemberQuals) 4581 ResultType = Context.getQualifiedType(ResultType, Combined); 4582 } else if (LHSTy->isArrayType()) { 4583 // If we see an array that wasn't promoted by 4584 // DefaultFunctionArrayLvalueConversion, it must be an array that 4585 // wasn't promoted because of the C90 rule that doesn't 4586 // allow promoting non-lvalue arrays. Warn, then 4587 // force the promotion here. 4588 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4589 << LHSExp->getSourceRange(); 4590 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4591 CK_ArrayToPointerDecay).get(); 4592 LHSTy = LHSExp->getType(); 4593 4594 BaseExpr = LHSExp; 4595 IndexExpr = RHSExp; 4596 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4597 } else if (RHSTy->isArrayType()) { 4598 // Same as previous, except for 123[f().a] case 4599 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4600 << RHSExp->getSourceRange(); 4601 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4602 CK_ArrayToPointerDecay).get(); 4603 RHSTy = RHSExp->getType(); 4604 4605 BaseExpr = RHSExp; 4606 IndexExpr = LHSExp; 4607 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4608 } else { 4609 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4610 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4611 } 4612 // C99 6.5.2.1p1 4613 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4614 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4615 << IndexExpr->getSourceRange()); 4616 4617 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4618 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4619 && !IndexExpr->isTypeDependent()) 4620 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4621 4622 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4623 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4624 // type. Note that Functions are not objects, and that (in C99 parlance) 4625 // incomplete types are not object types. 4626 if (ResultType->isFunctionType()) { 4627 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4628 << ResultType << BaseExpr->getSourceRange(); 4629 return ExprError(); 4630 } 4631 4632 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4633 // GNU extension: subscripting on pointer to void 4634 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4635 << BaseExpr->getSourceRange(); 4636 4637 // C forbids expressions of unqualified void type from being l-values. 4638 // See IsCForbiddenLValueType. 4639 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4640 } else if (!ResultType->isDependentType() && 4641 RequireCompleteType(LLoc, ResultType, 4642 diag::err_subscript_incomplete_type, BaseExpr)) 4643 return ExprError(); 4644 4645 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4646 !ResultType.isCForbiddenLValueType()); 4647 4648 return new (Context) 4649 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4650 } 4651 4652 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4653 ParmVarDecl *Param) { 4654 if (Param->hasUnparsedDefaultArg()) { 4655 Diag(CallLoc, 4656 diag::err_use_of_default_argument_to_function_declared_later) << 4657 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4658 Diag(UnparsedDefaultArgLocs[Param], 4659 diag::note_default_argument_declared_here); 4660 return true; 4661 } 4662 4663 if (Param->hasUninstantiatedDefaultArg()) { 4664 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4665 4666 EnterExpressionEvaluationContext EvalContext( 4667 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4668 4669 // Instantiate the expression. 4670 // 4671 // FIXME: Pass in a correct Pattern argument, otherwise 4672 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4673 // 4674 // template<typename T> 4675 // struct A { 4676 // static int FooImpl(); 4677 // 4678 // template<typename Tp> 4679 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4680 // // template argument list [[T], [Tp]], should be [[Tp]]. 4681 // friend A<Tp> Foo(int a); 4682 // }; 4683 // 4684 // template<typename T> 4685 // A<T> Foo(int a = A<T>::FooImpl()); 4686 MultiLevelTemplateArgumentList MutiLevelArgList 4687 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4688 4689 InstantiatingTemplate Inst(*this, CallLoc, Param, 4690 MutiLevelArgList.getInnermost()); 4691 if (Inst.isInvalid()) 4692 return true; 4693 if (Inst.isAlreadyInstantiating()) { 4694 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4695 Param->setInvalidDecl(); 4696 return true; 4697 } 4698 4699 ExprResult Result; 4700 { 4701 // C++ [dcl.fct.default]p5: 4702 // The names in the [default argument] expression are bound, and 4703 // the semantic constraints are checked, at the point where the 4704 // default argument expression appears. 4705 ContextRAII SavedContext(*this, FD); 4706 LocalInstantiationScope Local(*this); 4707 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4708 /*DirectInit*/false); 4709 } 4710 if (Result.isInvalid()) 4711 return true; 4712 4713 // Check the expression as an initializer for the parameter. 4714 InitializedEntity Entity 4715 = InitializedEntity::InitializeParameter(Context, Param); 4716 InitializationKind Kind = InitializationKind::CreateCopy( 4717 Param->getLocation(), 4718 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4719 Expr *ResultE = Result.getAs<Expr>(); 4720 4721 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4722 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4723 if (Result.isInvalid()) 4724 return true; 4725 4726 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4727 Param->getOuterLocStart()); 4728 if (Result.isInvalid()) 4729 return true; 4730 4731 // Remember the instantiated default argument. 4732 Param->setDefaultArg(Result.getAs<Expr>()); 4733 if (ASTMutationListener *L = getASTMutationListener()) { 4734 L->DefaultArgumentInstantiated(Param); 4735 } 4736 } 4737 4738 // If the default argument expression is not set yet, we are building it now. 4739 if (!Param->hasInit()) { 4740 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4741 Param->setInvalidDecl(); 4742 return true; 4743 } 4744 4745 // If the default expression creates temporaries, we need to 4746 // push them to the current stack of expression temporaries so they'll 4747 // be properly destroyed. 4748 // FIXME: We should really be rebuilding the default argument with new 4749 // bound temporaries; see the comment in PR5810. 4750 // We don't need to do that with block decls, though, because 4751 // blocks in default argument expression can never capture anything. 4752 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4753 // Set the "needs cleanups" bit regardless of whether there are 4754 // any explicit objects. 4755 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4756 4757 // Append all the objects to the cleanup list. Right now, this 4758 // should always be a no-op, because blocks in default argument 4759 // expressions should never be able to capture anything. 4760 assert(!Init->getNumObjects() && 4761 "default argument expression has capturing blocks?"); 4762 } 4763 4764 // We already type-checked the argument, so we know it works. 4765 // Just mark all of the declarations in this potentially-evaluated expression 4766 // as being "referenced". 4767 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4768 /*SkipLocalVariables=*/true); 4769 return false; 4770 } 4771 4772 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4773 FunctionDecl *FD, ParmVarDecl *Param) { 4774 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4775 return ExprError(); 4776 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4777 } 4778 4779 Sema::VariadicCallType 4780 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4781 Expr *Fn) { 4782 if (Proto && Proto->isVariadic()) { 4783 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4784 return VariadicConstructor; 4785 else if (Fn && Fn->getType()->isBlockPointerType()) 4786 return VariadicBlock; 4787 else if (FDecl) { 4788 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4789 if (Method->isInstance()) 4790 return VariadicMethod; 4791 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4792 return VariadicMethod; 4793 return VariadicFunction; 4794 } 4795 return VariadicDoesNotApply; 4796 } 4797 4798 namespace { 4799 class FunctionCallCCC : public FunctionCallFilterCCC { 4800 public: 4801 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4802 unsigned NumArgs, MemberExpr *ME) 4803 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4804 FunctionName(FuncName) {} 4805 4806 bool ValidateCandidate(const TypoCorrection &candidate) override { 4807 if (!candidate.getCorrectionSpecifier() || 4808 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4809 return false; 4810 } 4811 4812 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4813 } 4814 4815 private: 4816 const IdentifierInfo *const FunctionName; 4817 }; 4818 } 4819 4820 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4821 FunctionDecl *FDecl, 4822 ArrayRef<Expr *> Args) { 4823 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4824 DeclarationName FuncName = FDecl->getDeclName(); 4825 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4826 4827 if (TypoCorrection Corrected = S.CorrectTypo( 4828 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4829 S.getScopeForContext(S.CurContext), nullptr, 4830 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4831 Args.size(), ME), 4832 Sema::CTK_ErrorRecovery)) { 4833 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4834 if (Corrected.isOverloaded()) { 4835 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4836 OverloadCandidateSet::iterator Best; 4837 for (NamedDecl *CD : Corrected) { 4838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4839 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4840 OCS); 4841 } 4842 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4843 case OR_Success: 4844 ND = Best->FoundDecl; 4845 Corrected.setCorrectionDecl(ND); 4846 break; 4847 default: 4848 break; 4849 } 4850 } 4851 ND = ND->getUnderlyingDecl(); 4852 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4853 return Corrected; 4854 } 4855 } 4856 return TypoCorrection(); 4857 } 4858 4859 /// ConvertArgumentsForCall - Converts the arguments specified in 4860 /// Args/NumArgs to the parameter types of the function FDecl with 4861 /// function prototype Proto. Call is the call expression itself, and 4862 /// Fn is the function expression. For a C++ member function, this 4863 /// routine does not attempt to convert the object argument. Returns 4864 /// true if the call is ill-formed. 4865 bool 4866 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4867 FunctionDecl *FDecl, 4868 const FunctionProtoType *Proto, 4869 ArrayRef<Expr *> Args, 4870 SourceLocation RParenLoc, 4871 bool IsExecConfig) { 4872 // Bail out early if calling a builtin with custom typechecking. 4873 if (FDecl) 4874 if (unsigned ID = FDecl->getBuiltinID()) 4875 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4876 return false; 4877 4878 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4879 // assignment, to the types of the corresponding parameter, ... 4880 unsigned NumParams = Proto->getNumParams(); 4881 bool Invalid = false; 4882 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4883 unsigned FnKind = Fn->getType()->isBlockPointerType() 4884 ? 1 /* block */ 4885 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4886 : 0 /* function */); 4887 4888 // If too few arguments are available (and we don't have default 4889 // arguments for the remaining parameters), don't make the call. 4890 if (Args.size() < NumParams) { 4891 if (Args.size() < MinArgs) { 4892 TypoCorrection TC; 4893 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4894 unsigned diag_id = 4895 MinArgs == NumParams && !Proto->isVariadic() 4896 ? diag::err_typecheck_call_too_few_args_suggest 4897 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4898 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4899 << static_cast<unsigned>(Args.size()) 4900 << TC.getCorrectionRange()); 4901 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4902 Diag(RParenLoc, 4903 MinArgs == NumParams && !Proto->isVariadic() 4904 ? diag::err_typecheck_call_too_few_args_one 4905 : diag::err_typecheck_call_too_few_args_at_least_one) 4906 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4907 else 4908 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4909 ? diag::err_typecheck_call_too_few_args 4910 : diag::err_typecheck_call_too_few_args_at_least) 4911 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4912 << Fn->getSourceRange(); 4913 4914 // Emit the location of the prototype. 4915 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4916 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4917 4918 return true; 4919 } 4920 // We reserve space for the default arguments when we create 4921 // the call expression, before calling ConvertArgumentsForCall. 4922 assert((Call->getNumArgs() == NumParams) && 4923 "We should have reserved space for the default arguments before!"); 4924 } 4925 4926 // If too many are passed and not variadic, error on the extras and drop 4927 // them. 4928 if (Args.size() > NumParams) { 4929 if (!Proto->isVariadic()) { 4930 TypoCorrection TC; 4931 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4932 unsigned diag_id = 4933 MinArgs == NumParams && !Proto->isVariadic() 4934 ? diag::err_typecheck_call_too_many_args_suggest 4935 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4936 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4937 << static_cast<unsigned>(Args.size()) 4938 << TC.getCorrectionRange()); 4939 } else if (NumParams == 1 && FDecl && 4940 FDecl->getParamDecl(0)->getDeclName()) 4941 Diag(Args[NumParams]->getBeginLoc(), 4942 MinArgs == NumParams 4943 ? diag::err_typecheck_call_too_many_args_one 4944 : diag::err_typecheck_call_too_many_args_at_most_one) 4945 << FnKind << FDecl->getParamDecl(0) 4946 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4947 << SourceRange(Args[NumParams]->getBeginLoc(), 4948 Args.back()->getEndLoc()); 4949 else 4950 Diag(Args[NumParams]->getBeginLoc(), 4951 MinArgs == NumParams 4952 ? diag::err_typecheck_call_too_many_args 4953 : diag::err_typecheck_call_too_many_args_at_most) 4954 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4955 << Fn->getSourceRange() 4956 << SourceRange(Args[NumParams]->getBeginLoc(), 4957 Args.back()->getEndLoc()); 4958 4959 // Emit the location of the prototype. 4960 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4961 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4962 4963 // This deletes the extra arguments. 4964 Call->shrinkNumArgs(NumParams); 4965 return true; 4966 } 4967 } 4968 SmallVector<Expr *, 8> AllArgs; 4969 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4970 4971 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4972 AllArgs, CallType); 4973 if (Invalid) 4974 return true; 4975 unsigned TotalNumArgs = AllArgs.size(); 4976 for (unsigned i = 0; i < TotalNumArgs; ++i) 4977 Call->setArg(i, AllArgs[i]); 4978 4979 return false; 4980 } 4981 4982 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4983 const FunctionProtoType *Proto, 4984 unsigned FirstParam, ArrayRef<Expr *> Args, 4985 SmallVectorImpl<Expr *> &AllArgs, 4986 VariadicCallType CallType, bool AllowExplicit, 4987 bool IsListInitialization) { 4988 unsigned NumParams = Proto->getNumParams(); 4989 bool Invalid = false; 4990 size_t ArgIx = 0; 4991 // Continue to check argument types (even if we have too few/many args). 4992 for (unsigned i = FirstParam; i < NumParams; i++) { 4993 QualType ProtoArgType = Proto->getParamType(i); 4994 4995 Expr *Arg; 4996 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4997 if (ArgIx < Args.size()) { 4998 Arg = Args[ArgIx++]; 4999 5000 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5001 diag::err_call_incomplete_argument, Arg)) 5002 return true; 5003 5004 // Strip the unbridged-cast placeholder expression off, if applicable. 5005 bool CFAudited = false; 5006 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5007 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5008 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5009 Arg = stripARCUnbridgedCast(Arg); 5010 else if (getLangOpts().ObjCAutoRefCount && 5011 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5012 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5013 CFAudited = true; 5014 5015 if (Proto->getExtParameterInfo(i).isNoEscape()) 5016 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5017 BE->getBlockDecl()->setDoesNotEscape(); 5018 5019 InitializedEntity Entity = 5020 Param ? InitializedEntity::InitializeParameter(Context, Param, 5021 ProtoArgType) 5022 : InitializedEntity::InitializeParameter( 5023 Context, ProtoArgType, Proto->isParamConsumed(i)); 5024 5025 // Remember that parameter belongs to a CF audited API. 5026 if (CFAudited) 5027 Entity.setParameterCFAudited(); 5028 5029 ExprResult ArgE = PerformCopyInitialization( 5030 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5031 if (ArgE.isInvalid()) 5032 return true; 5033 5034 Arg = ArgE.getAs<Expr>(); 5035 } else { 5036 assert(Param && "can't use default arguments without a known callee"); 5037 5038 ExprResult ArgExpr = 5039 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5040 if (ArgExpr.isInvalid()) 5041 return true; 5042 5043 Arg = ArgExpr.getAs<Expr>(); 5044 } 5045 5046 // Check for array bounds violations for each argument to the call. This 5047 // check only triggers warnings when the argument isn't a more complex Expr 5048 // with its own checking, such as a BinaryOperator. 5049 CheckArrayAccess(Arg); 5050 5051 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5052 CheckStaticArrayArgument(CallLoc, Param, Arg); 5053 5054 AllArgs.push_back(Arg); 5055 } 5056 5057 // If this is a variadic call, handle args passed through "...". 5058 if (CallType != VariadicDoesNotApply) { 5059 // Assume that extern "C" functions with variadic arguments that 5060 // return __unknown_anytype aren't *really* variadic. 5061 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5062 FDecl->isExternC()) { 5063 for (Expr *A : Args.slice(ArgIx)) { 5064 QualType paramType; // ignored 5065 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5066 Invalid |= arg.isInvalid(); 5067 AllArgs.push_back(arg.get()); 5068 } 5069 5070 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5071 } else { 5072 for (Expr *A : Args.slice(ArgIx)) { 5073 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5074 Invalid |= Arg.isInvalid(); 5075 AllArgs.push_back(Arg.get()); 5076 } 5077 } 5078 5079 // Check for array bounds violations. 5080 for (Expr *A : Args.slice(ArgIx)) 5081 CheckArrayAccess(A); 5082 } 5083 return Invalid; 5084 } 5085 5086 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5087 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5088 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5089 TL = DTL.getOriginalLoc(); 5090 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5091 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5092 << ATL.getLocalSourceRange(); 5093 } 5094 5095 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5096 /// array parameter, check that it is non-null, and that if it is formed by 5097 /// array-to-pointer decay, the underlying array is sufficiently large. 5098 /// 5099 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5100 /// array type derivation, then for each call to the function, the value of the 5101 /// corresponding actual argument shall provide access to the first element of 5102 /// an array with at least as many elements as specified by the size expression. 5103 void 5104 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5105 ParmVarDecl *Param, 5106 const Expr *ArgExpr) { 5107 // Static array parameters are not supported in C++. 5108 if (!Param || getLangOpts().CPlusPlus) 5109 return; 5110 5111 QualType OrigTy = Param->getOriginalType(); 5112 5113 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5114 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5115 return; 5116 5117 if (ArgExpr->isNullPointerConstant(Context, 5118 Expr::NPC_NeverValueDependent)) { 5119 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5120 DiagnoseCalleeStaticArrayParam(*this, Param); 5121 return; 5122 } 5123 5124 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5125 if (!CAT) 5126 return; 5127 5128 const ConstantArrayType *ArgCAT = 5129 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5130 if (!ArgCAT) 5131 return; 5132 5133 if (ArgCAT->getSize().ult(CAT->getSize())) { 5134 Diag(CallLoc, diag::warn_static_array_too_small) 5135 << ArgExpr->getSourceRange() 5136 << (unsigned) ArgCAT->getSize().getZExtValue() 5137 << (unsigned) CAT->getSize().getZExtValue(); 5138 DiagnoseCalleeStaticArrayParam(*this, Param); 5139 } 5140 } 5141 5142 /// Given a function expression of unknown-any type, try to rebuild it 5143 /// to have a function type. 5144 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5145 5146 /// Is the given type a placeholder that we need to lower out 5147 /// immediately during argument processing? 5148 static bool isPlaceholderToRemoveAsArg(QualType type) { 5149 // Placeholders are never sugared. 5150 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5151 if (!placeholder) return false; 5152 5153 switch (placeholder->getKind()) { 5154 // Ignore all the non-placeholder types. 5155 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5156 case BuiltinType::Id: 5157 #include "clang/Basic/OpenCLImageTypes.def" 5158 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5159 case BuiltinType::Id: 5160 #include "clang/Basic/OpenCLExtensionTypes.def" 5161 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5162 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5163 #include "clang/AST/BuiltinTypes.def" 5164 return false; 5165 5166 // We cannot lower out overload sets; they might validly be resolved 5167 // by the call machinery. 5168 case BuiltinType::Overload: 5169 return false; 5170 5171 // Unbridged casts in ARC can be handled in some call positions and 5172 // should be left in place. 5173 case BuiltinType::ARCUnbridgedCast: 5174 return false; 5175 5176 // Pseudo-objects should be converted as soon as possible. 5177 case BuiltinType::PseudoObject: 5178 return true; 5179 5180 // The debugger mode could theoretically but currently does not try 5181 // to resolve unknown-typed arguments based on known parameter types. 5182 case BuiltinType::UnknownAny: 5183 return true; 5184 5185 // These are always invalid as call arguments and should be reported. 5186 case BuiltinType::BoundMember: 5187 case BuiltinType::BuiltinFn: 5188 case BuiltinType::OMPArraySection: 5189 return true; 5190 5191 } 5192 llvm_unreachable("bad builtin type kind"); 5193 } 5194 5195 /// Check an argument list for placeholders that we won't try to 5196 /// handle later. 5197 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5198 // Apply this processing to all the arguments at once instead of 5199 // dying at the first failure. 5200 bool hasInvalid = false; 5201 for (size_t i = 0, e = args.size(); i != e; i++) { 5202 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5203 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5204 if (result.isInvalid()) hasInvalid = true; 5205 else args[i] = result.get(); 5206 } else if (hasInvalid) { 5207 (void)S.CorrectDelayedTyposInExpr(args[i]); 5208 } 5209 } 5210 return hasInvalid; 5211 } 5212 5213 /// If a builtin function has a pointer argument with no explicit address 5214 /// space, then it should be able to accept a pointer to any address 5215 /// space as input. In order to do this, we need to replace the 5216 /// standard builtin declaration with one that uses the same address space 5217 /// as the call. 5218 /// 5219 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5220 /// it does not contain any pointer arguments without 5221 /// an address space qualifer. Otherwise the rewritten 5222 /// FunctionDecl is returned. 5223 /// TODO: Handle pointer return types. 5224 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5225 const FunctionDecl *FDecl, 5226 MultiExprArg ArgExprs) { 5227 5228 QualType DeclType = FDecl->getType(); 5229 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5230 5231 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5232 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5233 return nullptr; 5234 5235 bool NeedsNewDecl = false; 5236 unsigned i = 0; 5237 SmallVector<QualType, 8> OverloadParams; 5238 5239 for (QualType ParamType : FT->param_types()) { 5240 5241 // Convert array arguments to pointer to simplify type lookup. 5242 ExprResult ArgRes = 5243 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5244 if (ArgRes.isInvalid()) 5245 return nullptr; 5246 Expr *Arg = ArgRes.get(); 5247 QualType ArgType = Arg->getType(); 5248 if (!ParamType->isPointerType() || 5249 ParamType.getQualifiers().hasAddressSpace() || 5250 !ArgType->isPointerType() || 5251 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5252 OverloadParams.push_back(ParamType); 5253 continue; 5254 } 5255 5256 QualType PointeeType = ParamType->getPointeeType(); 5257 if (PointeeType.getQualifiers().hasAddressSpace()) 5258 continue; 5259 5260 NeedsNewDecl = true; 5261 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5262 5263 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5264 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5265 } 5266 5267 if (!NeedsNewDecl) 5268 return nullptr; 5269 5270 FunctionProtoType::ExtProtoInfo EPI; 5271 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5272 OverloadParams, EPI); 5273 DeclContext *Parent = Context.getTranslationUnitDecl(); 5274 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5275 FDecl->getLocation(), 5276 FDecl->getLocation(), 5277 FDecl->getIdentifier(), 5278 OverloadTy, 5279 /*TInfo=*/nullptr, 5280 SC_Extern, false, 5281 /*hasPrototype=*/true); 5282 SmallVector<ParmVarDecl*, 16> Params; 5283 FT = cast<FunctionProtoType>(OverloadTy); 5284 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5285 QualType ParamType = FT->getParamType(i); 5286 ParmVarDecl *Parm = 5287 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5288 SourceLocation(), nullptr, ParamType, 5289 /*TInfo=*/nullptr, SC_None, nullptr); 5290 Parm->setScopeInfo(0, i); 5291 Params.push_back(Parm); 5292 } 5293 OverloadDecl->setParams(Params); 5294 return OverloadDecl; 5295 } 5296 5297 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5298 FunctionDecl *Callee, 5299 MultiExprArg ArgExprs) { 5300 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5301 // similar attributes) really don't like it when functions are called with an 5302 // invalid number of args. 5303 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5304 /*PartialOverloading=*/false) && 5305 !Callee->isVariadic()) 5306 return; 5307 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5308 return; 5309 5310 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5311 S.Diag(Fn->getBeginLoc(), 5312 isa<CXXMethodDecl>(Callee) 5313 ? diag::err_ovl_no_viable_member_function_in_call 5314 : diag::err_ovl_no_viable_function_in_call) 5315 << Callee << Callee->getSourceRange(); 5316 S.Diag(Callee->getLocation(), 5317 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5318 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5319 return; 5320 } 5321 } 5322 5323 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5324 const UnresolvedMemberExpr *const UME, Sema &S) { 5325 5326 const auto GetFunctionLevelDCIfCXXClass = 5327 [](Sema &S) -> const CXXRecordDecl * { 5328 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5329 if (!DC || !DC->getParent()) 5330 return nullptr; 5331 5332 // If the call to some member function was made from within a member 5333 // function body 'M' return return 'M's parent. 5334 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5335 return MD->getParent()->getCanonicalDecl(); 5336 // else the call was made from within a default member initializer of a 5337 // class, so return the class. 5338 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5339 return RD->getCanonicalDecl(); 5340 return nullptr; 5341 }; 5342 // If our DeclContext is neither a member function nor a class (in the 5343 // case of a lambda in a default member initializer), we can't have an 5344 // enclosing 'this'. 5345 5346 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5347 if (!CurParentClass) 5348 return false; 5349 5350 // The naming class for implicit member functions call is the class in which 5351 // name lookup starts. 5352 const CXXRecordDecl *const NamingClass = 5353 UME->getNamingClass()->getCanonicalDecl(); 5354 assert(NamingClass && "Must have naming class even for implicit access"); 5355 5356 // If the unresolved member functions were found in a 'naming class' that is 5357 // related (either the same or derived from) to the class that contains the 5358 // member function that itself contained the implicit member access. 5359 5360 return CurParentClass == NamingClass || 5361 CurParentClass->isDerivedFrom(NamingClass); 5362 } 5363 5364 static void 5365 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5366 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5367 5368 if (!UME) 5369 return; 5370 5371 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5372 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5373 // already been captured, or if this is an implicit member function call (if 5374 // it isn't, an attempt to capture 'this' should already have been made). 5375 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5376 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5377 return; 5378 5379 // Check if the naming class in which the unresolved members were found is 5380 // related (same as or is a base of) to the enclosing class. 5381 5382 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5383 return; 5384 5385 5386 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5387 // If the enclosing function is not dependent, then this lambda is 5388 // capture ready, so if we can capture this, do so. 5389 if (!EnclosingFunctionCtx->isDependentContext()) { 5390 // If the current lambda and all enclosing lambdas can capture 'this' - 5391 // then go ahead and capture 'this' (since our unresolved overload set 5392 // contains at least one non-static member function). 5393 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5394 S.CheckCXXThisCapture(CallLoc); 5395 } else if (S.CurContext->isDependentContext()) { 5396 // ... since this is an implicit member reference, that might potentially 5397 // involve a 'this' capture, mark 'this' for potential capture in 5398 // enclosing lambdas. 5399 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5400 CurLSI->addPotentialThisCapture(CallLoc); 5401 } 5402 } 5403 5404 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5405 /// This provides the location of the left/right parens and a list of comma 5406 /// locations. 5407 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5408 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5409 Expr *ExecConfig, bool IsExecConfig) { 5410 // Since this might be a postfix expression, get rid of ParenListExprs. 5411 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5412 if (Result.isInvalid()) return ExprError(); 5413 Fn = Result.get(); 5414 5415 if (checkArgsForPlaceholders(*this, ArgExprs)) 5416 return ExprError(); 5417 5418 if (getLangOpts().CPlusPlus) { 5419 // If this is a pseudo-destructor expression, build the call immediately. 5420 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5421 if (!ArgExprs.empty()) { 5422 // Pseudo-destructor calls should not have any arguments. 5423 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5424 << FixItHint::CreateRemoval( 5425 SourceRange(ArgExprs.front()->getBeginLoc(), 5426 ArgExprs.back()->getEndLoc())); 5427 } 5428 5429 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5430 VK_RValue, RParenLoc); 5431 } 5432 if (Fn->getType() == Context.PseudoObjectTy) { 5433 ExprResult result = CheckPlaceholderExpr(Fn); 5434 if (result.isInvalid()) return ExprError(); 5435 Fn = result.get(); 5436 } 5437 5438 // Determine whether this is a dependent call inside a C++ template, 5439 // in which case we won't do any semantic analysis now. 5440 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5441 if (ExecConfig) { 5442 return CUDAKernelCallExpr::Create( 5443 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5444 Context.DependentTy, VK_RValue, RParenLoc); 5445 } else { 5446 5447 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5448 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5449 Fn->getBeginLoc()); 5450 5451 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5452 VK_RValue, RParenLoc); 5453 } 5454 } 5455 5456 // Determine whether this is a call to an object (C++ [over.call.object]). 5457 if (Fn->getType()->isRecordType()) 5458 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5459 RParenLoc); 5460 5461 if (Fn->getType() == Context.UnknownAnyTy) { 5462 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5463 if (result.isInvalid()) return ExprError(); 5464 Fn = result.get(); 5465 } 5466 5467 if (Fn->getType() == Context.BoundMemberTy) { 5468 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5469 RParenLoc); 5470 } 5471 } 5472 5473 // Check for overloaded calls. This can happen even in C due to extensions. 5474 if (Fn->getType() == Context.OverloadTy) { 5475 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5476 5477 // We aren't supposed to apply this logic if there's an '&' involved. 5478 if (!find.HasFormOfMemberPointer) { 5479 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5480 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5481 VK_RValue, RParenLoc); 5482 OverloadExpr *ovl = find.Expression; 5483 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5484 return BuildOverloadedCallExpr( 5485 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5486 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5487 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5488 RParenLoc); 5489 } 5490 } 5491 5492 // If we're directly calling a function, get the appropriate declaration. 5493 if (Fn->getType() == Context.UnknownAnyTy) { 5494 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5495 if (result.isInvalid()) return ExprError(); 5496 Fn = result.get(); 5497 } 5498 5499 Expr *NakedFn = Fn->IgnoreParens(); 5500 5501 bool CallingNDeclIndirectly = false; 5502 NamedDecl *NDecl = nullptr; 5503 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5504 if (UnOp->getOpcode() == UO_AddrOf) { 5505 CallingNDeclIndirectly = true; 5506 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5507 } 5508 } 5509 5510 if (isa<DeclRefExpr>(NakedFn)) { 5511 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5512 5513 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5514 if (FDecl && FDecl->getBuiltinID()) { 5515 // Rewrite the function decl for this builtin by replacing parameters 5516 // with no explicit address space with the address space of the arguments 5517 // in ArgExprs. 5518 if ((FDecl = 5519 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5520 NDecl = FDecl; 5521 Fn = DeclRefExpr::Create( 5522 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5523 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5524 } 5525 } 5526 } else if (isa<MemberExpr>(NakedFn)) 5527 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5528 5529 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5530 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5531 FD, /*Complain=*/true, Fn->getBeginLoc())) 5532 return ExprError(); 5533 5534 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5535 return ExprError(); 5536 5537 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5538 } 5539 5540 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5541 ExecConfig, IsExecConfig); 5542 } 5543 5544 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5545 /// 5546 /// __builtin_astype( value, dst type ) 5547 /// 5548 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5549 SourceLocation BuiltinLoc, 5550 SourceLocation RParenLoc) { 5551 ExprValueKind VK = VK_RValue; 5552 ExprObjectKind OK = OK_Ordinary; 5553 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5554 QualType SrcTy = E->getType(); 5555 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5556 return ExprError(Diag(BuiltinLoc, 5557 diag::err_invalid_astype_of_different_size) 5558 << DstTy 5559 << SrcTy 5560 << E->getSourceRange()); 5561 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5562 } 5563 5564 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5565 /// provided arguments. 5566 /// 5567 /// __builtin_convertvector( value, dst type ) 5568 /// 5569 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5570 SourceLocation BuiltinLoc, 5571 SourceLocation RParenLoc) { 5572 TypeSourceInfo *TInfo; 5573 GetTypeFromParser(ParsedDestTy, &TInfo); 5574 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5575 } 5576 5577 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5578 /// i.e. an expression not of \p OverloadTy. The expression should 5579 /// unary-convert to an expression of function-pointer or 5580 /// block-pointer type. 5581 /// 5582 /// \param NDecl the declaration being called, if available 5583 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5584 SourceLocation LParenLoc, 5585 ArrayRef<Expr *> Args, 5586 SourceLocation RParenLoc, Expr *Config, 5587 bool IsExecConfig, ADLCallKind UsesADL) { 5588 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5589 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5590 5591 // Functions with 'interrupt' attribute cannot be called directly. 5592 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5593 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5594 return ExprError(); 5595 } 5596 5597 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5598 // so there's some risk when calling out to non-interrupt handler functions 5599 // that the callee might not preserve them. This is easy to diagnose here, 5600 // but can be very challenging to debug. 5601 if (auto *Caller = getCurFunctionDecl()) 5602 if (Caller->hasAttr<ARMInterruptAttr>()) { 5603 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5604 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5605 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5606 } 5607 5608 // Promote the function operand. 5609 // We special-case function promotion here because we only allow promoting 5610 // builtin functions to function pointers in the callee of a call. 5611 ExprResult Result; 5612 QualType ResultTy; 5613 if (BuiltinID && 5614 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5615 // Extract the return type from the (builtin) function pointer type. 5616 // FIXME Several builtins still have setType in 5617 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5618 // Builtins.def to ensure they are correct before removing setType calls. 5619 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5620 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5621 ResultTy = FDecl->getCallResultType(); 5622 } else { 5623 Result = CallExprUnaryConversions(Fn); 5624 ResultTy = Context.BoolTy; 5625 } 5626 if (Result.isInvalid()) 5627 return ExprError(); 5628 Fn = Result.get(); 5629 5630 // Check for a valid function type, but only if it is not a builtin which 5631 // requires custom type checking. These will be handled by 5632 // CheckBuiltinFunctionCall below just after creation of the call expression. 5633 const FunctionType *FuncT = nullptr; 5634 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5635 retry: 5636 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5637 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5638 // have type pointer to function". 5639 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5640 if (!FuncT) 5641 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5642 << Fn->getType() << Fn->getSourceRange()); 5643 } else if (const BlockPointerType *BPT = 5644 Fn->getType()->getAs<BlockPointerType>()) { 5645 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5646 } else { 5647 // Handle calls to expressions of unknown-any type. 5648 if (Fn->getType() == Context.UnknownAnyTy) { 5649 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5650 if (rewrite.isInvalid()) return ExprError(); 5651 Fn = rewrite.get(); 5652 goto retry; 5653 } 5654 5655 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5656 << Fn->getType() << Fn->getSourceRange()); 5657 } 5658 } 5659 5660 // Get the number of parameters in the function prototype, if any. 5661 // We will allocate space for max(Args.size(), NumParams) arguments 5662 // in the call expression. 5663 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5664 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5665 5666 CallExpr *TheCall; 5667 if (Config) { 5668 assert(UsesADL == ADLCallKind::NotADL && 5669 "CUDAKernelCallExpr should not use ADL"); 5670 TheCall = 5671 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5672 ResultTy, VK_RValue, RParenLoc, NumParams); 5673 } else { 5674 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5675 RParenLoc, NumParams, UsesADL); 5676 } 5677 5678 if (!getLangOpts().CPlusPlus) { 5679 // Forget about the nulled arguments since typo correction 5680 // do not handle them well. 5681 TheCall->shrinkNumArgs(Args.size()); 5682 // C cannot always handle TypoExpr nodes in builtin calls and direct 5683 // function calls as their argument checking don't necessarily handle 5684 // dependent types properly, so make sure any TypoExprs have been 5685 // dealt with. 5686 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5687 if (!Result.isUsable()) return ExprError(); 5688 CallExpr *TheOldCall = TheCall; 5689 TheCall = dyn_cast<CallExpr>(Result.get()); 5690 bool CorrectedTypos = TheCall != TheOldCall; 5691 if (!TheCall) return Result; 5692 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5693 5694 // A new call expression node was created if some typos were corrected. 5695 // However it may not have been constructed with enough storage. In this 5696 // case, rebuild the node with enough storage. The waste of space is 5697 // immaterial since this only happens when some typos were corrected. 5698 if (CorrectedTypos && Args.size() < NumParams) { 5699 if (Config) 5700 TheCall = CUDAKernelCallExpr::Create( 5701 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5702 RParenLoc, NumParams); 5703 else 5704 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5705 RParenLoc, NumParams, UsesADL); 5706 } 5707 // We can now handle the nulled arguments for the default arguments. 5708 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 5709 } 5710 5711 // Bail out early if calling a builtin with custom type checking. 5712 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5713 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5714 5715 if (getLangOpts().CUDA) { 5716 if (Config) { 5717 // CUDA: Kernel calls must be to global functions 5718 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5719 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5720 << FDecl << Fn->getSourceRange()); 5721 5722 // CUDA: Kernel function must have 'void' return type 5723 if (!FuncT->getReturnType()->isVoidType()) 5724 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5725 << Fn->getType() << Fn->getSourceRange()); 5726 } else { 5727 // CUDA: Calls to global functions must be configured 5728 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5729 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5730 << FDecl << Fn->getSourceRange()); 5731 } 5732 } 5733 5734 // Check for a valid return type 5735 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5736 FDecl)) 5737 return ExprError(); 5738 5739 // We know the result type of the call, set it. 5740 TheCall->setType(FuncT->getCallResultType(Context)); 5741 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5742 5743 if (Proto) { 5744 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5745 IsExecConfig)) 5746 return ExprError(); 5747 } else { 5748 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5749 5750 if (FDecl) { 5751 // Check if we have too few/too many template arguments, based 5752 // on our knowledge of the function definition. 5753 const FunctionDecl *Def = nullptr; 5754 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5755 Proto = Def->getType()->getAs<FunctionProtoType>(); 5756 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5757 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5758 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5759 } 5760 5761 // If the function we're calling isn't a function prototype, but we have 5762 // a function prototype from a prior declaratiom, use that prototype. 5763 if (!FDecl->hasPrototype()) 5764 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5765 } 5766 5767 // Promote the arguments (C99 6.5.2.2p6). 5768 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5769 Expr *Arg = Args[i]; 5770 5771 if (Proto && i < Proto->getNumParams()) { 5772 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5773 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5774 ExprResult ArgE = 5775 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5776 if (ArgE.isInvalid()) 5777 return true; 5778 5779 Arg = ArgE.getAs<Expr>(); 5780 5781 } else { 5782 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5783 5784 if (ArgE.isInvalid()) 5785 return true; 5786 5787 Arg = ArgE.getAs<Expr>(); 5788 } 5789 5790 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5791 diag::err_call_incomplete_argument, Arg)) 5792 return ExprError(); 5793 5794 TheCall->setArg(i, Arg); 5795 } 5796 } 5797 5798 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5799 if (!Method->isStatic()) 5800 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5801 << Fn->getSourceRange()); 5802 5803 // Check for sentinels 5804 if (NDecl) 5805 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5806 5807 // Do special checking on direct calls to functions. 5808 if (FDecl) { 5809 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5810 return ExprError(); 5811 5812 if (BuiltinID) 5813 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5814 } else if (NDecl) { 5815 if (CheckPointerCall(NDecl, TheCall, Proto)) 5816 return ExprError(); 5817 } else { 5818 if (CheckOtherCall(TheCall, Proto)) 5819 return ExprError(); 5820 } 5821 5822 return MaybeBindToTemporary(TheCall); 5823 } 5824 5825 ExprResult 5826 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5827 SourceLocation RParenLoc, Expr *InitExpr) { 5828 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5829 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5830 5831 TypeSourceInfo *TInfo; 5832 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5833 if (!TInfo) 5834 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5835 5836 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5837 } 5838 5839 ExprResult 5840 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5841 SourceLocation RParenLoc, Expr *LiteralExpr) { 5842 QualType literalType = TInfo->getType(); 5843 5844 if (literalType->isArrayType()) { 5845 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5846 diag::err_illegal_decl_array_incomplete_type, 5847 SourceRange(LParenLoc, 5848 LiteralExpr->getSourceRange().getEnd()))) 5849 return ExprError(); 5850 if (literalType->isVariableArrayType()) 5851 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5852 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5853 } else if (!literalType->isDependentType() && 5854 RequireCompleteType(LParenLoc, literalType, 5855 diag::err_typecheck_decl_incomplete_type, 5856 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5857 return ExprError(); 5858 5859 InitializedEntity Entity 5860 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5861 InitializationKind Kind 5862 = InitializationKind::CreateCStyleCast(LParenLoc, 5863 SourceRange(LParenLoc, RParenLoc), 5864 /*InitList=*/true); 5865 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5866 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5867 &literalType); 5868 if (Result.isInvalid()) 5869 return ExprError(); 5870 LiteralExpr = Result.get(); 5871 5872 bool isFileScope = !CurContext->isFunctionOrMethod(); 5873 5874 // In C, compound literals are l-values for some reason. 5875 // For GCC compatibility, in C++, file-scope array compound literals with 5876 // constant initializers are also l-values, and compound literals are 5877 // otherwise prvalues. 5878 // 5879 // (GCC also treats C++ list-initialized file-scope array prvalues with 5880 // constant initializers as l-values, but that's non-conforming, so we don't 5881 // follow it there.) 5882 // 5883 // FIXME: It would be better to handle the lvalue cases as materializing and 5884 // lifetime-extending a temporary object, but our materialized temporaries 5885 // representation only supports lifetime extension from a variable, not "out 5886 // of thin air". 5887 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5888 // is bound to the result of applying array-to-pointer decay to the compound 5889 // literal. 5890 // FIXME: GCC supports compound literals of reference type, which should 5891 // obviously have a value kind derived from the kind of reference involved. 5892 ExprValueKind VK = 5893 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5894 ? VK_RValue 5895 : VK_LValue; 5896 5897 if (isFileScope) 5898 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 5899 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 5900 Expr *Init = ILE->getInit(i); 5901 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 5902 } 5903 5904 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5905 VK, LiteralExpr, isFileScope); 5906 if (isFileScope) { 5907 if (!LiteralExpr->isTypeDependent() && 5908 !LiteralExpr->isValueDependent() && 5909 !literalType->isDependentType()) // C99 6.5.2.5p3 5910 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5911 return ExprError(); 5912 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5913 literalType.getAddressSpace() != LangAS::Default) { 5914 // Embedded-C extensions to C99 6.5.2.5: 5915 // "If the compound literal occurs inside the body of a function, the 5916 // type name shall not be qualified by an address-space qualifier." 5917 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5918 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5919 return ExprError(); 5920 } 5921 5922 return MaybeBindToTemporary(E); 5923 } 5924 5925 ExprResult 5926 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5927 SourceLocation RBraceLoc) { 5928 // Immediately handle non-overload placeholders. Overloads can be 5929 // resolved contextually, but everything else here can't. 5930 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5931 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5932 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5933 5934 // Ignore failures; dropping the entire initializer list because 5935 // of one failure would be terrible for indexing/etc. 5936 if (result.isInvalid()) continue; 5937 5938 InitArgList[I] = result.get(); 5939 } 5940 } 5941 5942 // Semantic analysis for initializers is done by ActOnDeclarator() and 5943 // CheckInitializer() - it requires knowledge of the object being initialized. 5944 5945 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5946 RBraceLoc); 5947 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5948 return E; 5949 } 5950 5951 /// Do an explicit extend of the given block pointer if we're in ARC. 5952 void Sema::maybeExtendBlockObject(ExprResult &E) { 5953 assert(E.get()->getType()->isBlockPointerType()); 5954 assert(E.get()->isRValue()); 5955 5956 // Only do this in an r-value context. 5957 if (!getLangOpts().ObjCAutoRefCount) return; 5958 5959 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5960 CK_ARCExtendBlockObject, E.get(), 5961 /*base path*/ nullptr, VK_RValue); 5962 Cleanup.setExprNeedsCleanups(true); 5963 } 5964 5965 /// Prepare a conversion of the given expression to an ObjC object 5966 /// pointer type. 5967 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5968 QualType type = E.get()->getType(); 5969 if (type->isObjCObjectPointerType()) { 5970 return CK_BitCast; 5971 } else if (type->isBlockPointerType()) { 5972 maybeExtendBlockObject(E); 5973 return CK_BlockPointerToObjCPointerCast; 5974 } else { 5975 assert(type->isPointerType()); 5976 return CK_CPointerToObjCPointerCast; 5977 } 5978 } 5979 5980 /// Prepares for a scalar cast, performing all the necessary stages 5981 /// except the final cast and returning the kind required. 5982 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5983 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5984 // Also, callers should have filtered out the invalid cases with 5985 // pointers. Everything else should be possible. 5986 5987 QualType SrcTy = Src.get()->getType(); 5988 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5989 return CK_NoOp; 5990 5991 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5992 case Type::STK_MemberPointer: 5993 llvm_unreachable("member pointer type in C"); 5994 5995 case Type::STK_CPointer: 5996 case Type::STK_BlockPointer: 5997 case Type::STK_ObjCObjectPointer: 5998 switch (DestTy->getScalarTypeKind()) { 5999 case Type::STK_CPointer: { 6000 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6001 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6002 if (SrcAS != DestAS) 6003 return CK_AddressSpaceConversion; 6004 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6005 return CK_NoOp; 6006 return CK_BitCast; 6007 } 6008 case Type::STK_BlockPointer: 6009 return (SrcKind == Type::STK_BlockPointer 6010 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6011 case Type::STK_ObjCObjectPointer: 6012 if (SrcKind == Type::STK_ObjCObjectPointer) 6013 return CK_BitCast; 6014 if (SrcKind == Type::STK_CPointer) 6015 return CK_CPointerToObjCPointerCast; 6016 maybeExtendBlockObject(Src); 6017 return CK_BlockPointerToObjCPointerCast; 6018 case Type::STK_Bool: 6019 return CK_PointerToBoolean; 6020 case Type::STK_Integral: 6021 return CK_PointerToIntegral; 6022 case Type::STK_Floating: 6023 case Type::STK_FloatingComplex: 6024 case Type::STK_IntegralComplex: 6025 case Type::STK_MemberPointer: 6026 case Type::STK_FixedPoint: 6027 llvm_unreachable("illegal cast from pointer"); 6028 } 6029 llvm_unreachable("Should have returned before this"); 6030 6031 case Type::STK_FixedPoint: 6032 switch (DestTy->getScalarTypeKind()) { 6033 case Type::STK_FixedPoint: 6034 return CK_FixedPointCast; 6035 case Type::STK_Bool: 6036 return CK_FixedPointToBoolean; 6037 case Type::STK_Integral: 6038 case Type::STK_Floating: 6039 case Type::STK_IntegralComplex: 6040 case Type::STK_FloatingComplex: 6041 Diag(Src.get()->getExprLoc(), 6042 diag::err_unimplemented_conversion_with_fixed_point_type) 6043 << DestTy; 6044 return CK_IntegralCast; 6045 case Type::STK_CPointer: 6046 case Type::STK_ObjCObjectPointer: 6047 case Type::STK_BlockPointer: 6048 case Type::STK_MemberPointer: 6049 llvm_unreachable("illegal cast to pointer type"); 6050 } 6051 llvm_unreachable("Should have returned before this"); 6052 6053 case Type::STK_Bool: // casting from bool is like casting from an integer 6054 case Type::STK_Integral: 6055 switch (DestTy->getScalarTypeKind()) { 6056 case Type::STK_CPointer: 6057 case Type::STK_ObjCObjectPointer: 6058 case Type::STK_BlockPointer: 6059 if (Src.get()->isNullPointerConstant(Context, 6060 Expr::NPC_ValueDependentIsNull)) 6061 return CK_NullToPointer; 6062 return CK_IntegralToPointer; 6063 case Type::STK_Bool: 6064 return CK_IntegralToBoolean; 6065 case Type::STK_Integral: 6066 return CK_IntegralCast; 6067 case Type::STK_Floating: 6068 return CK_IntegralToFloating; 6069 case Type::STK_IntegralComplex: 6070 Src = ImpCastExprToType(Src.get(), 6071 DestTy->castAs<ComplexType>()->getElementType(), 6072 CK_IntegralCast); 6073 return CK_IntegralRealToComplex; 6074 case Type::STK_FloatingComplex: 6075 Src = ImpCastExprToType(Src.get(), 6076 DestTy->castAs<ComplexType>()->getElementType(), 6077 CK_IntegralToFloating); 6078 return CK_FloatingRealToComplex; 6079 case Type::STK_MemberPointer: 6080 llvm_unreachable("member pointer type in C"); 6081 case Type::STK_FixedPoint: 6082 Diag(Src.get()->getExprLoc(), 6083 diag::err_unimplemented_conversion_with_fixed_point_type) 6084 << SrcTy; 6085 return CK_IntegralCast; 6086 } 6087 llvm_unreachable("Should have returned before this"); 6088 6089 case Type::STK_Floating: 6090 switch (DestTy->getScalarTypeKind()) { 6091 case Type::STK_Floating: 6092 return CK_FloatingCast; 6093 case Type::STK_Bool: 6094 return CK_FloatingToBoolean; 6095 case Type::STK_Integral: 6096 return CK_FloatingToIntegral; 6097 case Type::STK_FloatingComplex: 6098 Src = ImpCastExprToType(Src.get(), 6099 DestTy->castAs<ComplexType>()->getElementType(), 6100 CK_FloatingCast); 6101 return CK_FloatingRealToComplex; 6102 case Type::STK_IntegralComplex: 6103 Src = ImpCastExprToType(Src.get(), 6104 DestTy->castAs<ComplexType>()->getElementType(), 6105 CK_FloatingToIntegral); 6106 return CK_IntegralRealToComplex; 6107 case Type::STK_CPointer: 6108 case Type::STK_ObjCObjectPointer: 6109 case Type::STK_BlockPointer: 6110 llvm_unreachable("valid float->pointer cast?"); 6111 case Type::STK_MemberPointer: 6112 llvm_unreachable("member pointer type in C"); 6113 case Type::STK_FixedPoint: 6114 Diag(Src.get()->getExprLoc(), 6115 diag::err_unimplemented_conversion_with_fixed_point_type) 6116 << SrcTy; 6117 return CK_IntegralCast; 6118 } 6119 llvm_unreachable("Should have returned before this"); 6120 6121 case Type::STK_FloatingComplex: 6122 switch (DestTy->getScalarTypeKind()) { 6123 case Type::STK_FloatingComplex: 6124 return CK_FloatingComplexCast; 6125 case Type::STK_IntegralComplex: 6126 return CK_FloatingComplexToIntegralComplex; 6127 case Type::STK_Floating: { 6128 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6129 if (Context.hasSameType(ET, DestTy)) 6130 return CK_FloatingComplexToReal; 6131 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6132 return CK_FloatingCast; 6133 } 6134 case Type::STK_Bool: 6135 return CK_FloatingComplexToBoolean; 6136 case Type::STK_Integral: 6137 Src = ImpCastExprToType(Src.get(), 6138 SrcTy->castAs<ComplexType>()->getElementType(), 6139 CK_FloatingComplexToReal); 6140 return CK_FloatingToIntegral; 6141 case Type::STK_CPointer: 6142 case Type::STK_ObjCObjectPointer: 6143 case Type::STK_BlockPointer: 6144 llvm_unreachable("valid complex float->pointer cast?"); 6145 case Type::STK_MemberPointer: 6146 llvm_unreachable("member pointer type in C"); 6147 case Type::STK_FixedPoint: 6148 Diag(Src.get()->getExprLoc(), 6149 diag::err_unimplemented_conversion_with_fixed_point_type) 6150 << SrcTy; 6151 return CK_IntegralCast; 6152 } 6153 llvm_unreachable("Should have returned before this"); 6154 6155 case Type::STK_IntegralComplex: 6156 switch (DestTy->getScalarTypeKind()) { 6157 case Type::STK_FloatingComplex: 6158 return CK_IntegralComplexToFloatingComplex; 6159 case Type::STK_IntegralComplex: 6160 return CK_IntegralComplexCast; 6161 case Type::STK_Integral: { 6162 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6163 if (Context.hasSameType(ET, DestTy)) 6164 return CK_IntegralComplexToReal; 6165 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6166 return CK_IntegralCast; 6167 } 6168 case Type::STK_Bool: 6169 return CK_IntegralComplexToBoolean; 6170 case Type::STK_Floating: 6171 Src = ImpCastExprToType(Src.get(), 6172 SrcTy->castAs<ComplexType>()->getElementType(), 6173 CK_IntegralComplexToReal); 6174 return CK_IntegralToFloating; 6175 case Type::STK_CPointer: 6176 case Type::STK_ObjCObjectPointer: 6177 case Type::STK_BlockPointer: 6178 llvm_unreachable("valid complex int->pointer cast?"); 6179 case Type::STK_MemberPointer: 6180 llvm_unreachable("member pointer type in C"); 6181 case Type::STK_FixedPoint: 6182 Diag(Src.get()->getExprLoc(), 6183 diag::err_unimplemented_conversion_with_fixed_point_type) 6184 << SrcTy; 6185 return CK_IntegralCast; 6186 } 6187 llvm_unreachable("Should have returned before this"); 6188 } 6189 6190 llvm_unreachable("Unhandled scalar cast"); 6191 } 6192 6193 static bool breakDownVectorType(QualType type, uint64_t &len, 6194 QualType &eltType) { 6195 // Vectors are simple. 6196 if (const VectorType *vecType = type->getAs<VectorType>()) { 6197 len = vecType->getNumElements(); 6198 eltType = vecType->getElementType(); 6199 assert(eltType->isScalarType()); 6200 return true; 6201 } 6202 6203 // We allow lax conversion to and from non-vector types, but only if 6204 // they're real types (i.e. non-complex, non-pointer scalar types). 6205 if (!type->isRealType()) return false; 6206 6207 len = 1; 6208 eltType = type; 6209 return true; 6210 } 6211 6212 /// Are the two types lax-compatible vector types? That is, given 6213 /// that one of them is a vector, do they have equal storage sizes, 6214 /// where the storage size is the number of elements times the element 6215 /// size? 6216 /// 6217 /// This will also return false if either of the types is neither a 6218 /// vector nor a real type. 6219 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6220 assert(destTy->isVectorType() || srcTy->isVectorType()); 6221 6222 // Disallow lax conversions between scalars and ExtVectors (these 6223 // conversions are allowed for other vector types because common headers 6224 // depend on them). Most scalar OP ExtVector cases are handled by the 6225 // splat path anyway, which does what we want (convert, not bitcast). 6226 // What this rules out for ExtVectors is crazy things like char4*float. 6227 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6228 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6229 6230 uint64_t srcLen, destLen; 6231 QualType srcEltTy, destEltTy; 6232 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6233 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6234 6235 // ASTContext::getTypeSize will return the size rounded up to a 6236 // power of 2, so instead of using that, we need to use the raw 6237 // element size multiplied by the element count. 6238 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6239 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6240 6241 return (srcLen * srcEltSize == destLen * destEltSize); 6242 } 6243 6244 /// Is this a legal conversion between two types, one of which is 6245 /// known to be a vector type? 6246 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6247 assert(destTy->isVectorType() || srcTy->isVectorType()); 6248 6249 if (!Context.getLangOpts().LaxVectorConversions) 6250 return false; 6251 return areLaxCompatibleVectorTypes(srcTy, destTy); 6252 } 6253 6254 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6255 CastKind &Kind) { 6256 assert(VectorTy->isVectorType() && "Not a vector type!"); 6257 6258 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6259 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6260 return Diag(R.getBegin(), 6261 Ty->isVectorType() ? 6262 diag::err_invalid_conversion_between_vectors : 6263 diag::err_invalid_conversion_between_vector_and_integer) 6264 << VectorTy << Ty << R; 6265 } else 6266 return Diag(R.getBegin(), 6267 diag::err_invalid_conversion_between_vector_and_scalar) 6268 << VectorTy << Ty << R; 6269 6270 Kind = CK_BitCast; 6271 return false; 6272 } 6273 6274 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6275 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6276 6277 if (DestElemTy == SplattedExpr->getType()) 6278 return SplattedExpr; 6279 6280 assert(DestElemTy->isFloatingType() || 6281 DestElemTy->isIntegralOrEnumerationType()); 6282 6283 CastKind CK; 6284 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6285 // OpenCL requires that we convert `true` boolean expressions to -1, but 6286 // only when splatting vectors. 6287 if (DestElemTy->isFloatingType()) { 6288 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6289 // in two steps: boolean to signed integral, then to floating. 6290 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6291 CK_BooleanToSignedIntegral); 6292 SplattedExpr = CastExprRes.get(); 6293 CK = CK_IntegralToFloating; 6294 } else { 6295 CK = CK_BooleanToSignedIntegral; 6296 } 6297 } else { 6298 ExprResult CastExprRes = SplattedExpr; 6299 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6300 if (CastExprRes.isInvalid()) 6301 return ExprError(); 6302 SplattedExpr = CastExprRes.get(); 6303 } 6304 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6305 } 6306 6307 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6308 Expr *CastExpr, CastKind &Kind) { 6309 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6310 6311 QualType SrcTy = CastExpr->getType(); 6312 6313 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6314 // an ExtVectorType. 6315 // In OpenCL, casts between vectors of different types are not allowed. 6316 // (See OpenCL 6.2). 6317 if (SrcTy->isVectorType()) { 6318 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6319 (getLangOpts().OpenCL && 6320 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6321 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6322 << DestTy << SrcTy << R; 6323 return ExprError(); 6324 } 6325 Kind = CK_BitCast; 6326 return CastExpr; 6327 } 6328 6329 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6330 // conversion will take place first from scalar to elt type, and then 6331 // splat from elt type to vector. 6332 if (SrcTy->isPointerType()) 6333 return Diag(R.getBegin(), 6334 diag::err_invalid_conversion_between_vector_and_scalar) 6335 << DestTy << SrcTy << R; 6336 6337 Kind = CK_VectorSplat; 6338 return prepareVectorSplat(DestTy, CastExpr); 6339 } 6340 6341 ExprResult 6342 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6343 Declarator &D, ParsedType &Ty, 6344 SourceLocation RParenLoc, Expr *CastExpr) { 6345 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6346 "ActOnCastExpr(): missing type or expr"); 6347 6348 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6349 if (D.isInvalidType()) 6350 return ExprError(); 6351 6352 if (getLangOpts().CPlusPlus) { 6353 // Check that there are no default arguments (C++ only). 6354 CheckExtraCXXDefaultArguments(D); 6355 } else { 6356 // Make sure any TypoExprs have been dealt with. 6357 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6358 if (!Res.isUsable()) 6359 return ExprError(); 6360 CastExpr = Res.get(); 6361 } 6362 6363 checkUnusedDeclAttributes(D); 6364 6365 QualType castType = castTInfo->getType(); 6366 Ty = CreateParsedType(castType, castTInfo); 6367 6368 bool isVectorLiteral = false; 6369 6370 // Check for an altivec or OpenCL literal, 6371 // i.e. all the elements are integer constants. 6372 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6373 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6374 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6375 && castType->isVectorType() && (PE || PLE)) { 6376 if (PLE && PLE->getNumExprs() == 0) { 6377 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6378 return ExprError(); 6379 } 6380 if (PE || PLE->getNumExprs() == 1) { 6381 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6382 if (!E->getType()->isVectorType()) 6383 isVectorLiteral = true; 6384 } 6385 else 6386 isVectorLiteral = true; 6387 } 6388 6389 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6390 // then handle it as such. 6391 if (isVectorLiteral) 6392 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6393 6394 // If the Expr being casted is a ParenListExpr, handle it specially. 6395 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6396 // sequence of BinOp comma operators. 6397 if (isa<ParenListExpr>(CastExpr)) { 6398 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6399 if (Result.isInvalid()) return ExprError(); 6400 CastExpr = Result.get(); 6401 } 6402 6403 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6404 !getSourceManager().isInSystemMacro(LParenLoc)) 6405 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6406 6407 CheckTollFreeBridgeCast(castType, CastExpr); 6408 6409 CheckObjCBridgeRelatedCast(castType, CastExpr); 6410 6411 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6412 6413 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6414 } 6415 6416 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6417 SourceLocation RParenLoc, Expr *E, 6418 TypeSourceInfo *TInfo) { 6419 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6420 "Expected paren or paren list expression"); 6421 6422 Expr **exprs; 6423 unsigned numExprs; 6424 Expr *subExpr; 6425 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6426 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6427 LiteralLParenLoc = PE->getLParenLoc(); 6428 LiteralRParenLoc = PE->getRParenLoc(); 6429 exprs = PE->getExprs(); 6430 numExprs = PE->getNumExprs(); 6431 } else { // isa<ParenExpr> by assertion at function entrance 6432 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6433 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6434 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6435 exprs = &subExpr; 6436 numExprs = 1; 6437 } 6438 6439 QualType Ty = TInfo->getType(); 6440 assert(Ty->isVectorType() && "Expected vector type"); 6441 6442 SmallVector<Expr *, 8> initExprs; 6443 const VectorType *VTy = Ty->getAs<VectorType>(); 6444 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6445 6446 // '(...)' form of vector initialization in AltiVec: the number of 6447 // initializers must be one or must match the size of the vector. 6448 // If a single value is specified in the initializer then it will be 6449 // replicated to all the components of the vector 6450 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6451 // The number of initializers must be one or must match the size of the 6452 // vector. If a single value is specified in the initializer then it will 6453 // be replicated to all the components of the vector 6454 if (numExprs == 1) { 6455 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6456 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6457 if (Literal.isInvalid()) 6458 return ExprError(); 6459 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6460 PrepareScalarCast(Literal, ElemTy)); 6461 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6462 } 6463 else if (numExprs < numElems) { 6464 Diag(E->getExprLoc(), 6465 diag::err_incorrect_number_of_vector_initializers); 6466 return ExprError(); 6467 } 6468 else 6469 initExprs.append(exprs, exprs + numExprs); 6470 } 6471 else { 6472 // For OpenCL, when the number of initializers is a single value, 6473 // it will be replicated to all components of the vector. 6474 if (getLangOpts().OpenCL && 6475 VTy->getVectorKind() == VectorType::GenericVector && 6476 numExprs == 1) { 6477 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6478 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6479 if (Literal.isInvalid()) 6480 return ExprError(); 6481 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6482 PrepareScalarCast(Literal, ElemTy)); 6483 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6484 } 6485 6486 initExprs.append(exprs, exprs + numExprs); 6487 } 6488 // FIXME: This means that pretty-printing the final AST will produce curly 6489 // braces instead of the original commas. 6490 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6491 initExprs, LiteralRParenLoc); 6492 initE->setType(Ty); 6493 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6494 } 6495 6496 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6497 /// the ParenListExpr into a sequence of comma binary operators. 6498 ExprResult 6499 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6500 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6501 if (!E) 6502 return OrigExpr; 6503 6504 ExprResult Result(E->getExpr(0)); 6505 6506 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6507 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6508 E->getExpr(i)); 6509 6510 if (Result.isInvalid()) return ExprError(); 6511 6512 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6513 } 6514 6515 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6516 SourceLocation R, 6517 MultiExprArg Val) { 6518 return ParenListExpr::Create(Context, L, Val, R); 6519 } 6520 6521 /// Emit a specialized diagnostic when one expression is a null pointer 6522 /// constant and the other is not a pointer. Returns true if a diagnostic is 6523 /// emitted. 6524 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6525 SourceLocation QuestionLoc) { 6526 Expr *NullExpr = LHSExpr; 6527 Expr *NonPointerExpr = RHSExpr; 6528 Expr::NullPointerConstantKind NullKind = 6529 NullExpr->isNullPointerConstant(Context, 6530 Expr::NPC_ValueDependentIsNotNull); 6531 6532 if (NullKind == Expr::NPCK_NotNull) { 6533 NullExpr = RHSExpr; 6534 NonPointerExpr = LHSExpr; 6535 NullKind = 6536 NullExpr->isNullPointerConstant(Context, 6537 Expr::NPC_ValueDependentIsNotNull); 6538 } 6539 6540 if (NullKind == Expr::NPCK_NotNull) 6541 return false; 6542 6543 if (NullKind == Expr::NPCK_ZeroExpression) 6544 return false; 6545 6546 if (NullKind == Expr::NPCK_ZeroLiteral) { 6547 // In this case, check to make sure that we got here from a "NULL" 6548 // string in the source code. 6549 NullExpr = NullExpr->IgnoreParenImpCasts(); 6550 SourceLocation loc = NullExpr->getExprLoc(); 6551 if (!findMacroSpelling(loc, "NULL")) 6552 return false; 6553 } 6554 6555 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6556 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6557 << NonPointerExpr->getType() << DiagType 6558 << NonPointerExpr->getSourceRange(); 6559 return true; 6560 } 6561 6562 /// Return false if the condition expression is valid, true otherwise. 6563 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6564 QualType CondTy = Cond->getType(); 6565 6566 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6567 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6568 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6569 << CondTy << Cond->getSourceRange(); 6570 return true; 6571 } 6572 6573 // C99 6.5.15p2 6574 if (CondTy->isScalarType()) return false; 6575 6576 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6577 << CondTy << Cond->getSourceRange(); 6578 return true; 6579 } 6580 6581 /// Handle when one or both operands are void type. 6582 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6583 ExprResult &RHS) { 6584 Expr *LHSExpr = LHS.get(); 6585 Expr *RHSExpr = RHS.get(); 6586 6587 if (!LHSExpr->getType()->isVoidType()) 6588 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6589 << RHSExpr->getSourceRange(); 6590 if (!RHSExpr->getType()->isVoidType()) 6591 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6592 << LHSExpr->getSourceRange(); 6593 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6594 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6595 return S.Context.VoidTy; 6596 } 6597 6598 /// Return false if the NullExpr can be promoted to PointerTy, 6599 /// true otherwise. 6600 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6601 QualType PointerTy) { 6602 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6603 !NullExpr.get()->isNullPointerConstant(S.Context, 6604 Expr::NPC_ValueDependentIsNull)) 6605 return true; 6606 6607 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6608 return false; 6609 } 6610 6611 /// Checks compatibility between two pointers and return the resulting 6612 /// type. 6613 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6614 ExprResult &RHS, 6615 SourceLocation Loc) { 6616 QualType LHSTy = LHS.get()->getType(); 6617 QualType RHSTy = RHS.get()->getType(); 6618 6619 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6620 // Two identical pointers types are always compatible. 6621 return LHSTy; 6622 } 6623 6624 QualType lhptee, rhptee; 6625 6626 // Get the pointee types. 6627 bool IsBlockPointer = false; 6628 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6629 lhptee = LHSBTy->getPointeeType(); 6630 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6631 IsBlockPointer = true; 6632 } else { 6633 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6634 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6635 } 6636 6637 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6638 // differently qualified versions of compatible types, the result type is 6639 // a pointer to an appropriately qualified version of the composite 6640 // type. 6641 6642 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6643 // clause doesn't make sense for our extensions. E.g. address space 2 should 6644 // be incompatible with address space 3: they may live on different devices or 6645 // anything. 6646 Qualifiers lhQual = lhptee.getQualifiers(); 6647 Qualifiers rhQual = rhptee.getQualifiers(); 6648 6649 LangAS ResultAddrSpace = LangAS::Default; 6650 LangAS LAddrSpace = lhQual.getAddressSpace(); 6651 LangAS RAddrSpace = rhQual.getAddressSpace(); 6652 6653 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6654 // spaces is disallowed. 6655 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6656 ResultAddrSpace = LAddrSpace; 6657 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6658 ResultAddrSpace = RAddrSpace; 6659 else { 6660 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6661 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6662 << RHS.get()->getSourceRange(); 6663 return QualType(); 6664 } 6665 6666 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6667 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6668 lhQual.removeCVRQualifiers(); 6669 rhQual.removeCVRQualifiers(); 6670 6671 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6672 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6673 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6674 // qual types are compatible iff 6675 // * corresponded types are compatible 6676 // * CVR qualifiers are equal 6677 // * address spaces are equal 6678 // Thus for conditional operator we merge CVR and address space unqualified 6679 // pointees and if there is a composite type we return a pointer to it with 6680 // merged qualifiers. 6681 LHSCastKind = 6682 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6683 RHSCastKind = 6684 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6685 lhQual.removeAddressSpace(); 6686 rhQual.removeAddressSpace(); 6687 6688 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6689 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6690 6691 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6692 6693 if (CompositeTy.isNull()) { 6694 // In this situation, we assume void* type. No especially good 6695 // reason, but this is what gcc does, and we do have to pick 6696 // to get a consistent AST. 6697 QualType incompatTy; 6698 incompatTy = S.Context.getPointerType( 6699 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6700 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6701 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6702 6703 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6704 // for casts between types with incompatible address space qualifiers. 6705 // For the following code the compiler produces casts between global and 6706 // local address spaces of the corresponded innermost pointees: 6707 // local int *global *a; 6708 // global int *global *b; 6709 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6710 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6711 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6712 << RHS.get()->getSourceRange(); 6713 6714 return incompatTy; 6715 } 6716 6717 // The pointer types are compatible. 6718 // In case of OpenCL ResultTy should have the address space qualifier 6719 // which is a superset of address spaces of both the 2nd and the 3rd 6720 // operands of the conditional operator. 6721 QualType ResultTy = [&, ResultAddrSpace]() { 6722 if (S.getLangOpts().OpenCL) { 6723 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6724 CompositeQuals.setAddressSpace(ResultAddrSpace); 6725 return S.Context 6726 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6727 .withCVRQualifiers(MergedCVRQual); 6728 } 6729 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6730 }(); 6731 if (IsBlockPointer) 6732 ResultTy = S.Context.getBlockPointerType(ResultTy); 6733 else 6734 ResultTy = S.Context.getPointerType(ResultTy); 6735 6736 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6737 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6738 return ResultTy; 6739 } 6740 6741 /// Return the resulting type when the operands are both block pointers. 6742 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6743 ExprResult &LHS, 6744 ExprResult &RHS, 6745 SourceLocation Loc) { 6746 QualType LHSTy = LHS.get()->getType(); 6747 QualType RHSTy = RHS.get()->getType(); 6748 6749 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6750 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6751 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6752 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6753 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6754 return destType; 6755 } 6756 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6757 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6758 << RHS.get()->getSourceRange(); 6759 return QualType(); 6760 } 6761 6762 // We have 2 block pointer types. 6763 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6764 } 6765 6766 /// Return the resulting type when the operands are both pointers. 6767 static QualType 6768 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6769 ExprResult &RHS, 6770 SourceLocation Loc) { 6771 // get the pointer types 6772 QualType LHSTy = LHS.get()->getType(); 6773 QualType RHSTy = RHS.get()->getType(); 6774 6775 // get the "pointed to" types 6776 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6777 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6778 6779 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6780 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6781 // Figure out necessary qualifiers (C99 6.5.15p6) 6782 QualType destPointee 6783 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6784 QualType destType = S.Context.getPointerType(destPointee); 6785 // Add qualifiers if necessary. 6786 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6787 // Promote to void*. 6788 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6789 return destType; 6790 } 6791 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6792 QualType destPointee 6793 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6794 QualType destType = S.Context.getPointerType(destPointee); 6795 // Add qualifiers if necessary. 6796 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6797 // Promote to void*. 6798 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6799 return destType; 6800 } 6801 6802 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6803 } 6804 6805 /// Return false if the first expression is not an integer and the second 6806 /// expression is not a pointer, true otherwise. 6807 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6808 Expr* PointerExpr, SourceLocation Loc, 6809 bool IsIntFirstExpr) { 6810 if (!PointerExpr->getType()->isPointerType() || 6811 !Int.get()->getType()->isIntegerType()) 6812 return false; 6813 6814 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6815 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6816 6817 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6818 << Expr1->getType() << Expr2->getType() 6819 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6820 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6821 CK_IntegralToPointer); 6822 return true; 6823 } 6824 6825 /// Simple conversion between integer and floating point types. 6826 /// 6827 /// Used when handling the OpenCL conditional operator where the 6828 /// condition is a vector while the other operands are scalar. 6829 /// 6830 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6831 /// types are either integer or floating type. Between the two 6832 /// operands, the type with the higher rank is defined as the "result 6833 /// type". The other operand needs to be promoted to the same type. No 6834 /// other type promotion is allowed. We cannot use 6835 /// UsualArithmeticConversions() for this purpose, since it always 6836 /// promotes promotable types. 6837 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6838 ExprResult &RHS, 6839 SourceLocation QuestionLoc) { 6840 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6841 if (LHS.isInvalid()) 6842 return QualType(); 6843 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6844 if (RHS.isInvalid()) 6845 return QualType(); 6846 6847 // For conversion purposes, we ignore any qualifiers. 6848 // For example, "const float" and "float" are equivalent. 6849 QualType LHSType = 6850 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6851 QualType RHSType = 6852 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6853 6854 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6855 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6856 << LHSType << LHS.get()->getSourceRange(); 6857 return QualType(); 6858 } 6859 6860 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6861 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6862 << RHSType << RHS.get()->getSourceRange(); 6863 return QualType(); 6864 } 6865 6866 // If both types are identical, no conversion is needed. 6867 if (LHSType == RHSType) 6868 return LHSType; 6869 6870 // Now handle "real" floating types (i.e. float, double, long double). 6871 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6872 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6873 /*IsCompAssign = */ false); 6874 6875 // Finally, we have two differing integer types. 6876 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6877 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6878 } 6879 6880 /// Convert scalar operands to a vector that matches the 6881 /// condition in length. 6882 /// 6883 /// Used when handling the OpenCL conditional operator where the 6884 /// condition is a vector while the other operands are scalar. 6885 /// 6886 /// We first compute the "result type" for the scalar operands 6887 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6888 /// into a vector of that type where the length matches the condition 6889 /// vector type. s6.11.6 requires that the element types of the result 6890 /// and the condition must have the same number of bits. 6891 static QualType 6892 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6893 QualType CondTy, SourceLocation QuestionLoc) { 6894 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6895 if (ResTy.isNull()) return QualType(); 6896 6897 const VectorType *CV = CondTy->getAs<VectorType>(); 6898 assert(CV); 6899 6900 // Determine the vector result type 6901 unsigned NumElements = CV->getNumElements(); 6902 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6903 6904 // Ensure that all types have the same number of bits 6905 if (S.Context.getTypeSize(CV->getElementType()) 6906 != S.Context.getTypeSize(ResTy)) { 6907 // Since VectorTy is created internally, it does not pretty print 6908 // with an OpenCL name. Instead, we just print a description. 6909 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6910 SmallString<64> Str; 6911 llvm::raw_svector_ostream OS(Str); 6912 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6913 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6914 << CondTy << OS.str(); 6915 return QualType(); 6916 } 6917 6918 // Convert operands to the vector result type 6919 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6920 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6921 6922 return VectorTy; 6923 } 6924 6925 /// Return false if this is a valid OpenCL condition vector 6926 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6927 SourceLocation QuestionLoc) { 6928 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6929 // integral type. 6930 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6931 assert(CondTy); 6932 QualType EleTy = CondTy->getElementType(); 6933 if (EleTy->isIntegerType()) return false; 6934 6935 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6936 << Cond->getType() << Cond->getSourceRange(); 6937 return true; 6938 } 6939 6940 /// Return false if the vector condition type and the vector 6941 /// result type are compatible. 6942 /// 6943 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6944 /// number of elements, and their element types have the same number 6945 /// of bits. 6946 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6947 SourceLocation QuestionLoc) { 6948 const VectorType *CV = CondTy->getAs<VectorType>(); 6949 const VectorType *RV = VecResTy->getAs<VectorType>(); 6950 assert(CV && RV); 6951 6952 if (CV->getNumElements() != RV->getNumElements()) { 6953 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6954 << CondTy << VecResTy; 6955 return true; 6956 } 6957 6958 QualType CVE = CV->getElementType(); 6959 QualType RVE = RV->getElementType(); 6960 6961 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6962 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6963 << CondTy << VecResTy; 6964 return true; 6965 } 6966 6967 return false; 6968 } 6969 6970 /// Return the resulting type for the conditional operator in 6971 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6972 /// s6.3.i) when the condition is a vector type. 6973 static QualType 6974 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6975 ExprResult &LHS, ExprResult &RHS, 6976 SourceLocation QuestionLoc) { 6977 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6978 if (Cond.isInvalid()) 6979 return QualType(); 6980 QualType CondTy = Cond.get()->getType(); 6981 6982 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6983 return QualType(); 6984 6985 // If either operand is a vector then find the vector type of the 6986 // result as specified in OpenCL v1.1 s6.3.i. 6987 if (LHS.get()->getType()->isVectorType() || 6988 RHS.get()->getType()->isVectorType()) { 6989 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6990 /*isCompAssign*/false, 6991 /*AllowBothBool*/true, 6992 /*AllowBoolConversions*/false); 6993 if (VecResTy.isNull()) return QualType(); 6994 // The result type must match the condition type as specified in 6995 // OpenCL v1.1 s6.11.6. 6996 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6997 return QualType(); 6998 return VecResTy; 6999 } 7000 7001 // Both operands are scalar. 7002 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7003 } 7004 7005 /// Return true if the Expr is block type 7006 static bool checkBlockType(Sema &S, const Expr *E) { 7007 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7008 QualType Ty = CE->getCallee()->getType(); 7009 if (Ty->isBlockPointerType()) { 7010 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7011 return true; 7012 } 7013 } 7014 return false; 7015 } 7016 7017 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7018 /// In that case, LHS = cond. 7019 /// C99 6.5.15 7020 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7021 ExprResult &RHS, ExprValueKind &VK, 7022 ExprObjectKind &OK, 7023 SourceLocation QuestionLoc) { 7024 7025 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7026 if (!LHSResult.isUsable()) return QualType(); 7027 LHS = LHSResult; 7028 7029 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7030 if (!RHSResult.isUsable()) return QualType(); 7031 RHS = RHSResult; 7032 7033 // C++ is sufficiently different to merit its own checker. 7034 if (getLangOpts().CPlusPlus) 7035 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7036 7037 VK = VK_RValue; 7038 OK = OK_Ordinary; 7039 7040 // The OpenCL operator with a vector condition is sufficiently 7041 // different to merit its own checker. 7042 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7043 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7044 7045 // First, check the condition. 7046 Cond = UsualUnaryConversions(Cond.get()); 7047 if (Cond.isInvalid()) 7048 return QualType(); 7049 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7050 return QualType(); 7051 7052 // Now check the two expressions. 7053 if (LHS.get()->getType()->isVectorType() || 7054 RHS.get()->getType()->isVectorType()) 7055 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7056 /*AllowBothBool*/true, 7057 /*AllowBoolConversions*/false); 7058 7059 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 7060 if (LHS.isInvalid() || RHS.isInvalid()) 7061 return QualType(); 7062 7063 QualType LHSTy = LHS.get()->getType(); 7064 QualType RHSTy = RHS.get()->getType(); 7065 7066 // Diagnose attempts to convert between __float128 and long double where 7067 // such conversions currently can't be handled. 7068 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7069 Diag(QuestionLoc, 7070 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7071 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7072 return QualType(); 7073 } 7074 7075 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7076 // selection operator (?:). 7077 if (getLangOpts().OpenCL && 7078 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7079 return QualType(); 7080 } 7081 7082 // If both operands have arithmetic type, do the usual arithmetic conversions 7083 // to find a common type: C99 6.5.15p3,5. 7084 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7085 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7086 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7087 7088 return ResTy; 7089 } 7090 7091 // If both operands are the same structure or union type, the result is that 7092 // type. 7093 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7094 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7095 if (LHSRT->getDecl() == RHSRT->getDecl()) 7096 // "If both the operands have structure or union type, the result has 7097 // that type." This implies that CV qualifiers are dropped. 7098 return LHSTy.getUnqualifiedType(); 7099 // FIXME: Type of conditional expression must be complete in C mode. 7100 } 7101 7102 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7103 // The following || allows only one side to be void (a GCC-ism). 7104 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7105 return checkConditionalVoidType(*this, LHS, RHS); 7106 } 7107 7108 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7109 // the type of the other operand." 7110 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7111 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7112 7113 // All objective-c pointer type analysis is done here. 7114 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7115 QuestionLoc); 7116 if (LHS.isInvalid() || RHS.isInvalid()) 7117 return QualType(); 7118 if (!compositeType.isNull()) 7119 return compositeType; 7120 7121 7122 // Handle block pointer types. 7123 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7124 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7125 QuestionLoc); 7126 7127 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7128 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7129 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7130 QuestionLoc); 7131 7132 // GCC compatibility: soften pointer/integer mismatch. Note that 7133 // null pointers have been filtered out by this point. 7134 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7135 /*isIntFirstExpr=*/true)) 7136 return RHSTy; 7137 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7138 /*isIntFirstExpr=*/false)) 7139 return LHSTy; 7140 7141 // Emit a better diagnostic if one of the expressions is a null pointer 7142 // constant and the other is not a pointer type. In this case, the user most 7143 // likely forgot to take the address of the other expression. 7144 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7145 return QualType(); 7146 7147 // Otherwise, the operands are not compatible. 7148 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7149 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7150 << RHS.get()->getSourceRange(); 7151 return QualType(); 7152 } 7153 7154 /// FindCompositeObjCPointerType - Helper method to find composite type of 7155 /// two objective-c pointer types of the two input expressions. 7156 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7157 SourceLocation QuestionLoc) { 7158 QualType LHSTy = LHS.get()->getType(); 7159 QualType RHSTy = RHS.get()->getType(); 7160 7161 // Handle things like Class and struct objc_class*. Here we case the result 7162 // to the pseudo-builtin, because that will be implicitly cast back to the 7163 // redefinition type if an attempt is made to access its fields. 7164 if (LHSTy->isObjCClassType() && 7165 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7166 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7167 return LHSTy; 7168 } 7169 if (RHSTy->isObjCClassType() && 7170 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7171 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7172 return RHSTy; 7173 } 7174 // And the same for struct objc_object* / id 7175 if (LHSTy->isObjCIdType() && 7176 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7177 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7178 return LHSTy; 7179 } 7180 if (RHSTy->isObjCIdType() && 7181 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7182 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7183 return RHSTy; 7184 } 7185 // And the same for struct objc_selector* / SEL 7186 if (Context.isObjCSelType(LHSTy) && 7187 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7188 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7189 return LHSTy; 7190 } 7191 if (Context.isObjCSelType(RHSTy) && 7192 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7193 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7194 return RHSTy; 7195 } 7196 // Check constraints for Objective-C object pointers types. 7197 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7198 7199 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7200 // Two identical object pointer types are always compatible. 7201 return LHSTy; 7202 } 7203 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7204 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7205 QualType compositeType = LHSTy; 7206 7207 // If both operands are interfaces and either operand can be 7208 // assigned to the other, use that type as the composite 7209 // type. This allows 7210 // xxx ? (A*) a : (B*) b 7211 // where B is a subclass of A. 7212 // 7213 // Additionally, as for assignment, if either type is 'id' 7214 // allow silent coercion. Finally, if the types are 7215 // incompatible then make sure to use 'id' as the composite 7216 // type so the result is acceptable for sending messages to. 7217 7218 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7219 // It could return the composite type. 7220 if (!(compositeType = 7221 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7222 // Nothing more to do. 7223 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7224 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7225 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7226 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7227 } else if ((LHSTy->isObjCQualifiedIdType() || 7228 RHSTy->isObjCQualifiedIdType()) && 7229 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7230 // Need to handle "id<xx>" explicitly. 7231 // GCC allows qualified id and any Objective-C type to devolve to 7232 // id. Currently localizing to here until clear this should be 7233 // part of ObjCQualifiedIdTypesAreCompatible. 7234 compositeType = Context.getObjCIdType(); 7235 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7236 compositeType = Context.getObjCIdType(); 7237 } else { 7238 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7239 << LHSTy << RHSTy 7240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7241 QualType incompatTy = Context.getObjCIdType(); 7242 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7243 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7244 return incompatTy; 7245 } 7246 // The object pointer types are compatible. 7247 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7248 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7249 return compositeType; 7250 } 7251 // Check Objective-C object pointer types and 'void *' 7252 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7253 if (getLangOpts().ObjCAutoRefCount) { 7254 // ARC forbids the implicit conversion of object pointers to 'void *', 7255 // so these types are not compatible. 7256 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7257 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7258 LHS = RHS = true; 7259 return QualType(); 7260 } 7261 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7262 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7263 QualType destPointee 7264 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7265 QualType destType = Context.getPointerType(destPointee); 7266 // Add qualifiers if necessary. 7267 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7268 // Promote to void*. 7269 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7270 return destType; 7271 } 7272 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7273 if (getLangOpts().ObjCAutoRefCount) { 7274 // ARC forbids the implicit conversion of object pointers to 'void *', 7275 // so these types are not compatible. 7276 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7278 LHS = RHS = true; 7279 return QualType(); 7280 } 7281 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7282 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7283 QualType destPointee 7284 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7285 QualType destType = Context.getPointerType(destPointee); 7286 // Add qualifiers if necessary. 7287 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7288 // Promote to void*. 7289 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7290 return destType; 7291 } 7292 return QualType(); 7293 } 7294 7295 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7296 /// ParenRange in parentheses. 7297 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7298 const PartialDiagnostic &Note, 7299 SourceRange ParenRange) { 7300 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7301 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7302 EndLoc.isValid()) { 7303 Self.Diag(Loc, Note) 7304 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7305 << FixItHint::CreateInsertion(EndLoc, ")"); 7306 } else { 7307 // We can't display the parentheses, so just show the bare note. 7308 Self.Diag(Loc, Note) << ParenRange; 7309 } 7310 } 7311 7312 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7313 return BinaryOperator::isAdditiveOp(Opc) || 7314 BinaryOperator::isMultiplicativeOp(Opc) || 7315 BinaryOperator::isShiftOp(Opc); 7316 } 7317 7318 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7319 /// expression, either using a built-in or overloaded operator, 7320 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7321 /// expression. 7322 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7323 Expr **RHSExprs) { 7324 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7325 E = E->IgnoreImpCasts(); 7326 E = E->IgnoreConversionOperator(); 7327 E = E->IgnoreImpCasts(); 7328 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7329 E = MTE->GetTemporaryExpr(); 7330 E = E->IgnoreImpCasts(); 7331 } 7332 7333 // Built-in binary operator. 7334 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7335 if (IsArithmeticOp(OP->getOpcode())) { 7336 *Opcode = OP->getOpcode(); 7337 *RHSExprs = OP->getRHS(); 7338 return true; 7339 } 7340 } 7341 7342 // Overloaded operator. 7343 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7344 if (Call->getNumArgs() != 2) 7345 return false; 7346 7347 // Make sure this is really a binary operator that is safe to pass into 7348 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7349 OverloadedOperatorKind OO = Call->getOperator(); 7350 if (OO < OO_Plus || OO > OO_Arrow || 7351 OO == OO_PlusPlus || OO == OO_MinusMinus) 7352 return false; 7353 7354 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7355 if (IsArithmeticOp(OpKind)) { 7356 *Opcode = OpKind; 7357 *RHSExprs = Call->getArg(1); 7358 return true; 7359 } 7360 } 7361 7362 return false; 7363 } 7364 7365 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7366 /// or is a logical expression such as (x==y) which has int type, but is 7367 /// commonly interpreted as boolean. 7368 static bool ExprLooksBoolean(Expr *E) { 7369 E = E->IgnoreParenImpCasts(); 7370 7371 if (E->getType()->isBooleanType()) 7372 return true; 7373 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7374 return OP->isComparisonOp() || OP->isLogicalOp(); 7375 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7376 return OP->getOpcode() == UO_LNot; 7377 if (E->getType()->isPointerType()) 7378 return true; 7379 // FIXME: What about overloaded operator calls returning "unspecified boolean 7380 // type"s (commonly pointer-to-members)? 7381 7382 return false; 7383 } 7384 7385 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7386 /// and binary operator are mixed in a way that suggests the programmer assumed 7387 /// the conditional operator has higher precedence, for example: 7388 /// "int x = a + someBinaryCondition ? 1 : 2". 7389 static void DiagnoseConditionalPrecedence(Sema &Self, 7390 SourceLocation OpLoc, 7391 Expr *Condition, 7392 Expr *LHSExpr, 7393 Expr *RHSExpr) { 7394 BinaryOperatorKind CondOpcode; 7395 Expr *CondRHS; 7396 7397 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7398 return; 7399 if (!ExprLooksBoolean(CondRHS)) 7400 return; 7401 7402 // The condition is an arithmetic binary expression, with a right- 7403 // hand side that looks boolean, so warn. 7404 7405 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7406 << Condition->getSourceRange() 7407 << BinaryOperator::getOpcodeStr(CondOpcode); 7408 7409 SuggestParentheses( 7410 Self, OpLoc, 7411 Self.PDiag(diag::note_precedence_silence) 7412 << BinaryOperator::getOpcodeStr(CondOpcode), 7413 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7414 7415 SuggestParentheses(Self, OpLoc, 7416 Self.PDiag(diag::note_precedence_conditional_first), 7417 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7418 } 7419 7420 /// Compute the nullability of a conditional expression. 7421 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7422 QualType LHSTy, QualType RHSTy, 7423 ASTContext &Ctx) { 7424 if (!ResTy->isAnyPointerType()) 7425 return ResTy; 7426 7427 auto GetNullability = [&Ctx](QualType Ty) { 7428 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7429 if (Kind) 7430 return *Kind; 7431 return NullabilityKind::Unspecified; 7432 }; 7433 7434 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7435 NullabilityKind MergedKind; 7436 7437 // Compute nullability of a binary conditional expression. 7438 if (IsBin) { 7439 if (LHSKind == NullabilityKind::NonNull) 7440 MergedKind = NullabilityKind::NonNull; 7441 else 7442 MergedKind = RHSKind; 7443 // Compute nullability of a normal conditional expression. 7444 } else { 7445 if (LHSKind == NullabilityKind::Nullable || 7446 RHSKind == NullabilityKind::Nullable) 7447 MergedKind = NullabilityKind::Nullable; 7448 else if (LHSKind == NullabilityKind::NonNull) 7449 MergedKind = RHSKind; 7450 else if (RHSKind == NullabilityKind::NonNull) 7451 MergedKind = LHSKind; 7452 else 7453 MergedKind = NullabilityKind::Unspecified; 7454 } 7455 7456 // Return if ResTy already has the correct nullability. 7457 if (GetNullability(ResTy) == MergedKind) 7458 return ResTy; 7459 7460 // Strip all nullability from ResTy. 7461 while (ResTy->getNullability(Ctx)) 7462 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7463 7464 // Create a new AttributedType with the new nullability kind. 7465 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7466 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7467 } 7468 7469 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7470 /// in the case of a the GNU conditional expr extension. 7471 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7472 SourceLocation ColonLoc, 7473 Expr *CondExpr, Expr *LHSExpr, 7474 Expr *RHSExpr) { 7475 if (!getLangOpts().CPlusPlus) { 7476 // C cannot handle TypoExpr nodes in the condition because it 7477 // doesn't handle dependent types properly, so make sure any TypoExprs have 7478 // been dealt with before checking the operands. 7479 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7480 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7481 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7482 7483 if (!CondResult.isUsable()) 7484 return ExprError(); 7485 7486 if (LHSExpr) { 7487 if (!LHSResult.isUsable()) 7488 return ExprError(); 7489 } 7490 7491 if (!RHSResult.isUsable()) 7492 return ExprError(); 7493 7494 CondExpr = CondResult.get(); 7495 LHSExpr = LHSResult.get(); 7496 RHSExpr = RHSResult.get(); 7497 } 7498 7499 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7500 // was the condition. 7501 OpaqueValueExpr *opaqueValue = nullptr; 7502 Expr *commonExpr = nullptr; 7503 if (!LHSExpr) { 7504 commonExpr = CondExpr; 7505 // Lower out placeholder types first. This is important so that we don't 7506 // try to capture a placeholder. This happens in few cases in C++; such 7507 // as Objective-C++'s dictionary subscripting syntax. 7508 if (commonExpr->hasPlaceholderType()) { 7509 ExprResult result = CheckPlaceholderExpr(commonExpr); 7510 if (!result.isUsable()) return ExprError(); 7511 commonExpr = result.get(); 7512 } 7513 // We usually want to apply unary conversions *before* saving, except 7514 // in the special case of a C++ l-value conditional. 7515 if (!(getLangOpts().CPlusPlus 7516 && !commonExpr->isTypeDependent() 7517 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7518 && commonExpr->isGLValue() 7519 && commonExpr->isOrdinaryOrBitFieldObject() 7520 && RHSExpr->isOrdinaryOrBitFieldObject() 7521 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7522 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7523 if (commonRes.isInvalid()) 7524 return ExprError(); 7525 commonExpr = commonRes.get(); 7526 } 7527 7528 // If the common expression is a class or array prvalue, materialize it 7529 // so that we can safely refer to it multiple times. 7530 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7531 commonExpr->getType()->isArrayType())) { 7532 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7533 if (MatExpr.isInvalid()) 7534 return ExprError(); 7535 commonExpr = MatExpr.get(); 7536 } 7537 7538 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7539 commonExpr->getType(), 7540 commonExpr->getValueKind(), 7541 commonExpr->getObjectKind(), 7542 commonExpr); 7543 LHSExpr = CondExpr = opaqueValue; 7544 } 7545 7546 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7547 ExprValueKind VK = VK_RValue; 7548 ExprObjectKind OK = OK_Ordinary; 7549 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7550 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7551 VK, OK, QuestionLoc); 7552 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7553 RHS.isInvalid()) 7554 return ExprError(); 7555 7556 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7557 RHS.get()); 7558 7559 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7560 7561 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7562 Context); 7563 7564 if (!commonExpr) 7565 return new (Context) 7566 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7567 RHS.get(), result, VK, OK); 7568 7569 return new (Context) BinaryConditionalOperator( 7570 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7571 ColonLoc, result, VK, OK); 7572 } 7573 7574 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7575 // being closely modeled after the C99 spec:-). The odd characteristic of this 7576 // routine is it effectively iqnores the qualifiers on the top level pointee. 7577 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7578 // FIXME: add a couple examples in this comment. 7579 static Sema::AssignConvertType 7580 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7581 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7582 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7583 7584 // get the "pointed to" type (ignoring qualifiers at the top level) 7585 const Type *lhptee, *rhptee; 7586 Qualifiers lhq, rhq; 7587 std::tie(lhptee, lhq) = 7588 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7589 std::tie(rhptee, rhq) = 7590 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7591 7592 Sema::AssignConvertType ConvTy = Sema::Compatible; 7593 7594 // C99 6.5.16.1p1: This following citation is common to constraints 7595 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7596 // qualifiers of the type *pointed to* by the right; 7597 7598 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7599 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7600 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7601 // Ignore lifetime for further calculation. 7602 lhq.removeObjCLifetime(); 7603 rhq.removeObjCLifetime(); 7604 } 7605 7606 if (!lhq.compatiblyIncludes(rhq)) { 7607 // Treat address-space mismatches as fatal. TODO: address subspaces 7608 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7609 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7610 7611 // It's okay to add or remove GC or lifetime qualifiers when converting to 7612 // and from void*. 7613 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7614 .compatiblyIncludes( 7615 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7616 && (lhptee->isVoidType() || rhptee->isVoidType())) 7617 ; // keep old 7618 7619 // Treat lifetime mismatches as fatal. 7620 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7621 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7622 7623 // For GCC/MS compatibility, other qualifier mismatches are treated 7624 // as still compatible in C. 7625 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7626 } 7627 7628 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7629 // incomplete type and the other is a pointer to a qualified or unqualified 7630 // version of void... 7631 if (lhptee->isVoidType()) { 7632 if (rhptee->isIncompleteOrObjectType()) 7633 return ConvTy; 7634 7635 // As an extension, we allow cast to/from void* to function pointer. 7636 assert(rhptee->isFunctionType()); 7637 return Sema::FunctionVoidPointer; 7638 } 7639 7640 if (rhptee->isVoidType()) { 7641 if (lhptee->isIncompleteOrObjectType()) 7642 return ConvTy; 7643 7644 // As an extension, we allow cast to/from void* to function pointer. 7645 assert(lhptee->isFunctionType()); 7646 return Sema::FunctionVoidPointer; 7647 } 7648 7649 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7650 // unqualified versions of compatible types, ... 7651 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7652 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7653 // Check if the pointee types are compatible ignoring the sign. 7654 // We explicitly check for char so that we catch "char" vs 7655 // "unsigned char" on systems where "char" is unsigned. 7656 if (lhptee->isCharType()) 7657 ltrans = S.Context.UnsignedCharTy; 7658 else if (lhptee->hasSignedIntegerRepresentation()) 7659 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7660 7661 if (rhptee->isCharType()) 7662 rtrans = S.Context.UnsignedCharTy; 7663 else if (rhptee->hasSignedIntegerRepresentation()) 7664 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7665 7666 if (ltrans == rtrans) { 7667 // Types are compatible ignoring the sign. Qualifier incompatibility 7668 // takes priority over sign incompatibility because the sign 7669 // warning can be disabled. 7670 if (ConvTy != Sema::Compatible) 7671 return ConvTy; 7672 7673 return Sema::IncompatiblePointerSign; 7674 } 7675 7676 // If we are a multi-level pointer, it's possible that our issue is simply 7677 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7678 // the eventual target type is the same and the pointers have the same 7679 // level of indirection, this must be the issue. 7680 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7681 do { 7682 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7683 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7684 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7685 7686 if (lhptee == rhptee) 7687 return Sema::IncompatibleNestedPointerQualifiers; 7688 } 7689 7690 // General pointer incompatibility takes priority over qualifiers. 7691 return Sema::IncompatiblePointer; 7692 } 7693 if (!S.getLangOpts().CPlusPlus && 7694 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7695 return Sema::IncompatiblePointer; 7696 return ConvTy; 7697 } 7698 7699 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7700 /// block pointer types are compatible or whether a block and normal pointer 7701 /// are compatible. It is more restrict than comparing two function pointer 7702 // types. 7703 static Sema::AssignConvertType 7704 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7705 QualType RHSType) { 7706 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7707 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7708 7709 QualType lhptee, rhptee; 7710 7711 // get the "pointed to" type (ignoring qualifiers at the top level) 7712 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7713 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7714 7715 // In C++, the types have to match exactly. 7716 if (S.getLangOpts().CPlusPlus) 7717 return Sema::IncompatibleBlockPointer; 7718 7719 Sema::AssignConvertType ConvTy = Sema::Compatible; 7720 7721 // For blocks we enforce that qualifiers are identical. 7722 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7723 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7724 if (S.getLangOpts().OpenCL) { 7725 LQuals.removeAddressSpace(); 7726 RQuals.removeAddressSpace(); 7727 } 7728 if (LQuals != RQuals) 7729 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7730 7731 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7732 // assignment. 7733 // The current behavior is similar to C++ lambdas. A block might be 7734 // assigned to a variable iff its return type and parameters are compatible 7735 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7736 // an assignment. Presumably it should behave in way that a function pointer 7737 // assignment does in C, so for each parameter and return type: 7738 // * CVR and address space of LHS should be a superset of CVR and address 7739 // space of RHS. 7740 // * unqualified types should be compatible. 7741 if (S.getLangOpts().OpenCL) { 7742 if (!S.Context.typesAreBlockPointerCompatible( 7743 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7744 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7745 return Sema::IncompatibleBlockPointer; 7746 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7747 return Sema::IncompatibleBlockPointer; 7748 7749 return ConvTy; 7750 } 7751 7752 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7753 /// for assignment compatibility. 7754 static Sema::AssignConvertType 7755 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7756 QualType RHSType) { 7757 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7758 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7759 7760 if (LHSType->isObjCBuiltinType()) { 7761 // Class is not compatible with ObjC object pointers. 7762 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7763 !RHSType->isObjCQualifiedClassType()) 7764 return Sema::IncompatiblePointer; 7765 return Sema::Compatible; 7766 } 7767 if (RHSType->isObjCBuiltinType()) { 7768 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7769 !LHSType->isObjCQualifiedClassType()) 7770 return Sema::IncompatiblePointer; 7771 return Sema::Compatible; 7772 } 7773 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7774 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7775 7776 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7777 // make an exception for id<P> 7778 !LHSType->isObjCQualifiedIdType()) 7779 return Sema::CompatiblePointerDiscardsQualifiers; 7780 7781 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7782 return Sema::Compatible; 7783 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7784 return Sema::IncompatibleObjCQualifiedId; 7785 return Sema::IncompatiblePointer; 7786 } 7787 7788 Sema::AssignConvertType 7789 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7790 QualType LHSType, QualType RHSType) { 7791 // Fake up an opaque expression. We don't actually care about what 7792 // cast operations are required, so if CheckAssignmentConstraints 7793 // adds casts to this they'll be wasted, but fortunately that doesn't 7794 // usually happen on valid code. 7795 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7796 ExprResult RHSPtr = &RHSExpr; 7797 CastKind K; 7798 7799 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7800 } 7801 7802 /// This helper function returns true if QT is a vector type that has element 7803 /// type ElementType. 7804 static bool isVector(QualType QT, QualType ElementType) { 7805 if (const VectorType *VT = QT->getAs<VectorType>()) 7806 return VT->getElementType() == ElementType; 7807 return false; 7808 } 7809 7810 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7811 /// has code to accommodate several GCC extensions when type checking 7812 /// pointers. Here are some objectionable examples that GCC considers warnings: 7813 /// 7814 /// int a, *pint; 7815 /// short *pshort; 7816 /// struct foo *pfoo; 7817 /// 7818 /// pint = pshort; // warning: assignment from incompatible pointer type 7819 /// a = pint; // warning: assignment makes integer from pointer without a cast 7820 /// pint = a; // warning: assignment makes pointer from integer without a cast 7821 /// pint = pfoo; // warning: assignment from incompatible pointer type 7822 /// 7823 /// As a result, the code for dealing with pointers is more complex than the 7824 /// C99 spec dictates. 7825 /// 7826 /// Sets 'Kind' for any result kind except Incompatible. 7827 Sema::AssignConvertType 7828 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7829 CastKind &Kind, bool ConvertRHS) { 7830 QualType RHSType = RHS.get()->getType(); 7831 QualType OrigLHSType = LHSType; 7832 7833 // Get canonical types. We're not formatting these types, just comparing 7834 // them. 7835 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7836 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7837 7838 // Common case: no conversion required. 7839 if (LHSType == RHSType) { 7840 Kind = CK_NoOp; 7841 return Compatible; 7842 } 7843 7844 // If we have an atomic type, try a non-atomic assignment, then just add an 7845 // atomic qualification step. 7846 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7847 Sema::AssignConvertType result = 7848 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7849 if (result != Compatible) 7850 return result; 7851 if (Kind != CK_NoOp && ConvertRHS) 7852 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7853 Kind = CK_NonAtomicToAtomic; 7854 return Compatible; 7855 } 7856 7857 // If the left-hand side is a reference type, then we are in a 7858 // (rare!) case where we've allowed the use of references in C, 7859 // e.g., as a parameter type in a built-in function. In this case, 7860 // just make sure that the type referenced is compatible with the 7861 // right-hand side type. The caller is responsible for adjusting 7862 // LHSType so that the resulting expression does not have reference 7863 // type. 7864 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7865 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7866 Kind = CK_LValueBitCast; 7867 return Compatible; 7868 } 7869 return Incompatible; 7870 } 7871 7872 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7873 // to the same ExtVector type. 7874 if (LHSType->isExtVectorType()) { 7875 if (RHSType->isExtVectorType()) 7876 return Incompatible; 7877 if (RHSType->isArithmeticType()) { 7878 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7879 if (ConvertRHS) 7880 RHS = prepareVectorSplat(LHSType, RHS.get()); 7881 Kind = CK_VectorSplat; 7882 return Compatible; 7883 } 7884 } 7885 7886 // Conversions to or from vector type. 7887 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7888 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7889 // Allow assignments of an AltiVec vector type to an equivalent GCC 7890 // vector type and vice versa 7891 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7892 Kind = CK_BitCast; 7893 return Compatible; 7894 } 7895 7896 // If we are allowing lax vector conversions, and LHS and RHS are both 7897 // vectors, the total size only needs to be the same. This is a bitcast; 7898 // no bits are changed but the result type is different. 7899 if (isLaxVectorConversion(RHSType, LHSType)) { 7900 Kind = CK_BitCast; 7901 return IncompatibleVectors; 7902 } 7903 } 7904 7905 // When the RHS comes from another lax conversion (e.g. binops between 7906 // scalars and vectors) the result is canonicalized as a vector. When the 7907 // LHS is also a vector, the lax is allowed by the condition above. Handle 7908 // the case where LHS is a scalar. 7909 if (LHSType->isScalarType()) { 7910 const VectorType *VecType = RHSType->getAs<VectorType>(); 7911 if (VecType && VecType->getNumElements() == 1 && 7912 isLaxVectorConversion(RHSType, LHSType)) { 7913 ExprResult *VecExpr = &RHS; 7914 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7915 Kind = CK_BitCast; 7916 return Compatible; 7917 } 7918 } 7919 7920 return Incompatible; 7921 } 7922 7923 // Diagnose attempts to convert between __float128 and long double where 7924 // such conversions currently can't be handled. 7925 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7926 return Incompatible; 7927 7928 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7929 // discards the imaginary part. 7930 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7931 !LHSType->getAs<ComplexType>()) 7932 return Incompatible; 7933 7934 // Arithmetic conversions. 7935 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7936 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7937 if (ConvertRHS) 7938 Kind = PrepareScalarCast(RHS, LHSType); 7939 return Compatible; 7940 } 7941 7942 // Conversions to normal pointers. 7943 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7944 // U* -> T* 7945 if (isa<PointerType>(RHSType)) { 7946 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7947 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7948 if (AddrSpaceL != AddrSpaceR) 7949 Kind = CK_AddressSpaceConversion; 7950 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 7951 Kind = CK_NoOp; 7952 else 7953 Kind = CK_BitCast; 7954 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7955 } 7956 7957 // int -> T* 7958 if (RHSType->isIntegerType()) { 7959 Kind = CK_IntegralToPointer; // FIXME: null? 7960 return IntToPointer; 7961 } 7962 7963 // C pointers are not compatible with ObjC object pointers, 7964 // with two exceptions: 7965 if (isa<ObjCObjectPointerType>(RHSType)) { 7966 // - conversions to void* 7967 if (LHSPointer->getPointeeType()->isVoidType()) { 7968 Kind = CK_BitCast; 7969 return Compatible; 7970 } 7971 7972 // - conversions from 'Class' to the redefinition type 7973 if (RHSType->isObjCClassType() && 7974 Context.hasSameType(LHSType, 7975 Context.getObjCClassRedefinitionType())) { 7976 Kind = CK_BitCast; 7977 return Compatible; 7978 } 7979 7980 Kind = CK_BitCast; 7981 return IncompatiblePointer; 7982 } 7983 7984 // U^ -> void* 7985 if (RHSType->getAs<BlockPointerType>()) { 7986 if (LHSPointer->getPointeeType()->isVoidType()) { 7987 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7988 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7989 ->getPointeeType() 7990 .getAddressSpace(); 7991 Kind = 7992 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7993 return Compatible; 7994 } 7995 } 7996 7997 return Incompatible; 7998 } 7999 8000 // Conversions to block pointers. 8001 if (isa<BlockPointerType>(LHSType)) { 8002 // U^ -> T^ 8003 if (RHSType->isBlockPointerType()) { 8004 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8005 ->getPointeeType() 8006 .getAddressSpace(); 8007 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8008 ->getPointeeType() 8009 .getAddressSpace(); 8010 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8011 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8012 } 8013 8014 // int or null -> T^ 8015 if (RHSType->isIntegerType()) { 8016 Kind = CK_IntegralToPointer; // FIXME: null 8017 return IntToBlockPointer; 8018 } 8019 8020 // id -> T^ 8021 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8022 Kind = CK_AnyPointerToBlockPointerCast; 8023 return Compatible; 8024 } 8025 8026 // void* -> T^ 8027 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8028 if (RHSPT->getPointeeType()->isVoidType()) { 8029 Kind = CK_AnyPointerToBlockPointerCast; 8030 return Compatible; 8031 } 8032 8033 return Incompatible; 8034 } 8035 8036 // Conversions to Objective-C pointers. 8037 if (isa<ObjCObjectPointerType>(LHSType)) { 8038 // A* -> B* 8039 if (RHSType->isObjCObjectPointerType()) { 8040 Kind = CK_BitCast; 8041 Sema::AssignConvertType result = 8042 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8043 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8044 result == Compatible && 8045 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8046 result = IncompatibleObjCWeakRef; 8047 return result; 8048 } 8049 8050 // int or null -> A* 8051 if (RHSType->isIntegerType()) { 8052 Kind = CK_IntegralToPointer; // FIXME: null 8053 return IntToPointer; 8054 } 8055 8056 // In general, C pointers are not compatible with ObjC object pointers, 8057 // with two exceptions: 8058 if (isa<PointerType>(RHSType)) { 8059 Kind = CK_CPointerToObjCPointerCast; 8060 8061 // - conversions from 'void*' 8062 if (RHSType->isVoidPointerType()) { 8063 return Compatible; 8064 } 8065 8066 // - conversions to 'Class' from its redefinition type 8067 if (LHSType->isObjCClassType() && 8068 Context.hasSameType(RHSType, 8069 Context.getObjCClassRedefinitionType())) { 8070 return Compatible; 8071 } 8072 8073 return IncompatiblePointer; 8074 } 8075 8076 // Only under strict condition T^ is compatible with an Objective-C pointer. 8077 if (RHSType->isBlockPointerType() && 8078 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8079 if (ConvertRHS) 8080 maybeExtendBlockObject(RHS); 8081 Kind = CK_BlockPointerToObjCPointerCast; 8082 return Compatible; 8083 } 8084 8085 return Incompatible; 8086 } 8087 8088 // Conversions from pointers that are not covered by the above. 8089 if (isa<PointerType>(RHSType)) { 8090 // T* -> _Bool 8091 if (LHSType == Context.BoolTy) { 8092 Kind = CK_PointerToBoolean; 8093 return Compatible; 8094 } 8095 8096 // T* -> int 8097 if (LHSType->isIntegerType()) { 8098 Kind = CK_PointerToIntegral; 8099 return PointerToInt; 8100 } 8101 8102 return Incompatible; 8103 } 8104 8105 // Conversions from Objective-C pointers that are not covered by the above. 8106 if (isa<ObjCObjectPointerType>(RHSType)) { 8107 // T* -> _Bool 8108 if (LHSType == Context.BoolTy) { 8109 Kind = CK_PointerToBoolean; 8110 return Compatible; 8111 } 8112 8113 // T* -> int 8114 if (LHSType->isIntegerType()) { 8115 Kind = CK_PointerToIntegral; 8116 return PointerToInt; 8117 } 8118 8119 return Incompatible; 8120 } 8121 8122 // struct A -> struct B 8123 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8124 if (Context.typesAreCompatible(LHSType, RHSType)) { 8125 Kind = CK_NoOp; 8126 return Compatible; 8127 } 8128 } 8129 8130 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8131 Kind = CK_IntToOCLSampler; 8132 return Compatible; 8133 } 8134 8135 return Incompatible; 8136 } 8137 8138 /// Constructs a transparent union from an expression that is 8139 /// used to initialize the transparent union. 8140 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8141 ExprResult &EResult, QualType UnionType, 8142 FieldDecl *Field) { 8143 // Build an initializer list that designates the appropriate member 8144 // of the transparent union. 8145 Expr *E = EResult.get(); 8146 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8147 E, SourceLocation()); 8148 Initializer->setType(UnionType); 8149 Initializer->setInitializedFieldInUnion(Field); 8150 8151 // Build a compound literal constructing a value of the transparent 8152 // union type from this initializer list. 8153 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8154 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8155 VK_RValue, Initializer, false); 8156 } 8157 8158 Sema::AssignConvertType 8159 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8160 ExprResult &RHS) { 8161 QualType RHSType = RHS.get()->getType(); 8162 8163 // If the ArgType is a Union type, we want to handle a potential 8164 // transparent_union GCC extension. 8165 const RecordType *UT = ArgType->getAsUnionType(); 8166 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8167 return Incompatible; 8168 8169 // The field to initialize within the transparent union. 8170 RecordDecl *UD = UT->getDecl(); 8171 FieldDecl *InitField = nullptr; 8172 // It's compatible if the expression matches any of the fields. 8173 for (auto *it : UD->fields()) { 8174 if (it->getType()->isPointerType()) { 8175 // If the transparent union contains a pointer type, we allow: 8176 // 1) void pointer 8177 // 2) null pointer constant 8178 if (RHSType->isPointerType()) 8179 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8180 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8181 InitField = it; 8182 break; 8183 } 8184 8185 if (RHS.get()->isNullPointerConstant(Context, 8186 Expr::NPC_ValueDependentIsNull)) { 8187 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8188 CK_NullToPointer); 8189 InitField = it; 8190 break; 8191 } 8192 } 8193 8194 CastKind Kind; 8195 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8196 == Compatible) { 8197 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8198 InitField = it; 8199 break; 8200 } 8201 } 8202 8203 if (!InitField) 8204 return Incompatible; 8205 8206 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8207 return Compatible; 8208 } 8209 8210 Sema::AssignConvertType 8211 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8212 bool Diagnose, 8213 bool DiagnoseCFAudited, 8214 bool ConvertRHS) { 8215 // We need to be able to tell the caller whether we diagnosed a problem, if 8216 // they ask us to issue diagnostics. 8217 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8218 8219 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8220 // we can't avoid *all* modifications at the moment, so we need some somewhere 8221 // to put the updated value. 8222 ExprResult LocalRHS = CallerRHS; 8223 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8224 8225 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8226 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8227 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8228 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8229 Diag(RHS.get()->getExprLoc(), 8230 diag::warn_noderef_to_dereferenceable_pointer) 8231 << RHS.get()->getSourceRange(); 8232 } 8233 } 8234 } 8235 8236 if (getLangOpts().CPlusPlus) { 8237 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8238 // C++ 5.17p3: If the left operand is not of class type, the 8239 // expression is implicitly converted (C++ 4) to the 8240 // cv-unqualified type of the left operand. 8241 QualType RHSType = RHS.get()->getType(); 8242 if (Diagnose) { 8243 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8244 AA_Assigning); 8245 } else { 8246 ImplicitConversionSequence ICS = 8247 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8248 /*SuppressUserConversions=*/false, 8249 /*AllowExplicit=*/false, 8250 /*InOverloadResolution=*/false, 8251 /*CStyle=*/false, 8252 /*AllowObjCWritebackConversion=*/false); 8253 if (ICS.isFailure()) 8254 return Incompatible; 8255 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8256 ICS, AA_Assigning); 8257 } 8258 if (RHS.isInvalid()) 8259 return Incompatible; 8260 Sema::AssignConvertType result = Compatible; 8261 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8262 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8263 result = IncompatibleObjCWeakRef; 8264 return result; 8265 } 8266 8267 // FIXME: Currently, we fall through and treat C++ classes like C 8268 // structures. 8269 // FIXME: We also fall through for atomics; not sure what should 8270 // happen there, though. 8271 } else if (RHS.get()->getType() == Context.OverloadTy) { 8272 // As a set of extensions to C, we support overloading on functions. These 8273 // functions need to be resolved here. 8274 DeclAccessPair DAP; 8275 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8276 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8277 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8278 else 8279 return Incompatible; 8280 } 8281 8282 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8283 // a null pointer constant. 8284 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8285 LHSType->isBlockPointerType()) && 8286 RHS.get()->isNullPointerConstant(Context, 8287 Expr::NPC_ValueDependentIsNull)) { 8288 if (Diagnose || ConvertRHS) { 8289 CastKind Kind; 8290 CXXCastPath Path; 8291 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8292 /*IgnoreBaseAccess=*/false, Diagnose); 8293 if (ConvertRHS) 8294 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8295 } 8296 return Compatible; 8297 } 8298 8299 // OpenCL queue_t type assignment. 8300 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8301 Context, Expr::NPC_ValueDependentIsNull)) { 8302 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8303 return Compatible; 8304 } 8305 8306 // This check seems unnatural, however it is necessary to ensure the proper 8307 // conversion of functions/arrays. If the conversion were done for all 8308 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8309 // expressions that suppress this implicit conversion (&, sizeof). 8310 // 8311 // Suppress this for references: C++ 8.5.3p5. 8312 if (!LHSType->isReferenceType()) { 8313 // FIXME: We potentially allocate here even if ConvertRHS is false. 8314 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8315 if (RHS.isInvalid()) 8316 return Incompatible; 8317 } 8318 CastKind Kind; 8319 Sema::AssignConvertType result = 8320 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8321 8322 // C99 6.5.16.1p2: The value of the right operand is converted to the 8323 // type of the assignment expression. 8324 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8325 // so that we can use references in built-in functions even in C. 8326 // The getNonReferenceType() call makes sure that the resulting expression 8327 // does not have reference type. 8328 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8329 QualType Ty = LHSType.getNonLValueExprType(Context); 8330 Expr *E = RHS.get(); 8331 8332 // Check for various Objective-C errors. If we are not reporting 8333 // diagnostics and just checking for errors, e.g., during overload 8334 // resolution, return Incompatible to indicate the failure. 8335 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8336 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8337 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8338 if (!Diagnose) 8339 return Incompatible; 8340 } 8341 if (getLangOpts().ObjC && 8342 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8343 E->getType(), E, Diagnose) || 8344 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8345 if (!Diagnose) 8346 return Incompatible; 8347 // Replace the expression with a corrected version and continue so we 8348 // can find further errors. 8349 RHS = E; 8350 return Compatible; 8351 } 8352 8353 if (ConvertRHS) 8354 RHS = ImpCastExprToType(E, Ty, Kind); 8355 } 8356 8357 return result; 8358 } 8359 8360 namespace { 8361 /// The original operand to an operator, prior to the application of the usual 8362 /// arithmetic conversions and converting the arguments of a builtin operator 8363 /// candidate. 8364 struct OriginalOperand { 8365 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8366 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8367 Op = MTE->GetTemporaryExpr(); 8368 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8369 Op = BTE->getSubExpr(); 8370 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8371 Orig = ICE->getSubExprAsWritten(); 8372 Conversion = ICE->getConversionFunction(); 8373 } 8374 } 8375 8376 QualType getType() const { return Orig->getType(); } 8377 8378 Expr *Orig; 8379 NamedDecl *Conversion; 8380 }; 8381 } 8382 8383 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8384 ExprResult &RHS) { 8385 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8386 8387 Diag(Loc, diag::err_typecheck_invalid_operands) 8388 << OrigLHS.getType() << OrigRHS.getType() 8389 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8390 8391 // If a user-defined conversion was applied to either of the operands prior 8392 // to applying the built-in operator rules, tell the user about it. 8393 if (OrigLHS.Conversion) { 8394 Diag(OrigLHS.Conversion->getLocation(), 8395 diag::note_typecheck_invalid_operands_converted) 8396 << 0 << LHS.get()->getType(); 8397 } 8398 if (OrigRHS.Conversion) { 8399 Diag(OrigRHS.Conversion->getLocation(), 8400 diag::note_typecheck_invalid_operands_converted) 8401 << 1 << RHS.get()->getType(); 8402 } 8403 8404 return QualType(); 8405 } 8406 8407 // Diagnose cases where a scalar was implicitly converted to a vector and 8408 // diagnose the underlying types. Otherwise, diagnose the error 8409 // as invalid vector logical operands for non-C++ cases. 8410 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8411 ExprResult &RHS) { 8412 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8413 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8414 8415 bool LHSNatVec = LHSType->isVectorType(); 8416 bool RHSNatVec = RHSType->isVectorType(); 8417 8418 if (!(LHSNatVec && RHSNatVec)) { 8419 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8420 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8421 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8422 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8423 << Vector->getSourceRange(); 8424 return QualType(); 8425 } 8426 8427 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8428 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8429 << RHS.get()->getSourceRange(); 8430 8431 return QualType(); 8432 } 8433 8434 /// Try to convert a value of non-vector type to a vector type by converting 8435 /// the type to the element type of the vector and then performing a splat. 8436 /// If the language is OpenCL, we only use conversions that promote scalar 8437 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8438 /// for float->int. 8439 /// 8440 /// OpenCL V2.0 6.2.6.p2: 8441 /// An error shall occur if any scalar operand type has greater rank 8442 /// than the type of the vector element. 8443 /// 8444 /// \param scalar - if non-null, actually perform the conversions 8445 /// \return true if the operation fails (but without diagnosing the failure) 8446 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8447 QualType scalarTy, 8448 QualType vectorEltTy, 8449 QualType vectorTy, 8450 unsigned &DiagID) { 8451 // The conversion to apply to the scalar before splatting it, 8452 // if necessary. 8453 CastKind scalarCast = CK_NoOp; 8454 8455 if (vectorEltTy->isIntegralType(S.Context)) { 8456 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8457 (scalarTy->isIntegerType() && 8458 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8459 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8460 return true; 8461 } 8462 if (!scalarTy->isIntegralType(S.Context)) 8463 return true; 8464 scalarCast = CK_IntegralCast; 8465 } else if (vectorEltTy->isRealFloatingType()) { 8466 if (scalarTy->isRealFloatingType()) { 8467 if (S.getLangOpts().OpenCL && 8468 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8469 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8470 return true; 8471 } 8472 scalarCast = CK_FloatingCast; 8473 } 8474 else if (scalarTy->isIntegralType(S.Context)) 8475 scalarCast = CK_IntegralToFloating; 8476 else 8477 return true; 8478 } else { 8479 return true; 8480 } 8481 8482 // Adjust scalar if desired. 8483 if (scalar) { 8484 if (scalarCast != CK_NoOp) 8485 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8486 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8487 } 8488 return false; 8489 } 8490 8491 /// Convert vector E to a vector with the same number of elements but different 8492 /// element type. 8493 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8494 const auto *VecTy = E->getType()->getAs<VectorType>(); 8495 assert(VecTy && "Expression E must be a vector"); 8496 QualType NewVecTy = S.Context.getVectorType(ElementType, 8497 VecTy->getNumElements(), 8498 VecTy->getVectorKind()); 8499 8500 // Look through the implicit cast. Return the subexpression if its type is 8501 // NewVecTy. 8502 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8503 if (ICE->getSubExpr()->getType() == NewVecTy) 8504 return ICE->getSubExpr(); 8505 8506 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8507 return S.ImpCastExprToType(E, NewVecTy, Cast); 8508 } 8509 8510 /// Test if a (constant) integer Int can be casted to another integer type 8511 /// IntTy without losing precision. 8512 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8513 QualType OtherIntTy) { 8514 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8515 8516 // Reject cases where the value of the Int is unknown as that would 8517 // possibly cause truncation, but accept cases where the scalar can be 8518 // demoted without loss of precision. 8519 Expr::EvalResult EVResult; 8520 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8521 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8522 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8523 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8524 8525 if (CstInt) { 8526 // If the scalar is constant and is of a higher order and has more active 8527 // bits that the vector element type, reject it. 8528 llvm::APSInt Result = EVResult.Val.getInt(); 8529 unsigned NumBits = IntSigned 8530 ? (Result.isNegative() ? Result.getMinSignedBits() 8531 : Result.getActiveBits()) 8532 : Result.getActiveBits(); 8533 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8534 return true; 8535 8536 // If the signedness of the scalar type and the vector element type 8537 // differs and the number of bits is greater than that of the vector 8538 // element reject it. 8539 return (IntSigned != OtherIntSigned && 8540 NumBits > S.Context.getIntWidth(OtherIntTy)); 8541 } 8542 8543 // Reject cases where the value of the scalar is not constant and it's 8544 // order is greater than that of the vector element type. 8545 return (Order < 0); 8546 } 8547 8548 /// Test if a (constant) integer Int can be casted to floating point type 8549 /// FloatTy without losing precision. 8550 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8551 QualType FloatTy) { 8552 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8553 8554 // Determine if the integer constant can be expressed as a floating point 8555 // number of the appropriate type. 8556 Expr::EvalResult EVResult; 8557 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8558 8559 uint64_t Bits = 0; 8560 if (CstInt) { 8561 // Reject constants that would be truncated if they were converted to 8562 // the floating point type. Test by simple to/from conversion. 8563 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8564 // could be avoided if there was a convertFromAPInt method 8565 // which could signal back if implicit truncation occurred. 8566 llvm::APSInt Result = EVResult.Val.getInt(); 8567 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8568 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8569 llvm::APFloat::rmTowardZero); 8570 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8571 !IntTy->hasSignedIntegerRepresentation()); 8572 bool Ignored = false; 8573 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8574 &Ignored); 8575 if (Result != ConvertBack) 8576 return true; 8577 } else { 8578 // Reject types that cannot be fully encoded into the mantissa of 8579 // the float. 8580 Bits = S.Context.getTypeSize(IntTy); 8581 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8582 S.Context.getFloatTypeSemantics(FloatTy)); 8583 if (Bits > FloatPrec) 8584 return true; 8585 } 8586 8587 return false; 8588 } 8589 8590 /// Attempt to convert and splat Scalar into a vector whose types matches 8591 /// Vector following GCC conversion rules. The rule is that implicit 8592 /// conversion can occur when Scalar can be casted to match Vector's element 8593 /// type without causing truncation of Scalar. 8594 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8595 ExprResult *Vector) { 8596 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8597 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8598 const VectorType *VT = VectorTy->getAs<VectorType>(); 8599 8600 assert(!isa<ExtVectorType>(VT) && 8601 "ExtVectorTypes should not be handled here!"); 8602 8603 QualType VectorEltTy = VT->getElementType(); 8604 8605 // Reject cases where the vector element type or the scalar element type are 8606 // not integral or floating point types. 8607 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8608 return true; 8609 8610 // The conversion to apply to the scalar before splatting it, 8611 // if necessary. 8612 CastKind ScalarCast = CK_NoOp; 8613 8614 // Accept cases where the vector elements are integers and the scalar is 8615 // an integer. 8616 // FIXME: Notionally if the scalar was a floating point value with a precise 8617 // integral representation, we could cast it to an appropriate integer 8618 // type and then perform the rest of the checks here. GCC will perform 8619 // this conversion in some cases as determined by the input language. 8620 // We should accept it on a language independent basis. 8621 if (VectorEltTy->isIntegralType(S.Context) && 8622 ScalarTy->isIntegralType(S.Context) && 8623 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8624 8625 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8626 return true; 8627 8628 ScalarCast = CK_IntegralCast; 8629 } else if (VectorEltTy->isRealFloatingType()) { 8630 if (ScalarTy->isRealFloatingType()) { 8631 8632 // Reject cases where the scalar type is not a constant and has a higher 8633 // Order than the vector element type. 8634 llvm::APFloat Result(0.0); 8635 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8636 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8637 if (!CstScalar && Order < 0) 8638 return true; 8639 8640 // If the scalar cannot be safely casted to the vector element type, 8641 // reject it. 8642 if (CstScalar) { 8643 bool Truncated = false; 8644 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8645 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8646 if (Truncated) 8647 return true; 8648 } 8649 8650 ScalarCast = CK_FloatingCast; 8651 } else if (ScalarTy->isIntegralType(S.Context)) { 8652 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8653 return true; 8654 8655 ScalarCast = CK_IntegralToFloating; 8656 } else 8657 return true; 8658 } 8659 8660 // Adjust scalar if desired. 8661 if (Scalar) { 8662 if (ScalarCast != CK_NoOp) 8663 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8664 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8665 } 8666 return false; 8667 } 8668 8669 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8670 SourceLocation Loc, bool IsCompAssign, 8671 bool AllowBothBool, 8672 bool AllowBoolConversions) { 8673 if (!IsCompAssign) { 8674 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8675 if (LHS.isInvalid()) 8676 return QualType(); 8677 } 8678 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8679 if (RHS.isInvalid()) 8680 return QualType(); 8681 8682 // For conversion purposes, we ignore any qualifiers. 8683 // For example, "const float" and "float" are equivalent. 8684 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8685 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8686 8687 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8688 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8689 assert(LHSVecType || RHSVecType); 8690 8691 // AltiVec-style "vector bool op vector bool" combinations are allowed 8692 // for some operators but not others. 8693 if (!AllowBothBool && 8694 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8695 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8696 return InvalidOperands(Loc, LHS, RHS); 8697 8698 // If the vector types are identical, return. 8699 if (Context.hasSameType(LHSType, RHSType)) 8700 return LHSType; 8701 8702 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8703 if (LHSVecType && RHSVecType && 8704 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8705 if (isa<ExtVectorType>(LHSVecType)) { 8706 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8707 return LHSType; 8708 } 8709 8710 if (!IsCompAssign) 8711 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8712 return RHSType; 8713 } 8714 8715 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8716 // can be mixed, with the result being the non-bool type. The non-bool 8717 // operand must have integer element type. 8718 if (AllowBoolConversions && LHSVecType && RHSVecType && 8719 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8720 (Context.getTypeSize(LHSVecType->getElementType()) == 8721 Context.getTypeSize(RHSVecType->getElementType()))) { 8722 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8723 LHSVecType->getElementType()->isIntegerType() && 8724 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8725 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8726 return LHSType; 8727 } 8728 if (!IsCompAssign && 8729 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8730 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8731 RHSVecType->getElementType()->isIntegerType()) { 8732 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8733 return RHSType; 8734 } 8735 } 8736 8737 // If there's a vector type and a scalar, try to convert the scalar to 8738 // the vector element type and splat. 8739 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8740 if (!RHSVecType) { 8741 if (isa<ExtVectorType>(LHSVecType)) { 8742 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8743 LHSVecType->getElementType(), LHSType, 8744 DiagID)) 8745 return LHSType; 8746 } else { 8747 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8748 return LHSType; 8749 } 8750 } 8751 if (!LHSVecType) { 8752 if (isa<ExtVectorType>(RHSVecType)) { 8753 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8754 LHSType, RHSVecType->getElementType(), 8755 RHSType, DiagID)) 8756 return RHSType; 8757 } else { 8758 if (LHS.get()->getValueKind() == VK_LValue || 8759 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8760 return RHSType; 8761 } 8762 } 8763 8764 // FIXME: The code below also handles conversion between vectors and 8765 // non-scalars, we should break this down into fine grained specific checks 8766 // and emit proper diagnostics. 8767 QualType VecType = LHSVecType ? LHSType : RHSType; 8768 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8769 QualType OtherType = LHSVecType ? RHSType : LHSType; 8770 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8771 if (isLaxVectorConversion(OtherType, VecType)) { 8772 // If we're allowing lax vector conversions, only the total (data) size 8773 // needs to be the same. For non compound assignment, if one of the types is 8774 // scalar, the result is always the vector type. 8775 if (!IsCompAssign) { 8776 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8777 return VecType; 8778 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8779 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8780 // type. Note that this is already done by non-compound assignments in 8781 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8782 // <1 x T> -> T. The result is also a vector type. 8783 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8784 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8785 ExprResult *RHSExpr = &RHS; 8786 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8787 return VecType; 8788 } 8789 } 8790 8791 // Okay, the expression is invalid. 8792 8793 // If there's a non-vector, non-real operand, diagnose that. 8794 if ((!RHSVecType && !RHSType->isRealType()) || 8795 (!LHSVecType && !LHSType->isRealType())) { 8796 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8797 << LHSType << RHSType 8798 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8799 return QualType(); 8800 } 8801 8802 // OpenCL V1.1 6.2.6.p1: 8803 // If the operands are of more than one vector type, then an error shall 8804 // occur. Implicit conversions between vector types are not permitted, per 8805 // section 6.2.1. 8806 if (getLangOpts().OpenCL && 8807 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8808 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8809 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8810 << RHSType; 8811 return QualType(); 8812 } 8813 8814 8815 // If there is a vector type that is not a ExtVector and a scalar, we reach 8816 // this point if scalar could not be converted to the vector's element type 8817 // without truncation. 8818 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8819 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8820 QualType Scalar = LHSVecType ? RHSType : LHSType; 8821 QualType Vector = LHSVecType ? LHSType : RHSType; 8822 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8823 Diag(Loc, 8824 diag::err_typecheck_vector_not_convertable_implict_truncation) 8825 << ScalarOrVector << Scalar << Vector; 8826 8827 return QualType(); 8828 } 8829 8830 // Otherwise, use the generic diagnostic. 8831 Diag(Loc, DiagID) 8832 << LHSType << RHSType 8833 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8834 return QualType(); 8835 } 8836 8837 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8838 // expression. These are mainly cases where the null pointer is used as an 8839 // integer instead of a pointer. 8840 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8841 SourceLocation Loc, bool IsCompare) { 8842 // The canonical way to check for a GNU null is with isNullPointerConstant, 8843 // but we use a bit of a hack here for speed; this is a relatively 8844 // hot path, and isNullPointerConstant is slow. 8845 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8846 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8847 8848 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8849 8850 // Avoid analyzing cases where the result will either be invalid (and 8851 // diagnosed as such) or entirely valid and not something to warn about. 8852 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8853 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8854 return; 8855 8856 // Comparison operations would not make sense with a null pointer no matter 8857 // what the other expression is. 8858 if (!IsCompare) { 8859 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8860 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8861 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8862 return; 8863 } 8864 8865 // The rest of the operations only make sense with a null pointer 8866 // if the other expression is a pointer. 8867 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8868 NonNullType->canDecayToPointerType()) 8869 return; 8870 8871 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8872 << LHSNull /* LHS is NULL */ << NonNullType 8873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8874 } 8875 8876 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8877 SourceLocation Loc) { 8878 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 8879 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 8880 if (!LUE || !RUE) 8881 return; 8882 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 8883 RUE->getKind() != UETT_SizeOf) 8884 return; 8885 8886 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 8887 QualType RHSTy; 8888 8889 if (RUE->isArgumentType()) 8890 RHSTy = RUE->getArgumentType(); 8891 else 8892 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 8893 8894 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 8895 return; 8896 if (LHSTy->getPointeeType() != RHSTy) 8897 return; 8898 8899 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 8900 } 8901 8902 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8903 ExprResult &RHS, 8904 SourceLocation Loc, bool IsDiv) { 8905 // Check for division/remainder by zero. 8906 Expr::EvalResult RHSValue; 8907 if (!RHS.get()->isValueDependent() && 8908 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 8909 RHSValue.Val.getInt() == 0) 8910 S.DiagRuntimeBehavior(Loc, RHS.get(), 8911 S.PDiag(diag::warn_remainder_division_by_zero) 8912 << IsDiv << RHS.get()->getSourceRange()); 8913 } 8914 8915 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8916 SourceLocation Loc, 8917 bool IsCompAssign, bool IsDiv) { 8918 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8919 8920 if (LHS.get()->getType()->isVectorType() || 8921 RHS.get()->getType()->isVectorType()) 8922 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8923 /*AllowBothBool*/getLangOpts().AltiVec, 8924 /*AllowBoolConversions*/false); 8925 8926 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8927 if (LHS.isInvalid() || RHS.isInvalid()) 8928 return QualType(); 8929 8930 8931 if (compType.isNull() || !compType->isArithmeticType()) 8932 return InvalidOperands(Loc, LHS, RHS); 8933 if (IsDiv) { 8934 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8935 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 8936 } 8937 return compType; 8938 } 8939 8940 QualType Sema::CheckRemainderOperands( 8941 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8942 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8943 8944 if (LHS.get()->getType()->isVectorType() || 8945 RHS.get()->getType()->isVectorType()) { 8946 if (LHS.get()->getType()->hasIntegerRepresentation() && 8947 RHS.get()->getType()->hasIntegerRepresentation()) 8948 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8949 /*AllowBothBool*/getLangOpts().AltiVec, 8950 /*AllowBoolConversions*/false); 8951 return InvalidOperands(Loc, LHS, RHS); 8952 } 8953 8954 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8955 if (LHS.isInvalid() || RHS.isInvalid()) 8956 return QualType(); 8957 8958 if (compType.isNull() || !compType->isIntegerType()) 8959 return InvalidOperands(Loc, LHS, RHS); 8960 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8961 return compType; 8962 } 8963 8964 /// Diagnose invalid arithmetic on two void pointers. 8965 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8966 Expr *LHSExpr, Expr *RHSExpr) { 8967 S.Diag(Loc, S.getLangOpts().CPlusPlus 8968 ? diag::err_typecheck_pointer_arith_void_type 8969 : diag::ext_gnu_void_ptr) 8970 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8971 << RHSExpr->getSourceRange(); 8972 } 8973 8974 /// Diagnose invalid arithmetic on a void pointer. 8975 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8976 Expr *Pointer) { 8977 S.Diag(Loc, S.getLangOpts().CPlusPlus 8978 ? diag::err_typecheck_pointer_arith_void_type 8979 : diag::ext_gnu_void_ptr) 8980 << 0 /* one pointer */ << Pointer->getSourceRange(); 8981 } 8982 8983 /// Diagnose invalid arithmetic on a null pointer. 8984 /// 8985 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8986 /// idiom, which we recognize as a GNU extension. 8987 /// 8988 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8989 Expr *Pointer, bool IsGNUIdiom) { 8990 if (IsGNUIdiom) 8991 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8992 << Pointer->getSourceRange(); 8993 else 8994 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8995 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8996 } 8997 8998 /// Diagnose invalid arithmetic on two function pointers. 8999 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9000 Expr *LHS, Expr *RHS) { 9001 assert(LHS->getType()->isAnyPointerType()); 9002 assert(RHS->getType()->isAnyPointerType()); 9003 S.Diag(Loc, S.getLangOpts().CPlusPlus 9004 ? diag::err_typecheck_pointer_arith_function_type 9005 : diag::ext_gnu_ptr_func_arith) 9006 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9007 // We only show the second type if it differs from the first. 9008 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9009 RHS->getType()) 9010 << RHS->getType()->getPointeeType() 9011 << LHS->getSourceRange() << RHS->getSourceRange(); 9012 } 9013 9014 /// Diagnose invalid arithmetic on a function pointer. 9015 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9016 Expr *Pointer) { 9017 assert(Pointer->getType()->isAnyPointerType()); 9018 S.Diag(Loc, S.getLangOpts().CPlusPlus 9019 ? diag::err_typecheck_pointer_arith_function_type 9020 : diag::ext_gnu_ptr_func_arith) 9021 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9022 << 0 /* one pointer, so only one type */ 9023 << Pointer->getSourceRange(); 9024 } 9025 9026 /// Emit error if Operand is incomplete pointer type 9027 /// 9028 /// \returns True if pointer has incomplete type 9029 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9030 Expr *Operand) { 9031 QualType ResType = Operand->getType(); 9032 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9033 ResType = ResAtomicType->getValueType(); 9034 9035 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9036 QualType PointeeTy = ResType->getPointeeType(); 9037 return S.RequireCompleteType(Loc, PointeeTy, 9038 diag::err_typecheck_arithmetic_incomplete_type, 9039 PointeeTy, Operand->getSourceRange()); 9040 } 9041 9042 /// Check the validity of an arithmetic pointer operand. 9043 /// 9044 /// If the operand has pointer type, this code will check for pointer types 9045 /// which are invalid in arithmetic operations. These will be diagnosed 9046 /// appropriately, including whether or not the use is supported as an 9047 /// extension. 9048 /// 9049 /// \returns True when the operand is valid to use (even if as an extension). 9050 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9051 Expr *Operand) { 9052 QualType ResType = Operand->getType(); 9053 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9054 ResType = ResAtomicType->getValueType(); 9055 9056 if (!ResType->isAnyPointerType()) return true; 9057 9058 QualType PointeeTy = ResType->getPointeeType(); 9059 if (PointeeTy->isVoidType()) { 9060 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9061 return !S.getLangOpts().CPlusPlus; 9062 } 9063 if (PointeeTy->isFunctionType()) { 9064 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9065 return !S.getLangOpts().CPlusPlus; 9066 } 9067 9068 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9069 9070 return true; 9071 } 9072 9073 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9074 /// operands. 9075 /// 9076 /// This routine will diagnose any invalid arithmetic on pointer operands much 9077 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9078 /// for emitting a single diagnostic even for operations where both LHS and RHS 9079 /// are (potentially problematic) pointers. 9080 /// 9081 /// \returns True when the operand is valid to use (even if as an extension). 9082 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9083 Expr *LHSExpr, Expr *RHSExpr) { 9084 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9085 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9086 if (!isLHSPointer && !isRHSPointer) return true; 9087 9088 QualType LHSPointeeTy, RHSPointeeTy; 9089 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9090 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9091 9092 // if both are pointers check if operation is valid wrt address spaces 9093 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9094 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9095 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9096 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9097 S.Diag(Loc, 9098 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9099 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9100 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9101 return false; 9102 } 9103 } 9104 9105 // Check for arithmetic on pointers to incomplete types. 9106 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9107 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9108 if (isLHSVoidPtr || isRHSVoidPtr) { 9109 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9110 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9111 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9112 9113 return !S.getLangOpts().CPlusPlus; 9114 } 9115 9116 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9117 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9118 if (isLHSFuncPtr || isRHSFuncPtr) { 9119 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9120 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9121 RHSExpr); 9122 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9123 9124 return !S.getLangOpts().CPlusPlus; 9125 } 9126 9127 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9128 return false; 9129 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9130 return false; 9131 9132 return true; 9133 } 9134 9135 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9136 /// literal. 9137 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9138 Expr *LHSExpr, Expr *RHSExpr) { 9139 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9140 Expr* IndexExpr = RHSExpr; 9141 if (!StrExpr) { 9142 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9143 IndexExpr = LHSExpr; 9144 } 9145 9146 bool IsStringPlusInt = StrExpr && 9147 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9148 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9149 return; 9150 9151 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9152 Self.Diag(OpLoc, diag::warn_string_plus_int) 9153 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9154 9155 // Only print a fixit for "str" + int, not for int + "str". 9156 if (IndexExpr == RHSExpr) { 9157 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9158 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9159 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9160 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9161 << FixItHint::CreateInsertion(EndLoc, "]"); 9162 } else 9163 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9164 } 9165 9166 /// Emit a warning when adding a char literal to a string. 9167 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9168 Expr *LHSExpr, Expr *RHSExpr) { 9169 const Expr *StringRefExpr = LHSExpr; 9170 const CharacterLiteral *CharExpr = 9171 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9172 9173 if (!CharExpr) { 9174 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9175 StringRefExpr = RHSExpr; 9176 } 9177 9178 if (!CharExpr || !StringRefExpr) 9179 return; 9180 9181 const QualType StringType = StringRefExpr->getType(); 9182 9183 // Return if not a PointerType. 9184 if (!StringType->isAnyPointerType()) 9185 return; 9186 9187 // Return if not a CharacterType. 9188 if (!StringType->getPointeeType()->isAnyCharacterType()) 9189 return; 9190 9191 ASTContext &Ctx = Self.getASTContext(); 9192 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9193 9194 const QualType CharType = CharExpr->getType(); 9195 if (!CharType->isAnyCharacterType() && 9196 CharType->isIntegerType() && 9197 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9198 Self.Diag(OpLoc, diag::warn_string_plus_char) 9199 << DiagRange << Ctx.CharTy; 9200 } else { 9201 Self.Diag(OpLoc, diag::warn_string_plus_char) 9202 << DiagRange << CharExpr->getType(); 9203 } 9204 9205 // Only print a fixit for str + char, not for char + str. 9206 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9207 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9208 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9209 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9210 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9211 << FixItHint::CreateInsertion(EndLoc, "]"); 9212 } else { 9213 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9214 } 9215 } 9216 9217 /// Emit error when two pointers are incompatible. 9218 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9219 Expr *LHSExpr, Expr *RHSExpr) { 9220 assert(LHSExpr->getType()->isAnyPointerType()); 9221 assert(RHSExpr->getType()->isAnyPointerType()); 9222 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9223 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9224 << RHSExpr->getSourceRange(); 9225 } 9226 9227 // C99 6.5.6 9228 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9229 SourceLocation Loc, BinaryOperatorKind Opc, 9230 QualType* CompLHSTy) { 9231 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9232 9233 if (LHS.get()->getType()->isVectorType() || 9234 RHS.get()->getType()->isVectorType()) { 9235 QualType compType = CheckVectorOperands( 9236 LHS, RHS, Loc, CompLHSTy, 9237 /*AllowBothBool*/getLangOpts().AltiVec, 9238 /*AllowBoolConversions*/getLangOpts().ZVector); 9239 if (CompLHSTy) *CompLHSTy = compType; 9240 return compType; 9241 } 9242 9243 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9244 if (LHS.isInvalid() || RHS.isInvalid()) 9245 return QualType(); 9246 9247 // Diagnose "string literal" '+' int and string '+' "char literal". 9248 if (Opc == BO_Add) { 9249 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9250 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9251 } 9252 9253 // handle the common case first (both operands are arithmetic). 9254 if (!compType.isNull() && compType->isArithmeticType()) { 9255 if (CompLHSTy) *CompLHSTy = compType; 9256 return compType; 9257 } 9258 9259 // Type-checking. Ultimately the pointer's going to be in PExp; 9260 // note that we bias towards the LHS being the pointer. 9261 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9262 9263 bool isObjCPointer; 9264 if (PExp->getType()->isPointerType()) { 9265 isObjCPointer = false; 9266 } else if (PExp->getType()->isObjCObjectPointerType()) { 9267 isObjCPointer = true; 9268 } else { 9269 std::swap(PExp, IExp); 9270 if (PExp->getType()->isPointerType()) { 9271 isObjCPointer = false; 9272 } else if (PExp->getType()->isObjCObjectPointerType()) { 9273 isObjCPointer = true; 9274 } else { 9275 return InvalidOperands(Loc, LHS, RHS); 9276 } 9277 } 9278 assert(PExp->getType()->isAnyPointerType()); 9279 9280 if (!IExp->getType()->isIntegerType()) 9281 return InvalidOperands(Loc, LHS, RHS); 9282 9283 // Adding to a null pointer results in undefined behavior. 9284 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9285 Context, Expr::NPC_ValueDependentIsNotNull)) { 9286 // In C++ adding zero to a null pointer is defined. 9287 Expr::EvalResult KnownVal; 9288 if (!getLangOpts().CPlusPlus || 9289 (!IExp->isValueDependent() && 9290 (!IExp->EvaluateAsInt(KnownVal, Context) || 9291 KnownVal.Val.getInt() != 0))) { 9292 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9293 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9294 Context, BO_Add, PExp, IExp); 9295 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9296 } 9297 } 9298 9299 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9300 return QualType(); 9301 9302 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9303 return QualType(); 9304 9305 // Check array bounds for pointer arithemtic 9306 CheckArrayAccess(PExp, IExp); 9307 9308 if (CompLHSTy) { 9309 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9310 if (LHSTy.isNull()) { 9311 LHSTy = LHS.get()->getType(); 9312 if (LHSTy->isPromotableIntegerType()) 9313 LHSTy = Context.getPromotedIntegerType(LHSTy); 9314 } 9315 *CompLHSTy = LHSTy; 9316 } 9317 9318 return PExp->getType(); 9319 } 9320 9321 // C99 6.5.6 9322 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9323 SourceLocation Loc, 9324 QualType* CompLHSTy) { 9325 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9326 9327 if (LHS.get()->getType()->isVectorType() || 9328 RHS.get()->getType()->isVectorType()) { 9329 QualType compType = CheckVectorOperands( 9330 LHS, RHS, Loc, CompLHSTy, 9331 /*AllowBothBool*/getLangOpts().AltiVec, 9332 /*AllowBoolConversions*/getLangOpts().ZVector); 9333 if (CompLHSTy) *CompLHSTy = compType; 9334 return compType; 9335 } 9336 9337 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9338 if (LHS.isInvalid() || RHS.isInvalid()) 9339 return QualType(); 9340 9341 // Enforce type constraints: C99 6.5.6p3. 9342 9343 // Handle the common case first (both operands are arithmetic). 9344 if (!compType.isNull() && compType->isArithmeticType()) { 9345 if (CompLHSTy) *CompLHSTy = compType; 9346 return compType; 9347 } 9348 9349 // Either ptr - int or ptr - ptr. 9350 if (LHS.get()->getType()->isAnyPointerType()) { 9351 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9352 9353 // Diagnose bad cases where we step over interface counts. 9354 if (LHS.get()->getType()->isObjCObjectPointerType() && 9355 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9356 return QualType(); 9357 9358 // The result type of a pointer-int computation is the pointer type. 9359 if (RHS.get()->getType()->isIntegerType()) { 9360 // Subtracting from a null pointer should produce a warning. 9361 // The last argument to the diagnose call says this doesn't match the 9362 // GNU int-to-pointer idiom. 9363 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9364 Expr::NPC_ValueDependentIsNotNull)) { 9365 // In C++ adding zero to a null pointer is defined. 9366 Expr::EvalResult KnownVal; 9367 if (!getLangOpts().CPlusPlus || 9368 (!RHS.get()->isValueDependent() && 9369 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9370 KnownVal.Val.getInt() != 0))) { 9371 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9372 } 9373 } 9374 9375 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9376 return QualType(); 9377 9378 // Check array bounds for pointer arithemtic 9379 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9380 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9381 9382 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9383 return LHS.get()->getType(); 9384 } 9385 9386 // Handle pointer-pointer subtractions. 9387 if (const PointerType *RHSPTy 9388 = RHS.get()->getType()->getAs<PointerType>()) { 9389 QualType rpointee = RHSPTy->getPointeeType(); 9390 9391 if (getLangOpts().CPlusPlus) { 9392 // Pointee types must be the same: C++ [expr.add] 9393 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9394 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9395 } 9396 } else { 9397 // Pointee types must be compatible C99 6.5.6p3 9398 if (!Context.typesAreCompatible( 9399 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9400 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9401 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9402 return QualType(); 9403 } 9404 } 9405 9406 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9407 LHS.get(), RHS.get())) 9408 return QualType(); 9409 9410 // FIXME: Add warnings for nullptr - ptr. 9411 9412 // The pointee type may have zero size. As an extension, a structure or 9413 // union may have zero size or an array may have zero length. In this 9414 // case subtraction does not make sense. 9415 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9416 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9417 if (ElementSize.isZero()) { 9418 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9419 << rpointee.getUnqualifiedType() 9420 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9421 } 9422 } 9423 9424 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9425 return Context.getPointerDiffType(); 9426 } 9427 } 9428 9429 return InvalidOperands(Loc, LHS, RHS); 9430 } 9431 9432 static bool isScopedEnumerationType(QualType T) { 9433 if (const EnumType *ET = T->getAs<EnumType>()) 9434 return ET->getDecl()->isScoped(); 9435 return false; 9436 } 9437 9438 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9439 SourceLocation Loc, BinaryOperatorKind Opc, 9440 QualType LHSType) { 9441 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9442 // so skip remaining warnings as we don't want to modify values within Sema. 9443 if (S.getLangOpts().OpenCL) 9444 return; 9445 9446 // Check right/shifter operand 9447 Expr::EvalResult RHSResult; 9448 if (RHS.get()->isValueDependent() || 9449 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9450 return; 9451 llvm::APSInt Right = RHSResult.Val.getInt(); 9452 9453 if (Right.isNegative()) { 9454 S.DiagRuntimeBehavior(Loc, RHS.get(), 9455 S.PDiag(diag::warn_shift_negative) 9456 << RHS.get()->getSourceRange()); 9457 return; 9458 } 9459 llvm::APInt LeftBits(Right.getBitWidth(), 9460 S.Context.getTypeSize(LHS.get()->getType())); 9461 if (Right.uge(LeftBits)) { 9462 S.DiagRuntimeBehavior(Loc, RHS.get(), 9463 S.PDiag(diag::warn_shift_gt_typewidth) 9464 << RHS.get()->getSourceRange()); 9465 return; 9466 } 9467 if (Opc != BO_Shl) 9468 return; 9469 9470 // When left shifting an ICE which is signed, we can check for overflow which 9471 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9472 // integers have defined behavior modulo one more than the maximum value 9473 // representable in the result type, so never warn for those. 9474 Expr::EvalResult LHSResult; 9475 if (LHS.get()->isValueDependent() || 9476 LHSType->hasUnsignedIntegerRepresentation() || 9477 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9478 return; 9479 llvm::APSInt Left = LHSResult.Val.getInt(); 9480 9481 // If LHS does not have a signed type and non-negative value 9482 // then, the behavior is undefined. Warn about it. 9483 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9484 S.DiagRuntimeBehavior(Loc, LHS.get(), 9485 S.PDiag(diag::warn_shift_lhs_negative) 9486 << LHS.get()->getSourceRange()); 9487 return; 9488 } 9489 9490 llvm::APInt ResultBits = 9491 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9492 if (LeftBits.uge(ResultBits)) 9493 return; 9494 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9495 Result = Result.shl(Right); 9496 9497 // Print the bit representation of the signed integer as an unsigned 9498 // hexadecimal number. 9499 SmallString<40> HexResult; 9500 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9501 9502 // If we are only missing a sign bit, this is less likely to result in actual 9503 // bugs -- if the result is cast back to an unsigned type, it will have the 9504 // expected value. Thus we place this behind a different warning that can be 9505 // turned off separately if needed. 9506 if (LeftBits == ResultBits - 1) { 9507 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9508 << HexResult << LHSType 9509 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9510 return; 9511 } 9512 9513 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9514 << HexResult.str() << Result.getMinSignedBits() << LHSType 9515 << Left.getBitWidth() << LHS.get()->getSourceRange() 9516 << RHS.get()->getSourceRange(); 9517 } 9518 9519 /// Return the resulting type when a vector is shifted 9520 /// by a scalar or vector shift amount. 9521 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9522 SourceLocation Loc, bool IsCompAssign) { 9523 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9524 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9525 !LHS.get()->getType()->isVectorType()) { 9526 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9527 << RHS.get()->getType() << LHS.get()->getType() 9528 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9529 return QualType(); 9530 } 9531 9532 if (!IsCompAssign) { 9533 LHS = S.UsualUnaryConversions(LHS.get()); 9534 if (LHS.isInvalid()) return QualType(); 9535 } 9536 9537 RHS = S.UsualUnaryConversions(RHS.get()); 9538 if (RHS.isInvalid()) return QualType(); 9539 9540 QualType LHSType = LHS.get()->getType(); 9541 // Note that LHS might be a scalar because the routine calls not only in 9542 // OpenCL case. 9543 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9544 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9545 9546 // Note that RHS might not be a vector. 9547 QualType RHSType = RHS.get()->getType(); 9548 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9549 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9550 9551 // The operands need to be integers. 9552 if (!LHSEleType->isIntegerType()) { 9553 S.Diag(Loc, diag::err_typecheck_expect_int) 9554 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9555 return QualType(); 9556 } 9557 9558 if (!RHSEleType->isIntegerType()) { 9559 S.Diag(Loc, diag::err_typecheck_expect_int) 9560 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9561 return QualType(); 9562 } 9563 9564 if (!LHSVecTy) { 9565 assert(RHSVecTy); 9566 if (IsCompAssign) 9567 return RHSType; 9568 if (LHSEleType != RHSEleType) { 9569 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9570 LHSEleType = RHSEleType; 9571 } 9572 QualType VecTy = 9573 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9574 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9575 LHSType = VecTy; 9576 } else if (RHSVecTy) { 9577 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9578 // are applied component-wise. So if RHS is a vector, then ensure 9579 // that the number of elements is the same as LHS... 9580 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9581 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9582 << LHS.get()->getType() << RHS.get()->getType() 9583 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9584 return QualType(); 9585 } 9586 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9587 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9588 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9589 if (LHSBT != RHSBT && 9590 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9591 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9592 << LHS.get()->getType() << RHS.get()->getType() 9593 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9594 } 9595 } 9596 } else { 9597 // ...else expand RHS to match the number of elements in LHS. 9598 QualType VecTy = 9599 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9600 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9601 } 9602 9603 return LHSType; 9604 } 9605 9606 // C99 6.5.7 9607 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9608 SourceLocation Loc, BinaryOperatorKind Opc, 9609 bool IsCompAssign) { 9610 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9611 9612 // Vector shifts promote their scalar inputs to vector type. 9613 if (LHS.get()->getType()->isVectorType() || 9614 RHS.get()->getType()->isVectorType()) { 9615 if (LangOpts.ZVector) { 9616 // The shift operators for the z vector extensions work basically 9617 // like general shifts, except that neither the LHS nor the RHS is 9618 // allowed to be a "vector bool". 9619 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9620 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9621 return InvalidOperands(Loc, LHS, RHS); 9622 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9623 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9624 return InvalidOperands(Loc, LHS, RHS); 9625 } 9626 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9627 } 9628 9629 // Shifts don't perform usual arithmetic conversions, they just do integer 9630 // promotions on each operand. C99 6.5.7p3 9631 9632 // For the LHS, do usual unary conversions, but then reset them away 9633 // if this is a compound assignment. 9634 ExprResult OldLHS = LHS; 9635 LHS = UsualUnaryConversions(LHS.get()); 9636 if (LHS.isInvalid()) 9637 return QualType(); 9638 QualType LHSType = LHS.get()->getType(); 9639 if (IsCompAssign) LHS = OldLHS; 9640 9641 // The RHS is simpler. 9642 RHS = UsualUnaryConversions(RHS.get()); 9643 if (RHS.isInvalid()) 9644 return QualType(); 9645 QualType RHSType = RHS.get()->getType(); 9646 9647 // C99 6.5.7p2: Each of the operands shall have integer type. 9648 if (!LHSType->hasIntegerRepresentation() || 9649 !RHSType->hasIntegerRepresentation()) 9650 return InvalidOperands(Loc, LHS, RHS); 9651 9652 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9653 // hasIntegerRepresentation() above instead of this. 9654 if (isScopedEnumerationType(LHSType) || 9655 isScopedEnumerationType(RHSType)) { 9656 return InvalidOperands(Loc, LHS, RHS); 9657 } 9658 // Sanity-check shift operands 9659 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9660 9661 // "The type of the result is that of the promoted left operand." 9662 return LHSType; 9663 } 9664 9665 /// If two different enums are compared, raise a warning. 9666 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9667 Expr *RHS) { 9668 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9669 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9670 9671 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9672 if (!LHSEnumType) 9673 return; 9674 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9675 if (!RHSEnumType) 9676 return; 9677 9678 // Ignore anonymous enums. 9679 if (!LHSEnumType->getDecl()->getIdentifier() && 9680 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9681 return; 9682 if (!RHSEnumType->getDecl()->getIdentifier() && 9683 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9684 return; 9685 9686 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9687 return; 9688 9689 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9690 << LHSStrippedType << RHSStrippedType 9691 << LHS->getSourceRange() << RHS->getSourceRange(); 9692 } 9693 9694 /// Diagnose bad pointer comparisons. 9695 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9696 ExprResult &LHS, ExprResult &RHS, 9697 bool IsError) { 9698 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9699 : diag::ext_typecheck_comparison_of_distinct_pointers) 9700 << LHS.get()->getType() << RHS.get()->getType() 9701 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9702 } 9703 9704 /// Returns false if the pointers are converted to a composite type, 9705 /// true otherwise. 9706 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9707 ExprResult &LHS, ExprResult &RHS) { 9708 // C++ [expr.rel]p2: 9709 // [...] Pointer conversions (4.10) and qualification 9710 // conversions (4.4) are performed on pointer operands (or on 9711 // a pointer operand and a null pointer constant) to bring 9712 // them to their composite pointer type. [...] 9713 // 9714 // C++ [expr.eq]p1 uses the same notion for (in)equality 9715 // comparisons of pointers. 9716 9717 QualType LHSType = LHS.get()->getType(); 9718 QualType RHSType = RHS.get()->getType(); 9719 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9720 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9721 9722 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9723 if (T.isNull()) { 9724 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9725 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9726 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9727 else 9728 S.InvalidOperands(Loc, LHS, RHS); 9729 return true; 9730 } 9731 9732 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9733 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9734 return false; 9735 } 9736 9737 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9738 ExprResult &LHS, 9739 ExprResult &RHS, 9740 bool IsError) { 9741 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9742 : diag::ext_typecheck_comparison_of_fptr_to_void) 9743 << LHS.get()->getType() << RHS.get()->getType() 9744 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9745 } 9746 9747 static bool isObjCObjectLiteral(ExprResult &E) { 9748 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9749 case Stmt::ObjCArrayLiteralClass: 9750 case Stmt::ObjCDictionaryLiteralClass: 9751 case Stmt::ObjCStringLiteralClass: 9752 case Stmt::ObjCBoxedExprClass: 9753 return true; 9754 default: 9755 // Note that ObjCBoolLiteral is NOT an object literal! 9756 return false; 9757 } 9758 } 9759 9760 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9761 const ObjCObjectPointerType *Type = 9762 LHS->getType()->getAs<ObjCObjectPointerType>(); 9763 9764 // If this is not actually an Objective-C object, bail out. 9765 if (!Type) 9766 return false; 9767 9768 // Get the LHS object's interface type. 9769 QualType InterfaceType = Type->getPointeeType(); 9770 9771 // If the RHS isn't an Objective-C object, bail out. 9772 if (!RHS->getType()->isObjCObjectPointerType()) 9773 return false; 9774 9775 // Try to find the -isEqual: method. 9776 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9777 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9778 InterfaceType, 9779 /*instance=*/true); 9780 if (!Method) { 9781 if (Type->isObjCIdType()) { 9782 // For 'id', just check the global pool. 9783 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9784 /*receiverId=*/true); 9785 } else { 9786 // Check protocols. 9787 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9788 /*instance=*/true); 9789 } 9790 } 9791 9792 if (!Method) 9793 return false; 9794 9795 QualType T = Method->parameters()[0]->getType(); 9796 if (!T->isObjCObjectPointerType()) 9797 return false; 9798 9799 QualType R = Method->getReturnType(); 9800 if (!R->isScalarType()) 9801 return false; 9802 9803 return true; 9804 } 9805 9806 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9807 FromE = FromE->IgnoreParenImpCasts(); 9808 switch (FromE->getStmtClass()) { 9809 default: 9810 break; 9811 case Stmt::ObjCStringLiteralClass: 9812 // "string literal" 9813 return LK_String; 9814 case Stmt::ObjCArrayLiteralClass: 9815 // "array literal" 9816 return LK_Array; 9817 case Stmt::ObjCDictionaryLiteralClass: 9818 // "dictionary literal" 9819 return LK_Dictionary; 9820 case Stmt::BlockExprClass: 9821 return LK_Block; 9822 case Stmt::ObjCBoxedExprClass: { 9823 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9824 switch (Inner->getStmtClass()) { 9825 case Stmt::IntegerLiteralClass: 9826 case Stmt::FloatingLiteralClass: 9827 case Stmt::CharacterLiteralClass: 9828 case Stmt::ObjCBoolLiteralExprClass: 9829 case Stmt::CXXBoolLiteralExprClass: 9830 // "numeric literal" 9831 return LK_Numeric; 9832 case Stmt::ImplicitCastExprClass: { 9833 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9834 // Boolean literals can be represented by implicit casts. 9835 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9836 return LK_Numeric; 9837 break; 9838 } 9839 default: 9840 break; 9841 } 9842 return LK_Boxed; 9843 } 9844 } 9845 return LK_None; 9846 } 9847 9848 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9849 ExprResult &LHS, ExprResult &RHS, 9850 BinaryOperator::Opcode Opc){ 9851 Expr *Literal; 9852 Expr *Other; 9853 if (isObjCObjectLiteral(LHS)) { 9854 Literal = LHS.get(); 9855 Other = RHS.get(); 9856 } else { 9857 Literal = RHS.get(); 9858 Other = LHS.get(); 9859 } 9860 9861 // Don't warn on comparisons against nil. 9862 Other = Other->IgnoreParenCasts(); 9863 if (Other->isNullPointerConstant(S.getASTContext(), 9864 Expr::NPC_ValueDependentIsNotNull)) 9865 return; 9866 9867 // This should be kept in sync with warn_objc_literal_comparison. 9868 // LK_String should always be after the other literals, since it has its own 9869 // warning flag. 9870 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9871 assert(LiteralKind != Sema::LK_Block); 9872 if (LiteralKind == Sema::LK_None) { 9873 llvm_unreachable("Unknown Objective-C object literal kind"); 9874 } 9875 9876 if (LiteralKind == Sema::LK_String) 9877 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9878 << Literal->getSourceRange(); 9879 else 9880 S.Diag(Loc, diag::warn_objc_literal_comparison) 9881 << LiteralKind << Literal->getSourceRange(); 9882 9883 if (BinaryOperator::isEqualityOp(Opc) && 9884 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9885 SourceLocation Start = LHS.get()->getBeginLoc(); 9886 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9887 CharSourceRange OpRange = 9888 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9889 9890 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9891 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9892 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9893 << FixItHint::CreateInsertion(End, "]"); 9894 } 9895 } 9896 9897 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9898 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9899 ExprResult &RHS, SourceLocation Loc, 9900 BinaryOperatorKind Opc) { 9901 // Check that left hand side is !something. 9902 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9903 if (!UO || UO->getOpcode() != UO_LNot) return; 9904 9905 // Only check if the right hand side is non-bool arithmetic type. 9906 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9907 9908 // Make sure that the something in !something is not bool. 9909 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9910 if (SubExpr->isKnownToHaveBooleanValue()) return; 9911 9912 // Emit warning. 9913 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9914 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9915 << Loc << IsBitwiseOp; 9916 9917 // First note suggest !(x < y) 9918 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9919 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9920 FirstClose = S.getLocForEndOfToken(FirstClose); 9921 if (FirstClose.isInvalid()) 9922 FirstOpen = SourceLocation(); 9923 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9924 << IsBitwiseOp 9925 << FixItHint::CreateInsertion(FirstOpen, "(") 9926 << FixItHint::CreateInsertion(FirstClose, ")"); 9927 9928 // Second note suggests (!x) < y 9929 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9930 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9931 SecondClose = S.getLocForEndOfToken(SecondClose); 9932 if (SecondClose.isInvalid()) 9933 SecondOpen = SourceLocation(); 9934 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9935 << FixItHint::CreateInsertion(SecondOpen, "(") 9936 << FixItHint::CreateInsertion(SecondClose, ")"); 9937 } 9938 9939 // Get the decl for a simple expression: a reference to a variable, 9940 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9941 static ValueDecl *getCompareDecl(Expr *E) { 9942 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9943 return DR->getDecl(); 9944 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9945 if (Ivar->isFreeIvar()) 9946 return Ivar->getDecl(); 9947 } 9948 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9949 if (Mem->isImplicitAccess()) 9950 return Mem->getMemberDecl(); 9951 } 9952 return nullptr; 9953 } 9954 9955 /// Diagnose some forms of syntactically-obvious tautological comparison. 9956 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9957 Expr *LHS, Expr *RHS, 9958 BinaryOperatorKind Opc) { 9959 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9960 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9961 9962 QualType LHSType = LHS->getType(); 9963 QualType RHSType = RHS->getType(); 9964 if (LHSType->hasFloatingRepresentation() || 9965 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9966 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9967 S.inTemplateInstantiation()) 9968 return; 9969 9970 // Comparisons between two array types are ill-formed for operator<=>, so 9971 // we shouldn't emit any additional warnings about it. 9972 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9973 return; 9974 9975 // For non-floating point types, check for self-comparisons of the form 9976 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9977 // often indicate logic errors in the program. 9978 // 9979 // NOTE: Don't warn about comparison expressions resulting from macro 9980 // expansion. Also don't warn about comparisons which are only self 9981 // comparisons within a template instantiation. The warnings should catch 9982 // obvious cases in the definition of the template anyways. The idea is to 9983 // warn when the typed comparison operator will always evaluate to the same 9984 // result. 9985 ValueDecl *DL = getCompareDecl(LHSStripped); 9986 ValueDecl *DR = getCompareDecl(RHSStripped); 9987 if (DL && DR && declaresSameEntity(DL, DR)) { 9988 StringRef Result; 9989 switch (Opc) { 9990 case BO_EQ: case BO_LE: case BO_GE: 9991 Result = "true"; 9992 break; 9993 case BO_NE: case BO_LT: case BO_GT: 9994 Result = "false"; 9995 break; 9996 case BO_Cmp: 9997 Result = "'std::strong_ordering::equal'"; 9998 break; 9999 default: 10000 break; 10001 } 10002 S.DiagRuntimeBehavior(Loc, nullptr, 10003 S.PDiag(diag::warn_comparison_always) 10004 << 0 /*self-comparison*/ << !Result.empty() 10005 << Result); 10006 } else if (DL && DR && 10007 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 10008 !DL->isWeak() && !DR->isWeak()) { 10009 // What is it always going to evaluate to? 10010 StringRef Result; 10011 switch(Opc) { 10012 case BO_EQ: // e.g. array1 == array2 10013 Result = "false"; 10014 break; 10015 case BO_NE: // e.g. array1 != array2 10016 Result = "true"; 10017 break; 10018 default: // e.g. array1 <= array2 10019 // The best we can say is 'a constant' 10020 break; 10021 } 10022 S.DiagRuntimeBehavior(Loc, nullptr, 10023 S.PDiag(diag::warn_comparison_always) 10024 << 1 /*array comparison*/ 10025 << !Result.empty() << Result); 10026 } 10027 10028 if (isa<CastExpr>(LHSStripped)) 10029 LHSStripped = LHSStripped->IgnoreParenCasts(); 10030 if (isa<CastExpr>(RHSStripped)) 10031 RHSStripped = RHSStripped->IgnoreParenCasts(); 10032 10033 // Warn about comparisons against a string constant (unless the other 10034 // operand is null); the user probably wants strcmp. 10035 Expr *LiteralString = nullptr; 10036 Expr *LiteralStringStripped = nullptr; 10037 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10038 !RHSStripped->isNullPointerConstant(S.Context, 10039 Expr::NPC_ValueDependentIsNull)) { 10040 LiteralString = LHS; 10041 LiteralStringStripped = LHSStripped; 10042 } else if ((isa<StringLiteral>(RHSStripped) || 10043 isa<ObjCEncodeExpr>(RHSStripped)) && 10044 !LHSStripped->isNullPointerConstant(S.Context, 10045 Expr::NPC_ValueDependentIsNull)) { 10046 LiteralString = RHS; 10047 LiteralStringStripped = RHSStripped; 10048 } 10049 10050 if (LiteralString) { 10051 S.DiagRuntimeBehavior(Loc, nullptr, 10052 S.PDiag(diag::warn_stringcompare) 10053 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10054 << LiteralString->getSourceRange()); 10055 } 10056 } 10057 10058 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10059 switch (CK) { 10060 default: { 10061 #ifndef NDEBUG 10062 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10063 << "\n"; 10064 #endif 10065 llvm_unreachable("unhandled cast kind"); 10066 } 10067 case CK_UserDefinedConversion: 10068 return ICK_Identity; 10069 case CK_LValueToRValue: 10070 return ICK_Lvalue_To_Rvalue; 10071 case CK_ArrayToPointerDecay: 10072 return ICK_Array_To_Pointer; 10073 case CK_FunctionToPointerDecay: 10074 return ICK_Function_To_Pointer; 10075 case CK_IntegralCast: 10076 return ICK_Integral_Conversion; 10077 case CK_FloatingCast: 10078 return ICK_Floating_Conversion; 10079 case CK_IntegralToFloating: 10080 case CK_FloatingToIntegral: 10081 return ICK_Floating_Integral; 10082 case CK_IntegralComplexCast: 10083 case CK_FloatingComplexCast: 10084 case CK_FloatingComplexToIntegralComplex: 10085 case CK_IntegralComplexToFloatingComplex: 10086 return ICK_Complex_Conversion; 10087 case CK_FloatingComplexToReal: 10088 case CK_FloatingRealToComplex: 10089 case CK_IntegralComplexToReal: 10090 case CK_IntegralRealToComplex: 10091 return ICK_Complex_Real; 10092 } 10093 } 10094 10095 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10096 QualType FromType, 10097 SourceLocation Loc) { 10098 // Check for a narrowing implicit conversion. 10099 StandardConversionSequence SCS; 10100 SCS.setAsIdentityConversion(); 10101 SCS.setToType(0, FromType); 10102 SCS.setToType(1, ToType); 10103 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10104 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10105 10106 APValue PreNarrowingValue; 10107 QualType PreNarrowingType; 10108 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10109 PreNarrowingType, 10110 /*IgnoreFloatToIntegralConversion*/ true)) { 10111 case NK_Dependent_Narrowing: 10112 // Implicit conversion to a narrower type, but the expression is 10113 // value-dependent so we can't tell whether it's actually narrowing. 10114 case NK_Not_Narrowing: 10115 return false; 10116 10117 case NK_Constant_Narrowing: 10118 // Implicit conversion to a narrower type, and the value is not a constant 10119 // expression. 10120 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10121 << /*Constant*/ 1 10122 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10123 return true; 10124 10125 case NK_Variable_Narrowing: 10126 // Implicit conversion to a narrower type, and the value is not a constant 10127 // expression. 10128 case NK_Type_Narrowing: 10129 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10130 << /*Constant*/ 0 << FromType << ToType; 10131 // TODO: It's not a constant expression, but what if the user intended it 10132 // to be? Can we produce notes to help them figure out why it isn't? 10133 return true; 10134 } 10135 llvm_unreachable("unhandled case in switch"); 10136 } 10137 10138 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10139 ExprResult &LHS, 10140 ExprResult &RHS, 10141 SourceLocation Loc) { 10142 using CCT = ComparisonCategoryType; 10143 10144 QualType LHSType = LHS.get()->getType(); 10145 QualType RHSType = RHS.get()->getType(); 10146 // Dig out the original argument type and expression before implicit casts 10147 // were applied. These are the types/expressions we need to check the 10148 // [expr.spaceship] requirements against. 10149 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10150 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10151 QualType LHSStrippedType = LHSStripped.get()->getType(); 10152 QualType RHSStrippedType = RHSStripped.get()->getType(); 10153 10154 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10155 // other is not, the program is ill-formed. 10156 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10157 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10158 return QualType(); 10159 } 10160 10161 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10162 RHSStrippedType->isEnumeralType(); 10163 if (NumEnumArgs == 1) { 10164 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10165 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10166 if (OtherTy->hasFloatingRepresentation()) { 10167 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10168 return QualType(); 10169 } 10170 } 10171 if (NumEnumArgs == 2) { 10172 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10173 // type E, the operator yields the result of converting the operands 10174 // to the underlying type of E and applying <=> to the converted operands. 10175 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10176 S.InvalidOperands(Loc, LHS, RHS); 10177 return QualType(); 10178 } 10179 QualType IntType = 10180 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10181 assert(IntType->isArithmeticType()); 10182 10183 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10184 // promote the boolean type, and all other promotable integer types, to 10185 // avoid this. 10186 if (IntType->isPromotableIntegerType()) 10187 IntType = S.Context.getPromotedIntegerType(IntType); 10188 10189 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10190 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10191 LHSType = RHSType = IntType; 10192 } 10193 10194 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10195 // usual arithmetic conversions are applied to the operands. 10196 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10197 if (LHS.isInvalid() || RHS.isInvalid()) 10198 return QualType(); 10199 if (Type.isNull()) 10200 return S.InvalidOperands(Loc, LHS, RHS); 10201 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10202 10203 bool HasNarrowing = checkThreeWayNarrowingConversion( 10204 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10205 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10206 RHS.get()->getBeginLoc()); 10207 if (HasNarrowing) 10208 return QualType(); 10209 10210 assert(!Type.isNull() && "composite type for <=> has not been set"); 10211 10212 auto TypeKind = [&]() { 10213 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10214 if (CT->getElementType()->hasFloatingRepresentation()) 10215 return CCT::WeakEquality; 10216 return CCT::StrongEquality; 10217 } 10218 if (Type->isIntegralOrEnumerationType()) 10219 return CCT::StrongOrdering; 10220 if (Type->hasFloatingRepresentation()) 10221 return CCT::PartialOrdering; 10222 llvm_unreachable("other types are unimplemented"); 10223 }(); 10224 10225 return S.CheckComparisonCategoryType(TypeKind, Loc); 10226 } 10227 10228 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10229 ExprResult &RHS, 10230 SourceLocation Loc, 10231 BinaryOperatorKind Opc) { 10232 if (Opc == BO_Cmp) 10233 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10234 10235 // C99 6.5.8p3 / C99 6.5.9p4 10236 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10237 if (LHS.isInvalid() || RHS.isInvalid()) 10238 return QualType(); 10239 if (Type.isNull()) 10240 return S.InvalidOperands(Loc, LHS, RHS); 10241 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10242 10243 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10244 10245 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10246 return S.InvalidOperands(Loc, LHS, RHS); 10247 10248 // Check for comparisons of floating point operands using != and ==. 10249 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10250 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10251 10252 // The result of comparisons is 'bool' in C++, 'int' in C. 10253 return S.Context.getLogicalOperationType(); 10254 } 10255 10256 // C99 6.5.8, C++ [expr.rel] 10257 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10258 SourceLocation Loc, 10259 BinaryOperatorKind Opc) { 10260 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10261 bool IsThreeWay = Opc == BO_Cmp; 10262 auto IsAnyPointerType = [](ExprResult E) { 10263 QualType Ty = E.get()->getType(); 10264 return Ty->isPointerType() || Ty->isMemberPointerType(); 10265 }; 10266 10267 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10268 // type, array-to-pointer, ..., conversions are performed on both operands to 10269 // bring them to their composite type. 10270 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10271 // any type-related checks. 10272 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10273 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10274 if (LHS.isInvalid()) 10275 return QualType(); 10276 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10277 if (RHS.isInvalid()) 10278 return QualType(); 10279 } else { 10280 LHS = DefaultLvalueConversion(LHS.get()); 10281 if (LHS.isInvalid()) 10282 return QualType(); 10283 RHS = DefaultLvalueConversion(RHS.get()); 10284 if (RHS.isInvalid()) 10285 return QualType(); 10286 } 10287 10288 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10289 10290 // Handle vector comparisons separately. 10291 if (LHS.get()->getType()->isVectorType() || 10292 RHS.get()->getType()->isVectorType()) 10293 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10294 10295 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10296 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10297 10298 QualType LHSType = LHS.get()->getType(); 10299 QualType RHSType = RHS.get()->getType(); 10300 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10301 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10302 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10303 10304 const Expr::NullPointerConstantKind LHSNullKind = 10305 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10306 const Expr::NullPointerConstantKind RHSNullKind = 10307 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10308 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10309 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10310 10311 auto computeResultTy = [&]() { 10312 if (Opc != BO_Cmp) 10313 return Context.getLogicalOperationType(); 10314 assert(getLangOpts().CPlusPlus); 10315 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10316 10317 QualType CompositeTy = LHS.get()->getType(); 10318 assert(!CompositeTy->isReferenceType()); 10319 10320 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10321 return CheckComparisonCategoryType(Kind, Loc); 10322 }; 10323 10324 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10325 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10326 // result is of type std::strong_equality 10327 if (CompositeTy->isFunctionPointerType() || 10328 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10329 // FIXME: consider making the function pointer case produce 10330 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10331 // and direction polls 10332 return buildResultTy(ComparisonCategoryType::StrongEquality); 10333 10334 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10335 // pointer type, p <=> q is of type std::strong_ordering. 10336 if (CompositeTy->isPointerType()) { 10337 // P0946R0: Comparisons between a null pointer constant and an object 10338 // pointer result in std::strong_equality 10339 if (LHSIsNull != RHSIsNull) 10340 return buildResultTy(ComparisonCategoryType::StrongEquality); 10341 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10342 } 10343 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10344 // TODO: Extend support for operator<=> to ObjC types. 10345 return InvalidOperands(Loc, LHS, RHS); 10346 }; 10347 10348 10349 if (!IsRelational && LHSIsNull != RHSIsNull) { 10350 bool IsEquality = Opc == BO_EQ; 10351 if (RHSIsNull) 10352 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10353 RHS.get()->getSourceRange()); 10354 else 10355 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10356 LHS.get()->getSourceRange()); 10357 } 10358 10359 if ((LHSType->isIntegerType() && !LHSIsNull) || 10360 (RHSType->isIntegerType() && !RHSIsNull)) { 10361 // Skip normal pointer conversion checks in this case; we have better 10362 // diagnostics for this below. 10363 } else if (getLangOpts().CPlusPlus) { 10364 // Equality comparison of a function pointer to a void pointer is invalid, 10365 // but we allow it as an extension. 10366 // FIXME: If we really want to allow this, should it be part of composite 10367 // pointer type computation so it works in conditionals too? 10368 if (!IsRelational && 10369 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10370 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10371 // This is a gcc extension compatibility comparison. 10372 // In a SFINAE context, we treat this as a hard error to maintain 10373 // conformance with the C++ standard. 10374 diagnoseFunctionPointerToVoidComparison( 10375 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10376 10377 if (isSFINAEContext()) 10378 return QualType(); 10379 10380 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10381 return computeResultTy(); 10382 } 10383 10384 // C++ [expr.eq]p2: 10385 // If at least one operand is a pointer [...] bring them to their 10386 // composite pointer type. 10387 // C++ [expr.spaceship]p6 10388 // If at least one of the operands is of pointer type, [...] bring them 10389 // to their composite pointer type. 10390 // C++ [expr.rel]p2: 10391 // If both operands are pointers, [...] bring them to their composite 10392 // pointer type. 10393 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10394 (IsRelational ? 2 : 1) && 10395 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10396 RHSType->isObjCObjectPointerType()))) { 10397 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10398 return QualType(); 10399 return computeResultTy(); 10400 } 10401 } else if (LHSType->isPointerType() && 10402 RHSType->isPointerType()) { // C99 6.5.8p2 10403 // All of the following pointer-related warnings are GCC extensions, except 10404 // when handling null pointer constants. 10405 QualType LCanPointeeTy = 10406 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10407 QualType RCanPointeeTy = 10408 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10409 10410 // C99 6.5.9p2 and C99 6.5.8p2 10411 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10412 RCanPointeeTy.getUnqualifiedType())) { 10413 // Valid unless a relational comparison of function pointers 10414 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10415 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10416 << LHSType << RHSType << LHS.get()->getSourceRange() 10417 << RHS.get()->getSourceRange(); 10418 } 10419 } else if (!IsRelational && 10420 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10421 // Valid unless comparison between non-null pointer and function pointer 10422 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10423 && !LHSIsNull && !RHSIsNull) 10424 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10425 /*isError*/false); 10426 } else { 10427 // Invalid 10428 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10429 } 10430 if (LCanPointeeTy != RCanPointeeTy) { 10431 // Treat NULL constant as a special case in OpenCL. 10432 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10433 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10434 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10435 Diag(Loc, 10436 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10437 << LHSType << RHSType << 0 /* comparison */ 10438 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10439 } 10440 } 10441 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10442 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10443 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10444 : CK_BitCast; 10445 if (LHSIsNull && !RHSIsNull) 10446 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10447 else 10448 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10449 } 10450 return computeResultTy(); 10451 } 10452 10453 if (getLangOpts().CPlusPlus) { 10454 // C++ [expr.eq]p4: 10455 // Two operands of type std::nullptr_t or one operand of type 10456 // std::nullptr_t and the other a null pointer constant compare equal. 10457 if (!IsRelational && LHSIsNull && RHSIsNull) { 10458 if (LHSType->isNullPtrType()) { 10459 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10460 return computeResultTy(); 10461 } 10462 if (RHSType->isNullPtrType()) { 10463 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10464 return computeResultTy(); 10465 } 10466 } 10467 10468 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10469 // These aren't covered by the composite pointer type rules. 10470 if (!IsRelational && RHSType->isNullPtrType() && 10471 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10472 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10473 return computeResultTy(); 10474 } 10475 if (!IsRelational && LHSType->isNullPtrType() && 10476 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10477 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10478 return computeResultTy(); 10479 } 10480 10481 if (IsRelational && 10482 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10483 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10484 // HACK: Relational comparison of nullptr_t against a pointer type is 10485 // invalid per DR583, but we allow it within std::less<> and friends, 10486 // since otherwise common uses of it break. 10487 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10488 // friends to have std::nullptr_t overload candidates. 10489 DeclContext *DC = CurContext; 10490 if (isa<FunctionDecl>(DC)) 10491 DC = DC->getParent(); 10492 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10493 if (CTSD->isInStdNamespace() && 10494 llvm::StringSwitch<bool>(CTSD->getName()) 10495 .Cases("less", "less_equal", "greater", "greater_equal", true) 10496 .Default(false)) { 10497 if (RHSType->isNullPtrType()) 10498 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10499 else 10500 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10501 return computeResultTy(); 10502 } 10503 } 10504 } 10505 10506 // C++ [expr.eq]p2: 10507 // If at least one operand is a pointer to member, [...] bring them to 10508 // their composite pointer type. 10509 if (!IsRelational && 10510 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10511 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10512 return QualType(); 10513 else 10514 return computeResultTy(); 10515 } 10516 } 10517 10518 // Handle block pointer types. 10519 if (!IsRelational && LHSType->isBlockPointerType() && 10520 RHSType->isBlockPointerType()) { 10521 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10522 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10523 10524 if (!LHSIsNull && !RHSIsNull && 10525 !Context.typesAreCompatible(lpointee, rpointee)) { 10526 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10527 << LHSType << RHSType << LHS.get()->getSourceRange() 10528 << RHS.get()->getSourceRange(); 10529 } 10530 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10531 return computeResultTy(); 10532 } 10533 10534 // Allow block pointers to be compared with null pointer constants. 10535 if (!IsRelational 10536 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10537 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10538 if (!LHSIsNull && !RHSIsNull) { 10539 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10540 ->getPointeeType()->isVoidType()) 10541 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10542 ->getPointeeType()->isVoidType()))) 10543 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10544 << LHSType << RHSType << LHS.get()->getSourceRange() 10545 << RHS.get()->getSourceRange(); 10546 } 10547 if (LHSIsNull && !RHSIsNull) 10548 LHS = ImpCastExprToType(LHS.get(), RHSType, 10549 RHSType->isPointerType() ? CK_BitCast 10550 : CK_AnyPointerToBlockPointerCast); 10551 else 10552 RHS = ImpCastExprToType(RHS.get(), LHSType, 10553 LHSType->isPointerType() ? CK_BitCast 10554 : CK_AnyPointerToBlockPointerCast); 10555 return computeResultTy(); 10556 } 10557 10558 if (LHSType->isObjCObjectPointerType() || 10559 RHSType->isObjCObjectPointerType()) { 10560 const PointerType *LPT = LHSType->getAs<PointerType>(); 10561 const PointerType *RPT = RHSType->getAs<PointerType>(); 10562 if (LPT || RPT) { 10563 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10564 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10565 10566 if (!LPtrToVoid && !RPtrToVoid && 10567 !Context.typesAreCompatible(LHSType, RHSType)) { 10568 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10569 /*isError*/false); 10570 } 10571 if (LHSIsNull && !RHSIsNull) { 10572 Expr *E = LHS.get(); 10573 if (getLangOpts().ObjCAutoRefCount) 10574 CheckObjCConversion(SourceRange(), RHSType, E, 10575 CCK_ImplicitConversion); 10576 LHS = ImpCastExprToType(E, RHSType, 10577 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10578 } 10579 else { 10580 Expr *E = RHS.get(); 10581 if (getLangOpts().ObjCAutoRefCount) 10582 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10583 /*Diagnose=*/true, 10584 /*DiagnoseCFAudited=*/false, Opc); 10585 RHS = ImpCastExprToType(E, LHSType, 10586 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10587 } 10588 return computeResultTy(); 10589 } 10590 if (LHSType->isObjCObjectPointerType() && 10591 RHSType->isObjCObjectPointerType()) { 10592 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10593 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10594 /*isError*/false); 10595 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10596 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10597 10598 if (LHSIsNull && !RHSIsNull) 10599 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10600 else 10601 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10602 return computeResultTy(); 10603 } 10604 10605 if (!IsRelational && LHSType->isBlockPointerType() && 10606 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10607 LHS = ImpCastExprToType(LHS.get(), RHSType, 10608 CK_BlockPointerToObjCPointerCast); 10609 return computeResultTy(); 10610 } else if (!IsRelational && 10611 LHSType->isBlockCompatibleObjCPointerType(Context) && 10612 RHSType->isBlockPointerType()) { 10613 RHS = ImpCastExprToType(RHS.get(), LHSType, 10614 CK_BlockPointerToObjCPointerCast); 10615 return computeResultTy(); 10616 } 10617 } 10618 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10619 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10620 unsigned DiagID = 0; 10621 bool isError = false; 10622 if (LangOpts.DebuggerSupport) { 10623 // Under a debugger, allow the comparison of pointers to integers, 10624 // since users tend to want to compare addresses. 10625 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10626 (RHSIsNull && RHSType->isIntegerType())) { 10627 if (IsRelational) { 10628 isError = getLangOpts().CPlusPlus; 10629 DiagID = 10630 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10631 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10632 } 10633 } else if (getLangOpts().CPlusPlus) { 10634 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10635 isError = true; 10636 } else if (IsRelational) 10637 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10638 else 10639 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10640 10641 if (DiagID) { 10642 Diag(Loc, DiagID) 10643 << LHSType << RHSType << LHS.get()->getSourceRange() 10644 << RHS.get()->getSourceRange(); 10645 if (isError) 10646 return QualType(); 10647 } 10648 10649 if (LHSType->isIntegerType()) 10650 LHS = ImpCastExprToType(LHS.get(), RHSType, 10651 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10652 else 10653 RHS = ImpCastExprToType(RHS.get(), LHSType, 10654 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10655 return computeResultTy(); 10656 } 10657 10658 // Handle block pointers. 10659 if (!IsRelational && RHSIsNull 10660 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10661 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10662 return computeResultTy(); 10663 } 10664 if (!IsRelational && LHSIsNull 10665 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10666 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10667 return computeResultTy(); 10668 } 10669 10670 if (getLangOpts().OpenCLVersion >= 200) { 10671 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10672 return computeResultTy(); 10673 } 10674 10675 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10676 return computeResultTy(); 10677 } 10678 10679 if (LHSIsNull && RHSType->isQueueT()) { 10680 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10681 return computeResultTy(); 10682 } 10683 10684 if (LHSType->isQueueT() && RHSIsNull) { 10685 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10686 return computeResultTy(); 10687 } 10688 } 10689 10690 return InvalidOperands(Loc, LHS, RHS); 10691 } 10692 10693 // Return a signed ext_vector_type that is of identical size and number of 10694 // elements. For floating point vectors, return an integer type of identical 10695 // size and number of elements. In the non ext_vector_type case, search from 10696 // the largest type to the smallest type to avoid cases where long long == long, 10697 // where long gets picked over long long. 10698 QualType Sema::GetSignedVectorType(QualType V) { 10699 const VectorType *VTy = V->getAs<VectorType>(); 10700 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10701 10702 if (isa<ExtVectorType>(VTy)) { 10703 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10704 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10705 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10706 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10707 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10708 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10709 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10710 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10711 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10712 "Unhandled vector element size in vector compare"); 10713 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10714 } 10715 10716 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10717 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10718 VectorType::GenericVector); 10719 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10720 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10721 VectorType::GenericVector); 10722 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10723 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10724 VectorType::GenericVector); 10725 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10726 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10727 VectorType::GenericVector); 10728 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10729 "Unhandled vector element size in vector compare"); 10730 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10731 VectorType::GenericVector); 10732 } 10733 10734 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10735 /// operates on extended vector types. Instead of producing an IntTy result, 10736 /// like a scalar comparison, a vector comparison produces a vector of integer 10737 /// types. 10738 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10739 SourceLocation Loc, 10740 BinaryOperatorKind Opc) { 10741 // Check to make sure we're operating on vectors of the same type and width, 10742 // Allowing one side to be a scalar of element type. 10743 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10744 /*AllowBothBool*/true, 10745 /*AllowBoolConversions*/getLangOpts().ZVector); 10746 if (vType.isNull()) 10747 return vType; 10748 10749 QualType LHSType = LHS.get()->getType(); 10750 10751 // If AltiVec, the comparison results in a numeric type, i.e. 10752 // bool for C++, int for C 10753 if (getLangOpts().AltiVec && 10754 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10755 return Context.getLogicalOperationType(); 10756 10757 // For non-floating point types, check for self-comparisons of the form 10758 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10759 // often indicate logic errors in the program. 10760 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10761 10762 // Check for comparisons of floating point operands using != and ==. 10763 if (BinaryOperator::isEqualityOp(Opc) && 10764 LHSType->hasFloatingRepresentation()) { 10765 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10766 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10767 } 10768 10769 // Return a signed type for the vector. 10770 return GetSignedVectorType(vType); 10771 } 10772 10773 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10774 SourceLocation Loc) { 10775 // Ensure that either both operands are of the same vector type, or 10776 // one operand is of a vector type and the other is of its element type. 10777 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10778 /*AllowBothBool*/true, 10779 /*AllowBoolConversions*/false); 10780 if (vType.isNull()) 10781 return InvalidOperands(Loc, LHS, RHS); 10782 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10783 vType->hasFloatingRepresentation()) 10784 return InvalidOperands(Loc, LHS, RHS); 10785 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10786 // usage of the logical operators && and || with vectors in C. This 10787 // check could be notionally dropped. 10788 if (!getLangOpts().CPlusPlus && 10789 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10790 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10791 10792 return GetSignedVectorType(LHS.get()->getType()); 10793 } 10794 10795 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10796 SourceLocation Loc, 10797 BinaryOperatorKind Opc) { 10798 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10799 10800 bool IsCompAssign = 10801 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10802 10803 if (LHS.get()->getType()->isVectorType() || 10804 RHS.get()->getType()->isVectorType()) { 10805 if (LHS.get()->getType()->hasIntegerRepresentation() && 10806 RHS.get()->getType()->hasIntegerRepresentation()) 10807 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10808 /*AllowBothBool*/true, 10809 /*AllowBoolConversions*/getLangOpts().ZVector); 10810 return InvalidOperands(Loc, LHS, RHS); 10811 } 10812 10813 if (Opc == BO_And) 10814 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10815 10816 ExprResult LHSResult = LHS, RHSResult = RHS; 10817 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10818 IsCompAssign); 10819 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10820 return QualType(); 10821 LHS = LHSResult.get(); 10822 RHS = RHSResult.get(); 10823 10824 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10825 return compType; 10826 return InvalidOperands(Loc, LHS, RHS); 10827 } 10828 10829 // C99 6.5.[13,14] 10830 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10831 SourceLocation Loc, 10832 BinaryOperatorKind Opc) { 10833 // Check vector operands differently. 10834 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10835 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10836 10837 // Diagnose cases where the user write a logical and/or but probably meant a 10838 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10839 // is a constant. 10840 if (LHS.get()->getType()->isIntegerType() && 10841 !LHS.get()->getType()->isBooleanType() && 10842 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10843 // Don't warn in macros or template instantiations. 10844 !Loc.isMacroID() && !inTemplateInstantiation()) { 10845 // If the RHS can be constant folded, and if it constant folds to something 10846 // that isn't 0 or 1 (which indicate a potential logical operation that 10847 // happened to fold to true/false) then warn. 10848 // Parens on the RHS are ignored. 10849 Expr::EvalResult EVResult; 10850 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 10851 llvm::APSInt Result = EVResult.Val.getInt(); 10852 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10853 !RHS.get()->getExprLoc().isMacroID()) || 10854 (Result != 0 && Result != 1)) { 10855 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10856 << RHS.get()->getSourceRange() 10857 << (Opc == BO_LAnd ? "&&" : "||"); 10858 // Suggest replacing the logical operator with the bitwise version 10859 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10860 << (Opc == BO_LAnd ? "&" : "|") 10861 << FixItHint::CreateReplacement(SourceRange( 10862 Loc, getLocForEndOfToken(Loc)), 10863 Opc == BO_LAnd ? "&" : "|"); 10864 if (Opc == BO_LAnd) 10865 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10866 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10867 << FixItHint::CreateRemoval( 10868 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10869 RHS.get()->getEndLoc())); 10870 } 10871 } 10872 } 10873 10874 if (!Context.getLangOpts().CPlusPlus) { 10875 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10876 // not operate on the built-in scalar and vector float types. 10877 if (Context.getLangOpts().OpenCL && 10878 Context.getLangOpts().OpenCLVersion < 120) { 10879 if (LHS.get()->getType()->isFloatingType() || 10880 RHS.get()->getType()->isFloatingType()) 10881 return InvalidOperands(Loc, LHS, RHS); 10882 } 10883 10884 LHS = UsualUnaryConversions(LHS.get()); 10885 if (LHS.isInvalid()) 10886 return QualType(); 10887 10888 RHS = UsualUnaryConversions(RHS.get()); 10889 if (RHS.isInvalid()) 10890 return QualType(); 10891 10892 if (!LHS.get()->getType()->isScalarType() || 10893 !RHS.get()->getType()->isScalarType()) 10894 return InvalidOperands(Loc, LHS, RHS); 10895 10896 return Context.IntTy; 10897 } 10898 10899 // The following is safe because we only use this method for 10900 // non-overloadable operands. 10901 10902 // C++ [expr.log.and]p1 10903 // C++ [expr.log.or]p1 10904 // The operands are both contextually converted to type bool. 10905 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10906 if (LHSRes.isInvalid()) 10907 return InvalidOperands(Loc, LHS, RHS); 10908 LHS = LHSRes; 10909 10910 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10911 if (RHSRes.isInvalid()) 10912 return InvalidOperands(Loc, LHS, RHS); 10913 RHS = RHSRes; 10914 10915 // C++ [expr.log.and]p2 10916 // C++ [expr.log.or]p2 10917 // The result is a bool. 10918 return Context.BoolTy; 10919 } 10920 10921 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10922 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10923 if (!ME) return false; 10924 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10925 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10926 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10927 if (!Base) return false; 10928 return Base->getMethodDecl() != nullptr; 10929 } 10930 10931 /// Is the given expression (which must be 'const') a reference to a 10932 /// variable which was originally non-const, but which has become 10933 /// 'const' due to being captured within a block? 10934 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10935 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10936 assert(E->isLValue() && E->getType().isConstQualified()); 10937 E = E->IgnoreParens(); 10938 10939 // Must be a reference to a declaration from an enclosing scope. 10940 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10941 if (!DRE) return NCCK_None; 10942 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10943 10944 // The declaration must be a variable which is not declared 'const'. 10945 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10946 if (!var) return NCCK_None; 10947 if (var->getType().isConstQualified()) return NCCK_None; 10948 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10949 10950 // Decide whether the first capture was for a block or a lambda. 10951 DeclContext *DC = S.CurContext, *Prev = nullptr; 10952 // Decide whether the first capture was for a block or a lambda. 10953 while (DC) { 10954 // For init-capture, it is possible that the variable belongs to the 10955 // template pattern of the current context. 10956 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10957 if (var->isInitCapture() && 10958 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10959 break; 10960 if (DC == var->getDeclContext()) 10961 break; 10962 Prev = DC; 10963 DC = DC->getParent(); 10964 } 10965 // Unless we have an init-capture, we've gone one step too far. 10966 if (!var->isInitCapture()) 10967 DC = Prev; 10968 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10969 } 10970 10971 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10972 Ty = Ty.getNonReferenceType(); 10973 if (IsDereference && Ty->isPointerType()) 10974 Ty = Ty->getPointeeType(); 10975 return !Ty.isConstQualified(); 10976 } 10977 10978 // Update err_typecheck_assign_const and note_typecheck_assign_const 10979 // when this enum is changed. 10980 enum { 10981 ConstFunction, 10982 ConstVariable, 10983 ConstMember, 10984 ConstMethod, 10985 NestedConstMember, 10986 ConstUnknown, // Keep as last element 10987 }; 10988 10989 /// Emit the "read-only variable not assignable" error and print notes to give 10990 /// more information about why the variable is not assignable, such as pointing 10991 /// to the declaration of a const variable, showing that a method is const, or 10992 /// that the function is returning a const reference. 10993 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10994 SourceLocation Loc) { 10995 SourceRange ExprRange = E->getSourceRange(); 10996 10997 // Only emit one error on the first const found. All other consts will emit 10998 // a note to the error. 10999 bool DiagnosticEmitted = false; 11000 11001 // Track if the current expression is the result of a dereference, and if the 11002 // next checked expression is the result of a dereference. 11003 bool IsDereference = false; 11004 bool NextIsDereference = false; 11005 11006 // Loop to process MemberExpr chains. 11007 while (true) { 11008 IsDereference = NextIsDereference; 11009 11010 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11011 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11012 NextIsDereference = ME->isArrow(); 11013 const ValueDecl *VD = ME->getMemberDecl(); 11014 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11015 // Mutable fields can be modified even if the class is const. 11016 if (Field->isMutable()) { 11017 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11018 break; 11019 } 11020 11021 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11022 if (!DiagnosticEmitted) { 11023 S.Diag(Loc, diag::err_typecheck_assign_const) 11024 << ExprRange << ConstMember << false /*static*/ << Field 11025 << Field->getType(); 11026 DiagnosticEmitted = true; 11027 } 11028 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11029 << ConstMember << false /*static*/ << Field << Field->getType() 11030 << Field->getSourceRange(); 11031 } 11032 E = ME->getBase(); 11033 continue; 11034 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11035 if (VDecl->getType().isConstQualified()) { 11036 if (!DiagnosticEmitted) { 11037 S.Diag(Loc, diag::err_typecheck_assign_const) 11038 << ExprRange << ConstMember << true /*static*/ << VDecl 11039 << VDecl->getType(); 11040 DiagnosticEmitted = true; 11041 } 11042 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11043 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11044 << VDecl->getSourceRange(); 11045 } 11046 // Static fields do not inherit constness from parents. 11047 break; 11048 } 11049 break; // End MemberExpr 11050 } else if (const ArraySubscriptExpr *ASE = 11051 dyn_cast<ArraySubscriptExpr>(E)) { 11052 E = ASE->getBase()->IgnoreParenImpCasts(); 11053 continue; 11054 } else if (const ExtVectorElementExpr *EVE = 11055 dyn_cast<ExtVectorElementExpr>(E)) { 11056 E = EVE->getBase()->IgnoreParenImpCasts(); 11057 continue; 11058 } 11059 break; 11060 } 11061 11062 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11063 // Function calls 11064 const FunctionDecl *FD = CE->getDirectCallee(); 11065 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11066 if (!DiagnosticEmitted) { 11067 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11068 << ConstFunction << FD; 11069 DiagnosticEmitted = true; 11070 } 11071 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11072 diag::note_typecheck_assign_const) 11073 << ConstFunction << FD << FD->getReturnType() 11074 << FD->getReturnTypeSourceRange(); 11075 } 11076 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11077 // Point to variable declaration. 11078 if (const ValueDecl *VD = DRE->getDecl()) { 11079 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11080 if (!DiagnosticEmitted) { 11081 S.Diag(Loc, diag::err_typecheck_assign_const) 11082 << ExprRange << ConstVariable << VD << VD->getType(); 11083 DiagnosticEmitted = true; 11084 } 11085 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11086 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11087 } 11088 } 11089 } else if (isa<CXXThisExpr>(E)) { 11090 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11091 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11092 if (MD->isConst()) { 11093 if (!DiagnosticEmitted) { 11094 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11095 << ConstMethod << MD; 11096 DiagnosticEmitted = true; 11097 } 11098 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11099 << ConstMethod << MD << MD->getSourceRange(); 11100 } 11101 } 11102 } 11103 } 11104 11105 if (DiagnosticEmitted) 11106 return; 11107 11108 // Can't determine a more specific message, so display the generic error. 11109 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11110 } 11111 11112 enum OriginalExprKind { 11113 OEK_Variable, 11114 OEK_Member, 11115 OEK_LValue 11116 }; 11117 11118 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11119 const RecordType *Ty, 11120 SourceLocation Loc, SourceRange Range, 11121 OriginalExprKind OEK, 11122 bool &DiagnosticEmitted) { 11123 std::vector<const RecordType *> RecordTypeList; 11124 RecordTypeList.push_back(Ty); 11125 unsigned NextToCheckIndex = 0; 11126 // We walk the record hierarchy breadth-first to ensure that we print 11127 // diagnostics in field nesting order. 11128 while (RecordTypeList.size() > NextToCheckIndex) { 11129 bool IsNested = NextToCheckIndex > 0; 11130 for (const FieldDecl *Field : 11131 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11132 // First, check every field for constness. 11133 QualType FieldTy = Field->getType(); 11134 if (FieldTy.isConstQualified()) { 11135 if (!DiagnosticEmitted) { 11136 S.Diag(Loc, diag::err_typecheck_assign_const) 11137 << Range << NestedConstMember << OEK << VD 11138 << IsNested << Field; 11139 DiagnosticEmitted = true; 11140 } 11141 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11142 << NestedConstMember << IsNested << Field 11143 << FieldTy << Field->getSourceRange(); 11144 } 11145 11146 // Then we append it to the list to check next in order. 11147 FieldTy = FieldTy.getCanonicalType(); 11148 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11149 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11150 RecordTypeList.push_back(FieldRecTy); 11151 } 11152 } 11153 ++NextToCheckIndex; 11154 } 11155 } 11156 11157 /// Emit an error for the case where a record we are trying to assign to has a 11158 /// const-qualified field somewhere in its hierarchy. 11159 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11160 SourceLocation Loc) { 11161 QualType Ty = E->getType(); 11162 assert(Ty->isRecordType() && "lvalue was not record?"); 11163 SourceRange Range = E->getSourceRange(); 11164 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11165 bool DiagEmitted = false; 11166 11167 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11168 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11169 Range, OEK_Member, DiagEmitted); 11170 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11171 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11172 Range, OEK_Variable, DiagEmitted); 11173 else 11174 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11175 Range, OEK_LValue, DiagEmitted); 11176 if (!DiagEmitted) 11177 DiagnoseConstAssignment(S, E, Loc); 11178 } 11179 11180 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11181 /// emit an error and return true. If so, return false. 11182 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11183 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11184 11185 S.CheckShadowingDeclModification(E, Loc); 11186 11187 SourceLocation OrigLoc = Loc; 11188 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11189 &Loc); 11190 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11191 IsLV = Expr::MLV_InvalidMessageExpression; 11192 if (IsLV == Expr::MLV_Valid) 11193 return false; 11194 11195 unsigned DiagID = 0; 11196 bool NeedType = false; 11197 switch (IsLV) { // C99 6.5.16p2 11198 case Expr::MLV_ConstQualified: 11199 // Use a specialized diagnostic when we're assigning to an object 11200 // from an enclosing function or block. 11201 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11202 if (NCCK == NCCK_Block) 11203 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11204 else 11205 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11206 break; 11207 } 11208 11209 // In ARC, use some specialized diagnostics for occasions where we 11210 // infer 'const'. These are always pseudo-strong variables. 11211 if (S.getLangOpts().ObjCAutoRefCount) { 11212 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11213 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11214 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11215 11216 // Use the normal diagnostic if it's pseudo-__strong but the 11217 // user actually wrote 'const'. 11218 if (var->isARCPseudoStrong() && 11219 (!var->getTypeSourceInfo() || 11220 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11221 // There are three pseudo-strong cases: 11222 // - self 11223 ObjCMethodDecl *method = S.getCurMethodDecl(); 11224 if (method && var == method->getSelfDecl()) { 11225 DiagID = method->isClassMethod() 11226 ? diag::err_typecheck_arc_assign_self_class_method 11227 : diag::err_typecheck_arc_assign_self; 11228 11229 // - Objective-C externally_retained attribute. 11230 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11231 isa<ParmVarDecl>(var)) { 11232 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11233 11234 // - fast enumeration variables 11235 } else { 11236 DiagID = diag::err_typecheck_arr_assign_enumeration; 11237 } 11238 11239 SourceRange Assign; 11240 if (Loc != OrigLoc) 11241 Assign = SourceRange(OrigLoc, OrigLoc); 11242 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11243 // We need to preserve the AST regardless, so migration tool 11244 // can do its job. 11245 return false; 11246 } 11247 } 11248 } 11249 11250 // If none of the special cases above are triggered, then this is a 11251 // simple const assignment. 11252 if (DiagID == 0) { 11253 DiagnoseConstAssignment(S, E, Loc); 11254 return true; 11255 } 11256 11257 break; 11258 case Expr::MLV_ConstAddrSpace: 11259 DiagnoseConstAssignment(S, E, Loc); 11260 return true; 11261 case Expr::MLV_ConstQualifiedField: 11262 DiagnoseRecursiveConstFields(S, E, Loc); 11263 return true; 11264 case Expr::MLV_ArrayType: 11265 case Expr::MLV_ArrayTemporary: 11266 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11267 NeedType = true; 11268 break; 11269 case Expr::MLV_NotObjectType: 11270 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11271 NeedType = true; 11272 break; 11273 case Expr::MLV_LValueCast: 11274 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11275 break; 11276 case Expr::MLV_Valid: 11277 llvm_unreachable("did not take early return for MLV_Valid"); 11278 case Expr::MLV_InvalidExpression: 11279 case Expr::MLV_MemberFunction: 11280 case Expr::MLV_ClassTemporary: 11281 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11282 break; 11283 case Expr::MLV_IncompleteType: 11284 case Expr::MLV_IncompleteVoidType: 11285 return S.RequireCompleteType(Loc, E->getType(), 11286 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11287 case Expr::MLV_DuplicateVectorComponents: 11288 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11289 break; 11290 case Expr::MLV_NoSetterProperty: 11291 llvm_unreachable("readonly properties should be processed differently"); 11292 case Expr::MLV_InvalidMessageExpression: 11293 DiagID = diag::err_readonly_message_assignment; 11294 break; 11295 case Expr::MLV_SubObjCPropertySetting: 11296 DiagID = diag::err_no_subobject_property_setting; 11297 break; 11298 } 11299 11300 SourceRange Assign; 11301 if (Loc != OrigLoc) 11302 Assign = SourceRange(OrigLoc, OrigLoc); 11303 if (NeedType) 11304 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11305 else 11306 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11307 return true; 11308 } 11309 11310 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11311 SourceLocation Loc, 11312 Sema &Sema) { 11313 if (Sema.inTemplateInstantiation()) 11314 return; 11315 if (Sema.isUnevaluatedContext()) 11316 return; 11317 if (Loc.isInvalid() || Loc.isMacroID()) 11318 return; 11319 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11320 return; 11321 11322 // C / C++ fields 11323 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11324 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11325 if (ML && MR) { 11326 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11327 return; 11328 const ValueDecl *LHSDecl = 11329 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11330 const ValueDecl *RHSDecl = 11331 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11332 if (LHSDecl != RHSDecl) 11333 return; 11334 if (LHSDecl->getType().isVolatileQualified()) 11335 return; 11336 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11337 if (RefTy->getPointeeType().isVolatileQualified()) 11338 return; 11339 11340 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11341 } 11342 11343 // Objective-C instance variables 11344 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11345 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11346 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11347 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11348 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11349 if (RL && RR && RL->getDecl() == RR->getDecl()) 11350 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11351 } 11352 } 11353 11354 // C99 6.5.16.1 11355 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11356 SourceLocation Loc, 11357 QualType CompoundType) { 11358 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11359 11360 // Verify that LHS is a modifiable lvalue, and emit error if not. 11361 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11362 return QualType(); 11363 11364 QualType LHSType = LHSExpr->getType(); 11365 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11366 CompoundType; 11367 // OpenCL v1.2 s6.1.1.1 p2: 11368 // The half data type can only be used to declare a pointer to a buffer that 11369 // contains half values 11370 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11371 LHSType->isHalfType()) { 11372 Diag(Loc, diag::err_opencl_half_load_store) << 1 11373 << LHSType.getUnqualifiedType(); 11374 return QualType(); 11375 } 11376 11377 AssignConvertType ConvTy; 11378 if (CompoundType.isNull()) { 11379 Expr *RHSCheck = RHS.get(); 11380 11381 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11382 11383 QualType LHSTy(LHSType); 11384 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11385 if (RHS.isInvalid()) 11386 return QualType(); 11387 // Special case of NSObject attributes on c-style pointer types. 11388 if (ConvTy == IncompatiblePointer && 11389 ((Context.isObjCNSObjectType(LHSType) && 11390 RHSType->isObjCObjectPointerType()) || 11391 (Context.isObjCNSObjectType(RHSType) && 11392 LHSType->isObjCObjectPointerType()))) 11393 ConvTy = Compatible; 11394 11395 if (ConvTy == Compatible && 11396 LHSType->isObjCObjectType()) 11397 Diag(Loc, diag::err_objc_object_assignment) 11398 << LHSType; 11399 11400 // If the RHS is a unary plus or minus, check to see if they = and + are 11401 // right next to each other. If so, the user may have typo'd "x =+ 4" 11402 // instead of "x += 4". 11403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11404 RHSCheck = ICE->getSubExpr(); 11405 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11406 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11407 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11408 // Only if the two operators are exactly adjacent. 11409 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11410 // And there is a space or other character before the subexpr of the 11411 // unary +/-. We don't want to warn on "x=-1". 11412 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11413 UO->getSubExpr()->getBeginLoc().isFileID()) { 11414 Diag(Loc, diag::warn_not_compound_assign) 11415 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11416 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11417 } 11418 } 11419 11420 if (ConvTy == Compatible) { 11421 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11422 // Warn about retain cycles where a block captures the LHS, but 11423 // not if the LHS is a simple variable into which the block is 11424 // being stored...unless that variable can be captured by reference! 11425 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11426 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11427 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11428 checkRetainCycles(LHSExpr, RHS.get()); 11429 } 11430 11431 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11432 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11433 // It is safe to assign a weak reference into a strong variable. 11434 // Although this code can still have problems: 11435 // id x = self.weakProp; 11436 // id y = self.weakProp; 11437 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11438 // paths through the function. This should be revisited if 11439 // -Wrepeated-use-of-weak is made flow-sensitive. 11440 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11441 // variable, which will be valid for the current autorelease scope. 11442 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11443 RHS.get()->getBeginLoc())) 11444 getCurFunction()->markSafeWeakUse(RHS.get()); 11445 11446 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11447 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11448 } 11449 } 11450 } else { 11451 // Compound assignment "x += y" 11452 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11453 } 11454 11455 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11456 RHS.get(), AA_Assigning)) 11457 return QualType(); 11458 11459 CheckForNullPointerDereference(*this, LHSExpr); 11460 11461 // C99 6.5.16p3: The type of an assignment expression is the type of the 11462 // left operand unless the left operand has qualified type, in which case 11463 // it is the unqualified version of the type of the left operand. 11464 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11465 // is converted to the type of the assignment expression (above). 11466 // C++ 5.17p1: the type of the assignment expression is that of its left 11467 // operand. 11468 return (getLangOpts().CPlusPlus 11469 ? LHSType : LHSType.getUnqualifiedType()); 11470 } 11471 11472 // Only ignore explicit casts to void. 11473 static bool IgnoreCommaOperand(const Expr *E) { 11474 E = E->IgnoreParens(); 11475 11476 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11477 if (CE->getCastKind() == CK_ToVoid) { 11478 return true; 11479 } 11480 11481 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11482 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11483 CE->getSubExpr()->getType()->isDependentType()) { 11484 return true; 11485 } 11486 } 11487 11488 return false; 11489 } 11490 11491 // Look for instances where it is likely the comma operator is confused with 11492 // another operator. There is a whitelist of acceptable expressions for the 11493 // left hand side of the comma operator, otherwise emit a warning. 11494 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11495 // No warnings in macros 11496 if (Loc.isMacroID()) 11497 return; 11498 11499 // Don't warn in template instantiations. 11500 if (inTemplateInstantiation()) 11501 return; 11502 11503 // Scope isn't fine-grained enough to whitelist the specific cases, so 11504 // instead, skip more than needed, then call back into here with the 11505 // CommaVisitor in SemaStmt.cpp. 11506 // The whitelisted locations are the initialization and increment portions 11507 // of a for loop. The additional checks are on the condition of 11508 // if statements, do/while loops, and for loops. 11509 // Differences in scope flags for C89 mode requires the extra logic. 11510 const unsigned ForIncrementFlags = 11511 getLangOpts().C99 || getLangOpts().CPlusPlus 11512 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11513 : Scope::ContinueScope | Scope::BreakScope; 11514 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11515 const unsigned ScopeFlags = getCurScope()->getFlags(); 11516 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11517 (ScopeFlags & ForInitFlags) == ForInitFlags) 11518 return; 11519 11520 // If there are multiple comma operators used together, get the RHS of the 11521 // of the comma operator as the LHS. 11522 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11523 if (BO->getOpcode() != BO_Comma) 11524 break; 11525 LHS = BO->getRHS(); 11526 } 11527 11528 // Only allow some expressions on LHS to not warn. 11529 if (IgnoreCommaOperand(LHS)) 11530 return; 11531 11532 Diag(Loc, diag::warn_comma_operator); 11533 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11534 << LHS->getSourceRange() 11535 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11536 LangOpts.CPlusPlus ? "static_cast<void>(" 11537 : "(void)(") 11538 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11539 ")"); 11540 } 11541 11542 // C99 6.5.17 11543 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11544 SourceLocation Loc) { 11545 LHS = S.CheckPlaceholderExpr(LHS.get()); 11546 RHS = S.CheckPlaceholderExpr(RHS.get()); 11547 if (LHS.isInvalid() || RHS.isInvalid()) 11548 return QualType(); 11549 11550 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11551 // operands, but not unary promotions. 11552 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11553 11554 // So we treat the LHS as a ignored value, and in C++ we allow the 11555 // containing site to determine what should be done with the RHS. 11556 LHS = S.IgnoredValueConversions(LHS.get()); 11557 if (LHS.isInvalid()) 11558 return QualType(); 11559 11560 S.DiagnoseUnusedExprResult(LHS.get()); 11561 11562 if (!S.getLangOpts().CPlusPlus) { 11563 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11564 if (RHS.isInvalid()) 11565 return QualType(); 11566 if (!RHS.get()->getType()->isVoidType()) 11567 S.RequireCompleteType(Loc, RHS.get()->getType(), 11568 diag::err_incomplete_type); 11569 } 11570 11571 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11572 S.DiagnoseCommaOperator(LHS.get(), Loc); 11573 11574 return RHS.get()->getType(); 11575 } 11576 11577 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11578 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11579 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11580 ExprValueKind &VK, 11581 ExprObjectKind &OK, 11582 SourceLocation OpLoc, 11583 bool IsInc, bool IsPrefix) { 11584 if (Op->isTypeDependent()) 11585 return S.Context.DependentTy; 11586 11587 QualType ResType = Op->getType(); 11588 // Atomic types can be used for increment / decrement where the non-atomic 11589 // versions can, so ignore the _Atomic() specifier for the purpose of 11590 // checking. 11591 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11592 ResType = ResAtomicType->getValueType(); 11593 11594 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11595 11596 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11597 // Decrement of bool is not allowed. 11598 if (!IsInc) { 11599 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11600 return QualType(); 11601 } 11602 // Increment of bool sets it to true, but is deprecated. 11603 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11604 : diag::warn_increment_bool) 11605 << Op->getSourceRange(); 11606 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11607 // Error on enum increments and decrements in C++ mode 11608 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11609 return QualType(); 11610 } else if (ResType->isRealType()) { 11611 // OK! 11612 } else if (ResType->isPointerType()) { 11613 // C99 6.5.2.4p2, 6.5.6p2 11614 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11615 return QualType(); 11616 } else if (ResType->isObjCObjectPointerType()) { 11617 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11618 // Otherwise, we just need a complete type. 11619 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11620 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11621 return QualType(); 11622 } else if (ResType->isAnyComplexType()) { 11623 // C99 does not support ++/-- on complex types, we allow as an extension. 11624 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11625 << ResType << Op->getSourceRange(); 11626 } else if (ResType->isPlaceholderType()) { 11627 ExprResult PR = S.CheckPlaceholderExpr(Op); 11628 if (PR.isInvalid()) return QualType(); 11629 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11630 IsInc, IsPrefix); 11631 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11632 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11633 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11634 (ResType->getAs<VectorType>()->getVectorKind() != 11635 VectorType::AltiVecBool)) { 11636 // The z vector extensions allow ++ and -- for non-bool vectors. 11637 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11638 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11639 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11640 } else { 11641 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11642 << ResType << int(IsInc) << Op->getSourceRange(); 11643 return QualType(); 11644 } 11645 // At this point, we know we have a real, complex or pointer type. 11646 // Now make sure the operand is a modifiable lvalue. 11647 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11648 return QualType(); 11649 // In C++, a prefix increment is the same type as the operand. Otherwise 11650 // (in C or with postfix), the increment is the unqualified type of the 11651 // operand. 11652 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11653 VK = VK_LValue; 11654 OK = Op->getObjectKind(); 11655 return ResType; 11656 } else { 11657 VK = VK_RValue; 11658 return ResType.getUnqualifiedType(); 11659 } 11660 } 11661 11662 11663 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11664 /// This routine allows us to typecheck complex/recursive expressions 11665 /// where the declaration is needed for type checking. We only need to 11666 /// handle cases when the expression references a function designator 11667 /// or is an lvalue. Here are some examples: 11668 /// - &(x) => x 11669 /// - &*****f => f for f a function designator. 11670 /// - &s.xx => s 11671 /// - &s.zz[1].yy -> s, if zz is an array 11672 /// - *(x + 1) -> x, if x is an array 11673 /// - &"123"[2] -> 0 11674 /// - & __real__ x -> x 11675 static ValueDecl *getPrimaryDecl(Expr *E) { 11676 switch (E->getStmtClass()) { 11677 case Stmt::DeclRefExprClass: 11678 return cast<DeclRefExpr>(E)->getDecl(); 11679 case Stmt::MemberExprClass: 11680 // If this is an arrow operator, the address is an offset from 11681 // the base's value, so the object the base refers to is 11682 // irrelevant. 11683 if (cast<MemberExpr>(E)->isArrow()) 11684 return nullptr; 11685 // Otherwise, the expression refers to a part of the base 11686 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11687 case Stmt::ArraySubscriptExprClass: { 11688 // FIXME: This code shouldn't be necessary! We should catch the implicit 11689 // promotion of register arrays earlier. 11690 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11691 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11692 if (ICE->getSubExpr()->getType()->isArrayType()) 11693 return getPrimaryDecl(ICE->getSubExpr()); 11694 } 11695 return nullptr; 11696 } 11697 case Stmt::UnaryOperatorClass: { 11698 UnaryOperator *UO = cast<UnaryOperator>(E); 11699 11700 switch(UO->getOpcode()) { 11701 case UO_Real: 11702 case UO_Imag: 11703 case UO_Extension: 11704 return getPrimaryDecl(UO->getSubExpr()); 11705 default: 11706 return nullptr; 11707 } 11708 } 11709 case Stmt::ParenExprClass: 11710 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11711 case Stmt::ImplicitCastExprClass: 11712 // If the result of an implicit cast is an l-value, we care about 11713 // the sub-expression; otherwise, the result here doesn't matter. 11714 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11715 default: 11716 return nullptr; 11717 } 11718 } 11719 11720 namespace { 11721 enum { 11722 AO_Bit_Field = 0, 11723 AO_Vector_Element = 1, 11724 AO_Property_Expansion = 2, 11725 AO_Register_Variable = 3, 11726 AO_No_Error = 4 11727 }; 11728 } 11729 /// Diagnose invalid operand for address of operations. 11730 /// 11731 /// \param Type The type of operand which cannot have its address taken. 11732 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11733 Expr *E, unsigned Type) { 11734 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11735 } 11736 11737 /// CheckAddressOfOperand - The operand of & must be either a function 11738 /// designator or an lvalue designating an object. If it is an lvalue, the 11739 /// object cannot be declared with storage class register or be a bit field. 11740 /// Note: The usual conversions are *not* applied to the operand of the & 11741 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11742 /// In C++, the operand might be an overloaded function name, in which case 11743 /// we allow the '&' but retain the overloaded-function type. 11744 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11745 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11746 if (PTy->getKind() == BuiltinType::Overload) { 11747 Expr *E = OrigOp.get()->IgnoreParens(); 11748 if (!isa<OverloadExpr>(E)) { 11749 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11750 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11751 << OrigOp.get()->getSourceRange(); 11752 return QualType(); 11753 } 11754 11755 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11756 if (isa<UnresolvedMemberExpr>(Ovl)) 11757 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11758 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11759 << OrigOp.get()->getSourceRange(); 11760 return QualType(); 11761 } 11762 11763 return Context.OverloadTy; 11764 } 11765 11766 if (PTy->getKind() == BuiltinType::UnknownAny) 11767 return Context.UnknownAnyTy; 11768 11769 if (PTy->getKind() == BuiltinType::BoundMember) { 11770 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11771 << OrigOp.get()->getSourceRange(); 11772 return QualType(); 11773 } 11774 11775 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11776 if (OrigOp.isInvalid()) return QualType(); 11777 } 11778 11779 if (OrigOp.get()->isTypeDependent()) 11780 return Context.DependentTy; 11781 11782 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11783 11784 // Make sure to ignore parentheses in subsequent checks 11785 Expr *op = OrigOp.get()->IgnoreParens(); 11786 11787 // In OpenCL captures for blocks called as lambda functions 11788 // are located in the private address space. Blocks used in 11789 // enqueue_kernel can be located in a different address space 11790 // depending on a vendor implementation. Thus preventing 11791 // taking an address of the capture to avoid invalid AS casts. 11792 if (LangOpts.OpenCL) { 11793 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11794 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11795 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11796 return QualType(); 11797 } 11798 } 11799 11800 if (getLangOpts().C99) { 11801 // Implement C99-only parts of addressof rules. 11802 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11803 if (uOp->getOpcode() == UO_Deref) 11804 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11805 // (assuming the deref expression is valid). 11806 return uOp->getSubExpr()->getType(); 11807 } 11808 // Technically, there should be a check for array subscript 11809 // expressions here, but the result of one is always an lvalue anyway. 11810 } 11811 ValueDecl *dcl = getPrimaryDecl(op); 11812 11813 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11814 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11815 op->getBeginLoc())) 11816 return QualType(); 11817 11818 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11819 unsigned AddressOfError = AO_No_Error; 11820 11821 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11822 bool sfinae = (bool)isSFINAEContext(); 11823 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11824 : diag::ext_typecheck_addrof_temporary) 11825 << op->getType() << op->getSourceRange(); 11826 if (sfinae) 11827 return QualType(); 11828 // Materialize the temporary as an lvalue so that we can take its address. 11829 OrigOp = op = 11830 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11831 } else if (isa<ObjCSelectorExpr>(op)) { 11832 return Context.getPointerType(op->getType()); 11833 } else if (lval == Expr::LV_MemberFunction) { 11834 // If it's an instance method, make a member pointer. 11835 // The expression must have exactly the form &A::foo. 11836 11837 // If the underlying expression isn't a decl ref, give up. 11838 if (!isa<DeclRefExpr>(op)) { 11839 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11840 << OrigOp.get()->getSourceRange(); 11841 return QualType(); 11842 } 11843 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11844 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11845 11846 // The id-expression was parenthesized. 11847 if (OrigOp.get() != DRE) { 11848 Diag(OpLoc, diag::err_parens_pointer_member_function) 11849 << OrigOp.get()->getSourceRange(); 11850 11851 // The method was named without a qualifier. 11852 } else if (!DRE->getQualifier()) { 11853 if (MD->getParent()->getName().empty()) 11854 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11855 << op->getSourceRange(); 11856 else { 11857 SmallString<32> Str; 11858 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11859 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11860 << op->getSourceRange() 11861 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11862 } 11863 } 11864 11865 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11866 if (isa<CXXDestructorDecl>(MD)) 11867 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11868 11869 QualType MPTy = Context.getMemberPointerType( 11870 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11871 // Under the MS ABI, lock down the inheritance model now. 11872 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11873 (void)isCompleteType(OpLoc, MPTy); 11874 return MPTy; 11875 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11876 // C99 6.5.3.2p1 11877 // The operand must be either an l-value or a function designator 11878 if (!op->getType()->isFunctionType()) { 11879 // Use a special diagnostic for loads from property references. 11880 if (isa<PseudoObjectExpr>(op)) { 11881 AddressOfError = AO_Property_Expansion; 11882 } else { 11883 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11884 << op->getType() << op->getSourceRange(); 11885 return QualType(); 11886 } 11887 } 11888 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11889 // The operand cannot be a bit-field 11890 AddressOfError = AO_Bit_Field; 11891 } else if (op->getObjectKind() == OK_VectorComponent) { 11892 // The operand cannot be an element of a vector 11893 AddressOfError = AO_Vector_Element; 11894 } else if (dcl) { // C99 6.5.3.2p1 11895 // We have an lvalue with a decl. Make sure the decl is not declared 11896 // with the register storage-class specifier. 11897 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11898 // in C++ it is not error to take address of a register 11899 // variable (c++03 7.1.1P3) 11900 if (vd->getStorageClass() == SC_Register && 11901 !getLangOpts().CPlusPlus) { 11902 AddressOfError = AO_Register_Variable; 11903 } 11904 } else if (isa<MSPropertyDecl>(dcl)) { 11905 AddressOfError = AO_Property_Expansion; 11906 } else if (isa<FunctionTemplateDecl>(dcl)) { 11907 return Context.OverloadTy; 11908 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11909 // Okay: we can take the address of a field. 11910 // Could be a pointer to member, though, if there is an explicit 11911 // scope qualifier for the class. 11912 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11913 DeclContext *Ctx = dcl->getDeclContext(); 11914 if (Ctx && Ctx->isRecord()) { 11915 if (dcl->getType()->isReferenceType()) { 11916 Diag(OpLoc, 11917 diag::err_cannot_form_pointer_to_member_of_reference_type) 11918 << dcl->getDeclName() << dcl->getType(); 11919 return QualType(); 11920 } 11921 11922 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11923 Ctx = Ctx->getParent(); 11924 11925 QualType MPTy = Context.getMemberPointerType( 11926 op->getType(), 11927 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11928 // Under the MS ABI, lock down the inheritance model now. 11929 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11930 (void)isCompleteType(OpLoc, MPTy); 11931 return MPTy; 11932 } 11933 } 11934 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11935 !isa<BindingDecl>(dcl)) 11936 llvm_unreachable("Unknown/unexpected decl type"); 11937 } 11938 11939 if (AddressOfError != AO_No_Error) { 11940 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11941 return QualType(); 11942 } 11943 11944 if (lval == Expr::LV_IncompleteVoidType) { 11945 // Taking the address of a void variable is technically illegal, but we 11946 // allow it in cases which are otherwise valid. 11947 // Example: "extern void x; void* y = &x;". 11948 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11949 } 11950 11951 // If the operand has type "type", the result has type "pointer to type". 11952 if (op->getType()->isObjCObjectType()) 11953 return Context.getObjCObjectPointerType(op->getType()); 11954 11955 CheckAddressOfPackedMember(op); 11956 11957 return Context.getPointerType(op->getType()); 11958 } 11959 11960 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11961 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11962 if (!DRE) 11963 return; 11964 const Decl *D = DRE->getDecl(); 11965 if (!D) 11966 return; 11967 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11968 if (!Param) 11969 return; 11970 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11971 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11972 return; 11973 if (FunctionScopeInfo *FD = S.getCurFunction()) 11974 if (!FD->ModifiedNonNullParams.count(Param)) 11975 FD->ModifiedNonNullParams.insert(Param); 11976 } 11977 11978 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11979 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11980 SourceLocation OpLoc) { 11981 if (Op->isTypeDependent()) 11982 return S.Context.DependentTy; 11983 11984 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11985 if (ConvResult.isInvalid()) 11986 return QualType(); 11987 Op = ConvResult.get(); 11988 QualType OpTy = Op->getType(); 11989 QualType Result; 11990 11991 if (isa<CXXReinterpretCastExpr>(Op)) { 11992 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11993 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11994 Op->getSourceRange()); 11995 } 11996 11997 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11998 { 11999 Result = PT->getPointeeType(); 12000 } 12001 else if (const ObjCObjectPointerType *OPT = 12002 OpTy->getAs<ObjCObjectPointerType>()) 12003 Result = OPT->getPointeeType(); 12004 else { 12005 ExprResult PR = S.CheckPlaceholderExpr(Op); 12006 if (PR.isInvalid()) return QualType(); 12007 if (PR.get() != Op) 12008 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12009 } 12010 12011 if (Result.isNull()) { 12012 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12013 << OpTy << Op->getSourceRange(); 12014 return QualType(); 12015 } 12016 12017 // Note that per both C89 and C99, indirection is always legal, even if Result 12018 // is an incomplete type or void. It would be possible to warn about 12019 // dereferencing a void pointer, but it's completely well-defined, and such a 12020 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12021 // for pointers to 'void' but is fine for any other pointer type: 12022 // 12023 // C++ [expr.unary.op]p1: 12024 // [...] the expression to which [the unary * operator] is applied shall 12025 // be a pointer to an object type, or a pointer to a function type 12026 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12027 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12028 << OpTy << Op->getSourceRange(); 12029 12030 // Dereferences are usually l-values... 12031 VK = VK_LValue; 12032 12033 // ...except that certain expressions are never l-values in C. 12034 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12035 VK = VK_RValue; 12036 12037 return Result; 12038 } 12039 12040 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12041 BinaryOperatorKind Opc; 12042 switch (Kind) { 12043 default: llvm_unreachable("Unknown binop!"); 12044 case tok::periodstar: Opc = BO_PtrMemD; break; 12045 case tok::arrowstar: Opc = BO_PtrMemI; break; 12046 case tok::star: Opc = BO_Mul; break; 12047 case tok::slash: Opc = BO_Div; break; 12048 case tok::percent: Opc = BO_Rem; break; 12049 case tok::plus: Opc = BO_Add; break; 12050 case tok::minus: Opc = BO_Sub; break; 12051 case tok::lessless: Opc = BO_Shl; break; 12052 case tok::greatergreater: Opc = BO_Shr; break; 12053 case tok::lessequal: Opc = BO_LE; break; 12054 case tok::less: Opc = BO_LT; break; 12055 case tok::greaterequal: Opc = BO_GE; break; 12056 case tok::greater: Opc = BO_GT; break; 12057 case tok::exclaimequal: Opc = BO_NE; break; 12058 case tok::equalequal: Opc = BO_EQ; break; 12059 case tok::spaceship: Opc = BO_Cmp; break; 12060 case tok::amp: Opc = BO_And; break; 12061 case tok::caret: Opc = BO_Xor; break; 12062 case tok::pipe: Opc = BO_Or; break; 12063 case tok::ampamp: Opc = BO_LAnd; break; 12064 case tok::pipepipe: Opc = BO_LOr; break; 12065 case tok::equal: Opc = BO_Assign; break; 12066 case tok::starequal: Opc = BO_MulAssign; break; 12067 case tok::slashequal: Opc = BO_DivAssign; break; 12068 case tok::percentequal: Opc = BO_RemAssign; break; 12069 case tok::plusequal: Opc = BO_AddAssign; break; 12070 case tok::minusequal: Opc = BO_SubAssign; break; 12071 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12072 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12073 case tok::ampequal: Opc = BO_AndAssign; break; 12074 case tok::caretequal: Opc = BO_XorAssign; break; 12075 case tok::pipeequal: Opc = BO_OrAssign; break; 12076 case tok::comma: Opc = BO_Comma; break; 12077 } 12078 return Opc; 12079 } 12080 12081 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12082 tok::TokenKind Kind) { 12083 UnaryOperatorKind Opc; 12084 switch (Kind) { 12085 default: llvm_unreachable("Unknown unary op!"); 12086 case tok::plusplus: Opc = UO_PreInc; break; 12087 case tok::minusminus: Opc = UO_PreDec; break; 12088 case tok::amp: Opc = UO_AddrOf; break; 12089 case tok::star: Opc = UO_Deref; break; 12090 case tok::plus: Opc = UO_Plus; break; 12091 case tok::minus: Opc = UO_Minus; break; 12092 case tok::tilde: Opc = UO_Not; break; 12093 case tok::exclaim: Opc = UO_LNot; break; 12094 case tok::kw___real: Opc = UO_Real; break; 12095 case tok::kw___imag: Opc = UO_Imag; break; 12096 case tok::kw___extension__: Opc = UO_Extension; break; 12097 } 12098 return Opc; 12099 } 12100 12101 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12102 /// This warning suppressed in the event of macro expansions. 12103 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12104 SourceLocation OpLoc, bool IsBuiltin) { 12105 if (S.inTemplateInstantiation()) 12106 return; 12107 if (S.isUnevaluatedContext()) 12108 return; 12109 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12110 return; 12111 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12112 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12113 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12114 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12115 if (!LHSDeclRef || !RHSDeclRef || 12116 LHSDeclRef->getLocation().isMacroID() || 12117 RHSDeclRef->getLocation().isMacroID()) 12118 return; 12119 const ValueDecl *LHSDecl = 12120 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12121 const ValueDecl *RHSDecl = 12122 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12123 if (LHSDecl != RHSDecl) 12124 return; 12125 if (LHSDecl->getType().isVolatileQualified()) 12126 return; 12127 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12128 if (RefTy->getPointeeType().isVolatileQualified()) 12129 return; 12130 12131 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12132 : diag::warn_self_assignment_overloaded) 12133 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12134 << RHSExpr->getSourceRange(); 12135 } 12136 12137 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12138 /// is usually indicative of introspection within the Objective-C pointer. 12139 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12140 SourceLocation OpLoc) { 12141 if (!S.getLangOpts().ObjC) 12142 return; 12143 12144 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12145 const Expr *LHS = L.get(); 12146 const Expr *RHS = R.get(); 12147 12148 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12149 ObjCPointerExpr = LHS; 12150 OtherExpr = RHS; 12151 } 12152 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12153 ObjCPointerExpr = RHS; 12154 OtherExpr = LHS; 12155 } 12156 12157 // This warning is deliberately made very specific to reduce false 12158 // positives with logic that uses '&' for hashing. This logic mainly 12159 // looks for code trying to introspect into tagged pointers, which 12160 // code should generally never do. 12161 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12162 unsigned Diag = diag::warn_objc_pointer_masking; 12163 // Determine if we are introspecting the result of performSelectorXXX. 12164 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12165 // Special case messages to -performSelector and friends, which 12166 // can return non-pointer values boxed in a pointer value. 12167 // Some clients may wish to silence warnings in this subcase. 12168 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12169 Selector S = ME->getSelector(); 12170 StringRef SelArg0 = S.getNameForSlot(0); 12171 if (SelArg0.startswith("performSelector")) 12172 Diag = diag::warn_objc_pointer_masking_performSelector; 12173 } 12174 12175 S.Diag(OpLoc, Diag) 12176 << ObjCPointerExpr->getSourceRange(); 12177 } 12178 } 12179 12180 static NamedDecl *getDeclFromExpr(Expr *E) { 12181 if (!E) 12182 return nullptr; 12183 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12184 return DRE->getDecl(); 12185 if (auto *ME = dyn_cast<MemberExpr>(E)) 12186 return ME->getMemberDecl(); 12187 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12188 return IRE->getDecl(); 12189 return nullptr; 12190 } 12191 12192 // This helper function promotes a binary operator's operands (which are of a 12193 // half vector type) to a vector of floats and then truncates the result to 12194 // a vector of either half or short. 12195 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12196 BinaryOperatorKind Opc, QualType ResultTy, 12197 ExprValueKind VK, ExprObjectKind OK, 12198 bool IsCompAssign, SourceLocation OpLoc, 12199 FPOptions FPFeatures) { 12200 auto &Context = S.getASTContext(); 12201 assert((isVector(ResultTy, Context.HalfTy) || 12202 isVector(ResultTy, Context.ShortTy)) && 12203 "Result must be a vector of half or short"); 12204 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12205 isVector(RHS.get()->getType(), Context.HalfTy) && 12206 "both operands expected to be a half vector"); 12207 12208 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12209 QualType BinOpResTy = RHS.get()->getType(); 12210 12211 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12212 // change BinOpResTy to a vector of ints. 12213 if (isVector(ResultTy, Context.ShortTy)) 12214 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12215 12216 if (IsCompAssign) 12217 return new (Context) CompoundAssignOperator( 12218 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12219 OpLoc, FPFeatures); 12220 12221 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12222 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12223 VK, OK, OpLoc, FPFeatures); 12224 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12225 } 12226 12227 static std::pair<ExprResult, ExprResult> 12228 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12229 Expr *RHSExpr) { 12230 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12231 if (!S.getLangOpts().CPlusPlus) { 12232 // C cannot handle TypoExpr nodes on either side of a binop because it 12233 // doesn't handle dependent types properly, so make sure any TypoExprs have 12234 // been dealt with before checking the operands. 12235 LHS = S.CorrectDelayedTyposInExpr(LHS); 12236 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12237 if (Opc != BO_Assign) 12238 return ExprResult(E); 12239 // Avoid correcting the RHS to the same Expr as the LHS. 12240 Decl *D = getDeclFromExpr(E); 12241 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12242 }); 12243 } 12244 return std::make_pair(LHS, RHS); 12245 } 12246 12247 /// Returns true if conversion between vectors of halfs and vectors of floats 12248 /// is needed. 12249 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12250 QualType SrcType) { 12251 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12252 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12253 isVector(SrcType, Ctx.HalfTy); 12254 } 12255 12256 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12257 /// operator @p Opc at location @c TokLoc. This routine only supports 12258 /// built-in operations; ActOnBinOp handles overloaded operators. 12259 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12260 BinaryOperatorKind Opc, 12261 Expr *LHSExpr, Expr *RHSExpr) { 12262 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12263 // The syntax only allows initializer lists on the RHS of assignment, 12264 // so we don't need to worry about accepting invalid code for 12265 // non-assignment operators. 12266 // C++11 5.17p9: 12267 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12268 // of x = {} is x = T(). 12269 InitializationKind Kind = InitializationKind::CreateDirectList( 12270 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12271 InitializedEntity Entity = 12272 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12273 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12274 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12275 if (Init.isInvalid()) 12276 return Init; 12277 RHSExpr = Init.get(); 12278 } 12279 12280 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12281 QualType ResultTy; // Result type of the binary operator. 12282 // The following two variables are used for compound assignment operators 12283 QualType CompLHSTy; // Type of LHS after promotions for computation 12284 QualType CompResultTy; // Type of computation result 12285 ExprValueKind VK = VK_RValue; 12286 ExprObjectKind OK = OK_Ordinary; 12287 bool ConvertHalfVec = false; 12288 12289 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12290 if (!LHS.isUsable() || !RHS.isUsable()) 12291 return ExprError(); 12292 12293 if (getLangOpts().OpenCL) { 12294 QualType LHSTy = LHSExpr->getType(); 12295 QualType RHSTy = RHSExpr->getType(); 12296 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12297 // the ATOMIC_VAR_INIT macro. 12298 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12299 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12300 if (BO_Assign == Opc) 12301 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12302 else 12303 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12304 return ExprError(); 12305 } 12306 12307 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12308 // only with a builtin functions and therefore should be disallowed here. 12309 if (LHSTy->isImageType() || RHSTy->isImageType() || 12310 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12311 LHSTy->isPipeType() || RHSTy->isPipeType() || 12312 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12313 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12314 return ExprError(); 12315 } 12316 } 12317 12318 switch (Opc) { 12319 case BO_Assign: 12320 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12321 if (getLangOpts().CPlusPlus && 12322 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12323 VK = LHS.get()->getValueKind(); 12324 OK = LHS.get()->getObjectKind(); 12325 } 12326 if (!ResultTy.isNull()) { 12327 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12328 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12329 } 12330 RecordModifiableNonNullParam(*this, LHS.get()); 12331 break; 12332 case BO_PtrMemD: 12333 case BO_PtrMemI: 12334 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12335 Opc == BO_PtrMemI); 12336 break; 12337 case BO_Mul: 12338 case BO_Div: 12339 ConvertHalfVec = true; 12340 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12341 Opc == BO_Div); 12342 break; 12343 case BO_Rem: 12344 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12345 break; 12346 case BO_Add: 12347 ConvertHalfVec = true; 12348 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12349 break; 12350 case BO_Sub: 12351 ConvertHalfVec = true; 12352 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12353 break; 12354 case BO_Shl: 12355 case BO_Shr: 12356 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12357 break; 12358 case BO_LE: 12359 case BO_LT: 12360 case BO_GE: 12361 case BO_GT: 12362 ConvertHalfVec = true; 12363 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12364 break; 12365 case BO_EQ: 12366 case BO_NE: 12367 ConvertHalfVec = true; 12368 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12369 break; 12370 case BO_Cmp: 12371 ConvertHalfVec = true; 12372 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12373 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12374 break; 12375 case BO_And: 12376 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12377 LLVM_FALLTHROUGH; 12378 case BO_Xor: 12379 case BO_Or: 12380 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12381 break; 12382 case BO_LAnd: 12383 case BO_LOr: 12384 ConvertHalfVec = true; 12385 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12386 break; 12387 case BO_MulAssign: 12388 case BO_DivAssign: 12389 ConvertHalfVec = true; 12390 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12391 Opc == BO_DivAssign); 12392 CompLHSTy = CompResultTy; 12393 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12394 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12395 break; 12396 case BO_RemAssign: 12397 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12398 CompLHSTy = CompResultTy; 12399 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12400 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12401 break; 12402 case BO_AddAssign: 12403 ConvertHalfVec = true; 12404 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12405 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12406 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12407 break; 12408 case BO_SubAssign: 12409 ConvertHalfVec = true; 12410 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12411 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12412 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12413 break; 12414 case BO_ShlAssign: 12415 case BO_ShrAssign: 12416 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12417 CompLHSTy = CompResultTy; 12418 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12419 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12420 break; 12421 case BO_AndAssign: 12422 case BO_OrAssign: // fallthrough 12423 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12424 LLVM_FALLTHROUGH; 12425 case BO_XorAssign: 12426 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12427 CompLHSTy = CompResultTy; 12428 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12429 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12430 break; 12431 case BO_Comma: 12432 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12433 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12434 VK = RHS.get()->getValueKind(); 12435 OK = RHS.get()->getObjectKind(); 12436 } 12437 break; 12438 } 12439 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12440 return ExprError(); 12441 12442 // Some of the binary operations require promoting operands of half vector to 12443 // float vectors and truncating the result back to half vector. For now, we do 12444 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12445 // arm64). 12446 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12447 isVector(LHS.get()->getType(), Context.HalfTy) && 12448 "both sides are half vectors or neither sides are"); 12449 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12450 LHS.get()->getType()); 12451 12452 // Check for array bounds violations for both sides of the BinaryOperator 12453 CheckArrayAccess(LHS.get()); 12454 CheckArrayAccess(RHS.get()); 12455 12456 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12457 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12458 &Context.Idents.get("object_setClass"), 12459 SourceLocation(), LookupOrdinaryName); 12460 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12461 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12462 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12463 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12464 "object_setClass(") 12465 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12466 ",") 12467 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12468 } 12469 else 12470 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12471 } 12472 else if (const ObjCIvarRefExpr *OIRE = 12473 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12474 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12475 12476 // Opc is not a compound assignment if CompResultTy is null. 12477 if (CompResultTy.isNull()) { 12478 if (ConvertHalfVec) 12479 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12480 OpLoc, FPFeatures); 12481 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12482 OK, OpLoc, FPFeatures); 12483 } 12484 12485 // Handle compound assignments. 12486 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12487 OK_ObjCProperty) { 12488 VK = VK_LValue; 12489 OK = LHS.get()->getObjectKind(); 12490 } 12491 12492 if (ConvertHalfVec) 12493 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12494 OpLoc, FPFeatures); 12495 12496 return new (Context) CompoundAssignOperator( 12497 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12498 OpLoc, FPFeatures); 12499 } 12500 12501 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12502 /// operators are mixed in a way that suggests that the programmer forgot that 12503 /// comparison operators have higher precedence. The most typical example of 12504 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12505 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12506 SourceLocation OpLoc, Expr *LHSExpr, 12507 Expr *RHSExpr) { 12508 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12509 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12510 12511 // Check that one of the sides is a comparison operator and the other isn't. 12512 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12513 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12514 if (isLeftComp == isRightComp) 12515 return; 12516 12517 // Bitwise operations are sometimes used as eager logical ops. 12518 // Don't diagnose this. 12519 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12520 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12521 if (isLeftBitwise || isRightBitwise) 12522 return; 12523 12524 SourceRange DiagRange = isLeftComp 12525 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12526 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12527 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12528 SourceRange ParensRange = 12529 isLeftComp 12530 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12531 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12532 12533 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12534 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12535 SuggestParentheses(Self, OpLoc, 12536 Self.PDiag(diag::note_precedence_silence) << OpStr, 12537 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12538 SuggestParentheses(Self, OpLoc, 12539 Self.PDiag(diag::note_precedence_bitwise_first) 12540 << BinaryOperator::getOpcodeStr(Opc), 12541 ParensRange); 12542 } 12543 12544 /// It accepts a '&&' expr that is inside a '||' one. 12545 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12546 /// in parentheses. 12547 static void 12548 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12549 BinaryOperator *Bop) { 12550 assert(Bop->getOpcode() == BO_LAnd); 12551 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12552 << Bop->getSourceRange() << OpLoc; 12553 SuggestParentheses(Self, Bop->getOperatorLoc(), 12554 Self.PDiag(diag::note_precedence_silence) 12555 << Bop->getOpcodeStr(), 12556 Bop->getSourceRange()); 12557 } 12558 12559 /// Returns true if the given expression can be evaluated as a constant 12560 /// 'true'. 12561 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12562 bool Res; 12563 return !E->isValueDependent() && 12564 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12565 } 12566 12567 /// Returns true if the given expression can be evaluated as a constant 12568 /// 'false'. 12569 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12570 bool Res; 12571 return !E->isValueDependent() && 12572 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12573 } 12574 12575 /// Look for '&&' in the left hand of a '||' expr. 12576 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12577 Expr *LHSExpr, Expr *RHSExpr) { 12578 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12579 if (Bop->getOpcode() == BO_LAnd) { 12580 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12581 if (EvaluatesAsFalse(S, RHSExpr)) 12582 return; 12583 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12584 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12585 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12586 } else if (Bop->getOpcode() == BO_LOr) { 12587 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12588 // If it's "a || b && 1 || c" we didn't warn earlier for 12589 // "a || b && 1", but warn now. 12590 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12591 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12592 } 12593 } 12594 } 12595 } 12596 12597 /// Look for '&&' in the right hand of a '||' expr. 12598 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12599 Expr *LHSExpr, Expr *RHSExpr) { 12600 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12601 if (Bop->getOpcode() == BO_LAnd) { 12602 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12603 if (EvaluatesAsFalse(S, LHSExpr)) 12604 return; 12605 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12606 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12607 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12608 } 12609 } 12610 } 12611 12612 /// Look for bitwise op in the left or right hand of a bitwise op with 12613 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12614 /// the '&' expression in parentheses. 12615 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12616 SourceLocation OpLoc, Expr *SubExpr) { 12617 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12618 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12619 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12620 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12621 << Bop->getSourceRange() << OpLoc; 12622 SuggestParentheses(S, Bop->getOperatorLoc(), 12623 S.PDiag(diag::note_precedence_silence) 12624 << Bop->getOpcodeStr(), 12625 Bop->getSourceRange()); 12626 } 12627 } 12628 } 12629 12630 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12631 Expr *SubExpr, StringRef Shift) { 12632 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12633 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12634 StringRef Op = Bop->getOpcodeStr(); 12635 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12636 << Bop->getSourceRange() << OpLoc << Shift << Op; 12637 SuggestParentheses(S, Bop->getOperatorLoc(), 12638 S.PDiag(diag::note_precedence_silence) << Op, 12639 Bop->getSourceRange()); 12640 } 12641 } 12642 } 12643 12644 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12645 Expr *LHSExpr, Expr *RHSExpr) { 12646 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12647 if (!OCE) 12648 return; 12649 12650 FunctionDecl *FD = OCE->getDirectCallee(); 12651 if (!FD || !FD->isOverloadedOperator()) 12652 return; 12653 12654 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12655 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12656 return; 12657 12658 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12659 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12660 << (Kind == OO_LessLess); 12661 SuggestParentheses(S, OCE->getOperatorLoc(), 12662 S.PDiag(diag::note_precedence_silence) 12663 << (Kind == OO_LessLess ? "<<" : ">>"), 12664 OCE->getSourceRange()); 12665 SuggestParentheses( 12666 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12667 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12668 } 12669 12670 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12671 /// precedence. 12672 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12673 SourceLocation OpLoc, Expr *LHSExpr, 12674 Expr *RHSExpr){ 12675 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12676 if (BinaryOperator::isBitwiseOp(Opc)) 12677 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12678 12679 // Diagnose "arg1 & arg2 | arg3" 12680 if ((Opc == BO_Or || Opc == BO_Xor) && 12681 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12682 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12683 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12684 } 12685 12686 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12687 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12688 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12689 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12690 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12691 } 12692 12693 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12694 || Opc == BO_Shr) { 12695 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12696 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12697 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12698 } 12699 12700 // Warn on overloaded shift operators and comparisons, such as: 12701 // cout << 5 == 4; 12702 if (BinaryOperator::isComparisonOp(Opc)) 12703 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12704 } 12705 12706 // Binary Operators. 'Tok' is the token for the operator. 12707 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12708 tok::TokenKind Kind, 12709 Expr *LHSExpr, Expr *RHSExpr) { 12710 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12711 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12712 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12713 12714 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12715 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12716 12717 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12718 } 12719 12720 /// Build an overloaded binary operator expression in the given scope. 12721 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12722 BinaryOperatorKind Opc, 12723 Expr *LHS, Expr *RHS) { 12724 switch (Opc) { 12725 case BO_Assign: 12726 case BO_DivAssign: 12727 case BO_RemAssign: 12728 case BO_SubAssign: 12729 case BO_AndAssign: 12730 case BO_OrAssign: 12731 case BO_XorAssign: 12732 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12733 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12734 break; 12735 default: 12736 break; 12737 } 12738 12739 // Find all of the overloaded operators visible from this 12740 // point. We perform both an operator-name lookup from the local 12741 // scope and an argument-dependent lookup based on the types of 12742 // the arguments. 12743 UnresolvedSet<16> Functions; 12744 OverloadedOperatorKind OverOp 12745 = BinaryOperator::getOverloadedOperator(Opc); 12746 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12747 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12748 RHS->getType(), Functions); 12749 12750 // Build the (potentially-overloaded, potentially-dependent) 12751 // binary operation. 12752 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12753 } 12754 12755 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12756 BinaryOperatorKind Opc, 12757 Expr *LHSExpr, Expr *RHSExpr) { 12758 ExprResult LHS, RHS; 12759 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12760 if (!LHS.isUsable() || !RHS.isUsable()) 12761 return ExprError(); 12762 LHSExpr = LHS.get(); 12763 RHSExpr = RHS.get(); 12764 12765 // We want to end up calling one of checkPseudoObjectAssignment 12766 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12767 // both expressions are overloadable or either is type-dependent), 12768 // or CreateBuiltinBinOp (in any other case). We also want to get 12769 // any placeholder types out of the way. 12770 12771 // Handle pseudo-objects in the LHS. 12772 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12773 // Assignments with a pseudo-object l-value need special analysis. 12774 if (pty->getKind() == BuiltinType::PseudoObject && 12775 BinaryOperator::isAssignmentOp(Opc)) 12776 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12777 12778 // Don't resolve overloads if the other type is overloadable. 12779 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12780 // We can't actually test that if we still have a placeholder, 12781 // though. Fortunately, none of the exceptions we see in that 12782 // code below are valid when the LHS is an overload set. Note 12783 // that an overload set can be dependently-typed, but it never 12784 // instantiates to having an overloadable type. 12785 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12786 if (resolvedRHS.isInvalid()) return ExprError(); 12787 RHSExpr = resolvedRHS.get(); 12788 12789 if (RHSExpr->isTypeDependent() || 12790 RHSExpr->getType()->isOverloadableType()) 12791 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12792 } 12793 12794 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12795 // template, diagnose the missing 'template' keyword instead of diagnosing 12796 // an invalid use of a bound member function. 12797 // 12798 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12799 // to C++1z [over.over]/1.4, but we already checked for that case above. 12800 if (Opc == BO_LT && inTemplateInstantiation() && 12801 (pty->getKind() == BuiltinType::BoundMember || 12802 pty->getKind() == BuiltinType::Overload)) { 12803 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12804 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12805 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12806 return isa<FunctionTemplateDecl>(ND); 12807 })) { 12808 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12809 : OE->getNameLoc(), 12810 diag::err_template_kw_missing) 12811 << OE->getName().getAsString() << ""; 12812 return ExprError(); 12813 } 12814 } 12815 12816 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12817 if (LHS.isInvalid()) return ExprError(); 12818 LHSExpr = LHS.get(); 12819 } 12820 12821 // Handle pseudo-objects in the RHS. 12822 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12823 // An overload in the RHS can potentially be resolved by the type 12824 // being assigned to. 12825 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12826 if (getLangOpts().CPlusPlus && 12827 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12828 LHSExpr->getType()->isOverloadableType())) 12829 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12830 12831 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12832 } 12833 12834 // Don't resolve overloads if the other type is overloadable. 12835 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12836 LHSExpr->getType()->isOverloadableType()) 12837 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12838 12839 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12840 if (!resolvedRHS.isUsable()) return ExprError(); 12841 RHSExpr = resolvedRHS.get(); 12842 } 12843 12844 if (getLangOpts().CPlusPlus) { 12845 // If either expression is type-dependent, always build an 12846 // overloaded op. 12847 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12848 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12849 12850 // Otherwise, build an overloaded op if either expression has an 12851 // overloadable type. 12852 if (LHSExpr->getType()->isOverloadableType() || 12853 RHSExpr->getType()->isOverloadableType()) 12854 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12855 } 12856 12857 // Build a built-in binary operation. 12858 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12859 } 12860 12861 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12862 if (T.isNull() || T->isDependentType()) 12863 return false; 12864 12865 if (!T->isPromotableIntegerType()) 12866 return true; 12867 12868 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12869 } 12870 12871 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12872 UnaryOperatorKind Opc, 12873 Expr *InputExpr) { 12874 ExprResult Input = InputExpr; 12875 ExprValueKind VK = VK_RValue; 12876 ExprObjectKind OK = OK_Ordinary; 12877 QualType resultType; 12878 bool CanOverflow = false; 12879 12880 bool ConvertHalfVec = false; 12881 if (getLangOpts().OpenCL) { 12882 QualType Ty = InputExpr->getType(); 12883 // The only legal unary operation for atomics is '&'. 12884 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12885 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12886 // only with a builtin functions and therefore should be disallowed here. 12887 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12888 || Ty->isBlockPointerType())) { 12889 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12890 << InputExpr->getType() 12891 << Input.get()->getSourceRange()); 12892 } 12893 } 12894 switch (Opc) { 12895 case UO_PreInc: 12896 case UO_PreDec: 12897 case UO_PostInc: 12898 case UO_PostDec: 12899 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12900 OpLoc, 12901 Opc == UO_PreInc || 12902 Opc == UO_PostInc, 12903 Opc == UO_PreInc || 12904 Opc == UO_PreDec); 12905 CanOverflow = isOverflowingIntegerType(Context, resultType); 12906 break; 12907 case UO_AddrOf: 12908 resultType = CheckAddressOfOperand(Input, OpLoc); 12909 CheckAddressOfNoDeref(InputExpr); 12910 RecordModifiableNonNullParam(*this, InputExpr); 12911 break; 12912 case UO_Deref: { 12913 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12914 if (Input.isInvalid()) return ExprError(); 12915 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12916 break; 12917 } 12918 case UO_Plus: 12919 case UO_Minus: 12920 CanOverflow = Opc == UO_Minus && 12921 isOverflowingIntegerType(Context, Input.get()->getType()); 12922 Input = UsualUnaryConversions(Input.get()); 12923 if (Input.isInvalid()) return ExprError(); 12924 // Unary plus and minus require promoting an operand of half vector to a 12925 // float vector and truncating the result back to a half vector. For now, we 12926 // do this only when HalfArgsAndReturns is set (that is, when the target is 12927 // arm or arm64). 12928 ConvertHalfVec = 12929 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12930 12931 // If the operand is a half vector, promote it to a float vector. 12932 if (ConvertHalfVec) 12933 Input = convertVector(Input.get(), Context.FloatTy, *this); 12934 resultType = Input.get()->getType(); 12935 if (resultType->isDependentType()) 12936 break; 12937 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12938 break; 12939 else if (resultType->isVectorType() && 12940 // The z vector extensions don't allow + or - with bool vectors. 12941 (!Context.getLangOpts().ZVector || 12942 resultType->getAs<VectorType>()->getVectorKind() != 12943 VectorType::AltiVecBool)) 12944 break; 12945 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12946 Opc == UO_Plus && 12947 resultType->isPointerType()) 12948 break; 12949 12950 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12951 << resultType << Input.get()->getSourceRange()); 12952 12953 case UO_Not: // bitwise complement 12954 Input = UsualUnaryConversions(Input.get()); 12955 if (Input.isInvalid()) 12956 return ExprError(); 12957 resultType = Input.get()->getType(); 12958 12959 if (resultType->isDependentType()) 12960 break; 12961 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12962 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12963 // C99 does not support '~' for complex conjugation. 12964 Diag(OpLoc, diag::ext_integer_complement_complex) 12965 << resultType << Input.get()->getSourceRange(); 12966 else if (resultType->hasIntegerRepresentation()) 12967 break; 12968 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12969 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12970 // on vector float types. 12971 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12972 if (!T->isIntegerType()) 12973 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12974 << resultType << Input.get()->getSourceRange()); 12975 } else { 12976 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12977 << resultType << Input.get()->getSourceRange()); 12978 } 12979 break; 12980 12981 case UO_LNot: // logical negation 12982 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12983 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12984 if (Input.isInvalid()) return ExprError(); 12985 resultType = Input.get()->getType(); 12986 12987 // Though we still have to promote half FP to float... 12988 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12989 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12990 resultType = Context.FloatTy; 12991 } 12992 12993 if (resultType->isDependentType()) 12994 break; 12995 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12996 // C99 6.5.3.3p1: ok, fallthrough; 12997 if (Context.getLangOpts().CPlusPlus) { 12998 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12999 // operand contextually converted to bool. 13000 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13001 ScalarTypeToBooleanCastKind(resultType)); 13002 } else if (Context.getLangOpts().OpenCL && 13003 Context.getLangOpts().OpenCLVersion < 120) { 13004 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13005 // operate on scalar float types. 13006 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13007 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13008 << resultType << Input.get()->getSourceRange()); 13009 } 13010 } else if (resultType->isExtVectorType()) { 13011 if (Context.getLangOpts().OpenCL && 13012 Context.getLangOpts().OpenCLVersion < 120) { 13013 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13014 // operate on vector float types. 13015 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 13016 if (!T->isIntegerType()) 13017 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13018 << resultType << Input.get()->getSourceRange()); 13019 } 13020 // Vector logical not returns the signed variant of the operand type. 13021 resultType = GetSignedVectorType(resultType); 13022 break; 13023 } else { 13024 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13025 // type in C++. We should allow that here too. 13026 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13027 << resultType << Input.get()->getSourceRange()); 13028 } 13029 13030 // LNot always has type int. C99 6.5.3.3p5. 13031 // In C++, it's bool. C++ 5.3.1p8 13032 resultType = Context.getLogicalOperationType(); 13033 break; 13034 case UO_Real: 13035 case UO_Imag: 13036 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13037 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13038 // complex l-values to ordinary l-values and all other values to r-values. 13039 if (Input.isInvalid()) return ExprError(); 13040 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13041 if (Input.get()->getValueKind() != VK_RValue && 13042 Input.get()->getObjectKind() == OK_Ordinary) 13043 VK = Input.get()->getValueKind(); 13044 } else if (!getLangOpts().CPlusPlus) { 13045 // In C, a volatile scalar is read by __imag. In C++, it is not. 13046 Input = DefaultLvalueConversion(Input.get()); 13047 } 13048 break; 13049 case UO_Extension: 13050 resultType = Input.get()->getType(); 13051 VK = Input.get()->getValueKind(); 13052 OK = Input.get()->getObjectKind(); 13053 break; 13054 case UO_Coawait: 13055 // It's unnecessary to represent the pass-through operator co_await in the 13056 // AST; just return the input expression instead. 13057 assert(!Input.get()->getType()->isDependentType() && 13058 "the co_await expression must be non-dependant before " 13059 "building operator co_await"); 13060 return Input; 13061 } 13062 if (resultType.isNull() || Input.isInvalid()) 13063 return ExprError(); 13064 13065 // Check for array bounds violations in the operand of the UnaryOperator, 13066 // except for the '*' and '&' operators that have to be handled specially 13067 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13068 // that are explicitly defined as valid by the standard). 13069 if (Opc != UO_AddrOf && Opc != UO_Deref) 13070 CheckArrayAccess(Input.get()); 13071 13072 auto *UO = new (Context) 13073 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13074 13075 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13076 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13077 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13078 13079 // Convert the result back to a half vector. 13080 if (ConvertHalfVec) 13081 return convertVector(UO, Context.HalfTy, *this); 13082 return UO; 13083 } 13084 13085 /// Determine whether the given expression is a qualified member 13086 /// access expression, of a form that could be turned into a pointer to member 13087 /// with the address-of operator. 13088 bool Sema::isQualifiedMemberAccess(Expr *E) { 13089 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13090 if (!DRE->getQualifier()) 13091 return false; 13092 13093 ValueDecl *VD = DRE->getDecl(); 13094 if (!VD->isCXXClassMember()) 13095 return false; 13096 13097 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13098 return true; 13099 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13100 return Method->isInstance(); 13101 13102 return false; 13103 } 13104 13105 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13106 if (!ULE->getQualifier()) 13107 return false; 13108 13109 for (NamedDecl *D : ULE->decls()) { 13110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13111 if (Method->isInstance()) 13112 return true; 13113 } else { 13114 // Overload set does not contain methods. 13115 break; 13116 } 13117 } 13118 13119 return false; 13120 } 13121 13122 return false; 13123 } 13124 13125 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13126 UnaryOperatorKind Opc, Expr *Input) { 13127 // First things first: handle placeholders so that the 13128 // overloaded-operator check considers the right type. 13129 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13130 // Increment and decrement of pseudo-object references. 13131 if (pty->getKind() == BuiltinType::PseudoObject && 13132 UnaryOperator::isIncrementDecrementOp(Opc)) 13133 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13134 13135 // extension is always a builtin operator. 13136 if (Opc == UO_Extension) 13137 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13138 13139 // & gets special logic for several kinds of placeholder. 13140 // The builtin code knows what to do. 13141 if (Opc == UO_AddrOf && 13142 (pty->getKind() == BuiltinType::Overload || 13143 pty->getKind() == BuiltinType::UnknownAny || 13144 pty->getKind() == BuiltinType::BoundMember)) 13145 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13146 13147 // Anything else needs to be handled now. 13148 ExprResult Result = CheckPlaceholderExpr(Input); 13149 if (Result.isInvalid()) return ExprError(); 13150 Input = Result.get(); 13151 } 13152 13153 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13154 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13155 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13156 // Find all of the overloaded operators visible from this 13157 // point. We perform both an operator-name lookup from the local 13158 // scope and an argument-dependent lookup based on the types of 13159 // the arguments. 13160 UnresolvedSet<16> Functions; 13161 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13162 if (S && OverOp != OO_None) 13163 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13164 Functions); 13165 13166 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13167 } 13168 13169 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13170 } 13171 13172 // Unary Operators. 'Tok' is the token for the operator. 13173 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13174 tok::TokenKind Op, Expr *Input) { 13175 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13176 } 13177 13178 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13179 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13180 LabelDecl *TheDecl) { 13181 TheDecl->markUsed(Context); 13182 // Create the AST node. The address of a label always has type 'void*'. 13183 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13184 Context.getPointerType(Context.VoidTy)); 13185 } 13186 13187 /// Given the last statement in a statement-expression, check whether 13188 /// the result is a producing expression (like a call to an 13189 /// ns_returns_retained function) and, if so, rebuild it to hoist the 13190 /// release out of the full-expression. Otherwise, return null. 13191 /// Cannot fail. 13192 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 13193 // Should always be wrapped with one of these. 13194 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 13195 if (!cleanups) return nullptr; 13196 13197 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 13198 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 13199 return nullptr; 13200 13201 // Splice out the cast. This shouldn't modify any interesting 13202 // features of the statement. 13203 Expr *producer = cast->getSubExpr(); 13204 assert(producer->getType() == cast->getType()); 13205 assert(producer->getValueKind() == cast->getValueKind()); 13206 cleanups->setSubExpr(producer); 13207 return cleanups; 13208 } 13209 13210 void Sema::ActOnStartStmtExpr() { 13211 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13212 } 13213 13214 void Sema::ActOnStmtExprError() { 13215 // Note that function is also called by TreeTransform when leaving a 13216 // StmtExpr scope without rebuilding anything. 13217 13218 DiscardCleanupsInEvaluationContext(); 13219 PopExpressionEvaluationContext(); 13220 } 13221 13222 ExprResult 13223 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13224 SourceLocation RPLoc) { // "({..})" 13225 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13226 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13227 13228 if (hasAnyUnrecoverableErrorsInThisFunction()) 13229 DiscardCleanupsInEvaluationContext(); 13230 assert(!Cleanup.exprNeedsCleanups() && 13231 "cleanups within StmtExpr not correctly bound!"); 13232 PopExpressionEvaluationContext(); 13233 13234 // FIXME: there are a variety of strange constraints to enforce here, for 13235 // example, it is not possible to goto into a stmt expression apparently. 13236 // More semantic analysis is needed. 13237 13238 // If there are sub-stmts in the compound stmt, take the type of the last one 13239 // as the type of the stmtexpr. 13240 QualType Ty = Context.VoidTy; 13241 bool StmtExprMayBindToTemp = false; 13242 if (!Compound->body_empty()) { 13243 Stmt *LastStmt = Compound->body_back(); 13244 LabelStmt *LastLabelStmt = nullptr; 13245 // If LastStmt is a label, skip down through into the body. 13246 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 13247 LastLabelStmt = Label; 13248 LastStmt = Label->getSubStmt(); 13249 } 13250 13251 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 13252 // Do function/array conversion on the last expression, but not 13253 // lvalue-to-rvalue. However, initialize an unqualified type. 13254 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 13255 if (LastExpr.isInvalid()) 13256 return ExprError(); 13257 Ty = LastExpr.get()->getType().getUnqualifiedType(); 13258 13259 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 13260 // In ARC, if the final expression ends in a consume, splice 13261 // the consume out and bind it later. In the alternate case 13262 // (when dealing with a retainable type), the result 13263 // initialization will create a produce. In both cases the 13264 // result will be +1, and we'll need to balance that out with 13265 // a bind. 13266 if (Expr *rebuiltLastStmt 13267 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 13268 LastExpr = rebuiltLastStmt; 13269 } else { 13270 LastExpr = PerformCopyInitialization( 13271 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 13272 SourceLocation(), LastExpr); 13273 } 13274 13275 if (LastExpr.isInvalid()) 13276 return ExprError(); 13277 if (LastExpr.get() != nullptr) { 13278 if (!LastLabelStmt) 13279 Compound->setLastStmt(LastExpr.get()); 13280 else 13281 LastLabelStmt->setSubStmt(LastExpr.get()); 13282 StmtExprMayBindToTemp = true; 13283 } 13284 } 13285 } 13286 } 13287 13288 // FIXME: Check that expression type is complete/non-abstract; statement 13289 // expressions are not lvalues. 13290 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13291 if (StmtExprMayBindToTemp) 13292 return MaybeBindToTemporary(ResStmtExpr); 13293 return ResStmtExpr; 13294 } 13295 13296 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13297 TypeSourceInfo *TInfo, 13298 ArrayRef<OffsetOfComponent> Components, 13299 SourceLocation RParenLoc) { 13300 QualType ArgTy = TInfo->getType(); 13301 bool Dependent = ArgTy->isDependentType(); 13302 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13303 13304 // We must have at least one component that refers to the type, and the first 13305 // one is known to be a field designator. Verify that the ArgTy represents 13306 // a struct/union/class. 13307 if (!Dependent && !ArgTy->isRecordType()) 13308 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13309 << ArgTy << TypeRange); 13310 13311 // Type must be complete per C99 7.17p3 because a declaring a variable 13312 // with an incomplete type would be ill-formed. 13313 if (!Dependent 13314 && RequireCompleteType(BuiltinLoc, ArgTy, 13315 diag::err_offsetof_incomplete_type, TypeRange)) 13316 return ExprError(); 13317 13318 bool DidWarnAboutNonPOD = false; 13319 QualType CurrentType = ArgTy; 13320 SmallVector<OffsetOfNode, 4> Comps; 13321 SmallVector<Expr*, 4> Exprs; 13322 for (const OffsetOfComponent &OC : Components) { 13323 if (OC.isBrackets) { 13324 // Offset of an array sub-field. TODO: Should we allow vector elements? 13325 if (!CurrentType->isDependentType()) { 13326 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13327 if(!AT) 13328 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13329 << CurrentType); 13330 CurrentType = AT->getElementType(); 13331 } else 13332 CurrentType = Context.DependentTy; 13333 13334 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13335 if (IdxRval.isInvalid()) 13336 return ExprError(); 13337 Expr *Idx = IdxRval.get(); 13338 13339 // The expression must be an integral expression. 13340 // FIXME: An integral constant expression? 13341 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13342 !Idx->getType()->isIntegerType()) 13343 return ExprError( 13344 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13345 << Idx->getSourceRange()); 13346 13347 // Record this array index. 13348 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13349 Exprs.push_back(Idx); 13350 continue; 13351 } 13352 13353 // Offset of a field. 13354 if (CurrentType->isDependentType()) { 13355 // We have the offset of a field, but we can't look into the dependent 13356 // type. Just record the identifier of the field. 13357 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13358 CurrentType = Context.DependentTy; 13359 continue; 13360 } 13361 13362 // We need to have a complete type to look into. 13363 if (RequireCompleteType(OC.LocStart, CurrentType, 13364 diag::err_offsetof_incomplete_type)) 13365 return ExprError(); 13366 13367 // Look for the designated field. 13368 const RecordType *RC = CurrentType->getAs<RecordType>(); 13369 if (!RC) 13370 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13371 << CurrentType); 13372 RecordDecl *RD = RC->getDecl(); 13373 13374 // C++ [lib.support.types]p5: 13375 // The macro offsetof accepts a restricted set of type arguments in this 13376 // International Standard. type shall be a POD structure or a POD union 13377 // (clause 9). 13378 // C++11 [support.types]p4: 13379 // If type is not a standard-layout class (Clause 9), the results are 13380 // undefined. 13381 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13382 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13383 unsigned DiagID = 13384 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13385 : diag::ext_offsetof_non_pod_type; 13386 13387 if (!IsSafe && !DidWarnAboutNonPOD && 13388 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13389 PDiag(DiagID) 13390 << SourceRange(Components[0].LocStart, OC.LocEnd) 13391 << CurrentType)) 13392 DidWarnAboutNonPOD = true; 13393 } 13394 13395 // Look for the field. 13396 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13397 LookupQualifiedName(R, RD); 13398 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13399 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13400 if (!MemberDecl) { 13401 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13402 MemberDecl = IndirectMemberDecl->getAnonField(); 13403 } 13404 13405 if (!MemberDecl) 13406 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13407 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13408 OC.LocEnd)); 13409 13410 // C99 7.17p3: 13411 // (If the specified member is a bit-field, the behavior is undefined.) 13412 // 13413 // We diagnose this as an error. 13414 if (MemberDecl->isBitField()) { 13415 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13416 << MemberDecl->getDeclName() 13417 << SourceRange(BuiltinLoc, RParenLoc); 13418 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13419 return ExprError(); 13420 } 13421 13422 RecordDecl *Parent = MemberDecl->getParent(); 13423 if (IndirectMemberDecl) 13424 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13425 13426 // If the member was found in a base class, introduce OffsetOfNodes for 13427 // the base class indirections. 13428 CXXBasePaths Paths; 13429 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13430 Paths)) { 13431 if (Paths.getDetectedVirtual()) { 13432 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13433 << MemberDecl->getDeclName() 13434 << SourceRange(BuiltinLoc, RParenLoc); 13435 return ExprError(); 13436 } 13437 13438 CXXBasePath &Path = Paths.front(); 13439 for (const CXXBasePathElement &B : Path) 13440 Comps.push_back(OffsetOfNode(B.Base)); 13441 } 13442 13443 if (IndirectMemberDecl) { 13444 for (auto *FI : IndirectMemberDecl->chain()) { 13445 assert(isa<FieldDecl>(FI)); 13446 Comps.push_back(OffsetOfNode(OC.LocStart, 13447 cast<FieldDecl>(FI), OC.LocEnd)); 13448 } 13449 } else 13450 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13451 13452 CurrentType = MemberDecl->getType().getNonReferenceType(); 13453 } 13454 13455 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13456 Comps, Exprs, RParenLoc); 13457 } 13458 13459 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13460 SourceLocation BuiltinLoc, 13461 SourceLocation TypeLoc, 13462 ParsedType ParsedArgTy, 13463 ArrayRef<OffsetOfComponent> Components, 13464 SourceLocation RParenLoc) { 13465 13466 TypeSourceInfo *ArgTInfo; 13467 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13468 if (ArgTy.isNull()) 13469 return ExprError(); 13470 13471 if (!ArgTInfo) 13472 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13473 13474 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13475 } 13476 13477 13478 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13479 Expr *CondExpr, 13480 Expr *LHSExpr, Expr *RHSExpr, 13481 SourceLocation RPLoc) { 13482 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13483 13484 ExprValueKind VK = VK_RValue; 13485 ExprObjectKind OK = OK_Ordinary; 13486 QualType resType; 13487 bool ValueDependent = false; 13488 bool CondIsTrue = false; 13489 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13490 resType = Context.DependentTy; 13491 ValueDependent = true; 13492 } else { 13493 // The conditional expression is required to be a constant expression. 13494 llvm::APSInt condEval(32); 13495 ExprResult CondICE 13496 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13497 diag::err_typecheck_choose_expr_requires_constant, false); 13498 if (CondICE.isInvalid()) 13499 return ExprError(); 13500 CondExpr = CondICE.get(); 13501 CondIsTrue = condEval.getZExtValue(); 13502 13503 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13504 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13505 13506 resType = ActiveExpr->getType(); 13507 ValueDependent = ActiveExpr->isValueDependent(); 13508 VK = ActiveExpr->getValueKind(); 13509 OK = ActiveExpr->getObjectKind(); 13510 } 13511 13512 return new (Context) 13513 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13514 CondIsTrue, resType->isDependentType(), ValueDependent); 13515 } 13516 13517 //===----------------------------------------------------------------------===// 13518 // Clang Extensions. 13519 //===----------------------------------------------------------------------===// 13520 13521 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13522 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13523 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13524 13525 if (LangOpts.CPlusPlus) { 13526 Decl *ManglingContextDecl; 13527 if (MangleNumberingContext *MCtx = 13528 getCurrentMangleNumberContext(Block->getDeclContext(), 13529 ManglingContextDecl)) { 13530 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13531 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13532 } 13533 } 13534 13535 PushBlockScope(CurScope, Block); 13536 CurContext->addDecl(Block); 13537 if (CurScope) 13538 PushDeclContext(CurScope, Block); 13539 else 13540 CurContext = Block; 13541 13542 getCurBlock()->HasImplicitReturnType = true; 13543 13544 // Enter a new evaluation context to insulate the block from any 13545 // cleanups from the enclosing full-expression. 13546 PushExpressionEvaluationContext( 13547 ExpressionEvaluationContext::PotentiallyEvaluated); 13548 } 13549 13550 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13551 Scope *CurScope) { 13552 assert(ParamInfo.getIdentifier() == nullptr && 13553 "block-id should have no identifier!"); 13554 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13555 BlockScopeInfo *CurBlock = getCurBlock(); 13556 13557 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13558 QualType T = Sig->getType(); 13559 13560 // FIXME: We should allow unexpanded parameter packs here, but that would, 13561 // in turn, make the block expression contain unexpanded parameter packs. 13562 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13563 // Drop the parameters. 13564 FunctionProtoType::ExtProtoInfo EPI; 13565 EPI.HasTrailingReturn = false; 13566 EPI.TypeQuals.addConst(); 13567 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13568 Sig = Context.getTrivialTypeSourceInfo(T); 13569 } 13570 13571 // GetTypeForDeclarator always produces a function type for a block 13572 // literal signature. Furthermore, it is always a FunctionProtoType 13573 // unless the function was written with a typedef. 13574 assert(T->isFunctionType() && 13575 "GetTypeForDeclarator made a non-function block signature"); 13576 13577 // Look for an explicit signature in that function type. 13578 FunctionProtoTypeLoc ExplicitSignature; 13579 13580 if ((ExplicitSignature = 13581 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13582 13583 // Check whether that explicit signature was synthesized by 13584 // GetTypeForDeclarator. If so, don't save that as part of the 13585 // written signature. 13586 if (ExplicitSignature.getLocalRangeBegin() == 13587 ExplicitSignature.getLocalRangeEnd()) { 13588 // This would be much cheaper if we stored TypeLocs instead of 13589 // TypeSourceInfos. 13590 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13591 unsigned Size = Result.getFullDataSize(); 13592 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13593 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13594 13595 ExplicitSignature = FunctionProtoTypeLoc(); 13596 } 13597 } 13598 13599 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13600 CurBlock->FunctionType = T; 13601 13602 const FunctionType *Fn = T->getAs<FunctionType>(); 13603 QualType RetTy = Fn->getReturnType(); 13604 bool isVariadic = 13605 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13606 13607 CurBlock->TheDecl->setIsVariadic(isVariadic); 13608 13609 // Context.DependentTy is used as a placeholder for a missing block 13610 // return type. TODO: what should we do with declarators like: 13611 // ^ * { ... } 13612 // If the answer is "apply template argument deduction".... 13613 if (RetTy != Context.DependentTy) { 13614 CurBlock->ReturnType = RetTy; 13615 CurBlock->TheDecl->setBlockMissingReturnType(false); 13616 CurBlock->HasImplicitReturnType = false; 13617 } 13618 13619 // Push block parameters from the declarator if we had them. 13620 SmallVector<ParmVarDecl*, 8> Params; 13621 if (ExplicitSignature) { 13622 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13623 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13624 if (Param->getIdentifier() == nullptr && 13625 !Param->isImplicit() && 13626 !Param->isInvalidDecl() && 13627 !getLangOpts().CPlusPlus) 13628 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13629 Params.push_back(Param); 13630 } 13631 13632 // Fake up parameter variables if we have a typedef, like 13633 // ^ fntype { ... } 13634 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13635 for (const auto &I : Fn->param_types()) { 13636 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13637 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13638 Params.push_back(Param); 13639 } 13640 } 13641 13642 // Set the parameters on the block decl. 13643 if (!Params.empty()) { 13644 CurBlock->TheDecl->setParams(Params); 13645 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13646 /*CheckParameterNames=*/false); 13647 } 13648 13649 // Finally we can process decl attributes. 13650 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13651 13652 // Put the parameter variables in scope. 13653 for (auto AI : CurBlock->TheDecl->parameters()) { 13654 AI->setOwningFunction(CurBlock->TheDecl); 13655 13656 // If this has an identifier, add it to the scope stack. 13657 if (AI->getIdentifier()) { 13658 CheckShadow(CurBlock->TheScope, AI); 13659 13660 PushOnScopeChains(AI, CurBlock->TheScope); 13661 } 13662 } 13663 } 13664 13665 /// ActOnBlockError - If there is an error parsing a block, this callback 13666 /// is invoked to pop the information about the block from the action impl. 13667 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13668 // Leave the expression-evaluation context. 13669 DiscardCleanupsInEvaluationContext(); 13670 PopExpressionEvaluationContext(); 13671 13672 // Pop off CurBlock, handle nested blocks. 13673 PopDeclContext(); 13674 PopFunctionScopeInfo(); 13675 } 13676 13677 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13678 /// literal was successfully completed. ^(int x){...} 13679 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13680 Stmt *Body, Scope *CurScope) { 13681 // If blocks are disabled, emit an error. 13682 if (!LangOpts.Blocks) 13683 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13684 13685 // Leave the expression-evaluation context. 13686 if (hasAnyUnrecoverableErrorsInThisFunction()) 13687 DiscardCleanupsInEvaluationContext(); 13688 assert(!Cleanup.exprNeedsCleanups() && 13689 "cleanups within block not correctly bound!"); 13690 PopExpressionEvaluationContext(); 13691 13692 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13693 BlockDecl *BD = BSI->TheDecl; 13694 13695 if (BSI->HasImplicitReturnType) 13696 deduceClosureReturnType(*BSI); 13697 13698 PopDeclContext(); 13699 13700 QualType RetTy = Context.VoidTy; 13701 if (!BSI->ReturnType.isNull()) 13702 RetTy = BSI->ReturnType; 13703 13704 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13705 QualType BlockTy; 13706 13707 // Set the captured variables on the block. 13708 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13709 SmallVector<BlockDecl::Capture, 4> Captures; 13710 for (Capture &Cap : BSI->Captures) { 13711 if (Cap.isThisCapture()) 13712 continue; 13713 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13714 Cap.isNested(), Cap.getInitExpr()); 13715 Captures.push_back(NewCap); 13716 } 13717 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13718 13719 // If the user wrote a function type in some form, try to use that. 13720 if (!BSI->FunctionType.isNull()) { 13721 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13722 13723 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13724 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13725 13726 // Turn protoless block types into nullary block types. 13727 if (isa<FunctionNoProtoType>(FTy)) { 13728 FunctionProtoType::ExtProtoInfo EPI; 13729 EPI.ExtInfo = Ext; 13730 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13731 13732 // Otherwise, if we don't need to change anything about the function type, 13733 // preserve its sugar structure. 13734 } else if (FTy->getReturnType() == RetTy && 13735 (!NoReturn || FTy->getNoReturnAttr())) { 13736 BlockTy = BSI->FunctionType; 13737 13738 // Otherwise, make the minimal modifications to the function type. 13739 } else { 13740 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13741 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13742 EPI.TypeQuals = Qualifiers(); 13743 EPI.ExtInfo = Ext; 13744 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13745 } 13746 13747 // If we don't have a function type, just build one from nothing. 13748 } else { 13749 FunctionProtoType::ExtProtoInfo EPI; 13750 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13751 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13752 } 13753 13754 DiagnoseUnusedParameters(BD->parameters()); 13755 BlockTy = Context.getBlockPointerType(BlockTy); 13756 13757 // If needed, diagnose invalid gotos and switches in the block. 13758 if (getCurFunction()->NeedsScopeChecking() && 13759 !PP.isCodeCompletionEnabled()) 13760 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13761 13762 BD->setBody(cast<CompoundStmt>(Body)); 13763 13764 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13765 DiagnoseUnguardedAvailabilityViolations(BD); 13766 13767 // Try to apply the named return value optimization. We have to check again 13768 // if we can do this, though, because blocks keep return statements around 13769 // to deduce an implicit return type. 13770 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13771 !BD->isDependentContext()) 13772 computeNRVO(Body, BSI); 13773 13774 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13775 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13776 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13777 13778 // If the block isn't obviously global, i.e. it captures anything at 13779 // all, then we need to do a few things in the surrounding context: 13780 if (Result->getBlockDecl()->hasCaptures()) { 13781 // First, this expression has a new cleanup object. 13782 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13783 Cleanup.setExprNeedsCleanups(true); 13784 13785 // It also gets a branch-protected scope if any of the captured 13786 // variables needs destruction. 13787 for (const auto &CI : Result->getBlockDecl()->captures()) { 13788 const VarDecl *var = CI.getVariable(); 13789 if (var->getType().isDestructedType() != QualType::DK_none) { 13790 setFunctionHasBranchProtectedScope(); 13791 break; 13792 } 13793 } 13794 } 13795 13796 if (getCurFunction()) 13797 getCurFunction()->addBlock(BD); 13798 13799 return Result; 13800 } 13801 13802 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13803 SourceLocation RPLoc) { 13804 TypeSourceInfo *TInfo; 13805 GetTypeFromParser(Ty, &TInfo); 13806 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13807 } 13808 13809 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13810 Expr *E, TypeSourceInfo *TInfo, 13811 SourceLocation RPLoc) { 13812 Expr *OrigExpr = E; 13813 bool IsMS = false; 13814 13815 // CUDA device code does not support varargs. 13816 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13817 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13818 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13819 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13820 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13821 } 13822 } 13823 13824 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13825 // as Microsoft ABI on an actual Microsoft platform, where 13826 // __builtin_ms_va_list and __builtin_va_list are the same.) 13827 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13828 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13829 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13830 if (Context.hasSameType(MSVaListType, E->getType())) { 13831 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13832 return ExprError(); 13833 IsMS = true; 13834 } 13835 } 13836 13837 // Get the va_list type 13838 QualType VaListType = Context.getBuiltinVaListType(); 13839 if (!IsMS) { 13840 if (VaListType->isArrayType()) { 13841 // Deal with implicit array decay; for example, on x86-64, 13842 // va_list is an array, but it's supposed to decay to 13843 // a pointer for va_arg. 13844 VaListType = Context.getArrayDecayedType(VaListType); 13845 // Make sure the input expression also decays appropriately. 13846 ExprResult Result = UsualUnaryConversions(E); 13847 if (Result.isInvalid()) 13848 return ExprError(); 13849 E = Result.get(); 13850 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13851 // If va_list is a record type and we are compiling in C++ mode, 13852 // check the argument using reference binding. 13853 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13854 Context, Context.getLValueReferenceType(VaListType), false); 13855 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13856 if (Init.isInvalid()) 13857 return ExprError(); 13858 E = Init.getAs<Expr>(); 13859 } else { 13860 // Otherwise, the va_list argument must be an l-value because 13861 // it is modified by va_arg. 13862 if (!E->isTypeDependent() && 13863 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13864 return ExprError(); 13865 } 13866 } 13867 13868 if (!IsMS && !E->isTypeDependent() && 13869 !Context.hasSameType(VaListType, E->getType())) 13870 return ExprError( 13871 Diag(E->getBeginLoc(), 13872 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13873 << OrigExpr->getType() << E->getSourceRange()); 13874 13875 if (!TInfo->getType()->isDependentType()) { 13876 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13877 diag::err_second_parameter_to_va_arg_incomplete, 13878 TInfo->getTypeLoc())) 13879 return ExprError(); 13880 13881 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13882 TInfo->getType(), 13883 diag::err_second_parameter_to_va_arg_abstract, 13884 TInfo->getTypeLoc())) 13885 return ExprError(); 13886 13887 if (!TInfo->getType().isPODType(Context)) { 13888 Diag(TInfo->getTypeLoc().getBeginLoc(), 13889 TInfo->getType()->isObjCLifetimeType() 13890 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13891 : diag::warn_second_parameter_to_va_arg_not_pod) 13892 << TInfo->getType() 13893 << TInfo->getTypeLoc().getSourceRange(); 13894 } 13895 13896 // Check for va_arg where arguments of the given type will be promoted 13897 // (i.e. this va_arg is guaranteed to have undefined behavior). 13898 QualType PromoteType; 13899 if (TInfo->getType()->isPromotableIntegerType()) { 13900 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13901 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13902 PromoteType = QualType(); 13903 } 13904 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13905 PromoteType = Context.DoubleTy; 13906 if (!PromoteType.isNull()) 13907 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13908 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13909 << TInfo->getType() 13910 << PromoteType 13911 << TInfo->getTypeLoc().getSourceRange()); 13912 } 13913 13914 QualType T = TInfo->getType().getNonLValueExprType(Context); 13915 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13916 } 13917 13918 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13919 // The type of __null will be int or long, depending on the size of 13920 // pointers on the target. 13921 QualType Ty; 13922 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13923 if (pw == Context.getTargetInfo().getIntWidth()) 13924 Ty = Context.IntTy; 13925 else if (pw == Context.getTargetInfo().getLongWidth()) 13926 Ty = Context.LongTy; 13927 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13928 Ty = Context.LongLongTy; 13929 else { 13930 llvm_unreachable("I don't know size of pointer!"); 13931 } 13932 13933 return new (Context) GNUNullExpr(Ty, TokenLoc); 13934 } 13935 13936 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13937 bool Diagnose) { 13938 if (!getLangOpts().ObjC) 13939 return false; 13940 13941 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13942 if (!PT) 13943 return false; 13944 13945 if (!PT->isObjCIdType()) { 13946 // Check if the destination is the 'NSString' interface. 13947 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13948 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13949 return false; 13950 } 13951 13952 // Ignore any parens, implicit casts (should only be 13953 // array-to-pointer decays), and not-so-opaque values. The last is 13954 // important for making this trigger for property assignments. 13955 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13956 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13957 if (OV->getSourceExpr()) 13958 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13959 13960 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13961 if (!SL || !SL->isAscii()) 13962 return false; 13963 if (Diagnose) { 13964 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13965 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13966 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13967 } 13968 return true; 13969 } 13970 13971 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13972 const Expr *SrcExpr) { 13973 if (!DstType->isFunctionPointerType() || 13974 !SrcExpr->getType()->isFunctionType()) 13975 return false; 13976 13977 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13978 if (!DRE) 13979 return false; 13980 13981 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13982 if (!FD) 13983 return false; 13984 13985 return !S.checkAddressOfFunctionIsAvailable(FD, 13986 /*Complain=*/true, 13987 SrcExpr->getBeginLoc()); 13988 } 13989 13990 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13991 SourceLocation Loc, 13992 QualType DstType, QualType SrcType, 13993 Expr *SrcExpr, AssignmentAction Action, 13994 bool *Complained) { 13995 if (Complained) 13996 *Complained = false; 13997 13998 // Decode the result (notice that AST's are still created for extensions). 13999 bool CheckInferredResultType = false; 14000 bool isInvalid = false; 14001 unsigned DiagKind = 0; 14002 FixItHint Hint; 14003 ConversionFixItGenerator ConvHints; 14004 bool MayHaveConvFixit = false; 14005 bool MayHaveFunctionDiff = false; 14006 const ObjCInterfaceDecl *IFace = nullptr; 14007 const ObjCProtocolDecl *PDecl = nullptr; 14008 14009 switch (ConvTy) { 14010 case Compatible: 14011 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14012 return false; 14013 14014 case PointerToInt: 14015 DiagKind = diag::ext_typecheck_convert_pointer_int; 14016 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14017 MayHaveConvFixit = true; 14018 break; 14019 case IntToPointer: 14020 DiagKind = diag::ext_typecheck_convert_int_pointer; 14021 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14022 MayHaveConvFixit = true; 14023 break; 14024 case IncompatiblePointer: 14025 if (Action == AA_Passing_CFAudited) 14026 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14027 else if (SrcType->isFunctionPointerType() && 14028 DstType->isFunctionPointerType()) 14029 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14030 else 14031 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14032 14033 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14034 SrcType->isObjCObjectPointerType(); 14035 if (Hint.isNull() && !CheckInferredResultType) { 14036 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14037 } 14038 else if (CheckInferredResultType) { 14039 SrcType = SrcType.getUnqualifiedType(); 14040 DstType = DstType.getUnqualifiedType(); 14041 } 14042 MayHaveConvFixit = true; 14043 break; 14044 case IncompatiblePointerSign: 14045 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14046 break; 14047 case FunctionVoidPointer: 14048 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14049 break; 14050 case IncompatiblePointerDiscardsQualifiers: { 14051 // Perform array-to-pointer decay if necessary. 14052 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14053 14054 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14055 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14056 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14057 DiagKind = diag::err_typecheck_incompatible_address_space; 14058 break; 14059 14060 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14061 DiagKind = diag::err_typecheck_incompatible_ownership; 14062 break; 14063 } 14064 14065 llvm_unreachable("unknown error case for discarding qualifiers!"); 14066 // fallthrough 14067 } 14068 case CompatiblePointerDiscardsQualifiers: 14069 // If the qualifiers lost were because we were applying the 14070 // (deprecated) C++ conversion from a string literal to a char* 14071 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14072 // Ideally, this check would be performed in 14073 // checkPointerTypesForAssignment. However, that would require a 14074 // bit of refactoring (so that the second argument is an 14075 // expression, rather than a type), which should be done as part 14076 // of a larger effort to fix checkPointerTypesForAssignment for 14077 // C++ semantics. 14078 if (getLangOpts().CPlusPlus && 14079 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14080 return false; 14081 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14082 break; 14083 case IncompatibleNestedPointerQualifiers: 14084 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14085 break; 14086 case IntToBlockPointer: 14087 DiagKind = diag::err_int_to_block_pointer; 14088 break; 14089 case IncompatibleBlockPointer: 14090 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14091 break; 14092 case IncompatibleObjCQualifiedId: { 14093 if (SrcType->isObjCQualifiedIdType()) { 14094 const ObjCObjectPointerType *srcOPT = 14095 SrcType->getAs<ObjCObjectPointerType>(); 14096 for (auto *srcProto : srcOPT->quals()) { 14097 PDecl = srcProto; 14098 break; 14099 } 14100 if (const ObjCInterfaceType *IFaceT = 14101 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14102 IFace = IFaceT->getDecl(); 14103 } 14104 else if (DstType->isObjCQualifiedIdType()) { 14105 const ObjCObjectPointerType *dstOPT = 14106 DstType->getAs<ObjCObjectPointerType>(); 14107 for (auto *dstProto : dstOPT->quals()) { 14108 PDecl = dstProto; 14109 break; 14110 } 14111 if (const ObjCInterfaceType *IFaceT = 14112 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14113 IFace = IFaceT->getDecl(); 14114 } 14115 DiagKind = diag::warn_incompatible_qualified_id; 14116 break; 14117 } 14118 case IncompatibleVectors: 14119 DiagKind = diag::warn_incompatible_vectors; 14120 break; 14121 case IncompatibleObjCWeakRef: 14122 DiagKind = diag::err_arc_weak_unavailable_assign; 14123 break; 14124 case Incompatible: 14125 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14126 if (Complained) 14127 *Complained = true; 14128 return true; 14129 } 14130 14131 DiagKind = diag::err_typecheck_convert_incompatible; 14132 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14133 MayHaveConvFixit = true; 14134 isInvalid = true; 14135 MayHaveFunctionDiff = true; 14136 break; 14137 } 14138 14139 QualType FirstType, SecondType; 14140 switch (Action) { 14141 case AA_Assigning: 14142 case AA_Initializing: 14143 // The destination type comes first. 14144 FirstType = DstType; 14145 SecondType = SrcType; 14146 break; 14147 14148 case AA_Returning: 14149 case AA_Passing: 14150 case AA_Passing_CFAudited: 14151 case AA_Converting: 14152 case AA_Sending: 14153 case AA_Casting: 14154 // The source type comes first. 14155 FirstType = SrcType; 14156 SecondType = DstType; 14157 break; 14158 } 14159 14160 PartialDiagnostic FDiag = PDiag(DiagKind); 14161 if (Action == AA_Passing_CFAudited) 14162 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14163 else 14164 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14165 14166 // If we can fix the conversion, suggest the FixIts. 14167 assert(ConvHints.isNull() || Hint.isNull()); 14168 if (!ConvHints.isNull()) { 14169 for (FixItHint &H : ConvHints.Hints) 14170 FDiag << H; 14171 } else { 14172 FDiag << Hint; 14173 } 14174 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14175 14176 if (MayHaveFunctionDiff) 14177 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14178 14179 Diag(Loc, FDiag); 14180 if (DiagKind == diag::warn_incompatible_qualified_id && 14181 PDecl && IFace && !IFace->hasDefinition()) 14182 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14183 << IFace << PDecl; 14184 14185 if (SecondType == Context.OverloadTy) 14186 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14187 FirstType, /*TakingAddress=*/true); 14188 14189 if (CheckInferredResultType) 14190 EmitRelatedResultTypeNote(SrcExpr); 14191 14192 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14193 EmitRelatedResultTypeNoteForReturn(DstType); 14194 14195 if (Complained) 14196 *Complained = true; 14197 return isInvalid; 14198 } 14199 14200 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14201 llvm::APSInt *Result) { 14202 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14203 public: 14204 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14205 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14206 } 14207 } Diagnoser; 14208 14209 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14210 } 14211 14212 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14213 llvm::APSInt *Result, 14214 unsigned DiagID, 14215 bool AllowFold) { 14216 class IDDiagnoser : public VerifyICEDiagnoser { 14217 unsigned DiagID; 14218 14219 public: 14220 IDDiagnoser(unsigned DiagID) 14221 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14222 14223 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14224 S.Diag(Loc, DiagID) << SR; 14225 } 14226 } Diagnoser(DiagID); 14227 14228 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14229 } 14230 14231 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14232 SourceRange SR) { 14233 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14234 } 14235 14236 ExprResult 14237 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14238 VerifyICEDiagnoser &Diagnoser, 14239 bool AllowFold) { 14240 SourceLocation DiagLoc = E->getBeginLoc(); 14241 14242 if (getLangOpts().CPlusPlus11) { 14243 // C++11 [expr.const]p5: 14244 // If an expression of literal class type is used in a context where an 14245 // integral constant expression is required, then that class type shall 14246 // have a single non-explicit conversion function to an integral or 14247 // unscoped enumeration type 14248 ExprResult Converted; 14249 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14250 public: 14251 CXX11ConvertDiagnoser(bool Silent) 14252 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14253 Silent, true) {} 14254 14255 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14256 QualType T) override { 14257 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14258 } 14259 14260 SemaDiagnosticBuilder diagnoseIncomplete( 14261 Sema &S, SourceLocation Loc, QualType T) override { 14262 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14263 } 14264 14265 SemaDiagnosticBuilder diagnoseExplicitConv( 14266 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14267 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14268 } 14269 14270 SemaDiagnosticBuilder noteExplicitConv( 14271 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14272 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14273 << ConvTy->isEnumeralType() << ConvTy; 14274 } 14275 14276 SemaDiagnosticBuilder diagnoseAmbiguous( 14277 Sema &S, SourceLocation Loc, QualType T) override { 14278 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14279 } 14280 14281 SemaDiagnosticBuilder noteAmbiguous( 14282 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14283 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14284 << ConvTy->isEnumeralType() << ConvTy; 14285 } 14286 14287 SemaDiagnosticBuilder diagnoseConversion( 14288 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14289 llvm_unreachable("conversion functions are permitted"); 14290 } 14291 } ConvertDiagnoser(Diagnoser.Suppress); 14292 14293 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14294 ConvertDiagnoser); 14295 if (Converted.isInvalid()) 14296 return Converted; 14297 E = Converted.get(); 14298 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14299 return ExprError(); 14300 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14301 // An ICE must be of integral or unscoped enumeration type. 14302 if (!Diagnoser.Suppress) 14303 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14304 return ExprError(); 14305 } 14306 14307 if (!isa<ConstantExpr>(E)) 14308 E = ConstantExpr::Create(Context, E); 14309 14310 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14311 // in the non-ICE case. 14312 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14313 if (Result) 14314 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14315 return E; 14316 } 14317 14318 Expr::EvalResult EvalResult; 14319 SmallVector<PartialDiagnosticAt, 8> Notes; 14320 EvalResult.Diag = &Notes; 14321 14322 // Try to evaluate the expression, and produce diagnostics explaining why it's 14323 // not a constant expression as a side-effect. 14324 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14325 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14326 14327 // In C++11, we can rely on diagnostics being produced for any expression 14328 // which is not a constant expression. If no diagnostics were produced, then 14329 // this is a constant expression. 14330 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14331 if (Result) 14332 *Result = EvalResult.Val.getInt(); 14333 return E; 14334 } 14335 14336 // If our only note is the usual "invalid subexpression" note, just point 14337 // the caret at its location rather than producing an essentially 14338 // redundant note. 14339 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14340 diag::note_invalid_subexpr_in_const_expr) { 14341 DiagLoc = Notes[0].first; 14342 Notes.clear(); 14343 } 14344 14345 if (!Folded || !AllowFold) { 14346 if (!Diagnoser.Suppress) { 14347 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14348 for (const PartialDiagnosticAt &Note : Notes) 14349 Diag(Note.first, Note.second); 14350 } 14351 14352 return ExprError(); 14353 } 14354 14355 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14356 for (const PartialDiagnosticAt &Note : Notes) 14357 Diag(Note.first, Note.second); 14358 14359 if (Result) 14360 *Result = EvalResult.Val.getInt(); 14361 return E; 14362 } 14363 14364 namespace { 14365 // Handle the case where we conclude a expression which we speculatively 14366 // considered to be unevaluated is actually evaluated. 14367 class TransformToPE : public TreeTransform<TransformToPE> { 14368 typedef TreeTransform<TransformToPE> BaseTransform; 14369 14370 public: 14371 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14372 14373 // Make sure we redo semantic analysis 14374 bool AlwaysRebuild() { return true; } 14375 14376 // Make sure we handle LabelStmts correctly. 14377 // FIXME: This does the right thing, but maybe we need a more general 14378 // fix to TreeTransform? 14379 StmtResult TransformLabelStmt(LabelStmt *S) { 14380 S->getDecl()->setStmt(nullptr); 14381 return BaseTransform::TransformLabelStmt(S); 14382 } 14383 14384 // We need to special-case DeclRefExprs referring to FieldDecls which 14385 // are not part of a member pointer formation; normal TreeTransforming 14386 // doesn't catch this case because of the way we represent them in the AST. 14387 // FIXME: This is a bit ugly; is it really the best way to handle this 14388 // case? 14389 // 14390 // Error on DeclRefExprs referring to FieldDecls. 14391 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14392 if (isa<FieldDecl>(E->getDecl()) && 14393 !SemaRef.isUnevaluatedContext()) 14394 return SemaRef.Diag(E->getLocation(), 14395 diag::err_invalid_non_static_member_use) 14396 << E->getDecl() << E->getSourceRange(); 14397 14398 return BaseTransform::TransformDeclRefExpr(E); 14399 } 14400 14401 // Exception: filter out member pointer formation 14402 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14403 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14404 return E; 14405 14406 return BaseTransform::TransformUnaryOperator(E); 14407 } 14408 14409 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14410 // Lambdas never need to be transformed. 14411 return E; 14412 } 14413 }; 14414 } 14415 14416 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14417 assert(isUnevaluatedContext() && 14418 "Should only transform unevaluated expressions"); 14419 ExprEvalContexts.back().Context = 14420 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14421 if (isUnevaluatedContext()) 14422 return E; 14423 return TransformToPE(*this).TransformExpr(E); 14424 } 14425 14426 void 14427 Sema::PushExpressionEvaluationContext( 14428 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14429 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14430 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14431 LambdaContextDecl, ExprContext); 14432 Cleanup.reset(); 14433 if (!MaybeODRUseExprs.empty()) 14434 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14435 } 14436 14437 void 14438 Sema::PushExpressionEvaluationContext( 14439 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14440 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14441 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14442 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14443 } 14444 14445 namespace { 14446 14447 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 14448 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 14449 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 14450 if (E->getOpcode() == UO_Deref) 14451 return CheckPossibleDeref(S, E->getSubExpr()); 14452 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 14453 return CheckPossibleDeref(S, E->getBase()); 14454 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 14455 return CheckPossibleDeref(S, E->getBase()); 14456 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 14457 QualType Inner; 14458 QualType Ty = E->getType(); 14459 if (const auto *Ptr = Ty->getAs<PointerType>()) 14460 Inner = Ptr->getPointeeType(); 14461 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 14462 Inner = Arr->getElementType(); 14463 else 14464 return nullptr; 14465 14466 if (Inner->hasAttr(attr::NoDeref)) 14467 return E; 14468 } 14469 return nullptr; 14470 } 14471 14472 } // namespace 14473 14474 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 14475 for (const Expr *E : Rec.PossibleDerefs) { 14476 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 14477 if (DeclRef) { 14478 const ValueDecl *Decl = DeclRef->getDecl(); 14479 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 14480 << Decl->getName() << E->getSourceRange(); 14481 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 14482 } else { 14483 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 14484 << E->getSourceRange(); 14485 } 14486 } 14487 Rec.PossibleDerefs.clear(); 14488 } 14489 14490 void Sema::PopExpressionEvaluationContext() { 14491 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14492 unsigned NumTypos = Rec.NumTypos; 14493 14494 if (!Rec.Lambdas.empty()) { 14495 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14496 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14497 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14498 unsigned D; 14499 if (Rec.isUnevaluated()) { 14500 // C++11 [expr.prim.lambda]p2: 14501 // A lambda-expression shall not appear in an unevaluated operand 14502 // (Clause 5). 14503 D = diag::err_lambda_unevaluated_operand; 14504 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14505 // C++1y [expr.const]p2: 14506 // A conditional-expression e is a core constant expression unless the 14507 // evaluation of e, following the rules of the abstract machine, would 14508 // evaluate [...] a lambda-expression. 14509 D = diag::err_lambda_in_constant_expression; 14510 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14511 // C++17 [expr.prim.lamda]p2: 14512 // A lambda-expression shall not appear [...] in a template-argument. 14513 D = diag::err_lambda_in_invalid_context; 14514 } else 14515 llvm_unreachable("Couldn't infer lambda error message."); 14516 14517 for (const auto *L : Rec.Lambdas) 14518 Diag(L->getBeginLoc(), D); 14519 } else { 14520 // Mark the capture expressions odr-used. This was deferred 14521 // during lambda expression creation. 14522 for (auto *Lambda : Rec.Lambdas) { 14523 for (auto *C : Lambda->capture_inits()) 14524 MarkDeclarationsReferencedInExpr(C); 14525 } 14526 } 14527 } 14528 14529 WarnOnPendingNoDerefs(Rec); 14530 14531 // When are coming out of an unevaluated context, clear out any 14532 // temporaries that we may have created as part of the evaluation of 14533 // the expression in that context: they aren't relevant because they 14534 // will never be constructed. 14535 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14536 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14537 ExprCleanupObjects.end()); 14538 Cleanup = Rec.ParentCleanup; 14539 CleanupVarDeclMarking(); 14540 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14541 // Otherwise, merge the contexts together. 14542 } else { 14543 Cleanup.mergeFrom(Rec.ParentCleanup); 14544 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14545 Rec.SavedMaybeODRUseExprs.end()); 14546 } 14547 14548 // Pop the current expression evaluation context off the stack. 14549 ExprEvalContexts.pop_back(); 14550 14551 // The global expression evaluation context record is never popped. 14552 ExprEvalContexts.back().NumTypos += NumTypos; 14553 } 14554 14555 void Sema::DiscardCleanupsInEvaluationContext() { 14556 ExprCleanupObjects.erase( 14557 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14558 ExprCleanupObjects.end()); 14559 Cleanup.reset(); 14560 MaybeODRUseExprs.clear(); 14561 } 14562 14563 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14564 ExprResult Result = CheckPlaceholderExpr(E); 14565 if (Result.isInvalid()) 14566 return ExprError(); 14567 E = Result.get(); 14568 if (!E->getType()->isVariablyModifiedType()) 14569 return E; 14570 return TransformToPotentiallyEvaluated(E); 14571 } 14572 14573 /// Are we within a context in which some evaluation could be performed (be it 14574 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14575 /// captured by C++'s idea of an "unevaluated context". 14576 static bool isEvaluatableContext(Sema &SemaRef) { 14577 switch (SemaRef.ExprEvalContexts.back().Context) { 14578 case Sema::ExpressionEvaluationContext::Unevaluated: 14579 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14580 // Expressions in this context are never evaluated. 14581 return false; 14582 14583 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14584 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14585 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14586 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14587 // Expressions in this context could be evaluated. 14588 return true; 14589 14590 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14591 // Referenced declarations will only be used if the construct in the 14592 // containing expression is used, at which point we'll be given another 14593 // turn to mark them. 14594 return false; 14595 } 14596 llvm_unreachable("Invalid context"); 14597 } 14598 14599 /// Are we within a context in which references to resolved functions or to 14600 /// variables result in odr-use? 14601 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14602 // An expression in a template is not really an expression until it's been 14603 // instantiated, so it doesn't trigger odr-use. 14604 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14605 return false; 14606 14607 switch (SemaRef.ExprEvalContexts.back().Context) { 14608 case Sema::ExpressionEvaluationContext::Unevaluated: 14609 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14610 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14611 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14612 return false; 14613 14614 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14615 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14616 return true; 14617 14618 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14619 return false; 14620 } 14621 llvm_unreachable("Invalid context"); 14622 } 14623 14624 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14625 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14626 return Func->isConstexpr() && 14627 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14628 } 14629 14630 /// Mark a function referenced, and check whether it is odr-used 14631 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14632 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14633 bool MightBeOdrUse) { 14634 assert(Func && "No function?"); 14635 14636 Func->setReferenced(); 14637 14638 // C++11 [basic.def.odr]p3: 14639 // A function whose name appears as a potentially-evaluated expression is 14640 // odr-used if it is the unique lookup result or the selected member of a 14641 // set of overloaded functions [...]. 14642 // 14643 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14644 // can just check that here. 14645 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14646 14647 // Determine whether we require a function definition to exist, per 14648 // C++11 [temp.inst]p3: 14649 // Unless a function template specialization has been explicitly 14650 // instantiated or explicitly specialized, the function template 14651 // specialization is implicitly instantiated when the specialization is 14652 // referenced in a context that requires a function definition to exist. 14653 // 14654 // That is either when this is an odr-use, or when a usage of a constexpr 14655 // function occurs within an evaluatable context. 14656 bool NeedDefinition = 14657 OdrUse || (isEvaluatableContext(*this) && 14658 isImplicitlyDefinableConstexprFunction(Func)); 14659 14660 // C++14 [temp.expl.spec]p6: 14661 // If a template [...] is explicitly specialized then that specialization 14662 // shall be declared before the first use of that specialization that would 14663 // cause an implicit instantiation to take place, in every translation unit 14664 // in which such a use occurs 14665 if (NeedDefinition && 14666 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14667 Func->getMemberSpecializationInfo())) 14668 checkSpecializationVisibility(Loc, Func); 14669 14670 // C++14 [except.spec]p17: 14671 // An exception-specification is considered to be needed when: 14672 // - the function is odr-used or, if it appears in an unevaluated operand, 14673 // would be odr-used if the expression were potentially-evaluated; 14674 // 14675 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14676 // function is a pure virtual function we're calling, and in that case the 14677 // function was selected by overload resolution and we need to resolve its 14678 // exception specification for a different reason. 14679 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14680 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14681 ResolveExceptionSpec(Loc, FPT); 14682 14683 // If we don't need to mark the function as used, and we don't need to 14684 // try to provide a definition, there's nothing more to do. 14685 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14686 (!NeedDefinition || Func->getBody())) 14687 return; 14688 14689 // Note that this declaration has been used. 14690 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14691 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14692 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14693 if (Constructor->isDefaultConstructor()) { 14694 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14695 return; 14696 DefineImplicitDefaultConstructor(Loc, Constructor); 14697 } else if (Constructor->isCopyConstructor()) { 14698 DefineImplicitCopyConstructor(Loc, Constructor); 14699 } else if (Constructor->isMoveConstructor()) { 14700 DefineImplicitMoveConstructor(Loc, Constructor); 14701 } 14702 } else if (Constructor->getInheritedConstructor()) { 14703 DefineInheritingConstructor(Loc, Constructor); 14704 } 14705 } else if (CXXDestructorDecl *Destructor = 14706 dyn_cast<CXXDestructorDecl>(Func)) { 14707 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14708 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14709 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14710 return; 14711 DefineImplicitDestructor(Loc, Destructor); 14712 } 14713 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14714 MarkVTableUsed(Loc, Destructor->getParent()); 14715 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14716 if (MethodDecl->isOverloadedOperator() && 14717 MethodDecl->getOverloadedOperator() == OO_Equal) { 14718 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14719 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14720 if (MethodDecl->isCopyAssignmentOperator()) 14721 DefineImplicitCopyAssignment(Loc, MethodDecl); 14722 else if (MethodDecl->isMoveAssignmentOperator()) 14723 DefineImplicitMoveAssignment(Loc, MethodDecl); 14724 } 14725 } else if (isa<CXXConversionDecl>(MethodDecl) && 14726 MethodDecl->getParent()->isLambda()) { 14727 CXXConversionDecl *Conversion = 14728 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14729 if (Conversion->isLambdaToBlockPointerConversion()) 14730 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14731 else 14732 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14733 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14734 MarkVTableUsed(Loc, MethodDecl->getParent()); 14735 } 14736 14737 // Recursive functions should be marked when used from another function. 14738 // FIXME: Is this really right? 14739 if (CurContext == Func) return; 14740 14741 // Implicit instantiation of function templates and member functions of 14742 // class templates. 14743 if (Func->isImplicitlyInstantiable()) { 14744 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14745 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14746 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14747 if (FirstInstantiation) { 14748 PointOfInstantiation = Loc; 14749 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14750 } else if (TSK != TSK_ImplicitInstantiation) { 14751 // Use the point of use as the point of instantiation, instead of the 14752 // point of explicit instantiation (which we track as the actual point of 14753 // instantiation). This gives better backtraces in diagnostics. 14754 PointOfInstantiation = Loc; 14755 } 14756 14757 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14758 Func->isConstexpr()) { 14759 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14760 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14761 CodeSynthesisContexts.size()) 14762 PendingLocalImplicitInstantiations.push_back( 14763 std::make_pair(Func, PointOfInstantiation)); 14764 else if (Func->isConstexpr()) 14765 // Do not defer instantiations of constexpr functions, to avoid the 14766 // expression evaluator needing to call back into Sema if it sees a 14767 // call to such a function. 14768 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14769 else { 14770 Func->setInstantiationIsPending(true); 14771 PendingInstantiations.push_back(std::make_pair(Func, 14772 PointOfInstantiation)); 14773 // Notify the consumer that a function was implicitly instantiated. 14774 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14775 } 14776 } 14777 } else { 14778 // Walk redefinitions, as some of them may be instantiable. 14779 for (auto i : Func->redecls()) { 14780 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14781 MarkFunctionReferenced(Loc, i, OdrUse); 14782 } 14783 } 14784 14785 if (!OdrUse) return; 14786 14787 // Keep track of used but undefined functions. 14788 if (!Func->isDefined()) { 14789 if (mightHaveNonExternalLinkage(Func)) 14790 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14791 else if (Func->getMostRecentDecl()->isInlined() && 14792 !LangOpts.GNUInline && 14793 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14794 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14795 else if (isExternalWithNoLinkageType(Func)) 14796 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14797 } 14798 14799 Func->markUsed(Context); 14800 } 14801 14802 static void 14803 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14804 ValueDecl *var, DeclContext *DC) { 14805 DeclContext *VarDC = var->getDeclContext(); 14806 14807 // If the parameter still belongs to the translation unit, then 14808 // we're actually just using one parameter in the declaration of 14809 // the next. 14810 if (isa<ParmVarDecl>(var) && 14811 isa<TranslationUnitDecl>(VarDC)) 14812 return; 14813 14814 // For C code, don't diagnose about capture if we're not actually in code 14815 // right now; it's impossible to write a non-constant expression outside of 14816 // function context, so we'll get other (more useful) diagnostics later. 14817 // 14818 // For C++, things get a bit more nasty... it would be nice to suppress this 14819 // diagnostic for certain cases like using a local variable in an array bound 14820 // for a member of a local class, but the correct predicate is not obvious. 14821 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14822 return; 14823 14824 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14825 unsigned ContextKind = 3; // unknown 14826 if (isa<CXXMethodDecl>(VarDC) && 14827 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14828 ContextKind = 2; 14829 } else if (isa<FunctionDecl>(VarDC)) { 14830 ContextKind = 0; 14831 } else if (isa<BlockDecl>(VarDC)) { 14832 ContextKind = 1; 14833 } 14834 14835 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14836 << var << ValueKind << ContextKind << VarDC; 14837 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14838 << var; 14839 14840 // FIXME: Add additional diagnostic info about class etc. which prevents 14841 // capture. 14842 } 14843 14844 14845 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14846 bool &SubCapturesAreNested, 14847 QualType &CaptureType, 14848 QualType &DeclRefType) { 14849 // Check whether we've already captured it. 14850 if (CSI->CaptureMap.count(Var)) { 14851 // If we found a capture, any subcaptures are nested. 14852 SubCapturesAreNested = true; 14853 14854 // Retrieve the capture type for this variable. 14855 CaptureType = CSI->getCapture(Var).getCaptureType(); 14856 14857 // Compute the type of an expression that refers to this variable. 14858 DeclRefType = CaptureType.getNonReferenceType(); 14859 14860 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14861 // are mutable in the sense that user can change their value - they are 14862 // private instances of the captured declarations. 14863 const Capture &Cap = CSI->getCapture(Var); 14864 if (Cap.isCopyCapture() && 14865 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14866 !(isa<CapturedRegionScopeInfo>(CSI) && 14867 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14868 DeclRefType.addConst(); 14869 return true; 14870 } 14871 return false; 14872 } 14873 14874 // Only block literals, captured statements, and lambda expressions can 14875 // capture; other scopes don't work. 14876 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14877 SourceLocation Loc, 14878 const bool Diagnose, Sema &S) { 14879 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14880 return getLambdaAwareParentOfDeclContext(DC); 14881 else if (Var->hasLocalStorage()) { 14882 if (Diagnose) 14883 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14884 } 14885 return nullptr; 14886 } 14887 14888 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14889 // certain types of variables (unnamed, variably modified types etc.) 14890 // so check for eligibility. 14891 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14892 SourceLocation Loc, 14893 const bool Diagnose, Sema &S) { 14894 14895 bool IsBlock = isa<BlockScopeInfo>(CSI); 14896 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14897 14898 // Lambdas are not allowed to capture unnamed variables 14899 // (e.g. anonymous unions). 14900 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14901 // assuming that's the intent. 14902 if (IsLambda && !Var->getDeclName()) { 14903 if (Diagnose) { 14904 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14905 S.Diag(Var->getLocation(), diag::note_declared_at); 14906 } 14907 return false; 14908 } 14909 14910 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14911 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14912 if (Diagnose) { 14913 S.Diag(Loc, diag::err_ref_vm_type); 14914 S.Diag(Var->getLocation(), diag::note_previous_decl) 14915 << Var->getDeclName(); 14916 } 14917 return false; 14918 } 14919 // Prohibit structs with flexible array members too. 14920 // We cannot capture what is in the tail end of the struct. 14921 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14922 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14923 if (Diagnose) { 14924 if (IsBlock) 14925 S.Diag(Loc, diag::err_ref_flexarray_type); 14926 else 14927 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14928 << Var->getDeclName(); 14929 S.Diag(Var->getLocation(), diag::note_previous_decl) 14930 << Var->getDeclName(); 14931 } 14932 return false; 14933 } 14934 } 14935 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14936 // Lambdas and captured statements are not allowed to capture __block 14937 // variables; they don't support the expected semantics. 14938 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14939 if (Diagnose) { 14940 S.Diag(Loc, diag::err_capture_block_variable) 14941 << Var->getDeclName() << !IsLambda; 14942 S.Diag(Var->getLocation(), diag::note_previous_decl) 14943 << Var->getDeclName(); 14944 } 14945 return false; 14946 } 14947 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14948 if (S.getLangOpts().OpenCL && IsBlock && 14949 Var->getType()->isBlockPointerType()) { 14950 if (Diagnose) 14951 S.Diag(Loc, diag::err_opencl_block_ref_block); 14952 return false; 14953 } 14954 14955 return true; 14956 } 14957 14958 // Returns true if the capture by block was successful. 14959 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14960 SourceLocation Loc, 14961 const bool BuildAndDiagnose, 14962 QualType &CaptureType, 14963 QualType &DeclRefType, 14964 const bool Nested, 14965 Sema &S) { 14966 Expr *CopyExpr = nullptr; 14967 bool ByRef = false; 14968 14969 // Blocks are not allowed to capture arrays, excepting OpenCL. 14970 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 14971 // (decayed to pointers). 14972 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 14973 if (BuildAndDiagnose) { 14974 S.Diag(Loc, diag::err_ref_array_type); 14975 S.Diag(Var->getLocation(), diag::note_previous_decl) 14976 << Var->getDeclName(); 14977 } 14978 return false; 14979 } 14980 14981 // Forbid the block-capture of autoreleasing variables. 14982 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14983 if (BuildAndDiagnose) { 14984 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14985 << /*block*/ 0; 14986 S.Diag(Var->getLocation(), diag::note_previous_decl) 14987 << Var->getDeclName(); 14988 } 14989 return false; 14990 } 14991 14992 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14993 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14994 // This function finds out whether there is an AttributedType of kind 14995 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14996 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14997 // rather than being added implicitly by the compiler. 14998 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14999 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 15000 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 15001 return true; 15002 15003 // Peel off AttributedTypes that are not of kind ObjCOwnership. 15004 Ty = AttrTy->getModifiedType(); 15005 } 15006 15007 return false; 15008 }; 15009 15010 QualType PointeeTy = PT->getPointeeType(); 15011 15012 if (PointeeTy->getAs<ObjCObjectPointerType>() && 15013 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15014 !IsObjCOwnershipAttributedType(PointeeTy)) { 15015 if (BuildAndDiagnose) { 15016 SourceLocation VarLoc = Var->getLocation(); 15017 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15018 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15019 } 15020 } 15021 } 15022 15023 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15024 if (HasBlocksAttr || CaptureType->isReferenceType() || 15025 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15026 // Block capture by reference does not change the capture or 15027 // declaration reference types. 15028 ByRef = true; 15029 } else { 15030 // Block capture by copy introduces 'const'. 15031 CaptureType = CaptureType.getNonReferenceType().withConst(); 15032 DeclRefType = CaptureType; 15033 15034 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 15035 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 15036 // The capture logic needs the destructor, so make sure we mark it. 15037 // Usually this is unnecessary because most local variables have 15038 // their destructors marked at declaration time, but parameters are 15039 // an exception because it's technically only the call site that 15040 // actually requires the destructor. 15041 if (isa<ParmVarDecl>(Var)) 15042 S.FinalizeVarWithDestructor(Var, Record); 15043 15044 // Enter a new evaluation context to insulate the copy 15045 // full-expression. 15046 EnterExpressionEvaluationContext scope( 15047 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 15048 15049 // According to the blocks spec, the capture of a variable from 15050 // the stack requires a const copy constructor. This is not true 15051 // of the copy/move done to move a __block variable to the heap. 15052 Expr *DeclRef = new (S.Context) DeclRefExpr( 15053 S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc); 15054 15055 ExprResult Result 15056 = S.PerformCopyInitialization( 15057 InitializedEntity::InitializeBlock(Var->getLocation(), 15058 CaptureType, false), 15059 Loc, DeclRef); 15060 15061 // Build a full-expression copy expression if initialization 15062 // succeeded and used a non-trivial constructor. Recover from 15063 // errors by pretending that the copy isn't necessary. 15064 if (!Result.isInvalid() && 15065 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15066 ->isTrivial()) { 15067 Result = S.MaybeCreateExprWithCleanups(Result); 15068 CopyExpr = Result.get(); 15069 } 15070 } 15071 } 15072 } 15073 15074 // Actually capture the variable. 15075 if (BuildAndDiagnose) 15076 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 15077 SourceLocation(), CaptureType, CopyExpr); 15078 15079 return true; 15080 15081 } 15082 15083 15084 /// Capture the given variable in the captured region. 15085 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15086 VarDecl *Var, 15087 SourceLocation Loc, 15088 const bool BuildAndDiagnose, 15089 QualType &CaptureType, 15090 QualType &DeclRefType, 15091 const bool RefersToCapturedVariable, 15092 Sema &S) { 15093 // By default, capture variables by reference. 15094 bool ByRef = true; 15095 // Using an LValue reference type is consistent with Lambdas (see below). 15096 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15097 if (S.isOpenMPCapturedDecl(Var)) { 15098 bool HasConst = DeclRefType.isConstQualified(); 15099 DeclRefType = DeclRefType.getUnqualifiedType(); 15100 // Don't lose diagnostics about assignments to const. 15101 if (HasConst) 15102 DeclRefType.addConst(); 15103 } 15104 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 15105 } 15106 15107 if (ByRef) 15108 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15109 else 15110 CaptureType = DeclRefType; 15111 15112 Expr *CopyExpr = nullptr; 15113 if (BuildAndDiagnose) { 15114 // The current implementation assumes that all variables are captured 15115 // by references. Since there is no capture by copy, no expression 15116 // evaluation will be needed. 15117 RecordDecl *RD = RSI->TheRecordDecl; 15118 15119 FieldDecl *Field 15120 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 15121 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 15122 nullptr, false, ICIS_NoInit); 15123 Field->setImplicit(true); 15124 Field->setAccess(AS_private); 15125 RD->addDecl(Field); 15126 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 15127 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 15128 15129 CopyExpr = new (S.Context) DeclRefExpr( 15130 S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc); 15131 Var->setReferenced(true); 15132 Var->markUsed(S.Context); 15133 } 15134 15135 // Actually capture the variable. 15136 if (BuildAndDiagnose) 15137 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 15138 SourceLocation(), CaptureType, CopyExpr); 15139 15140 15141 return true; 15142 } 15143 15144 /// Create a field within the lambda class for the variable 15145 /// being captured. 15146 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 15147 QualType FieldType, QualType DeclRefType, 15148 SourceLocation Loc, 15149 bool RefersToCapturedVariable) { 15150 CXXRecordDecl *Lambda = LSI->Lambda; 15151 15152 // Build the non-static data member. 15153 FieldDecl *Field 15154 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 15155 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 15156 nullptr, false, ICIS_NoInit); 15157 // If the variable being captured has an invalid type, mark the lambda class 15158 // as invalid as well. 15159 if (!FieldType->isDependentType()) { 15160 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 15161 Lambda->setInvalidDecl(); 15162 Field->setInvalidDecl(); 15163 } else { 15164 NamedDecl *Def; 15165 FieldType->isIncompleteType(&Def); 15166 if (Def && Def->isInvalidDecl()) { 15167 Lambda->setInvalidDecl(); 15168 Field->setInvalidDecl(); 15169 } 15170 } 15171 } 15172 Field->setImplicit(true); 15173 Field->setAccess(AS_private); 15174 Lambda->addDecl(Field); 15175 } 15176 15177 /// Capture the given variable in the lambda. 15178 static bool captureInLambda(LambdaScopeInfo *LSI, 15179 VarDecl *Var, 15180 SourceLocation Loc, 15181 const bool BuildAndDiagnose, 15182 QualType &CaptureType, 15183 QualType &DeclRefType, 15184 const bool RefersToCapturedVariable, 15185 const Sema::TryCaptureKind Kind, 15186 SourceLocation EllipsisLoc, 15187 const bool IsTopScope, 15188 Sema &S) { 15189 15190 // Determine whether we are capturing by reference or by value. 15191 bool ByRef = false; 15192 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15193 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15194 } else { 15195 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15196 } 15197 15198 // Compute the type of the field that will capture this variable. 15199 if (ByRef) { 15200 // C++11 [expr.prim.lambda]p15: 15201 // An entity is captured by reference if it is implicitly or 15202 // explicitly captured but not captured by copy. It is 15203 // unspecified whether additional unnamed non-static data 15204 // members are declared in the closure type for entities 15205 // captured by reference. 15206 // 15207 // FIXME: It is not clear whether we want to build an lvalue reference 15208 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15209 // to do the former, while EDG does the latter. Core issue 1249 will 15210 // clarify, but for now we follow GCC because it's a more permissive and 15211 // easily defensible position. 15212 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15213 } else { 15214 // C++11 [expr.prim.lambda]p14: 15215 // For each entity captured by copy, an unnamed non-static 15216 // data member is declared in the closure type. The 15217 // declaration order of these members is unspecified. The type 15218 // of such a data member is the type of the corresponding 15219 // captured entity if the entity is not a reference to an 15220 // object, or the referenced type otherwise. [Note: If the 15221 // captured entity is a reference to a function, the 15222 // corresponding data member is also a reference to a 15223 // function. - end note ] 15224 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15225 if (!RefType->getPointeeType()->isFunctionType()) 15226 CaptureType = RefType->getPointeeType(); 15227 } 15228 15229 // Forbid the lambda copy-capture of autoreleasing variables. 15230 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15231 if (BuildAndDiagnose) { 15232 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15233 S.Diag(Var->getLocation(), diag::note_previous_decl) 15234 << Var->getDeclName(); 15235 } 15236 return false; 15237 } 15238 15239 // Make sure that by-copy captures are of a complete and non-abstract type. 15240 if (BuildAndDiagnose) { 15241 if (!CaptureType->isDependentType() && 15242 S.RequireCompleteType(Loc, CaptureType, 15243 diag::err_capture_of_incomplete_type, 15244 Var->getDeclName())) 15245 return false; 15246 15247 if (S.RequireNonAbstractType(Loc, CaptureType, 15248 diag::err_capture_of_abstract_type)) 15249 return false; 15250 } 15251 } 15252 15253 // Capture this variable in the lambda. 15254 if (BuildAndDiagnose) 15255 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15256 RefersToCapturedVariable); 15257 15258 // Compute the type of a reference to this captured variable. 15259 if (ByRef) 15260 DeclRefType = CaptureType.getNonReferenceType(); 15261 else { 15262 // C++ [expr.prim.lambda]p5: 15263 // The closure type for a lambda-expression has a public inline 15264 // function call operator [...]. This function call operator is 15265 // declared const (9.3.1) if and only if the lambda-expression's 15266 // parameter-declaration-clause is not followed by mutable. 15267 DeclRefType = CaptureType.getNonReferenceType(); 15268 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15269 DeclRefType.addConst(); 15270 } 15271 15272 // Add the capture. 15273 if (BuildAndDiagnose) 15274 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15275 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15276 15277 return true; 15278 } 15279 15280 bool Sema::tryCaptureVariable( 15281 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15282 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15283 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15284 // An init-capture is notionally from the context surrounding its 15285 // declaration, but its parent DC is the lambda class. 15286 DeclContext *VarDC = Var->getDeclContext(); 15287 if (Var->isInitCapture()) 15288 VarDC = VarDC->getParent(); 15289 15290 DeclContext *DC = CurContext; 15291 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15292 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15293 // We need to sync up the Declaration Context with the 15294 // FunctionScopeIndexToStopAt 15295 if (FunctionScopeIndexToStopAt) { 15296 unsigned FSIndex = FunctionScopes.size() - 1; 15297 while (FSIndex != MaxFunctionScopesIndex) { 15298 DC = getLambdaAwareParentOfDeclContext(DC); 15299 --FSIndex; 15300 } 15301 } 15302 15303 15304 // If the variable is declared in the current context, there is no need to 15305 // capture it. 15306 if (VarDC == DC) return true; 15307 15308 // Capture global variables if it is required to use private copy of this 15309 // variable. 15310 bool IsGlobal = !Var->hasLocalStorage(); 15311 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15312 return true; 15313 Var = Var->getCanonicalDecl(); 15314 15315 // Walk up the stack to determine whether we can capture the variable, 15316 // performing the "simple" checks that don't depend on type. We stop when 15317 // we've either hit the declared scope of the variable or find an existing 15318 // capture of that variable. We start from the innermost capturing-entity 15319 // (the DC) and ensure that all intervening capturing-entities 15320 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15321 // declcontext can either capture the variable or have already captured 15322 // the variable. 15323 CaptureType = Var->getType(); 15324 DeclRefType = CaptureType.getNonReferenceType(); 15325 bool Nested = false; 15326 bool Explicit = (Kind != TryCapture_Implicit); 15327 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15328 do { 15329 // Only block literals, captured statements, and lambda expressions can 15330 // capture; other scopes don't work. 15331 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15332 ExprLoc, 15333 BuildAndDiagnose, 15334 *this); 15335 // We need to check for the parent *first* because, if we *have* 15336 // private-captured a global variable, we need to recursively capture it in 15337 // intermediate blocks, lambdas, etc. 15338 if (!ParentDC) { 15339 if (IsGlobal) { 15340 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15341 break; 15342 } 15343 return true; 15344 } 15345 15346 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15347 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15348 15349 15350 // Check whether we've already captured it. 15351 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15352 DeclRefType)) { 15353 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15354 break; 15355 } 15356 // If we are instantiating a generic lambda call operator body, 15357 // we do not want to capture new variables. What was captured 15358 // during either a lambdas transformation or initial parsing 15359 // should be used. 15360 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15361 if (BuildAndDiagnose) { 15362 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15363 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15364 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15365 Diag(Var->getLocation(), diag::note_previous_decl) 15366 << Var->getDeclName(); 15367 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15368 } else 15369 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15370 } 15371 return true; 15372 } 15373 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15374 // certain types of variables (unnamed, variably modified types etc.) 15375 // so check for eligibility. 15376 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15377 return true; 15378 15379 // Try to capture variable-length arrays types. 15380 if (Var->getType()->isVariablyModifiedType()) { 15381 // We're going to walk down into the type and look for VLA 15382 // expressions. 15383 QualType QTy = Var->getType(); 15384 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15385 QTy = PVD->getOriginalType(); 15386 captureVariablyModifiedType(Context, QTy, CSI); 15387 } 15388 15389 if (getLangOpts().OpenMP) { 15390 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15391 // OpenMP private variables should not be captured in outer scope, so 15392 // just break here. Similarly, global variables that are captured in a 15393 // target region should not be captured outside the scope of the region. 15394 if (RSI->CapRegionKind == CR_OpenMP) { 15395 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15396 auto IsTargetCap = !IsOpenMPPrivateDecl && 15397 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15398 // When we detect target captures we are looking from inside the 15399 // target region, therefore we need to propagate the capture from the 15400 // enclosing region. Therefore, the capture is not initially nested. 15401 if (IsTargetCap) 15402 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15403 15404 if (IsTargetCap || IsOpenMPPrivateDecl) { 15405 Nested = !IsTargetCap; 15406 DeclRefType = DeclRefType.getUnqualifiedType(); 15407 CaptureType = Context.getLValueReferenceType(DeclRefType); 15408 break; 15409 } 15410 } 15411 } 15412 } 15413 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15414 // No capture-default, and this is not an explicit capture 15415 // so cannot capture this variable. 15416 if (BuildAndDiagnose) { 15417 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15418 Diag(Var->getLocation(), diag::note_previous_decl) 15419 << Var->getDeclName(); 15420 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15421 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15422 diag::note_lambda_decl); 15423 // FIXME: If we error out because an outer lambda can not implicitly 15424 // capture a variable that an inner lambda explicitly captures, we 15425 // should have the inner lambda do the explicit capture - because 15426 // it makes for cleaner diagnostics later. This would purely be done 15427 // so that the diagnostic does not misleadingly claim that a variable 15428 // can not be captured by a lambda implicitly even though it is captured 15429 // explicitly. Suggestion: 15430 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15431 // at the function head 15432 // - cache the StartingDeclContext - this must be a lambda 15433 // - captureInLambda in the innermost lambda the variable. 15434 } 15435 return true; 15436 } 15437 15438 FunctionScopesIndex--; 15439 DC = ParentDC; 15440 Explicit = false; 15441 } while (!VarDC->Equals(DC)); 15442 15443 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15444 // computing the type of the capture at each step, checking type-specific 15445 // requirements, and adding captures if requested. 15446 // If the variable had already been captured previously, we start capturing 15447 // at the lambda nested within that one. 15448 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15449 ++I) { 15450 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15451 15452 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15453 if (!captureInBlock(BSI, Var, ExprLoc, 15454 BuildAndDiagnose, CaptureType, 15455 DeclRefType, Nested, *this)) 15456 return true; 15457 Nested = true; 15458 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15459 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15460 BuildAndDiagnose, CaptureType, 15461 DeclRefType, Nested, *this)) 15462 return true; 15463 Nested = true; 15464 } else { 15465 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15466 if (!captureInLambda(LSI, Var, ExprLoc, 15467 BuildAndDiagnose, CaptureType, 15468 DeclRefType, Nested, Kind, EllipsisLoc, 15469 /*IsTopScope*/I == N - 1, *this)) 15470 return true; 15471 Nested = true; 15472 } 15473 } 15474 return false; 15475 } 15476 15477 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15478 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15479 QualType CaptureType; 15480 QualType DeclRefType; 15481 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15482 /*BuildAndDiagnose=*/true, CaptureType, 15483 DeclRefType, nullptr); 15484 } 15485 15486 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15487 QualType CaptureType; 15488 QualType DeclRefType; 15489 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15490 /*BuildAndDiagnose=*/false, CaptureType, 15491 DeclRefType, nullptr); 15492 } 15493 15494 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15495 QualType CaptureType; 15496 QualType DeclRefType; 15497 15498 // Determine whether we can capture this variable. 15499 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15500 /*BuildAndDiagnose=*/false, CaptureType, 15501 DeclRefType, nullptr)) 15502 return QualType(); 15503 15504 return DeclRefType; 15505 } 15506 15507 15508 15509 // If either the type of the variable or the initializer is dependent, 15510 // return false. Otherwise, determine whether the variable is a constant 15511 // expression. Use this if you need to know if a variable that might or 15512 // might not be dependent is truly a constant expression. 15513 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15514 ASTContext &Context) { 15515 15516 if (Var->getType()->isDependentType()) 15517 return false; 15518 const VarDecl *DefVD = nullptr; 15519 Var->getAnyInitializer(DefVD); 15520 if (!DefVD) 15521 return false; 15522 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15523 Expr *Init = cast<Expr>(Eval->Value); 15524 if (Init->isValueDependent()) 15525 return false; 15526 return IsVariableAConstantExpression(Var, Context); 15527 } 15528 15529 15530 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15531 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15532 // an object that satisfies the requirements for appearing in a 15533 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15534 // is immediately applied." This function handles the lvalue-to-rvalue 15535 // conversion part. 15536 MaybeODRUseExprs.erase(E->IgnoreParens()); 15537 15538 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15539 // to a variable that is a constant expression, and if so, identify it as 15540 // a reference to a variable that does not involve an odr-use of that 15541 // variable. 15542 if (LambdaScopeInfo *LSI = getCurLambda()) { 15543 Expr *SansParensExpr = E->IgnoreParens(); 15544 VarDecl *Var = nullptr; 15545 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15546 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15547 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15548 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15549 15550 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15551 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15552 } 15553 } 15554 15555 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15556 Res = CorrectDelayedTyposInExpr(Res); 15557 15558 if (!Res.isUsable()) 15559 return Res; 15560 15561 // If a constant-expression is a reference to a variable where we delay 15562 // deciding whether it is an odr-use, just assume we will apply the 15563 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15564 // (a non-type template argument), we have special handling anyway. 15565 UpdateMarkingForLValueToRValue(Res.get()); 15566 return Res; 15567 } 15568 15569 void Sema::CleanupVarDeclMarking() { 15570 for (Expr *E : MaybeODRUseExprs) { 15571 VarDecl *Var; 15572 SourceLocation Loc; 15573 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15574 Var = cast<VarDecl>(DRE->getDecl()); 15575 Loc = DRE->getLocation(); 15576 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15577 Var = cast<VarDecl>(ME->getMemberDecl()); 15578 Loc = ME->getMemberLoc(); 15579 } else { 15580 llvm_unreachable("Unexpected expression"); 15581 } 15582 15583 MarkVarDeclODRUsed(Var, Loc, *this, 15584 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15585 } 15586 15587 MaybeODRUseExprs.clear(); 15588 } 15589 15590 15591 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15592 VarDecl *Var, Expr *E) { 15593 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15594 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15595 Var->setReferenced(); 15596 15597 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15598 15599 bool OdrUseContext = isOdrUseContext(SemaRef); 15600 bool UsableInConstantExpr = 15601 Var->isUsableInConstantExpressions(SemaRef.Context); 15602 bool NeedDefinition = 15603 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15604 15605 VarTemplateSpecializationDecl *VarSpec = 15606 dyn_cast<VarTemplateSpecializationDecl>(Var); 15607 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15608 "Can't instantiate a partial template specialization."); 15609 15610 // If this might be a member specialization of a static data member, check 15611 // the specialization is visible. We already did the checks for variable 15612 // template specializations when we created them. 15613 if (NeedDefinition && TSK != TSK_Undeclared && 15614 !isa<VarTemplateSpecializationDecl>(Var)) 15615 SemaRef.checkSpecializationVisibility(Loc, Var); 15616 15617 // Perform implicit instantiation of static data members, static data member 15618 // templates of class templates, and variable template specializations. Delay 15619 // instantiations of variable templates, except for those that could be used 15620 // in a constant expression. 15621 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15622 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15623 // instantiation declaration if a variable is usable in a constant 15624 // expression (among other cases). 15625 bool TryInstantiating = 15626 TSK == TSK_ImplicitInstantiation || 15627 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15628 15629 if (TryInstantiating) { 15630 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15631 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15632 if (FirstInstantiation) { 15633 PointOfInstantiation = Loc; 15634 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15635 } 15636 15637 bool InstantiationDependent = false; 15638 bool IsNonDependent = 15639 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15640 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15641 : true; 15642 15643 // Do not instantiate specializations that are still type-dependent. 15644 if (IsNonDependent) { 15645 if (UsableInConstantExpr) { 15646 // Do not defer instantiations of variables that could be used in a 15647 // constant expression. 15648 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15649 } else if (FirstInstantiation || 15650 isa<VarTemplateSpecializationDecl>(Var)) { 15651 // FIXME: For a specialization of a variable template, we don't 15652 // distinguish between "declaration and type implicitly instantiated" 15653 // and "implicit instantiation of definition requested", so we have 15654 // no direct way to avoid enqueueing the pending instantiation 15655 // multiple times. 15656 SemaRef.PendingInstantiations 15657 .push_back(std::make_pair(Var, PointOfInstantiation)); 15658 } 15659 } 15660 } 15661 } 15662 15663 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15664 // the requirements for appearing in a constant expression (5.19) and, if 15665 // it is an object, the lvalue-to-rvalue conversion (4.1) 15666 // is immediately applied." We check the first part here, and 15667 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15668 // Note that we use the C++11 definition everywhere because nothing in 15669 // C++03 depends on whether we get the C++03 version correct. The second 15670 // part does not apply to references, since they are not objects. 15671 if (OdrUseContext && E && 15672 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15673 // A reference initialized by a constant expression can never be 15674 // odr-used, so simply ignore it. 15675 if (!Var->getType()->isReferenceType() || 15676 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15677 SemaRef.MaybeODRUseExprs.insert(E); 15678 } else if (OdrUseContext) { 15679 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15680 /*MaxFunctionScopeIndex ptr*/ nullptr); 15681 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15682 // If this is a dependent context, we don't need to mark variables as 15683 // odr-used, but we may still need to track them for lambda capture. 15684 // FIXME: Do we also need to do this inside dependent typeid expressions 15685 // (which are modeled as unevaluated at this point)? 15686 const bool RefersToEnclosingScope = 15687 (SemaRef.CurContext != Var->getDeclContext() && 15688 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15689 if (RefersToEnclosingScope) { 15690 LambdaScopeInfo *const LSI = 15691 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15692 if (LSI && (!LSI->CallOperator || 15693 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15694 // If a variable could potentially be odr-used, defer marking it so 15695 // until we finish analyzing the full expression for any 15696 // lvalue-to-rvalue 15697 // or discarded value conversions that would obviate odr-use. 15698 // Add it to the list of potential captures that will be analyzed 15699 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15700 // unless the variable is a reference that was initialized by a constant 15701 // expression (this will never need to be captured or odr-used). 15702 assert(E && "Capture variable should be used in an expression."); 15703 if (!Var->getType()->isReferenceType() || 15704 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15705 LSI->addPotentialCapture(E->IgnoreParens()); 15706 } 15707 } 15708 } 15709 } 15710 15711 /// Mark a variable referenced, and check whether it is odr-used 15712 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15713 /// used directly for normal expressions referring to VarDecl. 15714 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15715 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15716 } 15717 15718 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15719 Decl *D, Expr *E, bool MightBeOdrUse) { 15720 if (SemaRef.isInOpenMPDeclareTargetContext()) 15721 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15722 15723 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15724 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15725 return; 15726 } 15727 15728 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15729 15730 // If this is a call to a method via a cast, also mark the method in the 15731 // derived class used in case codegen can devirtualize the call. 15732 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15733 if (!ME) 15734 return; 15735 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15736 if (!MD) 15737 return; 15738 // Only attempt to devirtualize if this is truly a virtual call. 15739 bool IsVirtualCall = MD->isVirtual() && 15740 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15741 if (!IsVirtualCall) 15742 return; 15743 15744 // If it's possible to devirtualize the call, mark the called function 15745 // referenced. 15746 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15747 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15748 if (DM) 15749 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15750 } 15751 15752 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15753 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15754 // TODO: update this with DR# once a defect report is filed. 15755 // C++11 defect. The address of a pure member should not be an ODR use, even 15756 // if it's a qualified reference. 15757 bool OdrUse = true; 15758 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15759 if (Method->isVirtual() && 15760 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15761 OdrUse = false; 15762 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15763 } 15764 15765 /// Perform reference-marking and odr-use handling for a MemberExpr. 15766 void Sema::MarkMemberReferenced(MemberExpr *E) { 15767 // C++11 [basic.def.odr]p2: 15768 // A non-overloaded function whose name appears as a potentially-evaluated 15769 // expression or a member of a set of candidate functions, if selected by 15770 // overload resolution when referred to from a potentially-evaluated 15771 // expression, is odr-used, unless it is a pure virtual function and its 15772 // name is not explicitly qualified. 15773 bool MightBeOdrUse = true; 15774 if (E->performsVirtualDispatch(getLangOpts())) { 15775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15776 if (Method->isPure()) 15777 MightBeOdrUse = false; 15778 } 15779 SourceLocation Loc = 15780 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15781 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15782 } 15783 15784 /// Perform marking for a reference to an arbitrary declaration. It 15785 /// marks the declaration referenced, and performs odr-use checking for 15786 /// functions and variables. This method should not be used when building a 15787 /// normal expression which refers to a variable. 15788 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15789 bool MightBeOdrUse) { 15790 if (MightBeOdrUse) { 15791 if (auto *VD = dyn_cast<VarDecl>(D)) { 15792 MarkVariableReferenced(Loc, VD); 15793 return; 15794 } 15795 } 15796 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15797 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15798 return; 15799 } 15800 D->setReferenced(); 15801 } 15802 15803 namespace { 15804 // Mark all of the declarations used by a type as referenced. 15805 // FIXME: Not fully implemented yet! We need to have a better understanding 15806 // of when we're entering a context we should not recurse into. 15807 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15808 // TreeTransforms rebuilding the type in a new context. Rather than 15809 // duplicating the TreeTransform logic, we should consider reusing it here. 15810 // Currently that causes problems when rebuilding LambdaExprs. 15811 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15812 Sema &S; 15813 SourceLocation Loc; 15814 15815 public: 15816 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15817 15818 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15819 15820 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15821 }; 15822 } 15823 15824 bool MarkReferencedDecls::TraverseTemplateArgument( 15825 const TemplateArgument &Arg) { 15826 { 15827 // A non-type template argument is a constant-evaluated context. 15828 EnterExpressionEvaluationContext Evaluated( 15829 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15830 if (Arg.getKind() == TemplateArgument::Declaration) { 15831 if (Decl *D = Arg.getAsDecl()) 15832 S.MarkAnyDeclReferenced(Loc, D, true); 15833 } else if (Arg.getKind() == TemplateArgument::Expression) { 15834 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15835 } 15836 } 15837 15838 return Inherited::TraverseTemplateArgument(Arg); 15839 } 15840 15841 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15842 MarkReferencedDecls Marker(*this, Loc); 15843 Marker.TraverseType(T); 15844 } 15845 15846 namespace { 15847 /// Helper class that marks all of the declarations referenced by 15848 /// potentially-evaluated subexpressions as "referenced". 15849 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15850 Sema &S; 15851 bool SkipLocalVariables; 15852 15853 public: 15854 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15855 15856 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15857 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15858 15859 void VisitDeclRefExpr(DeclRefExpr *E) { 15860 // If we were asked not to visit local variables, don't. 15861 if (SkipLocalVariables) { 15862 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15863 if (VD->hasLocalStorage()) 15864 return; 15865 } 15866 15867 S.MarkDeclRefReferenced(E); 15868 } 15869 15870 void VisitMemberExpr(MemberExpr *E) { 15871 S.MarkMemberReferenced(E); 15872 Inherited::VisitMemberExpr(E); 15873 } 15874 15875 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15876 S.MarkFunctionReferenced( 15877 E->getBeginLoc(), 15878 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15879 Visit(E->getSubExpr()); 15880 } 15881 15882 void VisitCXXNewExpr(CXXNewExpr *E) { 15883 if (E->getOperatorNew()) 15884 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15885 if (E->getOperatorDelete()) 15886 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15887 Inherited::VisitCXXNewExpr(E); 15888 } 15889 15890 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15891 if (E->getOperatorDelete()) 15892 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15893 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15894 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15895 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15896 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15897 } 15898 15899 Inherited::VisitCXXDeleteExpr(E); 15900 } 15901 15902 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15903 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15904 Inherited::VisitCXXConstructExpr(E); 15905 } 15906 15907 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15908 Visit(E->getExpr()); 15909 } 15910 15911 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15912 Inherited::VisitImplicitCastExpr(E); 15913 15914 if (E->getCastKind() == CK_LValueToRValue) 15915 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15916 } 15917 }; 15918 } 15919 15920 /// Mark any declarations that appear within this expression or any 15921 /// potentially-evaluated subexpressions as "referenced". 15922 /// 15923 /// \param SkipLocalVariables If true, don't mark local variables as 15924 /// 'referenced'. 15925 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15926 bool SkipLocalVariables) { 15927 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15928 } 15929 15930 /// Emit a diagnostic that describes an effect on the run-time behavior 15931 /// of the program being compiled. 15932 /// 15933 /// This routine emits the given diagnostic when the code currently being 15934 /// type-checked is "potentially evaluated", meaning that there is a 15935 /// possibility that the code will actually be executable. Code in sizeof() 15936 /// expressions, code used only during overload resolution, etc., are not 15937 /// potentially evaluated. This routine will suppress such diagnostics or, 15938 /// in the absolutely nutty case of potentially potentially evaluated 15939 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15940 /// later. 15941 /// 15942 /// This routine should be used for all diagnostics that describe the run-time 15943 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15944 /// Failure to do so will likely result in spurious diagnostics or failures 15945 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15946 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15947 const PartialDiagnostic &PD) { 15948 switch (ExprEvalContexts.back().Context) { 15949 case ExpressionEvaluationContext::Unevaluated: 15950 case ExpressionEvaluationContext::UnevaluatedList: 15951 case ExpressionEvaluationContext::UnevaluatedAbstract: 15952 case ExpressionEvaluationContext::DiscardedStatement: 15953 // The argument will never be evaluated, so don't complain. 15954 break; 15955 15956 case ExpressionEvaluationContext::ConstantEvaluated: 15957 // Relevant diagnostics should be produced by constant evaluation. 15958 break; 15959 15960 case ExpressionEvaluationContext::PotentiallyEvaluated: 15961 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15962 if (Statement && getCurFunctionOrMethodDecl()) { 15963 FunctionScopes.back()->PossiblyUnreachableDiags. 15964 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15965 return true; 15966 } 15967 15968 // The initializer of a constexpr variable or of the first declaration of a 15969 // static data member is not syntactically a constant evaluated constant, 15970 // but nonetheless is always required to be a constant expression, so we 15971 // can skip diagnosing. 15972 // FIXME: Using the mangling context here is a hack. 15973 if (auto *VD = dyn_cast_or_null<VarDecl>( 15974 ExprEvalContexts.back().ManglingContextDecl)) { 15975 if (VD->isConstexpr() || 15976 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15977 break; 15978 // FIXME: For any other kind of variable, we should build a CFG for its 15979 // initializer and check whether the context in question is reachable. 15980 } 15981 15982 Diag(Loc, PD); 15983 return true; 15984 } 15985 15986 return false; 15987 } 15988 15989 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15990 CallExpr *CE, FunctionDecl *FD) { 15991 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15992 return false; 15993 15994 // If we're inside a decltype's expression, don't check for a valid return 15995 // type or construct temporaries until we know whether this is the last call. 15996 if (ExprEvalContexts.back().ExprContext == 15997 ExpressionEvaluationContextRecord::EK_Decltype) { 15998 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15999 return false; 16000 } 16001 16002 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 16003 FunctionDecl *FD; 16004 CallExpr *CE; 16005 16006 public: 16007 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 16008 : FD(FD), CE(CE) { } 16009 16010 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16011 if (!FD) { 16012 S.Diag(Loc, diag::err_call_incomplete_return) 16013 << T << CE->getSourceRange(); 16014 return; 16015 } 16016 16017 S.Diag(Loc, diag::err_call_function_incomplete_return) 16018 << CE->getSourceRange() << FD->getDeclName() << T; 16019 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 16020 << FD->getDeclName(); 16021 } 16022 } Diagnoser(FD, CE); 16023 16024 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 16025 return true; 16026 16027 return false; 16028 } 16029 16030 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 16031 // will prevent this condition from triggering, which is what we want. 16032 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 16033 SourceLocation Loc; 16034 16035 unsigned diagnostic = diag::warn_condition_is_assignment; 16036 bool IsOrAssign = false; 16037 16038 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 16039 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 16040 return; 16041 16042 IsOrAssign = Op->getOpcode() == BO_OrAssign; 16043 16044 // Greylist some idioms by putting them into a warning subcategory. 16045 if (ObjCMessageExpr *ME 16046 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 16047 Selector Sel = ME->getSelector(); 16048 16049 // self = [<foo> init...] 16050 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 16051 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16052 16053 // <foo> = [<bar> nextObject] 16054 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 16055 diagnostic = diag::warn_condition_is_idiomatic_assignment; 16056 } 16057 16058 Loc = Op->getOperatorLoc(); 16059 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 16060 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 16061 return; 16062 16063 IsOrAssign = Op->getOperator() == OO_PipeEqual; 16064 Loc = Op->getOperatorLoc(); 16065 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 16066 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 16067 else { 16068 // Not an assignment. 16069 return; 16070 } 16071 16072 Diag(Loc, diagnostic) << E->getSourceRange(); 16073 16074 SourceLocation Open = E->getBeginLoc(); 16075 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 16076 Diag(Loc, diag::note_condition_assign_silence) 16077 << FixItHint::CreateInsertion(Open, "(") 16078 << FixItHint::CreateInsertion(Close, ")"); 16079 16080 if (IsOrAssign) 16081 Diag(Loc, diag::note_condition_or_assign_to_comparison) 16082 << FixItHint::CreateReplacement(Loc, "!="); 16083 else 16084 Diag(Loc, diag::note_condition_assign_to_comparison) 16085 << FixItHint::CreateReplacement(Loc, "=="); 16086 } 16087 16088 /// Redundant parentheses over an equality comparison can indicate 16089 /// that the user intended an assignment used as condition. 16090 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 16091 // Don't warn if the parens came from a macro. 16092 SourceLocation parenLoc = ParenE->getBeginLoc(); 16093 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 16094 return; 16095 // Don't warn for dependent expressions. 16096 if (ParenE->isTypeDependent()) 16097 return; 16098 16099 Expr *E = ParenE->IgnoreParens(); 16100 16101 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 16102 if (opE->getOpcode() == BO_EQ && 16103 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 16104 == Expr::MLV_Valid) { 16105 SourceLocation Loc = opE->getOperatorLoc(); 16106 16107 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 16108 SourceRange ParenERange = ParenE->getSourceRange(); 16109 Diag(Loc, diag::note_equality_comparison_silence) 16110 << FixItHint::CreateRemoval(ParenERange.getBegin()) 16111 << FixItHint::CreateRemoval(ParenERange.getEnd()); 16112 Diag(Loc, diag::note_equality_comparison_to_assign) 16113 << FixItHint::CreateReplacement(Loc, "="); 16114 } 16115 } 16116 16117 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 16118 bool IsConstexpr) { 16119 DiagnoseAssignmentAsCondition(E); 16120 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 16121 DiagnoseEqualityWithExtraParens(parenE); 16122 16123 ExprResult result = CheckPlaceholderExpr(E); 16124 if (result.isInvalid()) return ExprError(); 16125 E = result.get(); 16126 16127 if (!E->isTypeDependent()) { 16128 if (getLangOpts().CPlusPlus) 16129 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 16130 16131 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 16132 if (ERes.isInvalid()) 16133 return ExprError(); 16134 E = ERes.get(); 16135 16136 QualType T = E->getType(); 16137 if (!T->isScalarType()) { // C99 6.8.4.1p1 16138 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 16139 << T << E->getSourceRange(); 16140 return ExprError(); 16141 } 16142 CheckBoolLikeConversion(E, Loc); 16143 } 16144 16145 return E; 16146 } 16147 16148 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 16149 Expr *SubExpr, ConditionKind CK) { 16150 // Empty conditions are valid in for-statements. 16151 if (!SubExpr) 16152 return ConditionResult(); 16153 16154 ExprResult Cond; 16155 switch (CK) { 16156 case ConditionKind::Boolean: 16157 Cond = CheckBooleanCondition(Loc, SubExpr); 16158 break; 16159 16160 case ConditionKind::ConstexprIf: 16161 Cond = CheckBooleanCondition(Loc, SubExpr, true); 16162 break; 16163 16164 case ConditionKind::Switch: 16165 Cond = CheckSwitchCondition(Loc, SubExpr); 16166 break; 16167 } 16168 if (Cond.isInvalid()) 16169 return ConditionError(); 16170 16171 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 16172 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 16173 if (!FullExpr.get()) 16174 return ConditionError(); 16175 16176 return ConditionResult(*this, nullptr, FullExpr, 16177 CK == ConditionKind::ConstexprIf); 16178 } 16179 16180 namespace { 16181 /// A visitor for rebuilding a call to an __unknown_any expression 16182 /// to have an appropriate type. 16183 struct RebuildUnknownAnyFunction 16184 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 16185 16186 Sema &S; 16187 16188 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 16189 16190 ExprResult VisitStmt(Stmt *S) { 16191 llvm_unreachable("unexpected statement!"); 16192 } 16193 16194 ExprResult VisitExpr(Expr *E) { 16195 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 16196 << E->getSourceRange(); 16197 return ExprError(); 16198 } 16199 16200 /// Rebuild an expression which simply semantically wraps another 16201 /// expression which it shares the type and value kind of. 16202 template <class T> ExprResult rebuildSugarExpr(T *E) { 16203 ExprResult SubResult = Visit(E->getSubExpr()); 16204 if (SubResult.isInvalid()) return ExprError(); 16205 16206 Expr *SubExpr = SubResult.get(); 16207 E->setSubExpr(SubExpr); 16208 E->setType(SubExpr->getType()); 16209 E->setValueKind(SubExpr->getValueKind()); 16210 assert(E->getObjectKind() == OK_Ordinary); 16211 return E; 16212 } 16213 16214 ExprResult VisitParenExpr(ParenExpr *E) { 16215 return rebuildSugarExpr(E); 16216 } 16217 16218 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16219 return rebuildSugarExpr(E); 16220 } 16221 16222 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16223 ExprResult SubResult = Visit(E->getSubExpr()); 16224 if (SubResult.isInvalid()) return ExprError(); 16225 16226 Expr *SubExpr = SubResult.get(); 16227 E->setSubExpr(SubExpr); 16228 E->setType(S.Context.getPointerType(SubExpr->getType())); 16229 assert(E->getValueKind() == VK_RValue); 16230 assert(E->getObjectKind() == OK_Ordinary); 16231 return E; 16232 } 16233 16234 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16235 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16236 16237 E->setType(VD->getType()); 16238 16239 assert(E->getValueKind() == VK_RValue); 16240 if (S.getLangOpts().CPlusPlus && 16241 !(isa<CXXMethodDecl>(VD) && 16242 cast<CXXMethodDecl>(VD)->isInstance())) 16243 E->setValueKind(VK_LValue); 16244 16245 return E; 16246 } 16247 16248 ExprResult VisitMemberExpr(MemberExpr *E) { 16249 return resolveDecl(E, E->getMemberDecl()); 16250 } 16251 16252 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16253 return resolveDecl(E, E->getDecl()); 16254 } 16255 }; 16256 } 16257 16258 /// Given a function expression of unknown-any type, try to rebuild it 16259 /// to have a function type. 16260 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16261 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16262 if (Result.isInvalid()) return ExprError(); 16263 return S.DefaultFunctionArrayConversion(Result.get()); 16264 } 16265 16266 namespace { 16267 /// A visitor for rebuilding an expression of type __unknown_anytype 16268 /// into one which resolves the type directly on the referring 16269 /// expression. Strict preservation of the original source 16270 /// structure is not a goal. 16271 struct RebuildUnknownAnyExpr 16272 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16273 16274 Sema &S; 16275 16276 /// The current destination type. 16277 QualType DestType; 16278 16279 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16280 : S(S), DestType(CastType) {} 16281 16282 ExprResult VisitStmt(Stmt *S) { 16283 llvm_unreachable("unexpected statement!"); 16284 } 16285 16286 ExprResult VisitExpr(Expr *E) { 16287 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16288 << E->getSourceRange(); 16289 return ExprError(); 16290 } 16291 16292 ExprResult VisitCallExpr(CallExpr *E); 16293 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16294 16295 /// Rebuild an expression which simply semantically wraps another 16296 /// expression which it shares the type and value kind of. 16297 template <class T> ExprResult rebuildSugarExpr(T *E) { 16298 ExprResult SubResult = Visit(E->getSubExpr()); 16299 if (SubResult.isInvalid()) return ExprError(); 16300 Expr *SubExpr = SubResult.get(); 16301 E->setSubExpr(SubExpr); 16302 E->setType(SubExpr->getType()); 16303 E->setValueKind(SubExpr->getValueKind()); 16304 assert(E->getObjectKind() == OK_Ordinary); 16305 return E; 16306 } 16307 16308 ExprResult VisitParenExpr(ParenExpr *E) { 16309 return rebuildSugarExpr(E); 16310 } 16311 16312 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16313 return rebuildSugarExpr(E); 16314 } 16315 16316 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16317 const PointerType *Ptr = DestType->getAs<PointerType>(); 16318 if (!Ptr) { 16319 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16320 << E->getSourceRange(); 16321 return ExprError(); 16322 } 16323 16324 if (isa<CallExpr>(E->getSubExpr())) { 16325 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16326 << E->getSourceRange(); 16327 return ExprError(); 16328 } 16329 16330 assert(E->getValueKind() == VK_RValue); 16331 assert(E->getObjectKind() == OK_Ordinary); 16332 E->setType(DestType); 16333 16334 // Build the sub-expression as if it were an object of the pointee type. 16335 DestType = Ptr->getPointeeType(); 16336 ExprResult SubResult = Visit(E->getSubExpr()); 16337 if (SubResult.isInvalid()) return ExprError(); 16338 E->setSubExpr(SubResult.get()); 16339 return E; 16340 } 16341 16342 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16343 16344 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16345 16346 ExprResult VisitMemberExpr(MemberExpr *E) { 16347 return resolveDecl(E, E->getMemberDecl()); 16348 } 16349 16350 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16351 return resolveDecl(E, E->getDecl()); 16352 } 16353 }; 16354 } 16355 16356 /// Rebuilds a call expression which yielded __unknown_anytype. 16357 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16358 Expr *CalleeExpr = E->getCallee(); 16359 16360 enum FnKind { 16361 FK_MemberFunction, 16362 FK_FunctionPointer, 16363 FK_BlockPointer 16364 }; 16365 16366 FnKind Kind; 16367 QualType CalleeType = CalleeExpr->getType(); 16368 if (CalleeType == S.Context.BoundMemberTy) { 16369 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16370 Kind = FK_MemberFunction; 16371 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16372 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16373 CalleeType = Ptr->getPointeeType(); 16374 Kind = FK_FunctionPointer; 16375 } else { 16376 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16377 Kind = FK_BlockPointer; 16378 } 16379 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16380 16381 // Verify that this is a legal result type of a function. 16382 if (DestType->isArrayType() || DestType->isFunctionType()) { 16383 unsigned diagID = diag::err_func_returning_array_function; 16384 if (Kind == FK_BlockPointer) 16385 diagID = diag::err_block_returning_array_function; 16386 16387 S.Diag(E->getExprLoc(), diagID) 16388 << DestType->isFunctionType() << DestType; 16389 return ExprError(); 16390 } 16391 16392 // Otherwise, go ahead and set DestType as the call's result. 16393 E->setType(DestType.getNonLValueExprType(S.Context)); 16394 E->setValueKind(Expr::getValueKindForType(DestType)); 16395 assert(E->getObjectKind() == OK_Ordinary); 16396 16397 // Rebuild the function type, replacing the result type with DestType. 16398 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16399 if (Proto) { 16400 // __unknown_anytype(...) is a special case used by the debugger when 16401 // it has no idea what a function's signature is. 16402 // 16403 // We want to build this call essentially under the K&R 16404 // unprototyped rules, but making a FunctionNoProtoType in C++ 16405 // would foul up all sorts of assumptions. However, we cannot 16406 // simply pass all arguments as variadic arguments, nor can we 16407 // portably just call the function under a non-variadic type; see 16408 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16409 // However, it turns out that in practice it is generally safe to 16410 // call a function declared as "A foo(B,C,D);" under the prototype 16411 // "A foo(B,C,D,...);". The only known exception is with the 16412 // Windows ABI, where any variadic function is implicitly cdecl 16413 // regardless of its normal CC. Therefore we change the parameter 16414 // types to match the types of the arguments. 16415 // 16416 // This is a hack, but it is far superior to moving the 16417 // corresponding target-specific code from IR-gen to Sema/AST. 16418 16419 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16420 SmallVector<QualType, 8> ArgTypes; 16421 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16422 ArgTypes.reserve(E->getNumArgs()); 16423 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16424 Expr *Arg = E->getArg(i); 16425 QualType ArgType = Arg->getType(); 16426 if (E->isLValue()) { 16427 ArgType = S.Context.getLValueReferenceType(ArgType); 16428 } else if (E->isXValue()) { 16429 ArgType = S.Context.getRValueReferenceType(ArgType); 16430 } 16431 ArgTypes.push_back(ArgType); 16432 } 16433 ParamTypes = ArgTypes; 16434 } 16435 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16436 Proto->getExtProtoInfo()); 16437 } else { 16438 DestType = S.Context.getFunctionNoProtoType(DestType, 16439 FnType->getExtInfo()); 16440 } 16441 16442 // Rebuild the appropriate pointer-to-function type. 16443 switch (Kind) { 16444 case FK_MemberFunction: 16445 // Nothing to do. 16446 break; 16447 16448 case FK_FunctionPointer: 16449 DestType = S.Context.getPointerType(DestType); 16450 break; 16451 16452 case FK_BlockPointer: 16453 DestType = S.Context.getBlockPointerType(DestType); 16454 break; 16455 } 16456 16457 // Finally, we can recurse. 16458 ExprResult CalleeResult = Visit(CalleeExpr); 16459 if (!CalleeResult.isUsable()) return ExprError(); 16460 E->setCallee(CalleeResult.get()); 16461 16462 // Bind a temporary if necessary. 16463 return S.MaybeBindToTemporary(E); 16464 } 16465 16466 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16467 // Verify that this is a legal result type of a call. 16468 if (DestType->isArrayType() || DestType->isFunctionType()) { 16469 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16470 << DestType->isFunctionType() << DestType; 16471 return ExprError(); 16472 } 16473 16474 // Rewrite the method result type if available. 16475 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16476 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16477 Method->setReturnType(DestType); 16478 } 16479 16480 // Change the type of the message. 16481 E->setType(DestType.getNonReferenceType()); 16482 E->setValueKind(Expr::getValueKindForType(DestType)); 16483 16484 return S.MaybeBindToTemporary(E); 16485 } 16486 16487 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16488 // The only case we should ever see here is a function-to-pointer decay. 16489 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16490 assert(E->getValueKind() == VK_RValue); 16491 assert(E->getObjectKind() == OK_Ordinary); 16492 16493 E->setType(DestType); 16494 16495 // Rebuild the sub-expression as the pointee (function) type. 16496 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16497 16498 ExprResult Result = Visit(E->getSubExpr()); 16499 if (!Result.isUsable()) return ExprError(); 16500 16501 E->setSubExpr(Result.get()); 16502 return E; 16503 } else if (E->getCastKind() == CK_LValueToRValue) { 16504 assert(E->getValueKind() == VK_RValue); 16505 assert(E->getObjectKind() == OK_Ordinary); 16506 16507 assert(isa<BlockPointerType>(E->getType())); 16508 16509 E->setType(DestType); 16510 16511 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16512 DestType = S.Context.getLValueReferenceType(DestType); 16513 16514 ExprResult Result = Visit(E->getSubExpr()); 16515 if (!Result.isUsable()) return ExprError(); 16516 16517 E->setSubExpr(Result.get()); 16518 return E; 16519 } else { 16520 llvm_unreachable("Unhandled cast type!"); 16521 } 16522 } 16523 16524 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16525 ExprValueKind ValueKind = VK_LValue; 16526 QualType Type = DestType; 16527 16528 // We know how to make this work for certain kinds of decls: 16529 16530 // - functions 16531 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16532 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16533 DestType = Ptr->getPointeeType(); 16534 ExprResult Result = resolveDecl(E, VD); 16535 if (Result.isInvalid()) return ExprError(); 16536 return S.ImpCastExprToType(Result.get(), Type, 16537 CK_FunctionToPointerDecay, VK_RValue); 16538 } 16539 16540 if (!Type->isFunctionType()) { 16541 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16542 << VD << E->getSourceRange(); 16543 return ExprError(); 16544 } 16545 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16546 // We must match the FunctionDecl's type to the hack introduced in 16547 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16548 // type. See the lengthy commentary in that routine. 16549 QualType FDT = FD->getType(); 16550 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16551 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16552 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16553 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16554 SourceLocation Loc = FD->getLocation(); 16555 FunctionDecl *NewFD = FunctionDecl::Create(S.Context, 16556 FD->getDeclContext(), 16557 Loc, Loc, FD->getNameInfo().getName(), 16558 DestType, FD->getTypeSourceInfo(), 16559 SC_None, false/*isInlineSpecified*/, 16560 FD->hasPrototype(), 16561 false/*isConstexprSpecified*/); 16562 16563 if (FD->getQualifier()) 16564 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16565 16566 SmallVector<ParmVarDecl*, 16> Params; 16567 for (const auto &AI : FT->param_types()) { 16568 ParmVarDecl *Param = 16569 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16570 Param->setScopeInfo(0, Params.size()); 16571 Params.push_back(Param); 16572 } 16573 NewFD->setParams(Params); 16574 DRE->setDecl(NewFD); 16575 VD = DRE->getDecl(); 16576 } 16577 } 16578 16579 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16580 if (MD->isInstance()) { 16581 ValueKind = VK_RValue; 16582 Type = S.Context.BoundMemberTy; 16583 } 16584 16585 // Function references aren't l-values in C. 16586 if (!S.getLangOpts().CPlusPlus) 16587 ValueKind = VK_RValue; 16588 16589 // - variables 16590 } else if (isa<VarDecl>(VD)) { 16591 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16592 Type = RefTy->getPointeeType(); 16593 } else if (Type->isFunctionType()) { 16594 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16595 << VD << E->getSourceRange(); 16596 return ExprError(); 16597 } 16598 16599 // - nothing else 16600 } else { 16601 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16602 << VD << E->getSourceRange(); 16603 return ExprError(); 16604 } 16605 16606 // Modifying the declaration like this is friendly to IR-gen but 16607 // also really dangerous. 16608 VD->setType(DestType); 16609 E->setType(Type); 16610 E->setValueKind(ValueKind); 16611 return E; 16612 } 16613 16614 /// Check a cast of an unknown-any type. We intentionally only 16615 /// trigger this for C-style casts. 16616 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16617 Expr *CastExpr, CastKind &CastKind, 16618 ExprValueKind &VK, CXXCastPath &Path) { 16619 // The type we're casting to must be either void or complete. 16620 if (!CastType->isVoidType() && 16621 RequireCompleteType(TypeRange.getBegin(), CastType, 16622 diag::err_typecheck_cast_to_incomplete)) 16623 return ExprError(); 16624 16625 // Rewrite the casted expression from scratch. 16626 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16627 if (!result.isUsable()) return ExprError(); 16628 16629 CastExpr = result.get(); 16630 VK = CastExpr->getValueKind(); 16631 CastKind = CK_NoOp; 16632 16633 return CastExpr; 16634 } 16635 16636 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16637 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16638 } 16639 16640 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16641 Expr *arg, QualType ¶mType) { 16642 // If the syntactic form of the argument is not an explicit cast of 16643 // any sort, just do default argument promotion. 16644 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16645 if (!castArg) { 16646 ExprResult result = DefaultArgumentPromotion(arg); 16647 if (result.isInvalid()) return ExprError(); 16648 paramType = result.get()->getType(); 16649 return result; 16650 } 16651 16652 // Otherwise, use the type that was written in the explicit cast. 16653 assert(!arg->hasPlaceholderType()); 16654 paramType = castArg->getTypeAsWritten(); 16655 16656 // Copy-initialize a parameter of that type. 16657 InitializedEntity entity = 16658 InitializedEntity::InitializeParameter(Context, paramType, 16659 /*consumed*/ false); 16660 return PerformCopyInitialization(entity, callLoc, arg); 16661 } 16662 16663 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16664 Expr *orig = E; 16665 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16666 while (true) { 16667 E = E->IgnoreParenImpCasts(); 16668 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16669 E = call->getCallee(); 16670 diagID = diag::err_uncasted_call_of_unknown_any; 16671 } else { 16672 break; 16673 } 16674 } 16675 16676 SourceLocation loc; 16677 NamedDecl *d; 16678 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16679 loc = ref->getLocation(); 16680 d = ref->getDecl(); 16681 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16682 loc = mem->getMemberLoc(); 16683 d = mem->getMemberDecl(); 16684 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16685 diagID = diag::err_uncasted_call_of_unknown_any; 16686 loc = msg->getSelectorStartLoc(); 16687 d = msg->getMethodDecl(); 16688 if (!d) { 16689 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16690 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16691 << orig->getSourceRange(); 16692 return ExprError(); 16693 } 16694 } else { 16695 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16696 << E->getSourceRange(); 16697 return ExprError(); 16698 } 16699 16700 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16701 16702 // Never recoverable. 16703 return ExprError(); 16704 } 16705 16706 /// Check for operands with placeholder types and complain if found. 16707 /// Returns ExprError() if there was an error and no recovery was possible. 16708 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16709 if (!getLangOpts().CPlusPlus) { 16710 // C cannot handle TypoExpr nodes on either side of a binop because it 16711 // doesn't handle dependent types properly, so make sure any TypoExprs have 16712 // been dealt with before checking the operands. 16713 ExprResult Result = CorrectDelayedTyposInExpr(E); 16714 if (!Result.isUsable()) return ExprError(); 16715 E = Result.get(); 16716 } 16717 16718 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16719 if (!placeholderType) return E; 16720 16721 switch (placeholderType->getKind()) { 16722 16723 // Overloaded expressions. 16724 case BuiltinType::Overload: { 16725 // Try to resolve a single function template specialization. 16726 // This is obligatory. 16727 ExprResult Result = E; 16728 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16729 return Result; 16730 16731 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16732 // leaves Result unchanged on failure. 16733 Result = E; 16734 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16735 return Result; 16736 16737 // If that failed, try to recover with a call. 16738 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16739 /*complain*/ true); 16740 return Result; 16741 } 16742 16743 // Bound member functions. 16744 case BuiltinType::BoundMember: { 16745 ExprResult result = E; 16746 const Expr *BME = E->IgnoreParens(); 16747 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16748 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16749 if (isa<CXXPseudoDestructorExpr>(BME)) { 16750 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16751 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16752 if (ME->getMemberNameInfo().getName().getNameKind() == 16753 DeclarationName::CXXDestructorName) 16754 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16755 } 16756 tryToRecoverWithCall(result, PD, 16757 /*complain*/ true); 16758 return result; 16759 } 16760 16761 // ARC unbridged casts. 16762 case BuiltinType::ARCUnbridgedCast: { 16763 Expr *realCast = stripARCUnbridgedCast(E); 16764 diagnoseARCUnbridgedCast(realCast); 16765 return realCast; 16766 } 16767 16768 // Expressions of unknown type. 16769 case BuiltinType::UnknownAny: 16770 return diagnoseUnknownAnyExpr(*this, E); 16771 16772 // Pseudo-objects. 16773 case BuiltinType::PseudoObject: 16774 return checkPseudoObjectRValue(E); 16775 16776 case BuiltinType::BuiltinFn: { 16777 // Accept __noop without parens by implicitly converting it to a call expr. 16778 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16779 if (DRE) { 16780 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16781 if (FD->getBuiltinID() == Builtin::BI__noop) { 16782 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16783 CK_BuiltinFnToFnPtr) 16784 .get(); 16785 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 16786 VK_RValue, SourceLocation()); 16787 } 16788 } 16789 16790 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16791 return ExprError(); 16792 } 16793 16794 // Expressions of unknown type. 16795 case BuiltinType::OMPArraySection: 16796 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16797 return ExprError(); 16798 16799 // Everything else should be impossible. 16800 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16801 case BuiltinType::Id: 16802 #include "clang/Basic/OpenCLImageTypes.def" 16803 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16804 case BuiltinType::Id: 16805 #include "clang/Basic/OpenCLExtensionTypes.def" 16806 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16807 #define PLACEHOLDER_TYPE(Id, SingletonId) 16808 #include "clang/AST/BuiltinTypes.def" 16809 break; 16810 } 16811 16812 llvm_unreachable("invalid placeholder type!"); 16813 } 16814 16815 bool Sema::CheckCaseExpression(Expr *E) { 16816 if (E->isTypeDependent()) 16817 return true; 16818 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16819 return E->getType()->isIntegralOrEnumerationType(); 16820 return false; 16821 } 16822 16823 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16824 ExprResult 16825 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16826 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16827 "Unknown Objective-C Boolean value!"); 16828 QualType BoolT = Context.ObjCBuiltinBoolTy; 16829 if (!Context.getBOOLDecl()) { 16830 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16831 Sema::LookupOrdinaryName); 16832 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16833 NamedDecl *ND = Result.getFoundDecl(); 16834 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16835 Context.setBOOLDecl(TD); 16836 } 16837 } 16838 if (Context.getBOOLDecl()) 16839 BoolT = Context.getBOOLType(); 16840 return new (Context) 16841 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16842 } 16843 16844 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16845 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16846 SourceLocation RParen) { 16847 16848 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16849 16850 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16851 [&](const AvailabilitySpec &Spec) { 16852 return Spec.getPlatform() == Platform; 16853 }); 16854 16855 VersionTuple Version; 16856 if (Spec != AvailSpecs.end()) 16857 Version = Spec->getVersion(); 16858 16859 // The use of `@available` in the enclosing function should be analyzed to 16860 // warn when it's used inappropriately (i.e. not if(@available)). 16861 if (getCurFunctionOrMethodDecl()) 16862 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16863 else if (getCurBlock() || getCurLambda()) 16864 getCurFunction()->HasPotentialAvailabilityViolations = true; 16865 16866 return new (Context) 16867 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16868 } 16869