1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ExprOpenMP.h" 26 #include "clang/AST/RecursiveASTVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/Builtins.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 && Decl->isDeleted()); 102 103 if (Decl->isDefaulted()) { 104 // If the method was explicitly defaulted, point at that declaration. 105 if (!Decl->isImplicit()) 106 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 107 108 // Try to diagnose why this special member function was implicitly 109 // deleted. This might fail, if that reason no longer applies. 110 DiagnoseDeletedDefaultedFunction(Decl); 111 return; 112 } 113 114 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 115 if (Ctor && Ctor->isInheritingConstructor()) 116 return NoteDeletedInheritingConstructor(Ctor); 117 118 Diag(Decl->getLocation(), diag::note_availability_specified_here) 119 << Decl << 1; 120 } 121 122 /// Determine whether a FunctionDecl was ever declared with an 123 /// explicit storage class. 124 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 125 for (auto I : D->redecls()) { 126 if (I->getStorageClass() != SC_None) 127 return true; 128 } 129 return false; 130 } 131 132 /// Check whether we're in an extern inline function and referring to a 133 /// variable or function with internal linkage (C11 6.7.4p3). 134 /// 135 /// This is only a warning because we used to silently accept this code, but 136 /// in many cases it will not behave correctly. This is not enabled in C++ mode 137 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 138 /// and so while there may still be user mistakes, most of the time we can't 139 /// prove that there are errors. 140 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 141 const NamedDecl *D, 142 SourceLocation Loc) { 143 // This is disabled under C++; there are too many ways for this to fire in 144 // contexts where the warning is a false positive, or where it is technically 145 // correct but benign. 146 if (S.getLangOpts().CPlusPlus) 147 return; 148 149 // Check if this is an inlined function or method. 150 FunctionDecl *Current = S.getCurFunctionDecl(); 151 if (!Current) 152 return; 153 if (!Current->isInlined()) 154 return; 155 if (!Current->isExternallyVisible()) 156 return; 157 158 // Check if the decl has internal linkage. 159 if (D->getFormalLinkage() != InternalLinkage) 160 return; 161 162 // Downgrade from ExtWarn to Extension if 163 // (1) the supposedly external inline function is in the main file, 164 // and probably won't be included anywhere else. 165 // (2) the thing we're referencing is a pure function. 166 // (3) the thing we're referencing is another inline function. 167 // This last can give us false negatives, but it's better than warning on 168 // wrappers for simple C library functions. 169 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 170 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 171 if (!DowngradeWarning && UsedFn) 172 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 173 174 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 175 : diag::ext_internal_in_extern_inline) 176 << /*IsVar=*/!UsedFn << D; 177 178 S.MaybeSuggestAddingStaticToDecl(Current); 179 180 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 181 << D; 182 } 183 184 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 185 const FunctionDecl *First = Cur->getFirstDecl(); 186 187 // Suggest "static" on the function, if possible. 188 if (!hasAnyExplicitStorageClass(First)) { 189 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 190 Diag(DeclBegin, diag::note_convert_inline_to_static) 191 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 192 } 193 } 194 195 /// Determine whether the use of this declaration is valid, and 196 /// emit any corresponding diagnostics. 197 /// 198 /// This routine diagnoses various problems with referencing 199 /// declarations that can occur when using a declaration. For example, 200 /// it might warn if a deprecated or unavailable declaration is being 201 /// used, or produce an error (and return true) if a C++0x deleted 202 /// function is being used. 203 /// 204 /// \returns true if there was an error (this declaration cannot be 205 /// referenced), false otherwise. 206 /// 207 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 208 const ObjCInterfaceDecl *UnknownObjCClass, 209 bool ObjCPropertyAccess, 210 bool AvoidPartialAvailabilityChecks, 211 ObjCInterfaceDecl *ClassReceiver) { 212 SourceLocation Loc = Locs.front(); 213 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 214 // If there were any diagnostics suppressed by template argument deduction, 215 // emit them now. 216 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 217 if (Pos != SuppressedDiagnostics.end()) { 218 for (const PartialDiagnosticAt &Suppressed : Pos->second) 219 Diag(Suppressed.first, Suppressed.second); 220 221 // Clear out the list of suppressed diagnostics, so that we don't emit 222 // them again for this specialization. However, we don't obsolete this 223 // entry from the table, because we want to avoid ever emitting these 224 // diagnostics again. 225 Pos->second.clear(); 226 } 227 228 // C++ [basic.start.main]p3: 229 // The function 'main' shall not be used within a program. 230 if (cast<FunctionDecl>(D)->isMain()) 231 Diag(Loc, diag::ext_main_used); 232 233 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 234 } 235 236 // See if this is an auto-typed variable whose initializer we are parsing. 237 if (ParsingInitForAutoVars.count(D)) { 238 if (isa<BindingDecl>(D)) { 239 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 240 << D->getDeclName(); 241 } else { 242 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 243 << D->getDeclName() << cast<VarDecl>(D)->getType(); 244 } 245 return true; 246 } 247 248 // See if this is a deleted function. 249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 250 if (FD->isDeleted()) { 251 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 252 if (Ctor && Ctor->isInheritingConstructor()) 253 Diag(Loc, diag::err_deleted_inherited_ctor_use) 254 << Ctor->getParent() 255 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 256 else 257 Diag(Loc, diag::err_deleted_function_use); 258 NoteDeletedFunction(FD); 259 return true; 260 } 261 262 // If the function has a deduced return type, and we can't deduce it, 263 // then we can't use it either. 264 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 265 DeduceReturnType(FD, Loc)) 266 return true; 267 268 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 269 return true; 270 } 271 272 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 273 // Lambdas are only default-constructible or assignable in C++2a onwards. 274 if (MD->getParent()->isLambda() && 275 ((isa<CXXConstructorDecl>(MD) && 276 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 277 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 278 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 279 << !isa<CXXConstructorDecl>(MD); 280 } 281 } 282 283 auto getReferencedObjCProp = [](const NamedDecl *D) -> 284 const ObjCPropertyDecl * { 285 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 286 return MD->findPropertyDecl(); 287 return nullptr; 288 }; 289 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 290 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 291 return true; 292 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 293 return true; 294 } 295 296 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 297 // Only the variables omp_in and omp_out are allowed in the combiner. 298 // Only the variables omp_priv and omp_orig are allowed in the 299 // initializer-clause. 300 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 301 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 302 isa<VarDecl>(D)) { 303 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 304 << getCurFunction()->HasOMPDeclareReductionCombiner; 305 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 306 return true; 307 } 308 309 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 310 // List-items in map clauses on this construct may only refer to the declared 311 // variable var and entities that could be referenced by a procedure defined 312 // at the same location 313 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 314 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 315 isa<VarDecl>(D)) { 316 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 317 << DMD->getVarName().getAsString(); 318 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 319 return true; 320 } 321 322 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 323 AvoidPartialAvailabilityChecks, ClassReceiver); 324 325 DiagnoseUnusedOfDecl(*this, D, Loc); 326 327 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 328 329 return false; 330 } 331 332 /// DiagnoseSentinelCalls - This routine checks whether a call or 333 /// message-send is to a declaration with the sentinel attribute, and 334 /// if so, it checks that the requirements of the sentinel are 335 /// satisfied. 336 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 337 ArrayRef<Expr *> Args) { 338 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 339 if (!attr) 340 return; 341 342 // The number of formal parameters of the declaration. 343 unsigned numFormalParams; 344 345 // The kind of declaration. This is also an index into a %select in 346 // the diagnostic. 347 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 348 349 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 350 numFormalParams = MD->param_size(); 351 calleeType = CT_Method; 352 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 353 numFormalParams = FD->param_size(); 354 calleeType = CT_Function; 355 } else if (isa<VarDecl>(D)) { 356 QualType type = cast<ValueDecl>(D)->getType(); 357 const FunctionType *fn = nullptr; 358 if (const PointerType *ptr = type->getAs<PointerType>()) { 359 fn = ptr->getPointeeType()->getAs<FunctionType>(); 360 if (!fn) return; 361 calleeType = CT_Function; 362 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 363 fn = ptr->getPointeeType()->castAs<FunctionType>(); 364 calleeType = CT_Block; 365 } else { 366 return; 367 } 368 369 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 370 numFormalParams = proto->getNumParams(); 371 } else { 372 numFormalParams = 0; 373 } 374 } else { 375 return; 376 } 377 378 // "nullPos" is the number of formal parameters at the end which 379 // effectively count as part of the variadic arguments. This is 380 // useful if you would prefer to not have *any* formal parameters, 381 // but the language forces you to have at least one. 382 unsigned nullPos = attr->getNullPos(); 383 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 384 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 385 386 // The number of arguments which should follow the sentinel. 387 unsigned numArgsAfterSentinel = attr->getSentinel(); 388 389 // If there aren't enough arguments for all the formal parameters, 390 // the sentinel, and the args after the sentinel, complain. 391 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 392 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 393 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 394 return; 395 } 396 397 // Otherwise, find the sentinel expression. 398 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 399 if (!sentinelExpr) return; 400 if (sentinelExpr->isValueDependent()) return; 401 if (Context.isSentinelNullExpr(sentinelExpr)) return; 402 403 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 404 // or 'NULL' if those are actually defined in the context. Only use 405 // 'nil' for ObjC methods, where it's much more likely that the 406 // variadic arguments form a list of object pointers. 407 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 408 std::string NullValue; 409 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 410 NullValue = "nil"; 411 else if (getLangOpts().CPlusPlus11) 412 NullValue = "nullptr"; 413 else if (PP.isMacroDefined("NULL")) 414 NullValue = "NULL"; 415 else 416 NullValue = "(void*) 0"; 417 418 if (MissingNilLoc.isInvalid()) 419 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 420 else 421 Diag(MissingNilLoc, diag::warn_missing_sentinel) 422 << int(calleeType) 423 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 424 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 425 } 426 427 SourceRange Sema::getExprRange(Expr *E) const { 428 return E ? E->getSourceRange() : SourceRange(); 429 } 430 431 //===----------------------------------------------------------------------===// 432 // Standard Promotions and Conversions 433 //===----------------------------------------------------------------------===// 434 435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 437 // Handle any placeholder expressions which made it here. 438 if (E->getType()->isPlaceholderType()) { 439 ExprResult result = CheckPlaceholderExpr(E); 440 if (result.isInvalid()) return ExprError(); 441 E = result.get(); 442 } 443 444 QualType Ty = E->getType(); 445 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 446 447 if (Ty->isFunctionType()) { 448 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 449 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 450 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 451 return ExprError(); 452 453 E = ImpCastExprToType(E, Context.getPointerType(Ty), 454 CK_FunctionToPointerDecay).get(); 455 } else if (Ty->isArrayType()) { 456 // In C90 mode, arrays only promote to pointers if the array expression is 457 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 458 // type 'array of type' is converted to an expression that has type 'pointer 459 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 460 // that has type 'array of type' ...". The relevant change is "an lvalue" 461 // (C90) to "an expression" (C99). 462 // 463 // C++ 4.2p1: 464 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 465 // T" can be converted to an rvalue of type "pointer to T". 466 // 467 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 468 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 469 CK_ArrayToPointerDecay).get(); 470 } 471 return E; 472 } 473 474 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 475 // Check to see if we are dereferencing a null pointer. If so, 476 // and if not volatile-qualified, this is undefined behavior that the 477 // optimizer will delete, so warn about it. People sometimes try to use this 478 // to get a deterministic trap and are surprised by clang's behavior. This 479 // only handles the pattern "*null", which is a very syntactic check. 480 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 481 if (UO && UO->getOpcode() == UO_Deref && 482 UO->getSubExpr()->getType()->isPointerType()) { 483 const LangAS AS = 484 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 485 if ((!isTargetAddressSpace(AS) || 486 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 487 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 488 S.Context, Expr::NPC_ValueDependentIsNotNull) && 489 !UO->getType().isVolatileQualified()) { 490 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 491 S.PDiag(diag::warn_indirection_through_null) 492 << UO->getSubExpr()->getSourceRange()); 493 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 494 S.PDiag(diag::note_indirection_through_null)); 495 } 496 } 497 } 498 499 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 500 SourceLocation AssignLoc, 501 const Expr* RHS) { 502 const ObjCIvarDecl *IV = OIRE->getDecl(); 503 if (!IV) 504 return; 505 506 DeclarationName MemberName = IV->getDeclName(); 507 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 508 if (!Member || !Member->isStr("isa")) 509 return; 510 511 const Expr *Base = OIRE->getBase(); 512 QualType BaseType = Base->getType(); 513 if (OIRE->isArrow()) 514 BaseType = BaseType->getPointeeType(); 515 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 516 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 517 ObjCInterfaceDecl *ClassDeclared = nullptr; 518 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 519 if (!ClassDeclared->getSuperClass() 520 && (*ClassDeclared->ivar_begin()) == IV) { 521 if (RHS) { 522 NamedDecl *ObjectSetClass = 523 S.LookupSingleName(S.TUScope, 524 &S.Context.Idents.get("object_setClass"), 525 SourceLocation(), S.LookupOrdinaryName); 526 if (ObjectSetClass) { 527 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 528 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 529 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 530 "object_setClass(") 531 << FixItHint::CreateReplacement( 532 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 533 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 534 } 535 else 536 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 537 } else { 538 NamedDecl *ObjectGetClass = 539 S.LookupSingleName(S.TUScope, 540 &S.Context.Idents.get("object_getClass"), 541 SourceLocation(), S.LookupOrdinaryName); 542 if (ObjectGetClass) 543 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 544 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 545 "object_getClass(") 546 << FixItHint::CreateReplacement( 547 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 548 else 549 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 550 } 551 S.Diag(IV->getLocation(), diag::note_ivar_decl); 552 } 553 } 554 } 555 556 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 557 // Handle any placeholder expressions which made it here. 558 if (E->getType()->isPlaceholderType()) { 559 ExprResult result = CheckPlaceholderExpr(E); 560 if (result.isInvalid()) return ExprError(); 561 E = result.get(); 562 } 563 564 // C++ [conv.lval]p1: 565 // A glvalue of a non-function, non-array type T can be 566 // converted to a prvalue. 567 if (!E->isGLValue()) return E; 568 569 QualType T = E->getType(); 570 assert(!T.isNull() && "r-value conversion on typeless expression?"); 571 572 // We don't want to throw lvalue-to-rvalue casts on top of 573 // expressions of certain types in C++. 574 if (getLangOpts().CPlusPlus && 575 (E->getType() == Context.OverloadTy || 576 T->isDependentType() || 577 T->isRecordType())) 578 return E; 579 580 // The C standard is actually really unclear on this point, and 581 // DR106 tells us what the result should be but not why. It's 582 // generally best to say that void types just doesn't undergo 583 // lvalue-to-rvalue at all. Note that expressions of unqualified 584 // 'void' type are never l-values, but qualified void can be. 585 if (T->isVoidType()) 586 return E; 587 588 // OpenCL usually rejects direct accesses to values of 'half' type. 589 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 590 T->isHalfType()) { 591 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 592 << 0 << T; 593 return ExprError(); 594 } 595 596 CheckForNullPointerDereference(*this, E); 597 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 598 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 599 &Context.Idents.get("object_getClass"), 600 SourceLocation(), LookupOrdinaryName); 601 if (ObjectGetClass) 602 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 603 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 604 << FixItHint::CreateReplacement( 605 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 606 else 607 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 608 } 609 else if (const ObjCIvarRefExpr *OIRE = 610 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 611 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 612 613 // C++ [conv.lval]p1: 614 // [...] If T is a non-class type, the type of the prvalue is the 615 // cv-unqualified version of T. Otherwise, the type of the 616 // rvalue is T. 617 // 618 // C99 6.3.2.1p2: 619 // If the lvalue has qualified type, the value has the unqualified 620 // version of the type of the lvalue; otherwise, the value has the 621 // type of the lvalue. 622 if (T.hasQualifiers()) 623 T = T.getUnqualifiedType(); 624 625 // Under the MS ABI, lock down the inheritance model now. 626 if (T->isMemberPointerType() && 627 Context.getTargetInfo().getCXXABI().isMicrosoft()) 628 (void)isCompleteType(E->getExprLoc(), T); 629 630 ExprResult Res = CheckLValueToRValueConversionOperand(E); 631 if (Res.isInvalid()) 632 return Res; 633 E = Res.get(); 634 635 // Loading a __weak object implicitly retains the value, so we need a cleanup to 636 // balance that. 637 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 638 Cleanup.setExprNeedsCleanups(true); 639 640 // C++ [conv.lval]p3: 641 // If T is cv std::nullptr_t, the result is a null pointer constant. 642 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 643 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 644 645 // C11 6.3.2.1p2: 646 // ... if the lvalue has atomic type, the value has the non-atomic version 647 // of the type of the lvalue ... 648 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 649 T = Atomic->getValueType().getUnqualifiedType(); 650 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 651 nullptr, VK_RValue); 652 } 653 654 return Res; 655 } 656 657 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 658 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 659 if (Res.isInvalid()) 660 return ExprError(); 661 Res = DefaultLvalueConversion(Res.get()); 662 if (Res.isInvalid()) 663 return ExprError(); 664 return Res; 665 } 666 667 /// CallExprUnaryConversions - a special case of an unary conversion 668 /// performed on a function designator of a call expression. 669 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 670 QualType Ty = E->getType(); 671 ExprResult Res = E; 672 // Only do implicit cast for a function type, but not for a pointer 673 // to function type. 674 if (Ty->isFunctionType()) { 675 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 676 CK_FunctionToPointerDecay).get(); 677 if (Res.isInvalid()) 678 return ExprError(); 679 } 680 Res = DefaultLvalueConversion(Res.get()); 681 if (Res.isInvalid()) 682 return ExprError(); 683 return Res.get(); 684 } 685 686 /// UsualUnaryConversions - Performs various conversions that are common to most 687 /// operators (C99 6.3). The conversions of array and function types are 688 /// sometimes suppressed. For example, the array->pointer conversion doesn't 689 /// apply if the array is an argument to the sizeof or address (&) operators. 690 /// In these instances, this routine should *not* be called. 691 ExprResult Sema::UsualUnaryConversions(Expr *E) { 692 // First, convert to an r-value. 693 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 694 if (Res.isInvalid()) 695 return ExprError(); 696 E = Res.get(); 697 698 QualType Ty = E->getType(); 699 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 700 701 // Half FP have to be promoted to float unless it is natively supported 702 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 703 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 704 705 // Try to perform integral promotions if the object has a theoretically 706 // promotable type. 707 if (Ty->isIntegralOrUnscopedEnumerationType()) { 708 // C99 6.3.1.1p2: 709 // 710 // The following may be used in an expression wherever an int or 711 // unsigned int may be used: 712 // - an object or expression with an integer type whose integer 713 // conversion rank is less than or equal to the rank of int 714 // and unsigned int. 715 // - A bit-field of type _Bool, int, signed int, or unsigned int. 716 // 717 // If an int can represent all values of the original type, the 718 // value is converted to an int; otherwise, it is converted to an 719 // unsigned int. These are called the integer promotions. All 720 // other types are unchanged by the integer promotions. 721 722 QualType PTy = Context.isPromotableBitField(E); 723 if (!PTy.isNull()) { 724 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 725 return E; 726 } 727 if (Ty->isPromotableIntegerType()) { 728 QualType PT = Context.getPromotedIntegerType(Ty); 729 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 730 return E; 731 } 732 } 733 return E; 734 } 735 736 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 737 /// do not have a prototype. Arguments that have type float or __fp16 738 /// are promoted to double. All other argument types are converted by 739 /// UsualUnaryConversions(). 740 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 741 QualType Ty = E->getType(); 742 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 743 744 ExprResult Res = UsualUnaryConversions(E); 745 if (Res.isInvalid()) 746 return ExprError(); 747 E = Res.get(); 748 749 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 750 // promote to double. 751 // Note that default argument promotion applies only to float (and 752 // half/fp16); it does not apply to _Float16. 753 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 754 if (BTy && (BTy->getKind() == BuiltinType::Half || 755 BTy->getKind() == BuiltinType::Float)) { 756 if (getLangOpts().OpenCL && 757 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 758 if (BTy->getKind() == BuiltinType::Half) { 759 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 760 } 761 } else { 762 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 763 } 764 } 765 766 // C++ performs lvalue-to-rvalue conversion as a default argument 767 // promotion, even on class types, but note: 768 // C++11 [conv.lval]p2: 769 // When an lvalue-to-rvalue conversion occurs in an unevaluated 770 // operand or a subexpression thereof the value contained in the 771 // referenced object is not accessed. Otherwise, if the glvalue 772 // has a class type, the conversion copy-initializes a temporary 773 // of type T from the glvalue and the result of the conversion 774 // is a prvalue for the temporary. 775 // FIXME: add some way to gate this entire thing for correctness in 776 // potentially potentially evaluated contexts. 777 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 778 ExprResult Temp = PerformCopyInitialization( 779 InitializedEntity::InitializeTemporary(E->getType()), 780 E->getExprLoc(), E); 781 if (Temp.isInvalid()) 782 return ExprError(); 783 E = Temp.get(); 784 } 785 786 return E; 787 } 788 789 /// Determine the degree of POD-ness for an expression. 790 /// Incomplete types are considered POD, since this check can be performed 791 /// when we're in an unevaluated context. 792 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 793 if (Ty->isIncompleteType()) { 794 // C++11 [expr.call]p7: 795 // After these conversions, if the argument does not have arithmetic, 796 // enumeration, pointer, pointer to member, or class type, the program 797 // is ill-formed. 798 // 799 // Since we've already performed array-to-pointer and function-to-pointer 800 // decay, the only such type in C++ is cv void. This also handles 801 // initializer lists as variadic arguments. 802 if (Ty->isVoidType()) 803 return VAK_Invalid; 804 805 if (Ty->isObjCObjectType()) 806 return VAK_Invalid; 807 return VAK_Valid; 808 } 809 810 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 811 return VAK_Invalid; 812 813 if (Ty.isCXX98PODType(Context)) 814 return VAK_Valid; 815 816 // C++11 [expr.call]p7: 817 // Passing a potentially-evaluated argument of class type (Clause 9) 818 // having a non-trivial copy constructor, a non-trivial move constructor, 819 // or a non-trivial destructor, with no corresponding parameter, 820 // is conditionally-supported with implementation-defined semantics. 821 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 822 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 823 if (!Record->hasNonTrivialCopyConstructor() && 824 !Record->hasNonTrivialMoveConstructor() && 825 !Record->hasNonTrivialDestructor()) 826 return VAK_ValidInCXX11; 827 828 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 829 return VAK_Valid; 830 831 if (Ty->isObjCObjectType()) 832 return VAK_Invalid; 833 834 if (getLangOpts().MSVCCompat) 835 return VAK_MSVCUndefined; 836 837 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 838 // permitted to reject them. We should consider doing so. 839 return VAK_Undefined; 840 } 841 842 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 843 // Don't allow one to pass an Objective-C interface to a vararg. 844 const QualType &Ty = E->getType(); 845 VarArgKind VAK = isValidVarArgType(Ty); 846 847 // Complain about passing non-POD types through varargs. 848 switch (VAK) { 849 case VAK_ValidInCXX11: 850 DiagRuntimeBehavior( 851 E->getBeginLoc(), nullptr, 852 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 853 LLVM_FALLTHROUGH; 854 case VAK_Valid: 855 if (Ty->isRecordType()) { 856 // This is unlikely to be what the user intended. If the class has a 857 // 'c_str' member function, the user probably meant to call that. 858 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 859 PDiag(diag::warn_pass_class_arg_to_vararg) 860 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 861 } 862 break; 863 864 case VAK_Undefined: 865 case VAK_MSVCUndefined: 866 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 867 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 868 << getLangOpts().CPlusPlus11 << Ty << CT); 869 break; 870 871 case VAK_Invalid: 872 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 873 Diag(E->getBeginLoc(), 874 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 875 << Ty << CT; 876 else if (Ty->isObjCObjectType()) 877 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 878 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 879 << Ty << CT); 880 else 881 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 882 << isa<InitListExpr>(E) << Ty << CT; 883 break; 884 } 885 } 886 887 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 888 /// will create a trap if the resulting type is not a POD type. 889 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 890 FunctionDecl *FDecl) { 891 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 892 // Strip the unbridged-cast placeholder expression off, if applicable. 893 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 894 (CT == VariadicMethod || 895 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 896 E = stripARCUnbridgedCast(E); 897 898 // Otherwise, do normal placeholder checking. 899 } else { 900 ExprResult ExprRes = CheckPlaceholderExpr(E); 901 if (ExprRes.isInvalid()) 902 return ExprError(); 903 E = ExprRes.get(); 904 } 905 } 906 907 ExprResult ExprRes = DefaultArgumentPromotion(E); 908 if (ExprRes.isInvalid()) 909 return ExprError(); 910 E = ExprRes.get(); 911 912 // Diagnostics regarding non-POD argument types are 913 // emitted along with format string checking in Sema::CheckFunctionCall(). 914 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 915 // Turn this into a trap. 916 CXXScopeSpec SS; 917 SourceLocation TemplateKWLoc; 918 UnqualifiedId Name; 919 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 920 E->getBeginLoc()); 921 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 922 /*HasTrailingLParen=*/true, 923 /*IsAddressOfOperand=*/false); 924 if (TrapFn.isInvalid()) 925 return ExprError(); 926 927 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 928 None, E->getEndLoc()); 929 if (Call.isInvalid()) 930 return ExprError(); 931 932 ExprResult Comma = 933 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 934 if (Comma.isInvalid()) 935 return ExprError(); 936 return Comma.get(); 937 } 938 939 if (!getLangOpts().CPlusPlus && 940 RequireCompleteType(E->getExprLoc(), E->getType(), 941 diag::err_call_incomplete_argument)) 942 return ExprError(); 943 944 return E; 945 } 946 947 /// Converts an integer to complex float type. Helper function of 948 /// UsualArithmeticConversions() 949 /// 950 /// \return false if the integer expression is an integer type and is 951 /// successfully converted to the complex type. 952 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 953 ExprResult &ComplexExpr, 954 QualType IntTy, 955 QualType ComplexTy, 956 bool SkipCast) { 957 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 958 if (SkipCast) return false; 959 if (IntTy->isIntegerType()) { 960 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 961 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 962 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 963 CK_FloatingRealToComplex); 964 } else { 965 assert(IntTy->isComplexIntegerType()); 966 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 967 CK_IntegralComplexToFloatingComplex); 968 } 969 return false; 970 } 971 972 /// Handle arithmetic conversion with complex types. Helper function of 973 /// UsualArithmeticConversions() 974 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 975 ExprResult &RHS, QualType LHSType, 976 QualType RHSType, 977 bool IsCompAssign) { 978 // if we have an integer operand, the result is the complex type. 979 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 980 /*skipCast*/false)) 981 return LHSType; 982 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 983 /*skipCast*/IsCompAssign)) 984 return RHSType; 985 986 // This handles complex/complex, complex/float, or float/complex. 987 // When both operands are complex, the shorter operand is converted to the 988 // type of the longer, and that is the type of the result. This corresponds 989 // to what is done when combining two real floating-point operands. 990 // The fun begins when size promotion occur across type domains. 991 // From H&S 6.3.4: When one operand is complex and the other is a real 992 // floating-point type, the less precise type is converted, within it's 993 // real or complex domain, to the precision of the other type. For example, 994 // when combining a "long double" with a "double _Complex", the 995 // "double _Complex" is promoted to "long double _Complex". 996 997 // Compute the rank of the two types, regardless of whether they are complex. 998 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 999 1000 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1001 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1002 QualType LHSElementType = 1003 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1004 QualType RHSElementType = 1005 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1006 1007 QualType ResultType = S.Context.getComplexType(LHSElementType); 1008 if (Order < 0) { 1009 // Promote the precision of the LHS if not an assignment. 1010 ResultType = S.Context.getComplexType(RHSElementType); 1011 if (!IsCompAssign) { 1012 if (LHSComplexType) 1013 LHS = 1014 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1015 else 1016 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1017 } 1018 } else if (Order > 0) { 1019 // Promote the precision of the RHS. 1020 if (RHSComplexType) 1021 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1022 else 1023 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1024 } 1025 return ResultType; 1026 } 1027 1028 /// Handle arithmetic conversion from integer to float. Helper function 1029 /// of UsualArithmeticConversions() 1030 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1031 ExprResult &IntExpr, 1032 QualType FloatTy, QualType IntTy, 1033 bool ConvertFloat, bool ConvertInt) { 1034 if (IntTy->isIntegerType()) { 1035 if (ConvertInt) 1036 // Convert intExpr to the lhs floating point type. 1037 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1038 CK_IntegralToFloating); 1039 return FloatTy; 1040 } 1041 1042 // Convert both sides to the appropriate complex float. 1043 assert(IntTy->isComplexIntegerType()); 1044 QualType result = S.Context.getComplexType(FloatTy); 1045 1046 // _Complex int -> _Complex float 1047 if (ConvertInt) 1048 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1049 CK_IntegralComplexToFloatingComplex); 1050 1051 // float -> _Complex float 1052 if (ConvertFloat) 1053 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1054 CK_FloatingRealToComplex); 1055 1056 return result; 1057 } 1058 1059 /// Handle arithmethic conversion with floating point types. Helper 1060 /// function of UsualArithmeticConversions() 1061 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1062 ExprResult &RHS, QualType LHSType, 1063 QualType RHSType, bool IsCompAssign) { 1064 bool LHSFloat = LHSType->isRealFloatingType(); 1065 bool RHSFloat = RHSType->isRealFloatingType(); 1066 1067 // If we have two real floating types, convert the smaller operand 1068 // to the bigger result. 1069 if (LHSFloat && RHSFloat) { 1070 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1071 if (order > 0) { 1072 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1073 return LHSType; 1074 } 1075 1076 assert(order < 0 && "illegal float comparison"); 1077 if (!IsCompAssign) 1078 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1079 return RHSType; 1080 } 1081 1082 if (LHSFloat) { 1083 // Half FP has to be promoted to float unless it is natively supported 1084 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1085 LHSType = S.Context.FloatTy; 1086 1087 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1088 /*ConvertFloat=*/!IsCompAssign, 1089 /*ConvertInt=*/ true); 1090 } 1091 assert(RHSFloat); 1092 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1093 /*convertInt=*/ true, 1094 /*convertFloat=*/!IsCompAssign); 1095 } 1096 1097 /// Diagnose attempts to convert between __float128 and long double if 1098 /// there is no support for such conversion. Helper function of 1099 /// UsualArithmeticConversions(). 1100 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1101 QualType RHSType) { 1102 /* No issue converting if at least one of the types is not a floating point 1103 type or the two types have the same rank. 1104 */ 1105 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1106 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1107 return false; 1108 1109 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1110 "The remaining types must be floating point types."); 1111 1112 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1113 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1114 1115 QualType LHSElemType = LHSComplex ? 1116 LHSComplex->getElementType() : LHSType; 1117 QualType RHSElemType = RHSComplex ? 1118 RHSComplex->getElementType() : RHSType; 1119 1120 // No issue if the two types have the same representation 1121 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1122 &S.Context.getFloatTypeSemantics(RHSElemType)) 1123 return false; 1124 1125 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1126 RHSElemType == S.Context.LongDoubleTy); 1127 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1128 RHSElemType == S.Context.Float128Ty); 1129 1130 // We've handled the situation where __float128 and long double have the same 1131 // representation. We allow all conversions for all possible long double types 1132 // except PPC's double double. 1133 return Float128AndLongDouble && 1134 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1135 &llvm::APFloat::PPCDoubleDouble()); 1136 } 1137 1138 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1139 1140 namespace { 1141 /// These helper callbacks are placed in an anonymous namespace to 1142 /// permit their use as function template parameters. 1143 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1144 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1145 } 1146 1147 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1148 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1149 CK_IntegralComplexCast); 1150 } 1151 } 1152 1153 /// Handle integer arithmetic conversions. Helper function of 1154 /// UsualArithmeticConversions() 1155 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1156 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1157 ExprResult &RHS, QualType LHSType, 1158 QualType RHSType, bool IsCompAssign) { 1159 // The rules for this case are in C99 6.3.1.8 1160 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1161 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1162 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1163 if (LHSSigned == RHSSigned) { 1164 // Same signedness; use the higher-ranked type 1165 if (order >= 0) { 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 (order != (LHSSigned ? 1 : -1)) { 1172 // The unsigned type has greater than or equal rank to the 1173 // signed type, so use the unsigned type 1174 if (RHSSigned) { 1175 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1176 return LHSType; 1177 } else if (!IsCompAssign) 1178 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1179 return RHSType; 1180 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1181 // The two types are different widths; if we are here, that 1182 // means the signed type is larger than the unsigned type, so 1183 // use the signed type. 1184 if (LHSSigned) { 1185 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1186 return LHSType; 1187 } else if (!IsCompAssign) 1188 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1189 return RHSType; 1190 } else { 1191 // The signed type is higher-ranked than the unsigned type, 1192 // but isn't actually any bigger (like unsigned int and long 1193 // on most 32-bit systems). Use the unsigned type corresponding 1194 // to the signed type. 1195 QualType result = 1196 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1197 RHS = (*doRHSCast)(S, RHS.get(), result); 1198 if (!IsCompAssign) 1199 LHS = (*doLHSCast)(S, LHS.get(), result); 1200 return result; 1201 } 1202 } 1203 1204 /// Handle conversions with GCC complex int extension. Helper function 1205 /// of UsualArithmeticConversions() 1206 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1207 ExprResult &RHS, QualType LHSType, 1208 QualType RHSType, 1209 bool IsCompAssign) { 1210 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1211 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1212 1213 if (LHSComplexInt && RHSComplexInt) { 1214 QualType LHSEltType = LHSComplexInt->getElementType(); 1215 QualType RHSEltType = RHSComplexInt->getElementType(); 1216 QualType ScalarType = 1217 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1218 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1219 1220 return S.Context.getComplexType(ScalarType); 1221 } 1222 1223 if (LHSComplexInt) { 1224 QualType LHSEltType = LHSComplexInt->getElementType(); 1225 QualType ScalarType = 1226 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1227 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1228 QualType ComplexType = S.Context.getComplexType(ScalarType); 1229 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1230 CK_IntegralRealToComplex); 1231 1232 return ComplexType; 1233 } 1234 1235 assert(RHSComplexInt); 1236 1237 QualType RHSEltType = RHSComplexInt->getElementType(); 1238 QualType ScalarType = 1239 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1240 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1241 QualType ComplexType = S.Context.getComplexType(ScalarType); 1242 1243 if (!IsCompAssign) 1244 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1245 CK_IntegralRealToComplex); 1246 return ComplexType; 1247 } 1248 1249 /// Return the rank of a given fixed point or integer type. The value itself 1250 /// doesn't matter, but the values must be increasing with proper increasing 1251 /// rank as described in N1169 4.1.1. 1252 static unsigned GetFixedPointRank(QualType Ty) { 1253 const auto *BTy = Ty->getAs<BuiltinType>(); 1254 assert(BTy && "Expected a builtin type."); 1255 1256 switch (BTy->getKind()) { 1257 case BuiltinType::ShortFract: 1258 case BuiltinType::UShortFract: 1259 case BuiltinType::SatShortFract: 1260 case BuiltinType::SatUShortFract: 1261 return 1; 1262 case BuiltinType::Fract: 1263 case BuiltinType::UFract: 1264 case BuiltinType::SatFract: 1265 case BuiltinType::SatUFract: 1266 return 2; 1267 case BuiltinType::LongFract: 1268 case BuiltinType::ULongFract: 1269 case BuiltinType::SatLongFract: 1270 case BuiltinType::SatULongFract: 1271 return 3; 1272 case BuiltinType::ShortAccum: 1273 case BuiltinType::UShortAccum: 1274 case BuiltinType::SatShortAccum: 1275 case BuiltinType::SatUShortAccum: 1276 return 4; 1277 case BuiltinType::Accum: 1278 case BuiltinType::UAccum: 1279 case BuiltinType::SatAccum: 1280 case BuiltinType::SatUAccum: 1281 return 5; 1282 case BuiltinType::LongAccum: 1283 case BuiltinType::ULongAccum: 1284 case BuiltinType::SatLongAccum: 1285 case BuiltinType::SatULongAccum: 1286 return 6; 1287 default: 1288 if (BTy->isInteger()) 1289 return 0; 1290 llvm_unreachable("Unexpected fixed point or integer type"); 1291 } 1292 } 1293 1294 /// handleFixedPointConversion - Fixed point operations between fixed 1295 /// point types and integers or other fixed point types do not fall under 1296 /// usual arithmetic conversion since these conversions could result in loss 1297 /// of precsision (N1169 4.1.4). These operations should be calculated with 1298 /// the full precision of their result type (N1169 4.1.6.2.1). 1299 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1300 QualType RHSTy) { 1301 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1302 "Expected at least one of the operands to be a fixed point type"); 1303 assert((LHSTy->isFixedPointOrIntegerType() || 1304 RHSTy->isFixedPointOrIntegerType()) && 1305 "Special fixed point arithmetic operation conversions are only " 1306 "applied to ints or other fixed point types"); 1307 1308 // If one operand has signed fixed-point type and the other operand has 1309 // unsigned fixed-point type, then the unsigned fixed-point operand is 1310 // converted to its corresponding signed fixed-point type and the resulting 1311 // type is the type of the converted operand. 1312 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1313 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1314 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1315 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1316 1317 // The result type is the type with the highest rank, whereby a fixed-point 1318 // conversion rank is always greater than an integer conversion rank; if the 1319 // type of either of the operands is a saturating fixedpoint type, the result 1320 // type shall be the saturating fixed-point type corresponding to the type 1321 // with the highest rank; the resulting value is converted (taking into 1322 // account rounding and overflow) to the precision of the resulting type. 1323 // Same ranks between signed and unsigned types are resolved earlier, so both 1324 // types are either signed or both unsigned at this point. 1325 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1326 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1327 1328 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1329 1330 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1331 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1332 1333 return ResultTy; 1334 } 1335 1336 /// Check that the usual arithmetic conversions can be performed on this pair of 1337 /// expressions that might be of enumeration type. 1338 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1339 SourceLocation Loc, 1340 Sema::ArithConvKind ACK) { 1341 // C++2a [expr.arith.conv]p1: 1342 // If one operand is of enumeration type and the other operand is of a 1343 // different enumeration type or a floating-point type, this behavior is 1344 // deprecated ([depr.arith.conv.enum]). 1345 // 1346 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1347 // Eventually we will presumably reject these cases (in C++23 onwards?). 1348 QualType L = LHS->getType(), R = RHS->getType(); 1349 bool LEnum = L->isUnscopedEnumerationType(), 1350 REnum = R->isUnscopedEnumerationType(); 1351 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1352 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1353 (REnum && L->isFloatingType())) { 1354 S.Diag(Loc, S.getLangOpts().CPlusPlus2a 1355 ? diag::warn_arith_conv_enum_float_cxx2a 1356 : diag::warn_arith_conv_enum_float) 1357 << LHS->getSourceRange() << RHS->getSourceRange() 1358 << (int)ACK << LEnum << L << R; 1359 } else if (!IsCompAssign && LEnum && REnum && 1360 !S.Context.hasSameUnqualifiedType(L, R)) { 1361 unsigned DiagID; 1362 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1363 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1364 // If either enumeration type is unnamed, it's less likely that the 1365 // user cares about this, but this situation is still deprecated in 1366 // C++2a. Use a different warning group. 1367 DiagID = S.getLangOpts().CPlusPlus2a 1368 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a 1369 : diag::warn_arith_conv_mixed_anon_enum_types; 1370 } else if (ACK == Sema::ACK_Conditional) { 1371 // Conditional expressions are separated out because they have 1372 // historically had a different warning flag. 1373 DiagID = S.getLangOpts().CPlusPlus2a 1374 ? diag::warn_conditional_mixed_enum_types_cxx2a 1375 : diag::warn_conditional_mixed_enum_types; 1376 } else if (ACK == Sema::ACK_Comparison) { 1377 // Comparison expressions are separated out because they have 1378 // historically had a different warning flag. 1379 DiagID = S.getLangOpts().CPlusPlus2a 1380 ? diag::warn_comparison_mixed_enum_types_cxx2a 1381 : diag::warn_comparison_mixed_enum_types; 1382 } else { 1383 DiagID = S.getLangOpts().CPlusPlus2a 1384 ? diag::warn_arith_conv_mixed_enum_types_cxx2a 1385 : diag::warn_arith_conv_mixed_enum_types; 1386 } 1387 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1388 << (int)ACK << L << R; 1389 } 1390 } 1391 1392 /// UsualArithmeticConversions - Performs various conversions that are common to 1393 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1394 /// routine returns the first non-arithmetic type found. The client is 1395 /// responsible for emitting appropriate error diagnostics. 1396 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1397 SourceLocation Loc, 1398 ArithConvKind ACK) { 1399 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1400 1401 if (ACK != ACK_CompAssign) { 1402 LHS = UsualUnaryConversions(LHS.get()); 1403 if (LHS.isInvalid()) 1404 return QualType(); 1405 } 1406 1407 RHS = UsualUnaryConversions(RHS.get()); 1408 if (RHS.isInvalid()) 1409 return QualType(); 1410 1411 // For conversion purposes, we ignore any qualifiers. 1412 // For example, "const float" and "float" are equivalent. 1413 QualType LHSType = 1414 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1415 QualType RHSType = 1416 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1417 1418 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1419 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1420 LHSType = AtomicLHS->getValueType(); 1421 1422 // If both types are identical, no conversion is needed. 1423 if (LHSType == RHSType) 1424 return LHSType; 1425 1426 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1427 // The caller can deal with this (e.g. pointer + int). 1428 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1429 return QualType(); 1430 1431 // Apply unary and bitfield promotions to the LHS's type. 1432 QualType LHSUnpromotedType = LHSType; 1433 if (LHSType->isPromotableIntegerType()) 1434 LHSType = Context.getPromotedIntegerType(LHSType); 1435 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1436 if (!LHSBitfieldPromoteTy.isNull()) 1437 LHSType = LHSBitfieldPromoteTy; 1438 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1439 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1440 1441 // If both types are identical, no conversion is needed. 1442 if (LHSType == RHSType) 1443 return LHSType; 1444 1445 // At this point, we have two different arithmetic types. 1446 1447 // Diagnose attempts to convert between __float128 and long double where 1448 // such conversions currently can't be handled. 1449 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1450 return QualType(); 1451 1452 // Handle complex types first (C99 6.3.1.8p1). 1453 if (LHSType->isComplexType() || RHSType->isComplexType()) 1454 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1455 ACK == ACK_CompAssign); 1456 1457 // Now handle "real" floating types (i.e. float, double, long double). 1458 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1459 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1460 ACK == ACK_CompAssign); 1461 1462 // Handle GCC complex int extension. 1463 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1464 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1465 ACK == ACK_CompAssign); 1466 1467 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1468 return handleFixedPointConversion(*this, LHSType, RHSType); 1469 1470 // Finally, we have two differing integer types. 1471 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1472 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1473 } 1474 1475 //===----------------------------------------------------------------------===// 1476 // Semantic Analysis for various Expression Types 1477 //===----------------------------------------------------------------------===// 1478 1479 1480 ExprResult 1481 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1482 SourceLocation DefaultLoc, 1483 SourceLocation RParenLoc, 1484 Expr *ControllingExpr, 1485 ArrayRef<ParsedType> ArgTypes, 1486 ArrayRef<Expr *> ArgExprs) { 1487 unsigned NumAssocs = ArgTypes.size(); 1488 assert(NumAssocs == ArgExprs.size()); 1489 1490 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1491 for (unsigned i = 0; i < NumAssocs; ++i) { 1492 if (ArgTypes[i]) 1493 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1494 else 1495 Types[i] = nullptr; 1496 } 1497 1498 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1499 ControllingExpr, 1500 llvm::makeArrayRef(Types, NumAssocs), 1501 ArgExprs); 1502 delete [] Types; 1503 return ER; 1504 } 1505 1506 ExprResult 1507 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1508 SourceLocation DefaultLoc, 1509 SourceLocation RParenLoc, 1510 Expr *ControllingExpr, 1511 ArrayRef<TypeSourceInfo *> Types, 1512 ArrayRef<Expr *> Exprs) { 1513 unsigned NumAssocs = Types.size(); 1514 assert(NumAssocs == Exprs.size()); 1515 1516 // Decay and strip qualifiers for the controlling expression type, and handle 1517 // placeholder type replacement. See committee discussion from WG14 DR423. 1518 { 1519 EnterExpressionEvaluationContext Unevaluated( 1520 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1521 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1522 if (R.isInvalid()) 1523 return ExprError(); 1524 ControllingExpr = R.get(); 1525 } 1526 1527 // The controlling expression is an unevaluated operand, so side effects are 1528 // likely unintended. 1529 if (!inTemplateInstantiation() && 1530 ControllingExpr->HasSideEffects(Context, false)) 1531 Diag(ControllingExpr->getExprLoc(), 1532 diag::warn_side_effects_unevaluated_context); 1533 1534 bool TypeErrorFound = false, 1535 IsResultDependent = ControllingExpr->isTypeDependent(), 1536 ContainsUnexpandedParameterPack 1537 = ControllingExpr->containsUnexpandedParameterPack(); 1538 1539 for (unsigned i = 0; i < NumAssocs; ++i) { 1540 if (Exprs[i]->containsUnexpandedParameterPack()) 1541 ContainsUnexpandedParameterPack = true; 1542 1543 if (Types[i]) { 1544 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1545 ContainsUnexpandedParameterPack = true; 1546 1547 if (Types[i]->getType()->isDependentType()) { 1548 IsResultDependent = true; 1549 } else { 1550 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1551 // complete object type other than a variably modified type." 1552 unsigned D = 0; 1553 if (Types[i]->getType()->isIncompleteType()) 1554 D = diag::err_assoc_type_incomplete; 1555 else if (!Types[i]->getType()->isObjectType()) 1556 D = diag::err_assoc_type_nonobject; 1557 else if (Types[i]->getType()->isVariablyModifiedType()) 1558 D = diag::err_assoc_type_variably_modified; 1559 1560 if (D != 0) { 1561 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1562 << Types[i]->getTypeLoc().getSourceRange() 1563 << Types[i]->getType(); 1564 TypeErrorFound = true; 1565 } 1566 1567 // C11 6.5.1.1p2 "No two generic associations in the same generic 1568 // selection shall specify compatible types." 1569 for (unsigned j = i+1; j < NumAssocs; ++j) 1570 if (Types[j] && !Types[j]->getType()->isDependentType() && 1571 Context.typesAreCompatible(Types[i]->getType(), 1572 Types[j]->getType())) { 1573 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1574 diag::err_assoc_compatible_types) 1575 << Types[j]->getTypeLoc().getSourceRange() 1576 << Types[j]->getType() 1577 << Types[i]->getType(); 1578 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1579 diag::note_compat_assoc) 1580 << Types[i]->getTypeLoc().getSourceRange() 1581 << Types[i]->getType(); 1582 TypeErrorFound = true; 1583 } 1584 } 1585 } 1586 } 1587 if (TypeErrorFound) 1588 return ExprError(); 1589 1590 // If we determined that the generic selection is result-dependent, don't 1591 // try to compute the result expression. 1592 if (IsResultDependent) 1593 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1594 Exprs, DefaultLoc, RParenLoc, 1595 ContainsUnexpandedParameterPack); 1596 1597 SmallVector<unsigned, 1> CompatIndices; 1598 unsigned DefaultIndex = -1U; 1599 for (unsigned i = 0; i < NumAssocs; ++i) { 1600 if (!Types[i]) 1601 DefaultIndex = i; 1602 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1603 Types[i]->getType())) 1604 CompatIndices.push_back(i); 1605 } 1606 1607 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1608 // type compatible with at most one of the types named in its generic 1609 // association list." 1610 if (CompatIndices.size() > 1) { 1611 // We strip parens here because the controlling expression is typically 1612 // parenthesized in macro definitions. 1613 ControllingExpr = ControllingExpr->IgnoreParens(); 1614 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1615 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1616 << (unsigned)CompatIndices.size(); 1617 for (unsigned I : CompatIndices) { 1618 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1619 diag::note_compat_assoc) 1620 << Types[I]->getTypeLoc().getSourceRange() 1621 << Types[I]->getType(); 1622 } 1623 return ExprError(); 1624 } 1625 1626 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1627 // its controlling expression shall have type compatible with exactly one of 1628 // the types named in its generic association list." 1629 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1630 // We strip parens here because the controlling expression is typically 1631 // parenthesized in macro definitions. 1632 ControllingExpr = ControllingExpr->IgnoreParens(); 1633 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1634 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1635 return ExprError(); 1636 } 1637 1638 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1639 // type name that is compatible with the type of the controlling expression, 1640 // then the result expression of the generic selection is the expression 1641 // in that generic association. Otherwise, the result expression of the 1642 // generic selection is the expression in the default generic association." 1643 unsigned ResultIndex = 1644 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1645 1646 return GenericSelectionExpr::Create( 1647 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1648 ContainsUnexpandedParameterPack, ResultIndex); 1649 } 1650 1651 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1652 /// location of the token and the offset of the ud-suffix within it. 1653 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1654 unsigned Offset) { 1655 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1656 S.getLangOpts()); 1657 } 1658 1659 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1660 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1661 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1662 IdentifierInfo *UDSuffix, 1663 SourceLocation UDSuffixLoc, 1664 ArrayRef<Expr*> Args, 1665 SourceLocation LitEndLoc) { 1666 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1667 1668 QualType ArgTy[2]; 1669 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1670 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1671 if (ArgTy[ArgIdx]->isArrayType()) 1672 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1673 } 1674 1675 DeclarationName OpName = 1676 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1677 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1678 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1679 1680 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1681 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1682 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1683 /*AllowStringTemplate*/ false, 1684 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1685 return ExprError(); 1686 1687 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1688 } 1689 1690 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1691 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1692 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1693 /// multiple tokens. However, the common case is that StringToks points to one 1694 /// string. 1695 /// 1696 ExprResult 1697 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1698 assert(!StringToks.empty() && "Must have at least one string!"); 1699 1700 StringLiteralParser Literal(StringToks, PP); 1701 if (Literal.hadError) 1702 return ExprError(); 1703 1704 SmallVector<SourceLocation, 4> StringTokLocs; 1705 for (const Token &Tok : StringToks) 1706 StringTokLocs.push_back(Tok.getLocation()); 1707 1708 QualType CharTy = Context.CharTy; 1709 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1710 if (Literal.isWide()) { 1711 CharTy = Context.getWideCharType(); 1712 Kind = StringLiteral::Wide; 1713 } else if (Literal.isUTF8()) { 1714 if (getLangOpts().Char8) 1715 CharTy = Context.Char8Ty; 1716 Kind = StringLiteral::UTF8; 1717 } else if (Literal.isUTF16()) { 1718 CharTy = Context.Char16Ty; 1719 Kind = StringLiteral::UTF16; 1720 } else if (Literal.isUTF32()) { 1721 CharTy = Context.Char32Ty; 1722 Kind = StringLiteral::UTF32; 1723 } else if (Literal.isPascal()) { 1724 CharTy = Context.UnsignedCharTy; 1725 } 1726 1727 // Warn on initializing an array of char from a u8 string literal; this 1728 // becomes ill-formed in C++2a. 1729 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1730 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1731 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1732 1733 // Create removals for all 'u8' prefixes in the string literal(s). This 1734 // ensures C++2a compatibility (but may change the program behavior when 1735 // built by non-Clang compilers for which the execution character set is 1736 // not always UTF-8). 1737 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1738 SourceLocation RemovalDiagLoc; 1739 for (const Token &Tok : StringToks) { 1740 if (Tok.getKind() == tok::utf8_string_literal) { 1741 if (RemovalDiagLoc.isInvalid()) 1742 RemovalDiagLoc = Tok.getLocation(); 1743 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1744 Tok.getLocation(), 1745 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1746 getSourceManager(), getLangOpts()))); 1747 } 1748 } 1749 Diag(RemovalDiagLoc, RemovalDiag); 1750 } 1751 1752 QualType StrTy = 1753 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1754 1755 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1756 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1757 Kind, Literal.Pascal, StrTy, 1758 &StringTokLocs[0], 1759 StringTokLocs.size()); 1760 if (Literal.getUDSuffix().empty()) 1761 return Lit; 1762 1763 // We're building a user-defined literal. 1764 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1765 SourceLocation UDSuffixLoc = 1766 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1767 Literal.getUDSuffixOffset()); 1768 1769 // Make sure we're allowed user-defined literals here. 1770 if (!UDLScope) 1771 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1772 1773 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1774 // operator "" X (str, len) 1775 QualType SizeType = Context.getSizeType(); 1776 1777 DeclarationName OpName = 1778 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1779 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1780 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1781 1782 QualType ArgTy[] = { 1783 Context.getArrayDecayedType(StrTy), SizeType 1784 }; 1785 1786 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1787 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1788 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1789 /*AllowStringTemplate*/ true, 1790 /*DiagnoseMissing*/ true)) { 1791 1792 case LOLR_Cooked: { 1793 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1794 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1795 StringTokLocs[0]); 1796 Expr *Args[] = { Lit, LenArg }; 1797 1798 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1799 } 1800 1801 case LOLR_StringTemplate: { 1802 TemplateArgumentListInfo ExplicitArgs; 1803 1804 unsigned CharBits = Context.getIntWidth(CharTy); 1805 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1806 llvm::APSInt Value(CharBits, CharIsUnsigned); 1807 1808 TemplateArgument TypeArg(CharTy); 1809 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1810 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1811 1812 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1813 Value = Lit->getCodeUnit(I); 1814 TemplateArgument Arg(Context, Value, CharTy); 1815 TemplateArgumentLocInfo ArgInfo; 1816 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1817 } 1818 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1819 &ExplicitArgs); 1820 } 1821 case LOLR_Raw: 1822 case LOLR_Template: 1823 case LOLR_ErrorNoDiagnostic: 1824 llvm_unreachable("unexpected literal operator lookup result"); 1825 case LOLR_Error: 1826 return ExprError(); 1827 } 1828 llvm_unreachable("unexpected literal operator lookup result"); 1829 } 1830 1831 DeclRefExpr * 1832 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1833 SourceLocation Loc, 1834 const CXXScopeSpec *SS) { 1835 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1836 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1837 } 1838 1839 DeclRefExpr * 1840 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1841 const DeclarationNameInfo &NameInfo, 1842 const CXXScopeSpec *SS, NamedDecl *FoundD, 1843 SourceLocation TemplateKWLoc, 1844 const TemplateArgumentListInfo *TemplateArgs) { 1845 NestedNameSpecifierLoc NNS = 1846 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1847 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1848 TemplateArgs); 1849 } 1850 1851 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1852 // A declaration named in an unevaluated operand never constitutes an odr-use. 1853 if (isUnevaluatedContext()) 1854 return NOUR_Unevaluated; 1855 1856 // C++2a [basic.def.odr]p4: 1857 // A variable x whose name appears as a potentially-evaluated expression e 1858 // is odr-used by e unless [...] x is a reference that is usable in 1859 // constant expressions. 1860 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1861 if (VD->getType()->isReferenceType() && 1862 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1863 VD->isUsableInConstantExpressions(Context)) 1864 return NOUR_Constant; 1865 } 1866 1867 // All remaining non-variable cases constitute an odr-use. For variables, we 1868 // need to wait and see how the expression is used. 1869 return NOUR_None; 1870 } 1871 1872 /// BuildDeclRefExpr - Build an expression that references a 1873 /// declaration that does not require a closure capture. 1874 DeclRefExpr * 1875 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1876 const DeclarationNameInfo &NameInfo, 1877 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1878 SourceLocation TemplateKWLoc, 1879 const TemplateArgumentListInfo *TemplateArgs) { 1880 bool RefersToCapturedVariable = 1881 isa<VarDecl>(D) && 1882 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1883 1884 DeclRefExpr *E = DeclRefExpr::Create( 1885 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1886 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1887 MarkDeclRefReferenced(E); 1888 1889 // C++ [except.spec]p17: 1890 // An exception-specification is considered to be needed when: 1891 // - in an expression, the function is the unique lookup result or 1892 // the selected member of a set of overloaded functions. 1893 // 1894 // We delay doing this until after we've built the function reference and 1895 // marked it as used so that: 1896 // a) if the function is defaulted, we get errors from defining it before / 1897 // instead of errors from computing its exception specification, and 1898 // b) if the function is a defaulted comparison, we can use the body we 1899 // build when defining it as input to the exception specification 1900 // computation rather than computing a new body. 1901 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1902 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1903 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1904 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1905 } 1906 } 1907 1908 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1909 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1910 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1911 getCurFunction()->recordUseOfWeak(E); 1912 1913 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1914 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1915 FD = IFD->getAnonField(); 1916 if (FD) { 1917 UnusedPrivateFields.remove(FD); 1918 // Just in case we're building an illegal pointer-to-member. 1919 if (FD->isBitField()) 1920 E->setObjectKind(OK_BitField); 1921 } 1922 1923 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1924 // designates a bit-field. 1925 if (auto *BD = dyn_cast<BindingDecl>(D)) 1926 if (auto *BE = BD->getBinding()) 1927 E->setObjectKind(BE->getObjectKind()); 1928 1929 return E; 1930 } 1931 1932 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1933 /// possibly a list of template arguments. 1934 /// 1935 /// If this produces template arguments, it is permitted to call 1936 /// DecomposeTemplateName. 1937 /// 1938 /// This actually loses a lot of source location information for 1939 /// non-standard name kinds; we should consider preserving that in 1940 /// some way. 1941 void 1942 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1943 TemplateArgumentListInfo &Buffer, 1944 DeclarationNameInfo &NameInfo, 1945 const TemplateArgumentListInfo *&TemplateArgs) { 1946 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1947 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1948 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1949 1950 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1951 Id.TemplateId->NumArgs); 1952 translateTemplateArguments(TemplateArgsPtr, Buffer); 1953 1954 TemplateName TName = Id.TemplateId->Template.get(); 1955 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1956 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1957 TemplateArgs = &Buffer; 1958 } else { 1959 NameInfo = GetNameFromUnqualifiedId(Id); 1960 TemplateArgs = nullptr; 1961 } 1962 } 1963 1964 static void emitEmptyLookupTypoDiagnostic( 1965 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1966 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1967 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1968 DeclContext *Ctx = 1969 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1970 if (!TC) { 1971 // Emit a special diagnostic for failed member lookups. 1972 // FIXME: computing the declaration context might fail here (?) 1973 if (Ctx) 1974 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1975 << SS.getRange(); 1976 else 1977 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1978 return; 1979 } 1980 1981 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1982 bool DroppedSpecifier = 1983 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1984 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1985 ? diag::note_implicit_param_decl 1986 : diag::note_previous_decl; 1987 if (!Ctx) 1988 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1989 SemaRef.PDiag(NoteID)); 1990 else 1991 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1992 << Typo << Ctx << DroppedSpecifier 1993 << SS.getRange(), 1994 SemaRef.PDiag(NoteID)); 1995 } 1996 1997 /// Diagnose an empty lookup. 1998 /// 1999 /// \return false if new lookup candidates were found 2000 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2001 CorrectionCandidateCallback &CCC, 2002 TemplateArgumentListInfo *ExplicitTemplateArgs, 2003 ArrayRef<Expr *> Args, TypoExpr **Out) { 2004 DeclarationName Name = R.getLookupName(); 2005 2006 unsigned diagnostic = diag::err_undeclared_var_use; 2007 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2008 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2009 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2010 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2011 diagnostic = diag::err_undeclared_use; 2012 diagnostic_suggest = diag::err_undeclared_use_suggest; 2013 } 2014 2015 // If the original lookup was an unqualified lookup, fake an 2016 // unqualified lookup. This is useful when (for example) the 2017 // original lookup would not have found something because it was a 2018 // dependent name. 2019 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2020 while (DC) { 2021 if (isa<CXXRecordDecl>(DC)) { 2022 LookupQualifiedName(R, DC); 2023 2024 if (!R.empty()) { 2025 // Don't give errors about ambiguities in this lookup. 2026 R.suppressDiagnostics(); 2027 2028 // During a default argument instantiation the CurContext points 2029 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2030 // function parameter list, hence add an explicit check. 2031 bool isDefaultArgument = 2032 !CodeSynthesisContexts.empty() && 2033 CodeSynthesisContexts.back().Kind == 2034 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2035 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2036 bool isInstance = CurMethod && 2037 CurMethod->isInstance() && 2038 DC == CurMethod->getParent() && !isDefaultArgument; 2039 2040 // Give a code modification hint to insert 'this->'. 2041 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2042 // Actually quite difficult! 2043 if (getLangOpts().MSVCCompat) 2044 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2045 if (isInstance) { 2046 Diag(R.getNameLoc(), diagnostic) << Name 2047 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2048 CheckCXXThisCapture(R.getNameLoc()); 2049 } else { 2050 Diag(R.getNameLoc(), diagnostic) << Name; 2051 } 2052 2053 // Do we really want to note all of these? 2054 for (NamedDecl *D : R) 2055 Diag(D->getLocation(), diag::note_dependent_var_use); 2056 2057 // Return true if we are inside a default argument instantiation 2058 // and the found name refers to an instance member function, otherwise 2059 // the function calling DiagnoseEmptyLookup will try to create an 2060 // implicit member call and this is wrong for default argument. 2061 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2062 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2063 return true; 2064 } 2065 2066 // Tell the callee to try to recover. 2067 return false; 2068 } 2069 2070 R.clear(); 2071 } 2072 2073 DC = DC->getLookupParent(); 2074 } 2075 2076 // We didn't find anything, so try to correct for a typo. 2077 TypoCorrection Corrected; 2078 if (S && Out) { 2079 SourceLocation TypoLoc = R.getNameLoc(); 2080 assert(!ExplicitTemplateArgs && 2081 "Diagnosing an empty lookup with explicit template args!"); 2082 *Out = CorrectTypoDelayed( 2083 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2084 [=](const TypoCorrection &TC) { 2085 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2086 diagnostic, diagnostic_suggest); 2087 }, 2088 nullptr, CTK_ErrorRecovery); 2089 if (*Out) 2090 return true; 2091 } else if (S && 2092 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2093 S, &SS, CCC, CTK_ErrorRecovery))) { 2094 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2095 bool DroppedSpecifier = 2096 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2097 R.setLookupName(Corrected.getCorrection()); 2098 2099 bool AcceptableWithRecovery = false; 2100 bool AcceptableWithoutRecovery = false; 2101 NamedDecl *ND = Corrected.getFoundDecl(); 2102 if (ND) { 2103 if (Corrected.isOverloaded()) { 2104 OverloadCandidateSet OCS(R.getNameLoc(), 2105 OverloadCandidateSet::CSK_Normal); 2106 OverloadCandidateSet::iterator Best; 2107 for (NamedDecl *CD : Corrected) { 2108 if (FunctionTemplateDecl *FTD = 2109 dyn_cast<FunctionTemplateDecl>(CD)) 2110 AddTemplateOverloadCandidate( 2111 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2112 Args, OCS); 2113 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2114 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2115 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2116 Args, OCS); 2117 } 2118 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2119 case OR_Success: 2120 ND = Best->FoundDecl; 2121 Corrected.setCorrectionDecl(ND); 2122 break; 2123 default: 2124 // FIXME: Arbitrarily pick the first declaration for the note. 2125 Corrected.setCorrectionDecl(ND); 2126 break; 2127 } 2128 } 2129 R.addDecl(ND); 2130 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2131 CXXRecordDecl *Record = nullptr; 2132 if (Corrected.getCorrectionSpecifier()) { 2133 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2134 Record = Ty->getAsCXXRecordDecl(); 2135 } 2136 if (!Record) 2137 Record = cast<CXXRecordDecl>( 2138 ND->getDeclContext()->getRedeclContext()); 2139 R.setNamingClass(Record); 2140 } 2141 2142 auto *UnderlyingND = ND->getUnderlyingDecl(); 2143 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2144 isa<FunctionTemplateDecl>(UnderlyingND); 2145 // FIXME: If we ended up with a typo for a type name or 2146 // Objective-C class name, we're in trouble because the parser 2147 // is in the wrong place to recover. Suggest the typo 2148 // correction, but don't make it a fix-it since we're not going 2149 // to recover well anyway. 2150 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2151 getAsTypeTemplateDecl(UnderlyingND) || 2152 isa<ObjCInterfaceDecl>(UnderlyingND); 2153 } else { 2154 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2155 // because we aren't able to recover. 2156 AcceptableWithoutRecovery = true; 2157 } 2158 2159 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2160 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2161 ? diag::note_implicit_param_decl 2162 : diag::note_previous_decl; 2163 if (SS.isEmpty()) 2164 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2165 PDiag(NoteID), AcceptableWithRecovery); 2166 else 2167 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2168 << Name << computeDeclContext(SS, false) 2169 << DroppedSpecifier << SS.getRange(), 2170 PDiag(NoteID), AcceptableWithRecovery); 2171 2172 // Tell the callee whether to try to recover. 2173 return !AcceptableWithRecovery; 2174 } 2175 } 2176 R.clear(); 2177 2178 // Emit a special diagnostic for failed member lookups. 2179 // FIXME: computing the declaration context might fail here (?) 2180 if (!SS.isEmpty()) { 2181 Diag(R.getNameLoc(), diag::err_no_member) 2182 << Name << computeDeclContext(SS, false) 2183 << SS.getRange(); 2184 return true; 2185 } 2186 2187 // Give up, we can't recover. 2188 Diag(R.getNameLoc(), diagnostic) << Name; 2189 return true; 2190 } 2191 2192 /// In Microsoft mode, if we are inside a template class whose parent class has 2193 /// dependent base classes, and we can't resolve an unqualified identifier, then 2194 /// assume the identifier is a member of a dependent base class. We can only 2195 /// recover successfully in static methods, instance methods, and other contexts 2196 /// where 'this' is available. This doesn't precisely match MSVC's 2197 /// instantiation model, but it's close enough. 2198 static Expr * 2199 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2200 DeclarationNameInfo &NameInfo, 2201 SourceLocation TemplateKWLoc, 2202 const TemplateArgumentListInfo *TemplateArgs) { 2203 // Only try to recover from lookup into dependent bases in static methods or 2204 // contexts where 'this' is available. 2205 QualType ThisType = S.getCurrentThisType(); 2206 const CXXRecordDecl *RD = nullptr; 2207 if (!ThisType.isNull()) 2208 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2209 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2210 RD = MD->getParent(); 2211 if (!RD || !RD->hasAnyDependentBases()) 2212 return nullptr; 2213 2214 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2215 // is available, suggest inserting 'this->' as a fixit. 2216 SourceLocation Loc = NameInfo.getLoc(); 2217 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2218 DB << NameInfo.getName() << RD; 2219 2220 if (!ThisType.isNull()) { 2221 DB << FixItHint::CreateInsertion(Loc, "this->"); 2222 return CXXDependentScopeMemberExpr::Create( 2223 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2224 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2225 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2226 } 2227 2228 // Synthesize a fake NNS that points to the derived class. This will 2229 // perform name lookup during template instantiation. 2230 CXXScopeSpec SS; 2231 auto *NNS = 2232 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2233 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2234 return DependentScopeDeclRefExpr::Create( 2235 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2236 TemplateArgs); 2237 } 2238 2239 ExprResult 2240 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2241 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2242 bool HasTrailingLParen, bool IsAddressOfOperand, 2243 CorrectionCandidateCallback *CCC, 2244 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2245 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2246 "cannot be direct & operand and have a trailing lparen"); 2247 if (SS.isInvalid()) 2248 return ExprError(); 2249 2250 TemplateArgumentListInfo TemplateArgsBuffer; 2251 2252 // Decompose the UnqualifiedId into the following data. 2253 DeclarationNameInfo NameInfo; 2254 const TemplateArgumentListInfo *TemplateArgs; 2255 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2256 2257 DeclarationName Name = NameInfo.getName(); 2258 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2259 SourceLocation NameLoc = NameInfo.getLoc(); 2260 2261 if (II && II->isEditorPlaceholder()) { 2262 // FIXME: When typed placeholders are supported we can create a typed 2263 // placeholder expression node. 2264 return ExprError(); 2265 } 2266 2267 // C++ [temp.dep.expr]p3: 2268 // An id-expression is type-dependent if it contains: 2269 // -- an identifier that was declared with a dependent type, 2270 // (note: handled after lookup) 2271 // -- a template-id that is dependent, 2272 // (note: handled in BuildTemplateIdExpr) 2273 // -- a conversion-function-id that specifies a dependent type, 2274 // -- a nested-name-specifier that contains a class-name that 2275 // names a dependent type. 2276 // Determine whether this is a member of an unknown specialization; 2277 // we need to handle these differently. 2278 bool DependentID = false; 2279 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2280 Name.getCXXNameType()->isDependentType()) { 2281 DependentID = true; 2282 } else if (SS.isSet()) { 2283 if (DeclContext *DC = computeDeclContext(SS, false)) { 2284 if (RequireCompleteDeclContext(SS, DC)) 2285 return ExprError(); 2286 } else { 2287 DependentID = true; 2288 } 2289 } 2290 2291 if (DependentID) 2292 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2293 IsAddressOfOperand, TemplateArgs); 2294 2295 // Perform the required lookup. 2296 LookupResult R(*this, NameInfo, 2297 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2298 ? LookupObjCImplicitSelfParam 2299 : LookupOrdinaryName); 2300 if (TemplateKWLoc.isValid() || TemplateArgs) { 2301 // Lookup the template name again to correctly establish the context in 2302 // which it was found. This is really unfortunate as we already did the 2303 // lookup to determine that it was a template name in the first place. If 2304 // this becomes a performance hit, we can work harder to preserve those 2305 // results until we get here but it's likely not worth it. 2306 bool MemberOfUnknownSpecialization; 2307 AssumedTemplateKind AssumedTemplate; 2308 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2309 MemberOfUnknownSpecialization, TemplateKWLoc, 2310 &AssumedTemplate)) 2311 return ExprError(); 2312 2313 if (MemberOfUnknownSpecialization || 2314 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2315 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2316 IsAddressOfOperand, TemplateArgs); 2317 } else { 2318 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2319 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2320 2321 // If the result might be in a dependent base class, this is a dependent 2322 // id-expression. 2323 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2324 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2325 IsAddressOfOperand, TemplateArgs); 2326 2327 // If this reference is in an Objective-C method, then we need to do 2328 // some special Objective-C lookup, too. 2329 if (IvarLookupFollowUp) { 2330 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2331 if (E.isInvalid()) 2332 return ExprError(); 2333 2334 if (Expr *Ex = E.getAs<Expr>()) 2335 return Ex; 2336 } 2337 } 2338 2339 if (R.isAmbiguous()) 2340 return ExprError(); 2341 2342 // This could be an implicitly declared function reference (legal in C90, 2343 // extension in C99, forbidden in C++). 2344 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2345 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2346 if (D) R.addDecl(D); 2347 } 2348 2349 // Determine whether this name might be a candidate for 2350 // argument-dependent lookup. 2351 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2352 2353 if (R.empty() && !ADL) { 2354 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2355 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2356 TemplateKWLoc, TemplateArgs)) 2357 return E; 2358 } 2359 2360 // Don't diagnose an empty lookup for inline assembly. 2361 if (IsInlineAsmIdentifier) 2362 return ExprError(); 2363 2364 // If this name wasn't predeclared and if this is not a function 2365 // call, diagnose the problem. 2366 TypoExpr *TE = nullptr; 2367 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2368 : nullptr); 2369 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2370 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2371 "Typo correction callback misconfigured"); 2372 if (CCC) { 2373 // Make sure the callback knows what the typo being diagnosed is. 2374 CCC->setTypoName(II); 2375 if (SS.isValid()) 2376 CCC->setTypoNNS(SS.getScopeRep()); 2377 } 2378 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2379 // a template name, but we happen to have always already looked up the name 2380 // before we get here if it must be a template name. 2381 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2382 None, &TE)) { 2383 if (TE && KeywordReplacement) { 2384 auto &State = getTypoExprState(TE); 2385 auto BestTC = State.Consumer->getNextCorrection(); 2386 if (BestTC.isKeyword()) { 2387 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2388 if (State.DiagHandler) 2389 State.DiagHandler(BestTC); 2390 KeywordReplacement->startToken(); 2391 KeywordReplacement->setKind(II->getTokenID()); 2392 KeywordReplacement->setIdentifierInfo(II); 2393 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2394 // Clean up the state associated with the TypoExpr, since it has 2395 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2396 clearDelayedTypo(TE); 2397 // Signal that a correction to a keyword was performed by returning a 2398 // valid-but-null ExprResult. 2399 return (Expr*)nullptr; 2400 } 2401 State.Consumer->resetCorrectionStream(); 2402 } 2403 return TE ? TE : ExprError(); 2404 } 2405 2406 assert(!R.empty() && 2407 "DiagnoseEmptyLookup returned false but added no results"); 2408 2409 // If we found an Objective-C instance variable, let 2410 // LookupInObjCMethod build the appropriate expression to 2411 // reference the ivar. 2412 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2413 R.clear(); 2414 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2415 // In a hopelessly buggy code, Objective-C instance variable 2416 // lookup fails and no expression will be built to reference it. 2417 if (!E.isInvalid() && !E.get()) 2418 return ExprError(); 2419 return E; 2420 } 2421 } 2422 2423 // This is guaranteed from this point on. 2424 assert(!R.empty() || ADL); 2425 2426 // Check whether this might be a C++ implicit instance member access. 2427 // C++ [class.mfct.non-static]p3: 2428 // When an id-expression that is not part of a class member access 2429 // syntax and not used to form a pointer to member is used in the 2430 // body of a non-static member function of class X, if name lookup 2431 // resolves the name in the id-expression to a non-static non-type 2432 // member of some class C, the id-expression is transformed into a 2433 // class member access expression using (*this) as the 2434 // postfix-expression to the left of the . operator. 2435 // 2436 // But we don't actually need to do this for '&' operands if R 2437 // resolved to a function or overloaded function set, because the 2438 // expression is ill-formed if it actually works out to be a 2439 // non-static member function: 2440 // 2441 // C++ [expr.ref]p4: 2442 // Otherwise, if E1.E2 refers to a non-static member function. . . 2443 // [t]he expression can be used only as the left-hand operand of a 2444 // member function call. 2445 // 2446 // There are other safeguards against such uses, but it's important 2447 // to get this right here so that we don't end up making a 2448 // spuriously dependent expression if we're inside a dependent 2449 // instance method. 2450 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2451 bool MightBeImplicitMember; 2452 if (!IsAddressOfOperand) 2453 MightBeImplicitMember = true; 2454 else if (!SS.isEmpty()) 2455 MightBeImplicitMember = false; 2456 else if (R.isOverloadedResult()) 2457 MightBeImplicitMember = false; 2458 else if (R.isUnresolvableResult()) 2459 MightBeImplicitMember = true; 2460 else 2461 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2462 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2463 isa<MSPropertyDecl>(R.getFoundDecl()); 2464 2465 if (MightBeImplicitMember) 2466 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2467 R, TemplateArgs, S); 2468 } 2469 2470 if (TemplateArgs || TemplateKWLoc.isValid()) { 2471 2472 // In C++1y, if this is a variable template id, then check it 2473 // in BuildTemplateIdExpr(). 2474 // The single lookup result must be a variable template declaration. 2475 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2476 Id.TemplateId->Kind == TNK_Var_template) { 2477 assert(R.getAsSingle<VarTemplateDecl>() && 2478 "There should only be one declaration found."); 2479 } 2480 2481 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2482 } 2483 2484 return BuildDeclarationNameExpr(SS, R, ADL); 2485 } 2486 2487 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2488 /// declaration name, generally during template instantiation. 2489 /// There's a large number of things which don't need to be done along 2490 /// this path. 2491 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2492 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2493 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2494 DeclContext *DC = computeDeclContext(SS, false); 2495 if (!DC) 2496 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2497 NameInfo, /*TemplateArgs=*/nullptr); 2498 2499 if (RequireCompleteDeclContext(SS, DC)) 2500 return ExprError(); 2501 2502 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2503 LookupQualifiedName(R, DC); 2504 2505 if (R.isAmbiguous()) 2506 return ExprError(); 2507 2508 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2509 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2510 NameInfo, /*TemplateArgs=*/nullptr); 2511 2512 if (R.empty()) { 2513 Diag(NameInfo.getLoc(), diag::err_no_member) 2514 << NameInfo.getName() << DC << SS.getRange(); 2515 return ExprError(); 2516 } 2517 2518 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2519 // Diagnose a missing typename if this resolved unambiguously to a type in 2520 // a dependent context. If we can recover with a type, downgrade this to 2521 // a warning in Microsoft compatibility mode. 2522 unsigned DiagID = diag::err_typename_missing; 2523 if (RecoveryTSI && getLangOpts().MSVCCompat) 2524 DiagID = diag::ext_typename_missing; 2525 SourceLocation Loc = SS.getBeginLoc(); 2526 auto D = Diag(Loc, DiagID); 2527 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2528 << SourceRange(Loc, NameInfo.getEndLoc()); 2529 2530 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2531 // context. 2532 if (!RecoveryTSI) 2533 return ExprError(); 2534 2535 // Only issue the fixit if we're prepared to recover. 2536 D << FixItHint::CreateInsertion(Loc, "typename "); 2537 2538 // Recover by pretending this was an elaborated type. 2539 QualType Ty = Context.getTypeDeclType(TD); 2540 TypeLocBuilder TLB; 2541 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2542 2543 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2544 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2545 QTL.setElaboratedKeywordLoc(SourceLocation()); 2546 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2547 2548 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2549 2550 return ExprEmpty(); 2551 } 2552 2553 // Defend against this resolving to an implicit member access. We usually 2554 // won't get here if this might be a legitimate a class member (we end up in 2555 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2556 // a pointer-to-member or in an unevaluated context in C++11. 2557 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2558 return BuildPossibleImplicitMemberExpr(SS, 2559 /*TemplateKWLoc=*/SourceLocation(), 2560 R, /*TemplateArgs=*/nullptr, S); 2561 2562 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2563 } 2564 2565 /// The parser has read a name in, and Sema has detected that we're currently 2566 /// inside an ObjC method. Perform some additional checks and determine if we 2567 /// should form a reference to an ivar. 2568 /// 2569 /// Ideally, most of this would be done by lookup, but there's 2570 /// actually quite a lot of extra work involved. 2571 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2572 IdentifierInfo *II) { 2573 SourceLocation Loc = Lookup.getNameLoc(); 2574 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2575 2576 // Check for error condition which is already reported. 2577 if (!CurMethod) 2578 return DeclResult(true); 2579 2580 // There are two cases to handle here. 1) scoped lookup could have failed, 2581 // in which case we should look for an ivar. 2) scoped lookup could have 2582 // found a decl, but that decl is outside the current instance method (i.e. 2583 // a global variable). In these two cases, we do a lookup for an ivar with 2584 // this name, if the lookup sucedes, we replace it our current decl. 2585 2586 // If we're in a class method, we don't normally want to look for 2587 // ivars. But if we don't find anything else, and there's an 2588 // ivar, that's an error. 2589 bool IsClassMethod = CurMethod->isClassMethod(); 2590 2591 bool LookForIvars; 2592 if (Lookup.empty()) 2593 LookForIvars = true; 2594 else if (IsClassMethod) 2595 LookForIvars = false; 2596 else 2597 LookForIvars = (Lookup.isSingleResult() && 2598 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2599 ObjCInterfaceDecl *IFace = nullptr; 2600 if (LookForIvars) { 2601 IFace = CurMethod->getClassInterface(); 2602 ObjCInterfaceDecl *ClassDeclared; 2603 ObjCIvarDecl *IV = nullptr; 2604 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2605 // Diagnose using an ivar in a class method. 2606 if (IsClassMethod) { 2607 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2608 return DeclResult(true); 2609 } 2610 2611 // Diagnose the use of an ivar outside of the declaring class. 2612 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2613 !declaresSameEntity(ClassDeclared, IFace) && 2614 !getLangOpts().DebuggerSupport) 2615 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2616 2617 // Success. 2618 return IV; 2619 } 2620 } else if (CurMethod->isInstanceMethod()) { 2621 // We should warn if a local variable hides an ivar. 2622 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2623 ObjCInterfaceDecl *ClassDeclared; 2624 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2625 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2626 declaresSameEntity(IFace, ClassDeclared)) 2627 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2628 } 2629 } 2630 } else if (Lookup.isSingleResult() && 2631 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2632 // If accessing a stand-alone ivar in a class method, this is an error. 2633 if (const ObjCIvarDecl *IV = 2634 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2635 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2636 return DeclResult(true); 2637 } 2638 } 2639 2640 // Didn't encounter an error, didn't find an ivar. 2641 return DeclResult(false); 2642 } 2643 2644 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2645 ObjCIvarDecl *IV) { 2646 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2647 assert(CurMethod && CurMethod->isInstanceMethod() && 2648 "should not reference ivar from this context"); 2649 2650 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2651 assert(IFace && "should not reference ivar from this context"); 2652 2653 // If we're referencing an invalid decl, just return this as a silent 2654 // error node. The error diagnostic was already emitted on the decl. 2655 if (IV->isInvalidDecl()) 2656 return ExprError(); 2657 2658 // Check if referencing a field with __attribute__((deprecated)). 2659 if (DiagnoseUseOfDecl(IV, Loc)) 2660 return ExprError(); 2661 2662 // FIXME: This should use a new expr for a direct reference, don't 2663 // turn this into Self->ivar, just return a BareIVarExpr or something. 2664 IdentifierInfo &II = Context.Idents.get("self"); 2665 UnqualifiedId SelfName; 2666 SelfName.setIdentifier(&II, SourceLocation()); 2667 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2668 CXXScopeSpec SelfScopeSpec; 2669 SourceLocation TemplateKWLoc; 2670 ExprResult SelfExpr = 2671 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2672 /*HasTrailingLParen=*/false, 2673 /*IsAddressOfOperand=*/false); 2674 if (SelfExpr.isInvalid()) 2675 return ExprError(); 2676 2677 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2678 if (SelfExpr.isInvalid()) 2679 return ExprError(); 2680 2681 MarkAnyDeclReferenced(Loc, IV, true); 2682 2683 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2684 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2685 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2686 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2687 2688 ObjCIvarRefExpr *Result = new (Context) 2689 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2690 IV->getLocation(), SelfExpr.get(), true, true); 2691 2692 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2693 if (!isUnevaluatedContext() && 2694 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2695 getCurFunction()->recordUseOfWeak(Result); 2696 } 2697 if (getLangOpts().ObjCAutoRefCount) 2698 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2699 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2700 2701 return Result; 2702 } 2703 2704 /// The parser has read a name in, and Sema has detected that we're currently 2705 /// inside an ObjC method. Perform some additional checks and determine if we 2706 /// should form a reference to an ivar. If so, build an expression referencing 2707 /// that ivar. 2708 ExprResult 2709 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2710 IdentifierInfo *II, bool AllowBuiltinCreation) { 2711 // FIXME: Integrate this lookup step into LookupParsedName. 2712 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2713 if (Ivar.isInvalid()) 2714 return ExprError(); 2715 if (Ivar.isUsable()) 2716 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2717 cast<ObjCIvarDecl>(Ivar.get())); 2718 2719 if (Lookup.empty() && II && AllowBuiltinCreation) 2720 LookupBuiltin(Lookup); 2721 2722 // Sentinel value saying that we didn't do anything special. 2723 return ExprResult(false); 2724 } 2725 2726 /// Cast a base object to a member's actual type. 2727 /// 2728 /// Logically this happens in three phases: 2729 /// 2730 /// * First we cast from the base type to the naming class. 2731 /// The naming class is the class into which we were looking 2732 /// when we found the member; it's the qualifier type if a 2733 /// qualifier was provided, and otherwise it's the base type. 2734 /// 2735 /// * Next we cast from the naming class to the declaring class. 2736 /// If the member we found was brought into a class's scope by 2737 /// a using declaration, this is that class; otherwise it's 2738 /// the class declaring the member. 2739 /// 2740 /// * Finally we cast from the declaring class to the "true" 2741 /// declaring class of the member. This conversion does not 2742 /// obey access control. 2743 ExprResult 2744 Sema::PerformObjectMemberConversion(Expr *From, 2745 NestedNameSpecifier *Qualifier, 2746 NamedDecl *FoundDecl, 2747 NamedDecl *Member) { 2748 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2749 if (!RD) 2750 return From; 2751 2752 QualType DestRecordType; 2753 QualType DestType; 2754 QualType FromRecordType; 2755 QualType FromType = From->getType(); 2756 bool PointerConversions = false; 2757 if (isa<FieldDecl>(Member)) { 2758 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2759 auto FromPtrType = FromType->getAs<PointerType>(); 2760 DestRecordType = Context.getAddrSpaceQualType( 2761 DestRecordType, FromPtrType 2762 ? FromType->getPointeeType().getAddressSpace() 2763 : FromType.getAddressSpace()); 2764 2765 if (FromPtrType) { 2766 DestType = Context.getPointerType(DestRecordType); 2767 FromRecordType = FromPtrType->getPointeeType(); 2768 PointerConversions = true; 2769 } else { 2770 DestType = DestRecordType; 2771 FromRecordType = FromType; 2772 } 2773 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2774 if (Method->isStatic()) 2775 return From; 2776 2777 DestType = Method->getThisType(); 2778 DestRecordType = DestType->getPointeeType(); 2779 2780 if (FromType->getAs<PointerType>()) { 2781 FromRecordType = FromType->getPointeeType(); 2782 PointerConversions = true; 2783 } else { 2784 FromRecordType = FromType; 2785 DestType = DestRecordType; 2786 } 2787 2788 LangAS FromAS = FromRecordType.getAddressSpace(); 2789 LangAS DestAS = DestRecordType.getAddressSpace(); 2790 if (FromAS != DestAS) { 2791 QualType FromRecordTypeWithoutAS = 2792 Context.removeAddrSpaceQualType(FromRecordType); 2793 QualType FromTypeWithDestAS = 2794 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2795 if (PointerConversions) 2796 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2797 From = ImpCastExprToType(From, FromTypeWithDestAS, 2798 CK_AddressSpaceConversion, From->getValueKind()) 2799 .get(); 2800 } 2801 } else { 2802 // No conversion necessary. 2803 return From; 2804 } 2805 2806 if (DestType->isDependentType() || FromType->isDependentType()) 2807 return From; 2808 2809 // If the unqualified types are the same, no conversion is necessary. 2810 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2811 return From; 2812 2813 SourceRange FromRange = From->getSourceRange(); 2814 SourceLocation FromLoc = FromRange.getBegin(); 2815 2816 ExprValueKind VK = From->getValueKind(); 2817 2818 // C++ [class.member.lookup]p8: 2819 // [...] Ambiguities can often be resolved by qualifying a name with its 2820 // class name. 2821 // 2822 // If the member was a qualified name and the qualified referred to a 2823 // specific base subobject type, we'll cast to that intermediate type 2824 // first and then to the object in which the member is declared. That allows 2825 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2826 // 2827 // class Base { public: int x; }; 2828 // class Derived1 : public Base { }; 2829 // class Derived2 : public Base { }; 2830 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2831 // 2832 // void VeryDerived::f() { 2833 // x = 17; // error: ambiguous base subobjects 2834 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2835 // } 2836 if (Qualifier && Qualifier->getAsType()) { 2837 QualType QType = QualType(Qualifier->getAsType(), 0); 2838 assert(QType->isRecordType() && "lookup done with non-record type"); 2839 2840 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2841 2842 // In C++98, the qualifier type doesn't actually have to be a base 2843 // type of the object type, in which case we just ignore it. 2844 // Otherwise build the appropriate casts. 2845 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2846 CXXCastPath BasePath; 2847 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2848 FromLoc, FromRange, &BasePath)) 2849 return ExprError(); 2850 2851 if (PointerConversions) 2852 QType = Context.getPointerType(QType); 2853 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2854 VK, &BasePath).get(); 2855 2856 FromType = QType; 2857 FromRecordType = QRecordType; 2858 2859 // If the qualifier type was the same as the destination type, 2860 // we're done. 2861 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2862 return From; 2863 } 2864 } 2865 2866 bool IgnoreAccess = false; 2867 2868 // If we actually found the member through a using declaration, cast 2869 // down to the using declaration's type. 2870 // 2871 // Pointer equality is fine here because only one declaration of a 2872 // class ever has member declarations. 2873 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2874 assert(isa<UsingShadowDecl>(FoundDecl)); 2875 QualType URecordType = Context.getTypeDeclType( 2876 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2877 2878 // We only need to do this if the naming-class to declaring-class 2879 // conversion is non-trivial. 2880 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2881 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2882 CXXCastPath BasePath; 2883 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2884 FromLoc, FromRange, &BasePath)) 2885 return ExprError(); 2886 2887 QualType UType = URecordType; 2888 if (PointerConversions) 2889 UType = Context.getPointerType(UType); 2890 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2891 VK, &BasePath).get(); 2892 FromType = UType; 2893 FromRecordType = URecordType; 2894 } 2895 2896 // We don't do access control for the conversion from the 2897 // declaring class to the true declaring class. 2898 IgnoreAccess = true; 2899 } 2900 2901 CXXCastPath BasePath; 2902 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2903 FromLoc, FromRange, &BasePath, 2904 IgnoreAccess)) 2905 return ExprError(); 2906 2907 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2908 VK, &BasePath); 2909 } 2910 2911 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2912 const LookupResult &R, 2913 bool HasTrailingLParen) { 2914 // Only when used directly as the postfix-expression of a call. 2915 if (!HasTrailingLParen) 2916 return false; 2917 2918 // Never if a scope specifier was provided. 2919 if (SS.isSet()) 2920 return false; 2921 2922 // Only in C++ or ObjC++. 2923 if (!getLangOpts().CPlusPlus) 2924 return false; 2925 2926 // Turn off ADL when we find certain kinds of declarations during 2927 // normal lookup: 2928 for (NamedDecl *D : R) { 2929 // C++0x [basic.lookup.argdep]p3: 2930 // -- a declaration of a class member 2931 // Since using decls preserve this property, we check this on the 2932 // original decl. 2933 if (D->isCXXClassMember()) 2934 return false; 2935 2936 // C++0x [basic.lookup.argdep]p3: 2937 // -- a block-scope function declaration that is not a 2938 // using-declaration 2939 // NOTE: we also trigger this for function templates (in fact, we 2940 // don't check the decl type at all, since all other decl types 2941 // turn off ADL anyway). 2942 if (isa<UsingShadowDecl>(D)) 2943 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2944 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2945 return false; 2946 2947 // C++0x [basic.lookup.argdep]p3: 2948 // -- a declaration that is neither a function or a function 2949 // template 2950 // And also for builtin functions. 2951 if (isa<FunctionDecl>(D)) { 2952 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2953 2954 // But also builtin functions. 2955 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2956 return false; 2957 } else if (!isa<FunctionTemplateDecl>(D)) 2958 return false; 2959 } 2960 2961 return true; 2962 } 2963 2964 2965 /// Diagnoses obvious problems with the use of the given declaration 2966 /// as an expression. This is only actually called for lookups that 2967 /// were not overloaded, and it doesn't promise that the declaration 2968 /// will in fact be used. 2969 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2970 if (D->isInvalidDecl()) 2971 return true; 2972 2973 if (isa<TypedefNameDecl>(D)) { 2974 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2975 return true; 2976 } 2977 2978 if (isa<ObjCInterfaceDecl>(D)) { 2979 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2980 return true; 2981 } 2982 2983 if (isa<NamespaceDecl>(D)) { 2984 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2985 return true; 2986 } 2987 2988 return false; 2989 } 2990 2991 // Certain multiversion types should be treated as overloaded even when there is 2992 // only one result. 2993 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2994 assert(R.isSingleResult() && "Expected only a single result"); 2995 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2996 return FD && 2997 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2998 } 2999 3000 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3001 LookupResult &R, bool NeedsADL, 3002 bool AcceptInvalidDecl) { 3003 // If this is a single, fully-resolved result and we don't need ADL, 3004 // just build an ordinary singleton decl ref. 3005 if (!NeedsADL && R.isSingleResult() && 3006 !R.getAsSingle<FunctionTemplateDecl>() && 3007 !ShouldLookupResultBeMultiVersionOverload(R)) 3008 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3009 R.getRepresentativeDecl(), nullptr, 3010 AcceptInvalidDecl); 3011 3012 // We only need to check the declaration if there's exactly one 3013 // result, because in the overloaded case the results can only be 3014 // functions and function templates. 3015 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3016 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3017 return ExprError(); 3018 3019 // Otherwise, just build an unresolved lookup expression. Suppress 3020 // any lookup-related diagnostics; we'll hash these out later, when 3021 // we've picked a target. 3022 R.suppressDiagnostics(); 3023 3024 UnresolvedLookupExpr *ULE 3025 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3026 SS.getWithLocInContext(Context), 3027 R.getLookupNameInfo(), 3028 NeedsADL, R.isOverloadedResult(), 3029 R.begin(), R.end()); 3030 3031 return ULE; 3032 } 3033 3034 static void 3035 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3036 ValueDecl *var, DeclContext *DC); 3037 3038 /// Complete semantic analysis for a reference to the given declaration. 3039 ExprResult Sema::BuildDeclarationNameExpr( 3040 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3041 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3042 bool AcceptInvalidDecl) { 3043 assert(D && "Cannot refer to a NULL declaration"); 3044 assert(!isa<FunctionTemplateDecl>(D) && 3045 "Cannot refer unambiguously to a function template"); 3046 3047 SourceLocation Loc = NameInfo.getLoc(); 3048 if (CheckDeclInExpr(*this, Loc, D)) 3049 return ExprError(); 3050 3051 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3052 // Specifically diagnose references to class templates that are missing 3053 // a template argument list. 3054 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3055 return ExprError(); 3056 } 3057 3058 // Make sure that we're referring to a value. 3059 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3060 if (!VD) { 3061 Diag(Loc, diag::err_ref_non_value) 3062 << D << SS.getRange(); 3063 Diag(D->getLocation(), diag::note_declared_at); 3064 return ExprError(); 3065 } 3066 3067 // Check whether this declaration can be used. Note that we suppress 3068 // this check when we're going to perform argument-dependent lookup 3069 // on this function name, because this might not be the function 3070 // that overload resolution actually selects. 3071 if (DiagnoseUseOfDecl(VD, Loc)) 3072 return ExprError(); 3073 3074 // Only create DeclRefExpr's for valid Decl's. 3075 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3076 return ExprError(); 3077 3078 // Handle members of anonymous structs and unions. If we got here, 3079 // and the reference is to a class member indirect field, then this 3080 // must be the subject of a pointer-to-member expression. 3081 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3082 if (!indirectField->isCXXClassMember()) 3083 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3084 indirectField); 3085 3086 { 3087 QualType type = VD->getType(); 3088 if (type.isNull()) 3089 return ExprError(); 3090 ExprValueKind valueKind = VK_RValue; 3091 3092 switch (D->getKind()) { 3093 // Ignore all the non-ValueDecl kinds. 3094 #define ABSTRACT_DECL(kind) 3095 #define VALUE(type, base) 3096 #define DECL(type, base) \ 3097 case Decl::type: 3098 #include "clang/AST/DeclNodes.inc" 3099 llvm_unreachable("invalid value decl kind"); 3100 3101 // These shouldn't make it here. 3102 case Decl::ObjCAtDefsField: 3103 llvm_unreachable("forming non-member reference to ivar?"); 3104 3105 // Enum constants are always r-values and never references. 3106 // Unresolved using declarations are dependent. 3107 case Decl::EnumConstant: 3108 case Decl::UnresolvedUsingValue: 3109 case Decl::OMPDeclareReduction: 3110 case Decl::OMPDeclareMapper: 3111 valueKind = VK_RValue; 3112 break; 3113 3114 // Fields and indirect fields that got here must be for 3115 // pointer-to-member expressions; we just call them l-values for 3116 // internal consistency, because this subexpression doesn't really 3117 // exist in the high-level semantics. 3118 case Decl::Field: 3119 case Decl::IndirectField: 3120 case Decl::ObjCIvar: 3121 assert(getLangOpts().CPlusPlus && 3122 "building reference to field in C?"); 3123 3124 // These can't have reference type in well-formed programs, but 3125 // for internal consistency we do this anyway. 3126 type = type.getNonReferenceType(); 3127 valueKind = VK_LValue; 3128 break; 3129 3130 // Non-type template parameters are either l-values or r-values 3131 // depending on the type. 3132 case Decl::NonTypeTemplateParm: { 3133 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3134 type = reftype->getPointeeType(); 3135 valueKind = VK_LValue; // even if the parameter is an r-value reference 3136 break; 3137 } 3138 3139 // For non-references, we need to strip qualifiers just in case 3140 // the template parameter was declared as 'const int' or whatever. 3141 valueKind = VK_RValue; 3142 type = type.getUnqualifiedType(); 3143 break; 3144 } 3145 3146 case Decl::Var: 3147 case Decl::VarTemplateSpecialization: 3148 case Decl::VarTemplatePartialSpecialization: 3149 case Decl::Decomposition: 3150 case Decl::OMPCapturedExpr: 3151 // In C, "extern void blah;" is valid and is an r-value. 3152 if (!getLangOpts().CPlusPlus && 3153 !type.hasQualifiers() && 3154 type->isVoidType()) { 3155 valueKind = VK_RValue; 3156 break; 3157 } 3158 LLVM_FALLTHROUGH; 3159 3160 case Decl::ImplicitParam: 3161 case Decl::ParmVar: { 3162 // These are always l-values. 3163 valueKind = VK_LValue; 3164 type = type.getNonReferenceType(); 3165 3166 // FIXME: Does the addition of const really only apply in 3167 // potentially-evaluated contexts? Since the variable isn't actually 3168 // captured in an unevaluated context, it seems that the answer is no. 3169 if (!isUnevaluatedContext()) { 3170 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3171 if (!CapturedType.isNull()) 3172 type = CapturedType; 3173 } 3174 3175 break; 3176 } 3177 3178 case Decl::Binding: { 3179 // These are always lvalues. 3180 valueKind = VK_LValue; 3181 type = type.getNonReferenceType(); 3182 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3183 // decides how that's supposed to work. 3184 auto *BD = cast<BindingDecl>(VD); 3185 if (BD->getDeclContext() != CurContext) { 3186 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3187 if (DD && DD->hasLocalStorage()) 3188 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3189 } 3190 break; 3191 } 3192 3193 case Decl::Function: { 3194 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3195 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3196 type = Context.BuiltinFnTy; 3197 valueKind = VK_RValue; 3198 break; 3199 } 3200 } 3201 3202 const FunctionType *fty = type->castAs<FunctionType>(); 3203 3204 // If we're referring to a function with an __unknown_anytype 3205 // result type, make the entire expression __unknown_anytype. 3206 if (fty->getReturnType() == Context.UnknownAnyTy) { 3207 type = Context.UnknownAnyTy; 3208 valueKind = VK_RValue; 3209 break; 3210 } 3211 3212 // Functions are l-values in C++. 3213 if (getLangOpts().CPlusPlus) { 3214 valueKind = VK_LValue; 3215 break; 3216 } 3217 3218 // C99 DR 316 says that, if a function type comes from a 3219 // function definition (without a prototype), that type is only 3220 // used for checking compatibility. Therefore, when referencing 3221 // the function, we pretend that we don't have the full function 3222 // type. 3223 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3224 isa<FunctionProtoType>(fty)) 3225 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3226 fty->getExtInfo()); 3227 3228 // Functions are r-values in C. 3229 valueKind = VK_RValue; 3230 break; 3231 } 3232 3233 case Decl::CXXDeductionGuide: 3234 llvm_unreachable("building reference to deduction guide"); 3235 3236 case Decl::MSProperty: 3237 valueKind = VK_LValue; 3238 break; 3239 3240 case Decl::CXXMethod: 3241 // If we're referring to a method with an __unknown_anytype 3242 // result type, make the entire expression __unknown_anytype. 3243 // This should only be possible with a type written directly. 3244 if (const FunctionProtoType *proto 3245 = dyn_cast<FunctionProtoType>(VD->getType())) 3246 if (proto->getReturnType() == Context.UnknownAnyTy) { 3247 type = Context.UnknownAnyTy; 3248 valueKind = VK_RValue; 3249 break; 3250 } 3251 3252 // C++ methods are l-values if static, r-values if non-static. 3253 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3254 valueKind = VK_LValue; 3255 break; 3256 } 3257 LLVM_FALLTHROUGH; 3258 3259 case Decl::CXXConversion: 3260 case Decl::CXXDestructor: 3261 case Decl::CXXConstructor: 3262 valueKind = VK_RValue; 3263 break; 3264 } 3265 3266 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3267 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3268 TemplateArgs); 3269 } 3270 } 3271 3272 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3273 SmallString<32> &Target) { 3274 Target.resize(CharByteWidth * (Source.size() + 1)); 3275 char *ResultPtr = &Target[0]; 3276 const llvm::UTF8 *ErrorPtr; 3277 bool success = 3278 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3279 (void)success; 3280 assert(success); 3281 Target.resize(ResultPtr - &Target[0]); 3282 } 3283 3284 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3285 PredefinedExpr::IdentKind IK) { 3286 // Pick the current block, lambda, captured statement or function. 3287 Decl *currentDecl = nullptr; 3288 if (const BlockScopeInfo *BSI = getCurBlock()) 3289 currentDecl = BSI->TheDecl; 3290 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3291 currentDecl = LSI->CallOperator; 3292 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3293 currentDecl = CSI->TheCapturedDecl; 3294 else 3295 currentDecl = getCurFunctionOrMethodDecl(); 3296 3297 if (!currentDecl) { 3298 Diag(Loc, diag::ext_predef_outside_function); 3299 currentDecl = Context.getTranslationUnitDecl(); 3300 } 3301 3302 QualType ResTy; 3303 StringLiteral *SL = nullptr; 3304 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3305 ResTy = Context.DependentTy; 3306 else { 3307 // Pre-defined identifiers are of type char[x], where x is the length of 3308 // the string. 3309 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3310 unsigned Length = Str.length(); 3311 3312 llvm::APInt LengthI(32, Length + 1); 3313 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3314 ResTy = 3315 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3316 SmallString<32> RawChars; 3317 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3318 Str, RawChars); 3319 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3320 ArrayType::Normal, 3321 /*IndexTypeQuals*/ 0); 3322 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3323 /*Pascal*/ false, ResTy, Loc); 3324 } else { 3325 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3326 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3327 ArrayType::Normal, 3328 /*IndexTypeQuals*/ 0); 3329 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3330 /*Pascal*/ false, ResTy, Loc); 3331 } 3332 } 3333 3334 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3335 } 3336 3337 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3338 PredefinedExpr::IdentKind IK; 3339 3340 switch (Kind) { 3341 default: llvm_unreachable("Unknown simple primary expr!"); 3342 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3343 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3344 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3345 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3346 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3347 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3348 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3349 } 3350 3351 return BuildPredefinedExpr(Loc, IK); 3352 } 3353 3354 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3355 SmallString<16> CharBuffer; 3356 bool Invalid = false; 3357 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3358 if (Invalid) 3359 return ExprError(); 3360 3361 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3362 PP, Tok.getKind()); 3363 if (Literal.hadError()) 3364 return ExprError(); 3365 3366 QualType Ty; 3367 if (Literal.isWide()) 3368 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3369 else if (Literal.isUTF8() && getLangOpts().Char8) 3370 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3371 else if (Literal.isUTF16()) 3372 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3373 else if (Literal.isUTF32()) 3374 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3375 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3376 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3377 else 3378 Ty = Context.CharTy; // 'x' -> char in C++ 3379 3380 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3381 if (Literal.isWide()) 3382 Kind = CharacterLiteral::Wide; 3383 else if (Literal.isUTF16()) 3384 Kind = CharacterLiteral::UTF16; 3385 else if (Literal.isUTF32()) 3386 Kind = CharacterLiteral::UTF32; 3387 else if (Literal.isUTF8()) 3388 Kind = CharacterLiteral::UTF8; 3389 3390 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3391 Tok.getLocation()); 3392 3393 if (Literal.getUDSuffix().empty()) 3394 return Lit; 3395 3396 // We're building a user-defined literal. 3397 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3398 SourceLocation UDSuffixLoc = 3399 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3400 3401 // Make sure we're allowed user-defined literals here. 3402 if (!UDLScope) 3403 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3404 3405 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3406 // operator "" X (ch) 3407 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3408 Lit, Tok.getLocation()); 3409 } 3410 3411 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3412 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3413 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3414 Context.IntTy, Loc); 3415 } 3416 3417 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3418 QualType Ty, SourceLocation Loc) { 3419 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3420 3421 using llvm::APFloat; 3422 APFloat Val(Format); 3423 3424 APFloat::opStatus result = Literal.GetFloatValue(Val); 3425 3426 // Overflow is always an error, but underflow is only an error if 3427 // we underflowed to zero (APFloat reports denormals as underflow). 3428 if ((result & APFloat::opOverflow) || 3429 ((result & APFloat::opUnderflow) && Val.isZero())) { 3430 unsigned diagnostic; 3431 SmallString<20> buffer; 3432 if (result & APFloat::opOverflow) { 3433 diagnostic = diag::warn_float_overflow; 3434 APFloat::getLargest(Format).toString(buffer); 3435 } else { 3436 diagnostic = diag::warn_float_underflow; 3437 APFloat::getSmallest(Format).toString(buffer); 3438 } 3439 3440 S.Diag(Loc, diagnostic) 3441 << Ty 3442 << StringRef(buffer.data(), buffer.size()); 3443 } 3444 3445 bool isExact = (result == APFloat::opOK); 3446 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3447 } 3448 3449 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3450 assert(E && "Invalid expression"); 3451 3452 if (E->isValueDependent()) 3453 return false; 3454 3455 QualType QT = E->getType(); 3456 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3457 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3458 return true; 3459 } 3460 3461 llvm::APSInt ValueAPS; 3462 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3463 3464 if (R.isInvalid()) 3465 return true; 3466 3467 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3468 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3469 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3470 << ValueAPS.toString(10) << ValueIsPositive; 3471 return true; 3472 } 3473 3474 return false; 3475 } 3476 3477 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3478 // Fast path for a single digit (which is quite common). A single digit 3479 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3480 if (Tok.getLength() == 1) { 3481 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3482 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3483 } 3484 3485 SmallString<128> SpellingBuffer; 3486 // NumericLiteralParser wants to overread by one character. Add padding to 3487 // the buffer in case the token is copied to the buffer. If getSpelling() 3488 // returns a StringRef to the memory buffer, it should have a null char at 3489 // the EOF, so it is also safe. 3490 SpellingBuffer.resize(Tok.getLength() + 1); 3491 3492 // Get the spelling of the token, which eliminates trigraphs, etc. 3493 bool Invalid = false; 3494 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3495 if (Invalid) 3496 return ExprError(); 3497 3498 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3499 if (Literal.hadError) 3500 return ExprError(); 3501 3502 if (Literal.hasUDSuffix()) { 3503 // We're building a user-defined literal. 3504 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3505 SourceLocation UDSuffixLoc = 3506 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3507 3508 // Make sure we're allowed user-defined literals here. 3509 if (!UDLScope) 3510 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3511 3512 QualType CookedTy; 3513 if (Literal.isFloatingLiteral()) { 3514 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3515 // long double, the literal is treated as a call of the form 3516 // operator "" X (f L) 3517 CookedTy = Context.LongDoubleTy; 3518 } else { 3519 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3520 // unsigned long long, the literal is treated as a call of the form 3521 // operator "" X (n ULL) 3522 CookedTy = Context.UnsignedLongLongTy; 3523 } 3524 3525 DeclarationName OpName = 3526 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3527 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3528 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3529 3530 SourceLocation TokLoc = Tok.getLocation(); 3531 3532 // Perform literal operator lookup to determine if we're building a raw 3533 // literal or a cooked one. 3534 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3535 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3536 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3537 /*AllowStringTemplate*/ false, 3538 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3539 case LOLR_ErrorNoDiagnostic: 3540 // Lookup failure for imaginary constants isn't fatal, there's still the 3541 // GNU extension producing _Complex types. 3542 break; 3543 case LOLR_Error: 3544 return ExprError(); 3545 case LOLR_Cooked: { 3546 Expr *Lit; 3547 if (Literal.isFloatingLiteral()) { 3548 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3549 } else { 3550 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3551 if (Literal.GetIntegerValue(ResultVal)) 3552 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3553 << /* Unsigned */ 1; 3554 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3555 Tok.getLocation()); 3556 } 3557 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3558 } 3559 3560 case LOLR_Raw: { 3561 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3562 // literal is treated as a call of the form 3563 // operator "" X ("n") 3564 unsigned Length = Literal.getUDSuffixOffset(); 3565 QualType StrTy = Context.getConstantArrayType( 3566 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3567 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3568 Expr *Lit = StringLiteral::Create( 3569 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3570 /*Pascal*/false, StrTy, &TokLoc, 1); 3571 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3572 } 3573 3574 case LOLR_Template: { 3575 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3576 // template), L is treated as a call fo the form 3577 // operator "" X <'c1', 'c2', ... 'ck'>() 3578 // where n is the source character sequence c1 c2 ... ck. 3579 TemplateArgumentListInfo ExplicitArgs; 3580 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3581 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3582 llvm::APSInt Value(CharBits, CharIsUnsigned); 3583 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3584 Value = TokSpelling[I]; 3585 TemplateArgument Arg(Context, Value, Context.CharTy); 3586 TemplateArgumentLocInfo ArgInfo; 3587 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3588 } 3589 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3590 &ExplicitArgs); 3591 } 3592 case LOLR_StringTemplate: 3593 llvm_unreachable("unexpected literal operator lookup result"); 3594 } 3595 } 3596 3597 Expr *Res; 3598 3599 if (Literal.isFixedPointLiteral()) { 3600 QualType Ty; 3601 3602 if (Literal.isAccum) { 3603 if (Literal.isHalf) { 3604 Ty = Context.ShortAccumTy; 3605 } else if (Literal.isLong) { 3606 Ty = Context.LongAccumTy; 3607 } else { 3608 Ty = Context.AccumTy; 3609 } 3610 } else if (Literal.isFract) { 3611 if (Literal.isHalf) { 3612 Ty = Context.ShortFractTy; 3613 } else if (Literal.isLong) { 3614 Ty = Context.LongFractTy; 3615 } else { 3616 Ty = Context.FractTy; 3617 } 3618 } 3619 3620 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3621 3622 bool isSigned = !Literal.isUnsigned; 3623 unsigned scale = Context.getFixedPointScale(Ty); 3624 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3625 3626 llvm::APInt Val(bit_width, 0, isSigned); 3627 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3628 bool ValIsZero = Val.isNullValue() && !Overflowed; 3629 3630 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3631 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3632 // Clause 6.4.4 - The value of a constant shall be in the range of 3633 // representable values for its type, with exception for constants of a 3634 // fract type with a value of exactly 1; such a constant shall denote 3635 // the maximal value for the type. 3636 --Val; 3637 else if (Val.ugt(MaxVal) || Overflowed) 3638 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3639 3640 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3641 Tok.getLocation(), scale); 3642 } else if (Literal.isFloatingLiteral()) { 3643 QualType Ty; 3644 if (Literal.isHalf){ 3645 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3646 Ty = Context.HalfTy; 3647 else { 3648 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3649 return ExprError(); 3650 } 3651 } else if (Literal.isFloat) 3652 Ty = Context.FloatTy; 3653 else if (Literal.isLong) 3654 Ty = Context.LongDoubleTy; 3655 else if (Literal.isFloat16) 3656 Ty = Context.Float16Ty; 3657 else if (Literal.isFloat128) 3658 Ty = Context.Float128Ty; 3659 else 3660 Ty = Context.DoubleTy; 3661 3662 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3663 3664 if (Ty == Context.DoubleTy) { 3665 if (getLangOpts().SinglePrecisionConstants) { 3666 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3667 if (BTy->getKind() != BuiltinType::Float) { 3668 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3669 } 3670 } else if (getLangOpts().OpenCL && 3671 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3672 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3673 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3674 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3675 } 3676 } 3677 } else if (!Literal.isIntegerLiteral()) { 3678 return ExprError(); 3679 } else { 3680 QualType Ty; 3681 3682 // 'long long' is a C99 or C++11 feature. 3683 if (!getLangOpts().C99 && Literal.isLongLong) { 3684 if (getLangOpts().CPlusPlus) 3685 Diag(Tok.getLocation(), 3686 getLangOpts().CPlusPlus11 ? 3687 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3688 else 3689 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3690 } 3691 3692 // Get the value in the widest-possible width. 3693 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3694 llvm::APInt ResultVal(MaxWidth, 0); 3695 3696 if (Literal.GetIntegerValue(ResultVal)) { 3697 // If this value didn't fit into uintmax_t, error and force to ull. 3698 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3699 << /* Unsigned */ 1; 3700 Ty = Context.UnsignedLongLongTy; 3701 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3702 "long long is not intmax_t?"); 3703 } else { 3704 // If this value fits into a ULL, try to figure out what else it fits into 3705 // according to the rules of C99 6.4.4.1p5. 3706 3707 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3708 // be an unsigned int. 3709 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3710 3711 // Check from smallest to largest, picking the smallest type we can. 3712 unsigned Width = 0; 3713 3714 // Microsoft specific integer suffixes are explicitly sized. 3715 if (Literal.MicrosoftInteger) { 3716 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3717 Width = 8; 3718 Ty = Context.CharTy; 3719 } else { 3720 Width = Literal.MicrosoftInteger; 3721 Ty = Context.getIntTypeForBitwidth(Width, 3722 /*Signed=*/!Literal.isUnsigned); 3723 } 3724 } 3725 3726 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3727 // Are int/unsigned possibilities? 3728 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3729 3730 // Does it fit in a unsigned int? 3731 if (ResultVal.isIntN(IntSize)) { 3732 // Does it fit in a signed int? 3733 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3734 Ty = Context.IntTy; 3735 else if (AllowUnsigned) 3736 Ty = Context.UnsignedIntTy; 3737 Width = IntSize; 3738 } 3739 } 3740 3741 // Are long/unsigned long possibilities? 3742 if (Ty.isNull() && !Literal.isLongLong) { 3743 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3744 3745 // Does it fit in a unsigned long? 3746 if (ResultVal.isIntN(LongSize)) { 3747 // Does it fit in a signed long? 3748 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3749 Ty = Context.LongTy; 3750 else if (AllowUnsigned) 3751 Ty = Context.UnsignedLongTy; 3752 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3753 // is compatible. 3754 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3755 const unsigned LongLongSize = 3756 Context.getTargetInfo().getLongLongWidth(); 3757 Diag(Tok.getLocation(), 3758 getLangOpts().CPlusPlus 3759 ? Literal.isLong 3760 ? diag::warn_old_implicitly_unsigned_long_cxx 3761 : /*C++98 UB*/ diag:: 3762 ext_old_implicitly_unsigned_long_cxx 3763 : diag::warn_old_implicitly_unsigned_long) 3764 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3765 : /*will be ill-formed*/ 1); 3766 Ty = Context.UnsignedLongTy; 3767 } 3768 Width = LongSize; 3769 } 3770 } 3771 3772 // Check long long if needed. 3773 if (Ty.isNull()) { 3774 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3775 3776 // Does it fit in a unsigned long long? 3777 if (ResultVal.isIntN(LongLongSize)) { 3778 // Does it fit in a signed long long? 3779 // To be compatible with MSVC, hex integer literals ending with the 3780 // LL or i64 suffix are always signed in Microsoft mode. 3781 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3782 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3783 Ty = Context.LongLongTy; 3784 else if (AllowUnsigned) 3785 Ty = Context.UnsignedLongLongTy; 3786 Width = LongLongSize; 3787 } 3788 } 3789 3790 // If we still couldn't decide a type, we probably have something that 3791 // does not fit in a signed long long, but has no U suffix. 3792 if (Ty.isNull()) { 3793 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3794 Ty = Context.UnsignedLongLongTy; 3795 Width = Context.getTargetInfo().getLongLongWidth(); 3796 } 3797 3798 if (ResultVal.getBitWidth() != Width) 3799 ResultVal = ResultVal.trunc(Width); 3800 } 3801 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3802 } 3803 3804 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3805 if (Literal.isImaginary) { 3806 Res = new (Context) ImaginaryLiteral(Res, 3807 Context.getComplexType(Res->getType())); 3808 3809 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3810 } 3811 return Res; 3812 } 3813 3814 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3815 assert(E && "ActOnParenExpr() missing expr"); 3816 return new (Context) ParenExpr(L, R, E); 3817 } 3818 3819 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3820 SourceLocation Loc, 3821 SourceRange ArgRange) { 3822 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3823 // scalar or vector data type argument..." 3824 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3825 // type (C99 6.2.5p18) or void. 3826 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3827 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3828 << T << ArgRange; 3829 return true; 3830 } 3831 3832 assert((T->isVoidType() || !T->isIncompleteType()) && 3833 "Scalar types should always be complete"); 3834 return false; 3835 } 3836 3837 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3838 SourceLocation Loc, 3839 SourceRange ArgRange, 3840 UnaryExprOrTypeTrait TraitKind) { 3841 // Invalid types must be hard errors for SFINAE in C++. 3842 if (S.LangOpts.CPlusPlus) 3843 return true; 3844 3845 // C99 6.5.3.4p1: 3846 if (T->isFunctionType() && 3847 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3848 TraitKind == UETT_PreferredAlignOf)) { 3849 // sizeof(function)/alignof(function) is allowed as an extension. 3850 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3851 << TraitKind << ArgRange; 3852 return false; 3853 } 3854 3855 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3856 // this is an error (OpenCL v1.1 s6.3.k) 3857 if (T->isVoidType()) { 3858 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3859 : diag::ext_sizeof_alignof_void_type; 3860 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3861 return false; 3862 } 3863 3864 return true; 3865 } 3866 3867 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3868 SourceLocation Loc, 3869 SourceRange ArgRange, 3870 UnaryExprOrTypeTrait TraitKind) { 3871 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3872 // runtime doesn't allow it. 3873 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3874 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3875 << T << (TraitKind == UETT_SizeOf) 3876 << ArgRange; 3877 return true; 3878 } 3879 3880 return false; 3881 } 3882 3883 /// Check whether E is a pointer from a decayed array type (the decayed 3884 /// pointer type is equal to T) and emit a warning if it is. 3885 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3886 Expr *E) { 3887 // Don't warn if the operation changed the type. 3888 if (T != E->getType()) 3889 return; 3890 3891 // Now look for array decays. 3892 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3893 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3894 return; 3895 3896 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3897 << ICE->getType() 3898 << ICE->getSubExpr()->getType(); 3899 } 3900 3901 /// Check the constraints on expression operands to unary type expression 3902 /// and type traits. 3903 /// 3904 /// Completes any types necessary and validates the constraints on the operand 3905 /// expression. The logic mostly mirrors the type-based overload, but may modify 3906 /// the expression as it completes the type for that expression through template 3907 /// instantiation, etc. 3908 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3909 UnaryExprOrTypeTrait ExprKind) { 3910 QualType ExprTy = E->getType(); 3911 assert(!ExprTy->isReferenceType()); 3912 3913 bool IsUnevaluatedOperand = 3914 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3915 ExprKind == UETT_PreferredAlignOf); 3916 if (IsUnevaluatedOperand) { 3917 ExprResult Result = CheckUnevaluatedOperand(E); 3918 if (Result.isInvalid()) 3919 return true; 3920 E = Result.get(); 3921 } 3922 3923 if (ExprKind == UETT_VecStep) 3924 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3925 E->getSourceRange()); 3926 3927 // Whitelist some types as extensions 3928 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3929 E->getSourceRange(), ExprKind)) 3930 return false; 3931 3932 // 'alignof' applied to an expression only requires the base element type of 3933 // the expression to be complete. 'sizeof' requires the expression's type to 3934 // be complete (and will attempt to complete it if it's an array of unknown 3935 // bound). 3936 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3937 if (RequireCompleteType(E->getExprLoc(), 3938 Context.getBaseElementType(E->getType()), 3939 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3940 E->getSourceRange())) 3941 return true; 3942 } else { 3943 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3944 ExprKind, E->getSourceRange())) 3945 return true; 3946 } 3947 3948 // Completing the expression's type may have changed it. 3949 ExprTy = E->getType(); 3950 assert(!ExprTy->isReferenceType()); 3951 3952 if (ExprTy->isFunctionType()) { 3953 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3954 << ExprKind << E->getSourceRange(); 3955 return true; 3956 } 3957 3958 // The operand for sizeof and alignof is in an unevaluated expression context, 3959 // so side effects could result in unintended consequences. 3960 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 3961 E->HasSideEffects(Context, false)) 3962 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3963 3964 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3965 E->getSourceRange(), ExprKind)) 3966 return true; 3967 3968 if (ExprKind == UETT_SizeOf) { 3969 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3970 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3971 QualType OType = PVD->getOriginalType(); 3972 QualType Type = PVD->getType(); 3973 if (Type->isPointerType() && OType->isArrayType()) { 3974 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3975 << Type << OType; 3976 Diag(PVD->getLocation(), diag::note_declared_at); 3977 } 3978 } 3979 } 3980 3981 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3982 // decays into a pointer and returns an unintended result. This is most 3983 // likely a typo for "sizeof(array) op x". 3984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3985 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3986 BO->getLHS()); 3987 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3988 BO->getRHS()); 3989 } 3990 } 3991 3992 return false; 3993 } 3994 3995 /// Check the constraints on operands to unary expression and type 3996 /// traits. 3997 /// 3998 /// This will complete any types necessary, and validate the various constraints 3999 /// on those operands. 4000 /// 4001 /// The UsualUnaryConversions() function is *not* called by this routine. 4002 /// C99 6.3.2.1p[2-4] all state: 4003 /// Except when it is the operand of the sizeof operator ... 4004 /// 4005 /// C++ [expr.sizeof]p4 4006 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4007 /// standard conversions are not applied to the operand of sizeof. 4008 /// 4009 /// This policy is followed for all of the unary trait expressions. 4010 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4011 SourceLocation OpLoc, 4012 SourceRange ExprRange, 4013 UnaryExprOrTypeTrait ExprKind) { 4014 if (ExprType->isDependentType()) 4015 return false; 4016 4017 // C++ [expr.sizeof]p2: 4018 // When applied to a reference or a reference type, the result 4019 // is the size of the referenced type. 4020 // C++11 [expr.alignof]p3: 4021 // When alignof is applied to a reference type, the result 4022 // shall be the alignment of the referenced type. 4023 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4024 ExprType = Ref->getPointeeType(); 4025 4026 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4027 // When alignof or _Alignof is applied to an array type, the result 4028 // is the alignment of the element type. 4029 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4030 ExprKind == UETT_OpenMPRequiredSimdAlign) 4031 ExprType = Context.getBaseElementType(ExprType); 4032 4033 if (ExprKind == UETT_VecStep) 4034 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4035 4036 // Whitelist some types as extensions 4037 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4038 ExprKind)) 4039 return false; 4040 4041 if (RequireCompleteType(OpLoc, ExprType, 4042 diag::err_sizeof_alignof_incomplete_type, 4043 ExprKind, ExprRange)) 4044 return true; 4045 4046 if (ExprType->isFunctionType()) { 4047 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4048 << ExprKind << ExprRange; 4049 return true; 4050 } 4051 4052 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4053 ExprKind)) 4054 return true; 4055 4056 return false; 4057 } 4058 4059 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4060 // Cannot know anything else if the expression is dependent. 4061 if (E->isTypeDependent()) 4062 return false; 4063 4064 if (E->getObjectKind() == OK_BitField) { 4065 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4066 << 1 << E->getSourceRange(); 4067 return true; 4068 } 4069 4070 ValueDecl *D = nullptr; 4071 Expr *Inner = E->IgnoreParens(); 4072 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4073 D = DRE->getDecl(); 4074 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4075 D = ME->getMemberDecl(); 4076 } 4077 4078 // If it's a field, require the containing struct to have a 4079 // complete definition so that we can compute the layout. 4080 // 4081 // This can happen in C++11 onwards, either by naming the member 4082 // in a way that is not transformed into a member access expression 4083 // (in an unevaluated operand, for instance), or by naming the member 4084 // in a trailing-return-type. 4085 // 4086 // For the record, since __alignof__ on expressions is a GCC 4087 // extension, GCC seems to permit this but always gives the 4088 // nonsensical answer 0. 4089 // 4090 // We don't really need the layout here --- we could instead just 4091 // directly check for all the appropriate alignment-lowing 4092 // attributes --- but that would require duplicating a lot of 4093 // logic that just isn't worth duplicating for such a marginal 4094 // use-case. 4095 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4096 // Fast path this check, since we at least know the record has a 4097 // definition if we can find a member of it. 4098 if (!FD->getParent()->isCompleteDefinition()) { 4099 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4100 << E->getSourceRange(); 4101 return true; 4102 } 4103 4104 // Otherwise, if it's a field, and the field doesn't have 4105 // reference type, then it must have a complete type (or be a 4106 // flexible array member, which we explicitly want to 4107 // white-list anyway), which makes the following checks trivial. 4108 if (!FD->getType()->isReferenceType()) 4109 return false; 4110 } 4111 4112 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4113 } 4114 4115 bool Sema::CheckVecStepExpr(Expr *E) { 4116 E = E->IgnoreParens(); 4117 4118 // Cannot know anything else if the expression is dependent. 4119 if (E->isTypeDependent()) 4120 return false; 4121 4122 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4123 } 4124 4125 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4126 CapturingScopeInfo *CSI) { 4127 assert(T->isVariablyModifiedType()); 4128 assert(CSI != nullptr); 4129 4130 // We're going to walk down into the type and look for VLA expressions. 4131 do { 4132 const Type *Ty = T.getTypePtr(); 4133 switch (Ty->getTypeClass()) { 4134 #define TYPE(Class, Base) 4135 #define ABSTRACT_TYPE(Class, Base) 4136 #define NON_CANONICAL_TYPE(Class, Base) 4137 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4138 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4139 #include "clang/AST/TypeNodes.inc" 4140 T = QualType(); 4141 break; 4142 // These types are never variably-modified. 4143 case Type::Builtin: 4144 case Type::Complex: 4145 case Type::Vector: 4146 case Type::ExtVector: 4147 case Type::Record: 4148 case Type::Enum: 4149 case Type::Elaborated: 4150 case Type::TemplateSpecialization: 4151 case Type::ObjCObject: 4152 case Type::ObjCInterface: 4153 case Type::ObjCObjectPointer: 4154 case Type::ObjCTypeParam: 4155 case Type::Pipe: 4156 llvm_unreachable("type class is never variably-modified!"); 4157 case Type::Adjusted: 4158 T = cast<AdjustedType>(Ty)->getOriginalType(); 4159 break; 4160 case Type::Decayed: 4161 T = cast<DecayedType>(Ty)->getPointeeType(); 4162 break; 4163 case Type::Pointer: 4164 T = cast<PointerType>(Ty)->getPointeeType(); 4165 break; 4166 case Type::BlockPointer: 4167 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4168 break; 4169 case Type::LValueReference: 4170 case Type::RValueReference: 4171 T = cast<ReferenceType>(Ty)->getPointeeType(); 4172 break; 4173 case Type::MemberPointer: 4174 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4175 break; 4176 case Type::ConstantArray: 4177 case Type::IncompleteArray: 4178 // Losing element qualification here is fine. 4179 T = cast<ArrayType>(Ty)->getElementType(); 4180 break; 4181 case Type::VariableArray: { 4182 // Losing element qualification here is fine. 4183 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4184 4185 // Unknown size indication requires no size computation. 4186 // Otherwise, evaluate and record it. 4187 auto Size = VAT->getSizeExpr(); 4188 if (Size && !CSI->isVLATypeCaptured(VAT) && 4189 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4190 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4191 4192 T = VAT->getElementType(); 4193 break; 4194 } 4195 case Type::FunctionProto: 4196 case Type::FunctionNoProto: 4197 T = cast<FunctionType>(Ty)->getReturnType(); 4198 break; 4199 case Type::Paren: 4200 case Type::TypeOf: 4201 case Type::UnaryTransform: 4202 case Type::Attributed: 4203 case Type::SubstTemplateTypeParm: 4204 case Type::PackExpansion: 4205 case Type::MacroQualified: 4206 // Keep walking after single level desugaring. 4207 T = T.getSingleStepDesugaredType(Context); 4208 break; 4209 case Type::Typedef: 4210 T = cast<TypedefType>(Ty)->desugar(); 4211 break; 4212 case Type::Decltype: 4213 T = cast<DecltypeType>(Ty)->desugar(); 4214 break; 4215 case Type::Auto: 4216 case Type::DeducedTemplateSpecialization: 4217 T = cast<DeducedType>(Ty)->getDeducedType(); 4218 break; 4219 case Type::TypeOfExpr: 4220 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4221 break; 4222 case Type::Atomic: 4223 T = cast<AtomicType>(Ty)->getValueType(); 4224 break; 4225 } 4226 } while (!T.isNull() && T->isVariablyModifiedType()); 4227 } 4228 4229 /// Build a sizeof or alignof expression given a type operand. 4230 ExprResult 4231 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4232 SourceLocation OpLoc, 4233 UnaryExprOrTypeTrait ExprKind, 4234 SourceRange R) { 4235 if (!TInfo) 4236 return ExprError(); 4237 4238 QualType T = TInfo->getType(); 4239 4240 if (!T->isDependentType() && 4241 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4242 return ExprError(); 4243 4244 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4245 if (auto *TT = T->getAs<TypedefType>()) { 4246 for (auto I = FunctionScopes.rbegin(), 4247 E = std::prev(FunctionScopes.rend()); 4248 I != E; ++I) { 4249 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4250 if (CSI == nullptr) 4251 break; 4252 DeclContext *DC = nullptr; 4253 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4254 DC = LSI->CallOperator; 4255 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4256 DC = CRSI->TheCapturedDecl; 4257 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4258 DC = BSI->TheDecl; 4259 if (DC) { 4260 if (DC->containsDecl(TT->getDecl())) 4261 break; 4262 captureVariablyModifiedType(Context, T, CSI); 4263 } 4264 } 4265 } 4266 } 4267 4268 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4269 return new (Context) UnaryExprOrTypeTraitExpr( 4270 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4271 } 4272 4273 /// Build a sizeof or alignof expression given an expression 4274 /// operand. 4275 ExprResult 4276 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4277 UnaryExprOrTypeTrait ExprKind) { 4278 ExprResult PE = CheckPlaceholderExpr(E); 4279 if (PE.isInvalid()) 4280 return ExprError(); 4281 4282 E = PE.get(); 4283 4284 // Verify that the operand is valid. 4285 bool isInvalid = false; 4286 if (E->isTypeDependent()) { 4287 // Delay type-checking for type-dependent expressions. 4288 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4289 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4290 } else if (ExprKind == UETT_VecStep) { 4291 isInvalid = CheckVecStepExpr(E); 4292 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4293 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4294 isInvalid = true; 4295 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4296 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4297 isInvalid = true; 4298 } else { 4299 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4300 } 4301 4302 if (isInvalid) 4303 return ExprError(); 4304 4305 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4306 PE = TransformToPotentiallyEvaluated(E); 4307 if (PE.isInvalid()) return ExprError(); 4308 E = PE.get(); 4309 } 4310 4311 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4312 return new (Context) UnaryExprOrTypeTraitExpr( 4313 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4314 } 4315 4316 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4317 /// expr and the same for @c alignof and @c __alignof 4318 /// Note that the ArgRange is invalid if isType is false. 4319 ExprResult 4320 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4321 UnaryExprOrTypeTrait ExprKind, bool IsType, 4322 void *TyOrEx, SourceRange ArgRange) { 4323 // If error parsing type, ignore. 4324 if (!TyOrEx) return ExprError(); 4325 4326 if (IsType) { 4327 TypeSourceInfo *TInfo; 4328 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4329 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4330 } 4331 4332 Expr *ArgEx = (Expr *)TyOrEx; 4333 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4334 return Result; 4335 } 4336 4337 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4338 bool IsReal) { 4339 if (V.get()->isTypeDependent()) 4340 return S.Context.DependentTy; 4341 4342 // _Real and _Imag are only l-values for normal l-values. 4343 if (V.get()->getObjectKind() != OK_Ordinary) { 4344 V = S.DefaultLvalueConversion(V.get()); 4345 if (V.isInvalid()) 4346 return QualType(); 4347 } 4348 4349 // These operators return the element type of a complex type. 4350 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4351 return CT->getElementType(); 4352 4353 // Otherwise they pass through real integer and floating point types here. 4354 if (V.get()->getType()->isArithmeticType()) 4355 return V.get()->getType(); 4356 4357 // Test for placeholders. 4358 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4359 if (PR.isInvalid()) return QualType(); 4360 if (PR.get() != V.get()) { 4361 V = PR; 4362 return CheckRealImagOperand(S, V, Loc, IsReal); 4363 } 4364 4365 // Reject anything else. 4366 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4367 << (IsReal ? "__real" : "__imag"); 4368 return QualType(); 4369 } 4370 4371 4372 4373 ExprResult 4374 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4375 tok::TokenKind Kind, Expr *Input) { 4376 UnaryOperatorKind Opc; 4377 switch (Kind) { 4378 default: llvm_unreachable("Unknown unary op!"); 4379 case tok::plusplus: Opc = UO_PostInc; break; 4380 case tok::minusminus: Opc = UO_PostDec; break; 4381 } 4382 4383 // Since this might is a postfix expression, get rid of ParenListExprs. 4384 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4385 if (Result.isInvalid()) return ExprError(); 4386 Input = Result.get(); 4387 4388 return BuildUnaryOp(S, OpLoc, Opc, Input); 4389 } 4390 4391 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4392 /// 4393 /// \return true on error 4394 static bool checkArithmeticOnObjCPointer(Sema &S, 4395 SourceLocation opLoc, 4396 Expr *op) { 4397 assert(op->getType()->isObjCObjectPointerType()); 4398 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4399 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4400 return false; 4401 4402 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4403 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4404 << op->getSourceRange(); 4405 return true; 4406 } 4407 4408 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4409 auto *BaseNoParens = Base->IgnoreParens(); 4410 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4411 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4412 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4413 } 4414 4415 ExprResult 4416 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4417 Expr *idx, SourceLocation rbLoc) { 4418 if (base && !base->getType().isNull() && 4419 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4420 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4421 /*Length=*/nullptr, rbLoc); 4422 4423 // Since this might be a postfix expression, get rid of ParenListExprs. 4424 if (isa<ParenListExpr>(base)) { 4425 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4426 if (result.isInvalid()) return ExprError(); 4427 base = result.get(); 4428 } 4429 4430 // A comma-expression as the index is deprecated in C++2a onwards. 4431 if (getLangOpts().CPlusPlus2a && 4432 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4433 (isa<CXXOperatorCallExpr>(idx) && 4434 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4435 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4436 << SourceRange(base->getBeginLoc(), rbLoc); 4437 } 4438 4439 // Handle any non-overload placeholder types in the base and index 4440 // expressions. We can't handle overloads here because the other 4441 // operand might be an overloadable type, in which case the overload 4442 // resolution for the operator overload should get the first crack 4443 // at the overload. 4444 bool IsMSPropertySubscript = false; 4445 if (base->getType()->isNonOverloadPlaceholderType()) { 4446 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4447 if (!IsMSPropertySubscript) { 4448 ExprResult result = CheckPlaceholderExpr(base); 4449 if (result.isInvalid()) 4450 return ExprError(); 4451 base = result.get(); 4452 } 4453 } 4454 if (idx->getType()->isNonOverloadPlaceholderType()) { 4455 ExprResult result = CheckPlaceholderExpr(idx); 4456 if (result.isInvalid()) return ExprError(); 4457 idx = result.get(); 4458 } 4459 4460 // Build an unanalyzed expression if either operand is type-dependent. 4461 if (getLangOpts().CPlusPlus && 4462 (base->isTypeDependent() || idx->isTypeDependent())) { 4463 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4464 VK_LValue, OK_Ordinary, rbLoc); 4465 } 4466 4467 // MSDN, property (C++) 4468 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4469 // This attribute can also be used in the declaration of an empty array in a 4470 // class or structure definition. For example: 4471 // __declspec(property(get=GetX, put=PutX)) int x[]; 4472 // The above statement indicates that x[] can be used with one or more array 4473 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4474 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4475 if (IsMSPropertySubscript) { 4476 // Build MS property subscript expression if base is MS property reference 4477 // or MS property subscript. 4478 return new (Context) MSPropertySubscriptExpr( 4479 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4480 } 4481 4482 // Use C++ overloaded-operator rules if either operand has record 4483 // type. The spec says to do this if either type is *overloadable*, 4484 // but enum types can't declare subscript operators or conversion 4485 // operators, so there's nothing interesting for overload resolution 4486 // to do if there aren't any record types involved. 4487 // 4488 // ObjC pointers have their own subscripting logic that is not tied 4489 // to overload resolution and so should not take this path. 4490 if (getLangOpts().CPlusPlus && 4491 (base->getType()->isRecordType() || 4492 (!base->getType()->isObjCObjectPointerType() && 4493 idx->getType()->isRecordType()))) { 4494 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4495 } 4496 4497 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4498 4499 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4500 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4501 4502 return Res; 4503 } 4504 4505 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4506 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4507 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4508 4509 // For expressions like `&(*s).b`, the base is recorded and what should be 4510 // checked. 4511 const MemberExpr *Member = nullptr; 4512 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4513 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4514 4515 LastRecord.PossibleDerefs.erase(StrippedExpr); 4516 } 4517 4518 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4519 QualType ResultTy = E->getType(); 4520 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4521 4522 // Bail if the element is an array since it is not memory access. 4523 if (isa<ArrayType>(ResultTy)) 4524 return; 4525 4526 if (ResultTy->hasAttr(attr::NoDeref)) { 4527 LastRecord.PossibleDerefs.insert(E); 4528 return; 4529 } 4530 4531 // Check if the base type is a pointer to a member access of a struct 4532 // marked with noderef. 4533 const Expr *Base = E->getBase(); 4534 QualType BaseTy = Base->getType(); 4535 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4536 // Not a pointer access 4537 return; 4538 4539 const MemberExpr *Member = nullptr; 4540 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4541 Member->isArrow()) 4542 Base = Member->getBase(); 4543 4544 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4545 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4546 LastRecord.PossibleDerefs.insert(E); 4547 } 4548 } 4549 4550 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4551 Expr *LowerBound, 4552 SourceLocation ColonLoc, Expr *Length, 4553 SourceLocation RBLoc) { 4554 if (Base->getType()->isPlaceholderType() && 4555 !Base->getType()->isSpecificPlaceholderType( 4556 BuiltinType::OMPArraySection)) { 4557 ExprResult Result = CheckPlaceholderExpr(Base); 4558 if (Result.isInvalid()) 4559 return ExprError(); 4560 Base = Result.get(); 4561 } 4562 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4563 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4564 if (Result.isInvalid()) 4565 return ExprError(); 4566 Result = DefaultLvalueConversion(Result.get()); 4567 if (Result.isInvalid()) 4568 return ExprError(); 4569 LowerBound = Result.get(); 4570 } 4571 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4572 ExprResult Result = CheckPlaceholderExpr(Length); 4573 if (Result.isInvalid()) 4574 return ExprError(); 4575 Result = DefaultLvalueConversion(Result.get()); 4576 if (Result.isInvalid()) 4577 return ExprError(); 4578 Length = Result.get(); 4579 } 4580 4581 // Build an unanalyzed expression if either operand is type-dependent. 4582 if (Base->isTypeDependent() || 4583 (LowerBound && 4584 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4585 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4586 return new (Context) 4587 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4588 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4589 } 4590 4591 // Perform default conversions. 4592 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4593 QualType ResultTy; 4594 if (OriginalTy->isAnyPointerType()) { 4595 ResultTy = OriginalTy->getPointeeType(); 4596 } else if (OriginalTy->isArrayType()) { 4597 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4598 } else { 4599 return ExprError( 4600 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4601 << Base->getSourceRange()); 4602 } 4603 // C99 6.5.2.1p1 4604 if (LowerBound) { 4605 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4606 LowerBound); 4607 if (Res.isInvalid()) 4608 return ExprError(Diag(LowerBound->getExprLoc(), 4609 diag::err_omp_typecheck_section_not_integer) 4610 << 0 << LowerBound->getSourceRange()); 4611 LowerBound = Res.get(); 4612 4613 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4614 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4615 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4616 << 0 << LowerBound->getSourceRange(); 4617 } 4618 if (Length) { 4619 auto Res = 4620 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4621 if (Res.isInvalid()) 4622 return ExprError(Diag(Length->getExprLoc(), 4623 diag::err_omp_typecheck_section_not_integer) 4624 << 1 << Length->getSourceRange()); 4625 Length = Res.get(); 4626 4627 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4628 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4629 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4630 << 1 << Length->getSourceRange(); 4631 } 4632 4633 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4634 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4635 // type. Note that functions are not objects, and that (in C99 parlance) 4636 // incomplete types are not object types. 4637 if (ResultTy->isFunctionType()) { 4638 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4639 << ResultTy << Base->getSourceRange(); 4640 return ExprError(); 4641 } 4642 4643 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4644 diag::err_omp_section_incomplete_type, Base)) 4645 return ExprError(); 4646 4647 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4648 Expr::EvalResult Result; 4649 if (LowerBound->EvaluateAsInt(Result, Context)) { 4650 // OpenMP 4.5, [2.4 Array Sections] 4651 // The array section must be a subset of the original array. 4652 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4653 if (LowerBoundValue.isNegative()) { 4654 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4655 << LowerBound->getSourceRange(); 4656 return ExprError(); 4657 } 4658 } 4659 } 4660 4661 if (Length) { 4662 Expr::EvalResult Result; 4663 if (Length->EvaluateAsInt(Result, Context)) { 4664 // OpenMP 4.5, [2.4 Array Sections] 4665 // The length must evaluate to non-negative integers. 4666 llvm::APSInt LengthValue = Result.Val.getInt(); 4667 if (LengthValue.isNegative()) { 4668 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4669 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4670 << Length->getSourceRange(); 4671 return ExprError(); 4672 } 4673 } 4674 } else if (ColonLoc.isValid() && 4675 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4676 !OriginalTy->isVariableArrayType()))) { 4677 // OpenMP 4.5, [2.4 Array Sections] 4678 // When the size of the array dimension is not known, the length must be 4679 // specified explicitly. 4680 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4681 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4682 return ExprError(); 4683 } 4684 4685 if (!Base->getType()->isSpecificPlaceholderType( 4686 BuiltinType::OMPArraySection)) { 4687 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4688 if (Result.isInvalid()) 4689 return ExprError(); 4690 Base = Result.get(); 4691 } 4692 return new (Context) 4693 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4694 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4695 } 4696 4697 ExprResult 4698 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4699 Expr *Idx, SourceLocation RLoc) { 4700 Expr *LHSExp = Base; 4701 Expr *RHSExp = Idx; 4702 4703 ExprValueKind VK = VK_LValue; 4704 ExprObjectKind OK = OK_Ordinary; 4705 4706 // Per C++ core issue 1213, the result is an xvalue if either operand is 4707 // a non-lvalue array, and an lvalue otherwise. 4708 if (getLangOpts().CPlusPlus11) { 4709 for (auto *Op : {LHSExp, RHSExp}) { 4710 Op = Op->IgnoreImplicit(); 4711 if (Op->getType()->isArrayType() && !Op->isLValue()) 4712 VK = VK_XValue; 4713 } 4714 } 4715 4716 // Perform default conversions. 4717 if (!LHSExp->getType()->getAs<VectorType>()) { 4718 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4719 if (Result.isInvalid()) 4720 return ExprError(); 4721 LHSExp = Result.get(); 4722 } 4723 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4724 if (Result.isInvalid()) 4725 return ExprError(); 4726 RHSExp = Result.get(); 4727 4728 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4729 4730 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4731 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4732 // in the subscript position. As a result, we need to derive the array base 4733 // and index from the expression types. 4734 Expr *BaseExpr, *IndexExpr; 4735 QualType ResultType; 4736 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4737 BaseExpr = LHSExp; 4738 IndexExpr = RHSExp; 4739 ResultType = Context.DependentTy; 4740 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4741 BaseExpr = LHSExp; 4742 IndexExpr = RHSExp; 4743 ResultType = PTy->getPointeeType(); 4744 } else if (const ObjCObjectPointerType *PTy = 4745 LHSTy->getAs<ObjCObjectPointerType>()) { 4746 BaseExpr = LHSExp; 4747 IndexExpr = RHSExp; 4748 4749 // Use custom logic if this should be the pseudo-object subscript 4750 // expression. 4751 if (!LangOpts.isSubscriptPointerArithmetic()) 4752 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4753 nullptr); 4754 4755 ResultType = PTy->getPointeeType(); 4756 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4757 // Handle the uncommon case of "123[Ptr]". 4758 BaseExpr = RHSExp; 4759 IndexExpr = LHSExp; 4760 ResultType = PTy->getPointeeType(); 4761 } else if (const ObjCObjectPointerType *PTy = 4762 RHSTy->getAs<ObjCObjectPointerType>()) { 4763 // Handle the uncommon case of "123[Ptr]". 4764 BaseExpr = RHSExp; 4765 IndexExpr = LHSExp; 4766 ResultType = PTy->getPointeeType(); 4767 if (!LangOpts.isSubscriptPointerArithmetic()) { 4768 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4769 << ResultType << BaseExpr->getSourceRange(); 4770 return ExprError(); 4771 } 4772 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4773 BaseExpr = LHSExp; // vectors: V[123] 4774 IndexExpr = RHSExp; 4775 // We apply C++ DR1213 to vector subscripting too. 4776 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4777 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4778 if (Materialized.isInvalid()) 4779 return ExprError(); 4780 LHSExp = Materialized.get(); 4781 } 4782 VK = LHSExp->getValueKind(); 4783 if (VK != VK_RValue) 4784 OK = OK_VectorComponent; 4785 4786 ResultType = VTy->getElementType(); 4787 QualType BaseType = BaseExpr->getType(); 4788 Qualifiers BaseQuals = BaseType.getQualifiers(); 4789 Qualifiers MemberQuals = ResultType.getQualifiers(); 4790 Qualifiers Combined = BaseQuals + MemberQuals; 4791 if (Combined != MemberQuals) 4792 ResultType = Context.getQualifiedType(ResultType, Combined); 4793 } else if (LHSTy->isArrayType()) { 4794 // If we see an array that wasn't promoted by 4795 // DefaultFunctionArrayLvalueConversion, it must be an array that 4796 // wasn't promoted because of the C90 rule that doesn't 4797 // allow promoting non-lvalue arrays. Warn, then 4798 // force the promotion here. 4799 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4800 << LHSExp->getSourceRange(); 4801 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4802 CK_ArrayToPointerDecay).get(); 4803 LHSTy = LHSExp->getType(); 4804 4805 BaseExpr = LHSExp; 4806 IndexExpr = RHSExp; 4807 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4808 } else if (RHSTy->isArrayType()) { 4809 // Same as previous, except for 123[f().a] case 4810 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4811 << RHSExp->getSourceRange(); 4812 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4813 CK_ArrayToPointerDecay).get(); 4814 RHSTy = RHSExp->getType(); 4815 4816 BaseExpr = RHSExp; 4817 IndexExpr = LHSExp; 4818 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4819 } else { 4820 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4821 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4822 } 4823 // C99 6.5.2.1p1 4824 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4825 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4826 << IndexExpr->getSourceRange()); 4827 4828 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4829 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4830 && !IndexExpr->isTypeDependent()) 4831 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4832 4833 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4834 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4835 // type. Note that Functions are not objects, and that (in C99 parlance) 4836 // incomplete types are not object types. 4837 if (ResultType->isFunctionType()) { 4838 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4839 << ResultType << BaseExpr->getSourceRange(); 4840 return ExprError(); 4841 } 4842 4843 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4844 // GNU extension: subscripting on pointer to void 4845 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4846 << BaseExpr->getSourceRange(); 4847 4848 // C forbids expressions of unqualified void type from being l-values. 4849 // See IsCForbiddenLValueType. 4850 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4851 } else if (!ResultType->isDependentType() && 4852 RequireCompleteType(LLoc, ResultType, 4853 diag::err_subscript_incomplete_type, BaseExpr)) 4854 return ExprError(); 4855 4856 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4857 !ResultType.isCForbiddenLValueType()); 4858 4859 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4860 FunctionScopes.size() > 1) { 4861 if (auto *TT = 4862 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4863 for (auto I = FunctionScopes.rbegin(), 4864 E = std::prev(FunctionScopes.rend()); 4865 I != E; ++I) { 4866 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4867 if (CSI == nullptr) 4868 break; 4869 DeclContext *DC = nullptr; 4870 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4871 DC = LSI->CallOperator; 4872 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4873 DC = CRSI->TheCapturedDecl; 4874 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4875 DC = BSI->TheDecl; 4876 if (DC) { 4877 if (DC->containsDecl(TT->getDecl())) 4878 break; 4879 captureVariablyModifiedType( 4880 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4881 } 4882 } 4883 } 4884 } 4885 4886 return new (Context) 4887 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4888 } 4889 4890 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4891 ParmVarDecl *Param) { 4892 if (Param->hasUnparsedDefaultArg()) { 4893 Diag(CallLoc, 4894 diag::err_use_of_default_argument_to_function_declared_later) << 4895 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4896 Diag(UnparsedDefaultArgLocs[Param], 4897 diag::note_default_argument_declared_here); 4898 return true; 4899 } 4900 4901 if (Param->hasUninstantiatedDefaultArg()) { 4902 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4903 4904 EnterExpressionEvaluationContext EvalContext( 4905 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4906 4907 // Instantiate the expression. 4908 // 4909 // FIXME: Pass in a correct Pattern argument, otherwise 4910 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4911 // 4912 // template<typename T> 4913 // struct A { 4914 // static int FooImpl(); 4915 // 4916 // template<typename Tp> 4917 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4918 // // template argument list [[T], [Tp]], should be [[Tp]]. 4919 // friend A<Tp> Foo(int a); 4920 // }; 4921 // 4922 // template<typename T> 4923 // A<T> Foo(int a = A<T>::FooImpl()); 4924 MultiLevelTemplateArgumentList MutiLevelArgList 4925 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4926 4927 InstantiatingTemplate Inst(*this, CallLoc, Param, 4928 MutiLevelArgList.getInnermost()); 4929 if (Inst.isInvalid()) 4930 return true; 4931 if (Inst.isAlreadyInstantiating()) { 4932 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4933 Param->setInvalidDecl(); 4934 return true; 4935 } 4936 4937 ExprResult Result; 4938 { 4939 // C++ [dcl.fct.default]p5: 4940 // The names in the [default argument] expression are bound, and 4941 // the semantic constraints are checked, at the point where the 4942 // default argument expression appears. 4943 ContextRAII SavedContext(*this, FD); 4944 LocalInstantiationScope Local(*this); 4945 runWithSufficientStackSpace(CallLoc, [&] { 4946 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4947 /*DirectInit*/false); 4948 }); 4949 } 4950 if (Result.isInvalid()) 4951 return true; 4952 4953 // Check the expression as an initializer for the parameter. 4954 InitializedEntity Entity 4955 = InitializedEntity::InitializeParameter(Context, Param); 4956 InitializationKind Kind = InitializationKind::CreateCopy( 4957 Param->getLocation(), 4958 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4959 Expr *ResultE = Result.getAs<Expr>(); 4960 4961 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4962 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4963 if (Result.isInvalid()) 4964 return true; 4965 4966 Result = 4967 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4968 /*DiscardedValue*/ false); 4969 if (Result.isInvalid()) 4970 return true; 4971 4972 // Remember the instantiated default argument. 4973 Param->setDefaultArg(Result.getAs<Expr>()); 4974 if (ASTMutationListener *L = getASTMutationListener()) { 4975 L->DefaultArgumentInstantiated(Param); 4976 } 4977 } 4978 4979 // If the default argument expression is not set yet, we are building it now. 4980 if (!Param->hasInit()) { 4981 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4982 Param->setInvalidDecl(); 4983 return true; 4984 } 4985 4986 // If the default expression creates temporaries, we need to 4987 // push them to the current stack of expression temporaries so they'll 4988 // be properly destroyed. 4989 // FIXME: We should really be rebuilding the default argument with new 4990 // bound temporaries; see the comment in PR5810. 4991 // We don't need to do that with block decls, though, because 4992 // blocks in default argument expression can never capture anything. 4993 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4994 // Set the "needs cleanups" bit regardless of whether there are 4995 // any explicit objects. 4996 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4997 4998 // Append all the objects to the cleanup list. Right now, this 4999 // should always be a no-op, because blocks in default argument 5000 // expressions should never be able to capture anything. 5001 assert(!Init->getNumObjects() && 5002 "default argument expression has capturing blocks?"); 5003 } 5004 5005 // We already type-checked the argument, so we know it works. 5006 // Just mark all of the declarations in this potentially-evaluated expression 5007 // as being "referenced". 5008 EnterExpressionEvaluationContext EvalContext( 5009 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5010 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5011 /*SkipLocalVariables=*/true); 5012 return false; 5013 } 5014 5015 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5016 FunctionDecl *FD, ParmVarDecl *Param) { 5017 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5018 return ExprError(); 5019 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5020 } 5021 5022 Sema::VariadicCallType 5023 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5024 Expr *Fn) { 5025 if (Proto && Proto->isVariadic()) { 5026 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5027 return VariadicConstructor; 5028 else if (Fn && Fn->getType()->isBlockPointerType()) 5029 return VariadicBlock; 5030 else if (FDecl) { 5031 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5032 if (Method->isInstance()) 5033 return VariadicMethod; 5034 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5035 return VariadicMethod; 5036 return VariadicFunction; 5037 } 5038 return VariadicDoesNotApply; 5039 } 5040 5041 namespace { 5042 class FunctionCallCCC final : public FunctionCallFilterCCC { 5043 public: 5044 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5045 unsigned NumArgs, MemberExpr *ME) 5046 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5047 FunctionName(FuncName) {} 5048 5049 bool ValidateCandidate(const TypoCorrection &candidate) override { 5050 if (!candidate.getCorrectionSpecifier() || 5051 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5052 return false; 5053 } 5054 5055 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5056 } 5057 5058 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5059 return std::make_unique<FunctionCallCCC>(*this); 5060 } 5061 5062 private: 5063 const IdentifierInfo *const FunctionName; 5064 }; 5065 } 5066 5067 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5068 FunctionDecl *FDecl, 5069 ArrayRef<Expr *> Args) { 5070 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5071 DeclarationName FuncName = FDecl->getDeclName(); 5072 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5073 5074 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5075 if (TypoCorrection Corrected = S.CorrectTypo( 5076 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5077 S.getScopeForContext(S.CurContext), nullptr, CCC, 5078 Sema::CTK_ErrorRecovery)) { 5079 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5080 if (Corrected.isOverloaded()) { 5081 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5082 OverloadCandidateSet::iterator Best; 5083 for (NamedDecl *CD : Corrected) { 5084 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5085 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5086 OCS); 5087 } 5088 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5089 case OR_Success: 5090 ND = Best->FoundDecl; 5091 Corrected.setCorrectionDecl(ND); 5092 break; 5093 default: 5094 break; 5095 } 5096 } 5097 ND = ND->getUnderlyingDecl(); 5098 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5099 return Corrected; 5100 } 5101 } 5102 return TypoCorrection(); 5103 } 5104 5105 /// ConvertArgumentsForCall - Converts the arguments specified in 5106 /// Args/NumArgs to the parameter types of the function FDecl with 5107 /// function prototype Proto. Call is the call expression itself, and 5108 /// Fn is the function expression. For a C++ member function, this 5109 /// routine does not attempt to convert the object argument. Returns 5110 /// true if the call is ill-formed. 5111 bool 5112 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5113 FunctionDecl *FDecl, 5114 const FunctionProtoType *Proto, 5115 ArrayRef<Expr *> Args, 5116 SourceLocation RParenLoc, 5117 bool IsExecConfig) { 5118 // Bail out early if calling a builtin with custom typechecking. 5119 if (FDecl) 5120 if (unsigned ID = FDecl->getBuiltinID()) 5121 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5122 return false; 5123 5124 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5125 // assignment, to the types of the corresponding parameter, ... 5126 unsigned NumParams = Proto->getNumParams(); 5127 bool Invalid = false; 5128 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5129 unsigned FnKind = Fn->getType()->isBlockPointerType() 5130 ? 1 /* block */ 5131 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5132 : 0 /* function */); 5133 5134 // If too few arguments are available (and we don't have default 5135 // arguments for the remaining parameters), don't make the call. 5136 if (Args.size() < NumParams) { 5137 if (Args.size() < MinArgs) { 5138 TypoCorrection TC; 5139 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5140 unsigned diag_id = 5141 MinArgs == NumParams && !Proto->isVariadic() 5142 ? diag::err_typecheck_call_too_few_args_suggest 5143 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5144 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5145 << static_cast<unsigned>(Args.size()) 5146 << TC.getCorrectionRange()); 5147 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5148 Diag(RParenLoc, 5149 MinArgs == NumParams && !Proto->isVariadic() 5150 ? diag::err_typecheck_call_too_few_args_one 5151 : diag::err_typecheck_call_too_few_args_at_least_one) 5152 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5153 else 5154 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5155 ? diag::err_typecheck_call_too_few_args 5156 : diag::err_typecheck_call_too_few_args_at_least) 5157 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5158 << Fn->getSourceRange(); 5159 5160 // Emit the location of the prototype. 5161 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5162 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5163 5164 return true; 5165 } 5166 // We reserve space for the default arguments when we create 5167 // the call expression, before calling ConvertArgumentsForCall. 5168 assert((Call->getNumArgs() == NumParams) && 5169 "We should have reserved space for the default arguments before!"); 5170 } 5171 5172 // If too many are passed and not variadic, error on the extras and drop 5173 // them. 5174 if (Args.size() > NumParams) { 5175 if (!Proto->isVariadic()) { 5176 TypoCorrection TC; 5177 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5178 unsigned diag_id = 5179 MinArgs == NumParams && !Proto->isVariadic() 5180 ? diag::err_typecheck_call_too_many_args_suggest 5181 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5182 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5183 << static_cast<unsigned>(Args.size()) 5184 << TC.getCorrectionRange()); 5185 } else if (NumParams == 1 && FDecl && 5186 FDecl->getParamDecl(0)->getDeclName()) 5187 Diag(Args[NumParams]->getBeginLoc(), 5188 MinArgs == NumParams 5189 ? diag::err_typecheck_call_too_many_args_one 5190 : diag::err_typecheck_call_too_many_args_at_most_one) 5191 << FnKind << FDecl->getParamDecl(0) 5192 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5193 << SourceRange(Args[NumParams]->getBeginLoc(), 5194 Args.back()->getEndLoc()); 5195 else 5196 Diag(Args[NumParams]->getBeginLoc(), 5197 MinArgs == NumParams 5198 ? diag::err_typecheck_call_too_many_args 5199 : diag::err_typecheck_call_too_many_args_at_most) 5200 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5201 << Fn->getSourceRange() 5202 << SourceRange(Args[NumParams]->getBeginLoc(), 5203 Args.back()->getEndLoc()); 5204 5205 // Emit the location of the prototype. 5206 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5207 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 5208 5209 // This deletes the extra arguments. 5210 Call->shrinkNumArgs(NumParams); 5211 return true; 5212 } 5213 } 5214 SmallVector<Expr *, 8> AllArgs; 5215 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5216 5217 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5218 AllArgs, CallType); 5219 if (Invalid) 5220 return true; 5221 unsigned TotalNumArgs = AllArgs.size(); 5222 for (unsigned i = 0; i < TotalNumArgs; ++i) 5223 Call->setArg(i, AllArgs[i]); 5224 5225 return false; 5226 } 5227 5228 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5229 const FunctionProtoType *Proto, 5230 unsigned FirstParam, ArrayRef<Expr *> Args, 5231 SmallVectorImpl<Expr *> &AllArgs, 5232 VariadicCallType CallType, bool AllowExplicit, 5233 bool IsListInitialization) { 5234 unsigned NumParams = Proto->getNumParams(); 5235 bool Invalid = false; 5236 size_t ArgIx = 0; 5237 // Continue to check argument types (even if we have too few/many args). 5238 for (unsigned i = FirstParam; i < NumParams; i++) { 5239 QualType ProtoArgType = Proto->getParamType(i); 5240 5241 Expr *Arg; 5242 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5243 if (ArgIx < Args.size()) { 5244 Arg = Args[ArgIx++]; 5245 5246 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5247 diag::err_call_incomplete_argument, Arg)) 5248 return true; 5249 5250 // Strip the unbridged-cast placeholder expression off, if applicable. 5251 bool CFAudited = false; 5252 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5253 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5254 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5255 Arg = stripARCUnbridgedCast(Arg); 5256 else if (getLangOpts().ObjCAutoRefCount && 5257 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5258 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5259 CFAudited = true; 5260 5261 if (Proto->getExtParameterInfo(i).isNoEscape()) 5262 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5263 BE->getBlockDecl()->setDoesNotEscape(); 5264 5265 InitializedEntity Entity = 5266 Param ? InitializedEntity::InitializeParameter(Context, Param, 5267 ProtoArgType) 5268 : InitializedEntity::InitializeParameter( 5269 Context, ProtoArgType, Proto->isParamConsumed(i)); 5270 5271 // Remember that parameter belongs to a CF audited API. 5272 if (CFAudited) 5273 Entity.setParameterCFAudited(); 5274 5275 ExprResult ArgE = PerformCopyInitialization( 5276 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5277 if (ArgE.isInvalid()) 5278 return true; 5279 5280 Arg = ArgE.getAs<Expr>(); 5281 } else { 5282 assert(Param && "can't use default arguments without a known callee"); 5283 5284 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5285 if (ArgExpr.isInvalid()) 5286 return true; 5287 5288 Arg = ArgExpr.getAs<Expr>(); 5289 } 5290 5291 // Check for array bounds violations for each argument to the call. This 5292 // check only triggers warnings when the argument isn't a more complex Expr 5293 // with its own checking, such as a BinaryOperator. 5294 CheckArrayAccess(Arg); 5295 5296 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5297 CheckStaticArrayArgument(CallLoc, Param, Arg); 5298 5299 AllArgs.push_back(Arg); 5300 } 5301 5302 // If this is a variadic call, handle args passed through "...". 5303 if (CallType != VariadicDoesNotApply) { 5304 // Assume that extern "C" functions with variadic arguments that 5305 // return __unknown_anytype aren't *really* variadic. 5306 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5307 FDecl->isExternC()) { 5308 for (Expr *A : Args.slice(ArgIx)) { 5309 QualType paramType; // ignored 5310 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5311 Invalid |= arg.isInvalid(); 5312 AllArgs.push_back(arg.get()); 5313 } 5314 5315 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5316 } else { 5317 for (Expr *A : Args.slice(ArgIx)) { 5318 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5319 Invalid |= Arg.isInvalid(); 5320 // Copy blocks to the heap. 5321 if (A->getType()->isBlockPointerType()) 5322 maybeExtendBlockObject(Arg); 5323 AllArgs.push_back(Arg.get()); 5324 } 5325 } 5326 5327 // Check for array bounds violations. 5328 for (Expr *A : Args.slice(ArgIx)) 5329 CheckArrayAccess(A); 5330 } 5331 return Invalid; 5332 } 5333 5334 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5335 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5336 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5337 TL = DTL.getOriginalLoc(); 5338 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5339 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5340 << ATL.getLocalSourceRange(); 5341 } 5342 5343 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5344 /// array parameter, check that it is non-null, and that if it is formed by 5345 /// array-to-pointer decay, the underlying array is sufficiently large. 5346 /// 5347 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5348 /// array type derivation, then for each call to the function, the value of the 5349 /// corresponding actual argument shall provide access to the first element of 5350 /// an array with at least as many elements as specified by the size expression. 5351 void 5352 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5353 ParmVarDecl *Param, 5354 const Expr *ArgExpr) { 5355 // Static array parameters are not supported in C++. 5356 if (!Param || getLangOpts().CPlusPlus) 5357 return; 5358 5359 QualType OrigTy = Param->getOriginalType(); 5360 5361 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5362 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5363 return; 5364 5365 if (ArgExpr->isNullPointerConstant(Context, 5366 Expr::NPC_NeverValueDependent)) { 5367 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5368 DiagnoseCalleeStaticArrayParam(*this, Param); 5369 return; 5370 } 5371 5372 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5373 if (!CAT) 5374 return; 5375 5376 const ConstantArrayType *ArgCAT = 5377 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5378 if (!ArgCAT) 5379 return; 5380 5381 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5382 ArgCAT->getElementType())) { 5383 if (ArgCAT->getSize().ult(CAT->getSize())) { 5384 Diag(CallLoc, diag::warn_static_array_too_small) 5385 << ArgExpr->getSourceRange() 5386 << (unsigned)ArgCAT->getSize().getZExtValue() 5387 << (unsigned)CAT->getSize().getZExtValue() << 0; 5388 DiagnoseCalleeStaticArrayParam(*this, Param); 5389 } 5390 return; 5391 } 5392 5393 Optional<CharUnits> ArgSize = 5394 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5395 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5396 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5397 Diag(CallLoc, diag::warn_static_array_too_small) 5398 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5399 << (unsigned)ParmSize->getQuantity() << 1; 5400 DiagnoseCalleeStaticArrayParam(*this, Param); 5401 } 5402 } 5403 5404 /// Given a function expression of unknown-any type, try to rebuild it 5405 /// to have a function type. 5406 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5407 5408 /// Is the given type a placeholder that we need to lower out 5409 /// immediately during argument processing? 5410 static bool isPlaceholderToRemoveAsArg(QualType type) { 5411 // Placeholders are never sugared. 5412 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5413 if (!placeholder) return false; 5414 5415 switch (placeholder->getKind()) { 5416 // Ignore all the non-placeholder types. 5417 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5418 case BuiltinType::Id: 5419 #include "clang/Basic/OpenCLImageTypes.def" 5420 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5421 case BuiltinType::Id: 5422 #include "clang/Basic/OpenCLExtensionTypes.def" 5423 // In practice we'll never use this, since all SVE types are sugared 5424 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5425 #define SVE_TYPE(Name, Id, SingletonId) \ 5426 case BuiltinType::Id: 5427 #include "clang/Basic/AArch64SVEACLETypes.def" 5428 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5429 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5430 #include "clang/AST/BuiltinTypes.def" 5431 return false; 5432 5433 // We cannot lower out overload sets; they might validly be resolved 5434 // by the call machinery. 5435 case BuiltinType::Overload: 5436 return false; 5437 5438 // Unbridged casts in ARC can be handled in some call positions and 5439 // should be left in place. 5440 case BuiltinType::ARCUnbridgedCast: 5441 return false; 5442 5443 // Pseudo-objects should be converted as soon as possible. 5444 case BuiltinType::PseudoObject: 5445 return true; 5446 5447 // The debugger mode could theoretically but currently does not try 5448 // to resolve unknown-typed arguments based on known parameter types. 5449 case BuiltinType::UnknownAny: 5450 return true; 5451 5452 // These are always invalid as call arguments and should be reported. 5453 case BuiltinType::BoundMember: 5454 case BuiltinType::BuiltinFn: 5455 case BuiltinType::OMPArraySection: 5456 return true; 5457 5458 } 5459 llvm_unreachable("bad builtin type kind"); 5460 } 5461 5462 /// Check an argument list for placeholders that we won't try to 5463 /// handle later. 5464 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5465 // Apply this processing to all the arguments at once instead of 5466 // dying at the first failure. 5467 bool hasInvalid = false; 5468 for (size_t i = 0, e = args.size(); i != e; i++) { 5469 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5470 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5471 if (result.isInvalid()) hasInvalid = true; 5472 else args[i] = result.get(); 5473 } else if (hasInvalid) { 5474 (void)S.CorrectDelayedTyposInExpr(args[i]); 5475 } 5476 } 5477 return hasInvalid; 5478 } 5479 5480 /// If a builtin function has a pointer argument with no explicit address 5481 /// space, then it should be able to accept a pointer to any address 5482 /// space as input. In order to do this, we need to replace the 5483 /// standard builtin declaration with one that uses the same address space 5484 /// as the call. 5485 /// 5486 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5487 /// it does not contain any pointer arguments without 5488 /// an address space qualifer. Otherwise the rewritten 5489 /// FunctionDecl is returned. 5490 /// TODO: Handle pointer return types. 5491 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5492 FunctionDecl *FDecl, 5493 MultiExprArg ArgExprs) { 5494 5495 QualType DeclType = FDecl->getType(); 5496 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5497 5498 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5499 ArgExprs.size() < FT->getNumParams()) 5500 return nullptr; 5501 5502 bool NeedsNewDecl = false; 5503 unsigned i = 0; 5504 SmallVector<QualType, 8> OverloadParams; 5505 5506 for (QualType ParamType : FT->param_types()) { 5507 5508 // Convert array arguments to pointer to simplify type lookup. 5509 ExprResult ArgRes = 5510 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5511 if (ArgRes.isInvalid()) 5512 return nullptr; 5513 Expr *Arg = ArgRes.get(); 5514 QualType ArgType = Arg->getType(); 5515 if (!ParamType->isPointerType() || 5516 ParamType.hasAddressSpace() || 5517 !ArgType->isPointerType() || 5518 !ArgType->getPointeeType().hasAddressSpace()) { 5519 OverloadParams.push_back(ParamType); 5520 continue; 5521 } 5522 5523 QualType PointeeType = ParamType->getPointeeType(); 5524 if (PointeeType.hasAddressSpace()) 5525 continue; 5526 5527 NeedsNewDecl = true; 5528 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5529 5530 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5531 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5532 } 5533 5534 if (!NeedsNewDecl) 5535 return nullptr; 5536 5537 FunctionProtoType::ExtProtoInfo EPI; 5538 EPI.Variadic = FT->isVariadic(); 5539 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5540 OverloadParams, EPI); 5541 DeclContext *Parent = FDecl->getParent(); 5542 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5543 FDecl->getLocation(), 5544 FDecl->getLocation(), 5545 FDecl->getIdentifier(), 5546 OverloadTy, 5547 /*TInfo=*/nullptr, 5548 SC_Extern, false, 5549 /*hasPrototype=*/true); 5550 SmallVector<ParmVarDecl*, 16> Params; 5551 FT = cast<FunctionProtoType>(OverloadTy); 5552 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5553 QualType ParamType = FT->getParamType(i); 5554 ParmVarDecl *Parm = 5555 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5556 SourceLocation(), nullptr, ParamType, 5557 /*TInfo=*/nullptr, SC_None, nullptr); 5558 Parm->setScopeInfo(0, i); 5559 Params.push_back(Parm); 5560 } 5561 OverloadDecl->setParams(Params); 5562 return OverloadDecl; 5563 } 5564 5565 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5566 FunctionDecl *Callee, 5567 MultiExprArg ArgExprs) { 5568 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5569 // similar attributes) really don't like it when functions are called with an 5570 // invalid number of args. 5571 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5572 /*PartialOverloading=*/false) && 5573 !Callee->isVariadic()) 5574 return; 5575 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5576 return; 5577 5578 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5579 S.Diag(Fn->getBeginLoc(), 5580 isa<CXXMethodDecl>(Callee) 5581 ? diag::err_ovl_no_viable_member_function_in_call 5582 : diag::err_ovl_no_viable_function_in_call) 5583 << Callee << Callee->getSourceRange(); 5584 S.Diag(Callee->getLocation(), 5585 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5586 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5587 return; 5588 } 5589 } 5590 5591 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5592 const UnresolvedMemberExpr *const UME, Sema &S) { 5593 5594 const auto GetFunctionLevelDCIfCXXClass = 5595 [](Sema &S) -> const CXXRecordDecl * { 5596 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5597 if (!DC || !DC->getParent()) 5598 return nullptr; 5599 5600 // If the call to some member function was made from within a member 5601 // function body 'M' return return 'M's parent. 5602 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5603 return MD->getParent()->getCanonicalDecl(); 5604 // else the call was made from within a default member initializer of a 5605 // class, so return the class. 5606 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5607 return RD->getCanonicalDecl(); 5608 return nullptr; 5609 }; 5610 // If our DeclContext is neither a member function nor a class (in the 5611 // case of a lambda in a default member initializer), we can't have an 5612 // enclosing 'this'. 5613 5614 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5615 if (!CurParentClass) 5616 return false; 5617 5618 // The naming class for implicit member functions call is the class in which 5619 // name lookup starts. 5620 const CXXRecordDecl *const NamingClass = 5621 UME->getNamingClass()->getCanonicalDecl(); 5622 assert(NamingClass && "Must have naming class even for implicit access"); 5623 5624 // If the unresolved member functions were found in a 'naming class' that is 5625 // related (either the same or derived from) to the class that contains the 5626 // member function that itself contained the implicit member access. 5627 5628 return CurParentClass == NamingClass || 5629 CurParentClass->isDerivedFrom(NamingClass); 5630 } 5631 5632 static void 5633 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5634 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5635 5636 if (!UME) 5637 return; 5638 5639 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5640 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5641 // already been captured, or if this is an implicit member function call (if 5642 // it isn't, an attempt to capture 'this' should already have been made). 5643 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5644 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5645 return; 5646 5647 // Check if the naming class in which the unresolved members were found is 5648 // related (same as or is a base of) to the enclosing class. 5649 5650 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5651 return; 5652 5653 5654 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5655 // If the enclosing function is not dependent, then this lambda is 5656 // capture ready, so if we can capture this, do so. 5657 if (!EnclosingFunctionCtx->isDependentContext()) { 5658 // If the current lambda and all enclosing lambdas can capture 'this' - 5659 // then go ahead and capture 'this' (since our unresolved overload set 5660 // contains at least one non-static member function). 5661 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5662 S.CheckCXXThisCapture(CallLoc); 5663 } else if (S.CurContext->isDependentContext()) { 5664 // ... since this is an implicit member reference, that might potentially 5665 // involve a 'this' capture, mark 'this' for potential capture in 5666 // enclosing lambdas. 5667 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5668 CurLSI->addPotentialThisCapture(CallLoc); 5669 } 5670 } 5671 5672 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5673 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5674 Expr *ExecConfig) { 5675 ExprResult Call = 5676 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5677 if (Call.isInvalid()) 5678 return Call; 5679 5680 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5681 // language modes. 5682 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5683 if (ULE->hasExplicitTemplateArgs() && 5684 ULE->decls_begin() == ULE->decls_end()) { 5685 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5686 ? diag::warn_cxx17_compat_adl_only_template_id 5687 : diag::ext_adl_only_template_id) 5688 << ULE->getName(); 5689 } 5690 } 5691 5692 return Call; 5693 } 5694 5695 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5696 /// This provides the location of the left/right parens and a list of comma 5697 /// locations. 5698 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5699 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5700 Expr *ExecConfig, bool IsExecConfig) { 5701 // Since this might be a postfix expression, get rid of ParenListExprs. 5702 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5703 if (Result.isInvalid()) return ExprError(); 5704 Fn = Result.get(); 5705 5706 if (checkArgsForPlaceholders(*this, ArgExprs)) 5707 return ExprError(); 5708 5709 if (getLangOpts().CPlusPlus) { 5710 // If this is a pseudo-destructor expression, build the call immediately. 5711 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5712 if (!ArgExprs.empty()) { 5713 // Pseudo-destructor calls should not have any arguments. 5714 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5715 << FixItHint::CreateRemoval( 5716 SourceRange(ArgExprs.front()->getBeginLoc(), 5717 ArgExprs.back()->getEndLoc())); 5718 } 5719 5720 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5721 VK_RValue, RParenLoc); 5722 } 5723 if (Fn->getType() == Context.PseudoObjectTy) { 5724 ExprResult result = CheckPlaceholderExpr(Fn); 5725 if (result.isInvalid()) return ExprError(); 5726 Fn = result.get(); 5727 } 5728 5729 // Determine whether this is a dependent call inside a C++ template, 5730 // in which case we won't do any semantic analysis now. 5731 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5732 if (ExecConfig) { 5733 return CUDAKernelCallExpr::Create( 5734 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5735 Context.DependentTy, VK_RValue, RParenLoc); 5736 } else { 5737 5738 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5739 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5740 Fn->getBeginLoc()); 5741 5742 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5743 VK_RValue, RParenLoc); 5744 } 5745 } 5746 5747 // Determine whether this is a call to an object (C++ [over.call.object]). 5748 if (Fn->getType()->isRecordType()) 5749 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5750 RParenLoc); 5751 5752 if (Fn->getType() == Context.UnknownAnyTy) { 5753 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5754 if (result.isInvalid()) return ExprError(); 5755 Fn = result.get(); 5756 } 5757 5758 if (Fn->getType() == Context.BoundMemberTy) { 5759 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5760 RParenLoc); 5761 } 5762 } 5763 5764 // Check for overloaded calls. This can happen even in C due to extensions. 5765 if (Fn->getType() == Context.OverloadTy) { 5766 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5767 5768 // We aren't supposed to apply this logic if there's an '&' involved. 5769 if (!find.HasFormOfMemberPointer) { 5770 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5771 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5772 VK_RValue, RParenLoc); 5773 OverloadExpr *ovl = find.Expression; 5774 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5775 return BuildOverloadedCallExpr( 5776 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5777 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5778 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5779 RParenLoc); 5780 } 5781 } 5782 5783 // If we're directly calling a function, get the appropriate declaration. 5784 if (Fn->getType() == Context.UnknownAnyTy) { 5785 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5786 if (result.isInvalid()) return ExprError(); 5787 Fn = result.get(); 5788 } 5789 5790 Expr *NakedFn = Fn->IgnoreParens(); 5791 5792 bool CallingNDeclIndirectly = false; 5793 NamedDecl *NDecl = nullptr; 5794 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5795 if (UnOp->getOpcode() == UO_AddrOf) { 5796 CallingNDeclIndirectly = true; 5797 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5798 } 5799 } 5800 5801 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5802 NDecl = DRE->getDecl(); 5803 5804 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5805 if (FDecl && FDecl->getBuiltinID()) { 5806 // Rewrite the function decl for this builtin by replacing parameters 5807 // with no explicit address space with the address space of the arguments 5808 // in ArgExprs. 5809 if ((FDecl = 5810 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5811 NDecl = FDecl; 5812 Fn = DeclRefExpr::Create( 5813 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5814 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5815 nullptr, DRE->isNonOdrUse()); 5816 } 5817 } 5818 } else if (isa<MemberExpr>(NakedFn)) 5819 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5820 5821 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5822 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5823 FD, /*Complain=*/true, Fn->getBeginLoc())) 5824 return ExprError(); 5825 5826 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5827 return ExprError(); 5828 5829 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5830 } 5831 5832 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5833 ExecConfig, IsExecConfig); 5834 } 5835 5836 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5837 /// 5838 /// __builtin_astype( value, dst type ) 5839 /// 5840 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5841 SourceLocation BuiltinLoc, 5842 SourceLocation RParenLoc) { 5843 ExprValueKind VK = VK_RValue; 5844 ExprObjectKind OK = OK_Ordinary; 5845 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5846 QualType SrcTy = E->getType(); 5847 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5848 return ExprError(Diag(BuiltinLoc, 5849 diag::err_invalid_astype_of_different_size) 5850 << DstTy 5851 << SrcTy 5852 << E->getSourceRange()); 5853 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5854 } 5855 5856 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5857 /// provided arguments. 5858 /// 5859 /// __builtin_convertvector( value, dst type ) 5860 /// 5861 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5862 SourceLocation BuiltinLoc, 5863 SourceLocation RParenLoc) { 5864 TypeSourceInfo *TInfo; 5865 GetTypeFromParser(ParsedDestTy, &TInfo); 5866 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5867 } 5868 5869 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5870 /// i.e. an expression not of \p OverloadTy. The expression should 5871 /// unary-convert to an expression of function-pointer or 5872 /// block-pointer type. 5873 /// 5874 /// \param NDecl the declaration being called, if available 5875 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5876 SourceLocation LParenLoc, 5877 ArrayRef<Expr *> Args, 5878 SourceLocation RParenLoc, Expr *Config, 5879 bool IsExecConfig, ADLCallKind UsesADL) { 5880 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5881 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5882 5883 // Functions with 'interrupt' attribute cannot be called directly. 5884 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5885 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5886 return ExprError(); 5887 } 5888 5889 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5890 // so there's some risk when calling out to non-interrupt handler functions 5891 // that the callee might not preserve them. This is easy to diagnose here, 5892 // but can be very challenging to debug. 5893 if (auto *Caller = getCurFunctionDecl()) 5894 if (Caller->hasAttr<ARMInterruptAttr>()) { 5895 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5896 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5897 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5898 } 5899 5900 // Promote the function operand. 5901 // We special-case function promotion here because we only allow promoting 5902 // builtin functions to function pointers in the callee of a call. 5903 ExprResult Result; 5904 QualType ResultTy; 5905 if (BuiltinID && 5906 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5907 // Extract the return type from the (builtin) function pointer type. 5908 // FIXME Several builtins still have setType in 5909 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5910 // Builtins.def to ensure they are correct before removing setType calls. 5911 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5912 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5913 ResultTy = FDecl->getCallResultType(); 5914 } else { 5915 Result = CallExprUnaryConversions(Fn); 5916 ResultTy = Context.BoolTy; 5917 } 5918 if (Result.isInvalid()) 5919 return ExprError(); 5920 Fn = Result.get(); 5921 5922 // Check for a valid function type, but only if it is not a builtin which 5923 // requires custom type checking. These will be handled by 5924 // CheckBuiltinFunctionCall below just after creation of the call expression. 5925 const FunctionType *FuncT = nullptr; 5926 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5927 retry: 5928 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5929 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5930 // have type pointer to function". 5931 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5932 if (!FuncT) 5933 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5934 << Fn->getType() << Fn->getSourceRange()); 5935 } else if (const BlockPointerType *BPT = 5936 Fn->getType()->getAs<BlockPointerType>()) { 5937 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5938 } else { 5939 // Handle calls to expressions of unknown-any type. 5940 if (Fn->getType() == Context.UnknownAnyTy) { 5941 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5942 if (rewrite.isInvalid()) 5943 return ExprError(); 5944 Fn = rewrite.get(); 5945 goto retry; 5946 } 5947 5948 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5949 << Fn->getType() << Fn->getSourceRange()); 5950 } 5951 } 5952 5953 // Get the number of parameters in the function prototype, if any. 5954 // We will allocate space for max(Args.size(), NumParams) arguments 5955 // in the call expression. 5956 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5957 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5958 5959 CallExpr *TheCall; 5960 if (Config) { 5961 assert(UsesADL == ADLCallKind::NotADL && 5962 "CUDAKernelCallExpr should not use ADL"); 5963 TheCall = 5964 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 5965 ResultTy, VK_RValue, RParenLoc, NumParams); 5966 } else { 5967 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5968 RParenLoc, NumParams, UsesADL); 5969 } 5970 5971 if (!getLangOpts().CPlusPlus) { 5972 // Forget about the nulled arguments since typo correction 5973 // do not handle them well. 5974 TheCall->shrinkNumArgs(Args.size()); 5975 // C cannot always handle TypoExpr nodes in builtin calls and direct 5976 // function calls as their argument checking don't necessarily handle 5977 // dependent types properly, so make sure any TypoExprs have been 5978 // dealt with. 5979 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5980 if (!Result.isUsable()) return ExprError(); 5981 CallExpr *TheOldCall = TheCall; 5982 TheCall = dyn_cast<CallExpr>(Result.get()); 5983 bool CorrectedTypos = TheCall != TheOldCall; 5984 if (!TheCall) return Result; 5985 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5986 5987 // A new call expression node was created if some typos were corrected. 5988 // However it may not have been constructed with enough storage. In this 5989 // case, rebuild the node with enough storage. The waste of space is 5990 // immaterial since this only happens when some typos were corrected. 5991 if (CorrectedTypos && Args.size() < NumParams) { 5992 if (Config) 5993 TheCall = CUDAKernelCallExpr::Create( 5994 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 5995 RParenLoc, NumParams); 5996 else 5997 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 5998 RParenLoc, NumParams, UsesADL); 5999 } 6000 // We can now handle the nulled arguments for the default arguments. 6001 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6002 } 6003 6004 // Bail out early if calling a builtin with custom type checking. 6005 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6006 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6007 6008 if (getLangOpts().CUDA) { 6009 if (Config) { 6010 // CUDA: Kernel calls must be to global functions 6011 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6012 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6013 << FDecl << Fn->getSourceRange()); 6014 6015 // CUDA: Kernel function must have 'void' return type 6016 if (!FuncT->getReturnType()->isVoidType() && 6017 !FuncT->getReturnType()->getAs<AutoType>() && 6018 !FuncT->getReturnType()->isInstantiationDependentType()) 6019 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6020 << Fn->getType() << Fn->getSourceRange()); 6021 } else { 6022 // CUDA: Calls to global functions must be configured 6023 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6024 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6025 << FDecl << Fn->getSourceRange()); 6026 } 6027 } 6028 6029 // Check for a valid return type 6030 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6031 FDecl)) 6032 return ExprError(); 6033 6034 // We know the result type of the call, set it. 6035 TheCall->setType(FuncT->getCallResultType(Context)); 6036 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6037 6038 if (Proto) { 6039 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6040 IsExecConfig)) 6041 return ExprError(); 6042 } else { 6043 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6044 6045 if (FDecl) { 6046 // Check if we have too few/too many template arguments, based 6047 // on our knowledge of the function definition. 6048 const FunctionDecl *Def = nullptr; 6049 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6050 Proto = Def->getType()->getAs<FunctionProtoType>(); 6051 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6052 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6053 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6054 } 6055 6056 // If the function we're calling isn't a function prototype, but we have 6057 // a function prototype from a prior declaratiom, use that prototype. 6058 if (!FDecl->hasPrototype()) 6059 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6060 } 6061 6062 // Promote the arguments (C99 6.5.2.2p6). 6063 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6064 Expr *Arg = Args[i]; 6065 6066 if (Proto && i < Proto->getNumParams()) { 6067 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6068 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6069 ExprResult ArgE = 6070 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6071 if (ArgE.isInvalid()) 6072 return true; 6073 6074 Arg = ArgE.getAs<Expr>(); 6075 6076 } else { 6077 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6078 6079 if (ArgE.isInvalid()) 6080 return true; 6081 6082 Arg = ArgE.getAs<Expr>(); 6083 } 6084 6085 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6086 diag::err_call_incomplete_argument, Arg)) 6087 return ExprError(); 6088 6089 TheCall->setArg(i, Arg); 6090 } 6091 } 6092 6093 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6094 if (!Method->isStatic()) 6095 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6096 << Fn->getSourceRange()); 6097 6098 // Check for sentinels 6099 if (NDecl) 6100 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6101 6102 // Do special checking on direct calls to functions. 6103 if (FDecl) { 6104 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6105 return ExprError(); 6106 6107 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6108 6109 if (BuiltinID) 6110 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6111 } else if (NDecl) { 6112 if (CheckPointerCall(NDecl, TheCall, Proto)) 6113 return ExprError(); 6114 } else { 6115 if (CheckOtherCall(TheCall, Proto)) 6116 return ExprError(); 6117 } 6118 6119 return MaybeBindToTemporary(TheCall); 6120 } 6121 6122 ExprResult 6123 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6124 SourceLocation RParenLoc, Expr *InitExpr) { 6125 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6126 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6127 6128 TypeSourceInfo *TInfo; 6129 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6130 if (!TInfo) 6131 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6132 6133 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6134 } 6135 6136 ExprResult 6137 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6138 SourceLocation RParenLoc, Expr *LiteralExpr) { 6139 QualType literalType = TInfo->getType(); 6140 6141 if (literalType->isArrayType()) { 6142 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 6143 diag::err_illegal_decl_array_incomplete_type, 6144 SourceRange(LParenLoc, 6145 LiteralExpr->getSourceRange().getEnd()))) 6146 return ExprError(); 6147 if (literalType->isVariableArrayType()) 6148 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6149 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6150 } else if (!literalType->isDependentType() && 6151 RequireCompleteType(LParenLoc, literalType, 6152 diag::err_typecheck_decl_incomplete_type, 6153 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6154 return ExprError(); 6155 6156 InitializedEntity Entity 6157 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6158 InitializationKind Kind 6159 = InitializationKind::CreateCStyleCast(LParenLoc, 6160 SourceRange(LParenLoc, RParenLoc), 6161 /*InitList=*/true); 6162 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6163 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6164 &literalType); 6165 if (Result.isInvalid()) 6166 return ExprError(); 6167 LiteralExpr = Result.get(); 6168 6169 bool isFileScope = !CurContext->isFunctionOrMethod(); 6170 6171 // In C, compound literals are l-values for some reason. 6172 // For GCC compatibility, in C++, file-scope array compound literals with 6173 // constant initializers are also l-values, and compound literals are 6174 // otherwise prvalues. 6175 // 6176 // (GCC also treats C++ list-initialized file-scope array prvalues with 6177 // constant initializers as l-values, but that's non-conforming, so we don't 6178 // follow it there.) 6179 // 6180 // FIXME: It would be better to handle the lvalue cases as materializing and 6181 // lifetime-extending a temporary object, but our materialized temporaries 6182 // representation only supports lifetime extension from a variable, not "out 6183 // of thin air". 6184 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6185 // is bound to the result of applying array-to-pointer decay to the compound 6186 // literal. 6187 // FIXME: GCC supports compound literals of reference type, which should 6188 // obviously have a value kind derived from the kind of reference involved. 6189 ExprValueKind VK = 6190 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6191 ? VK_RValue 6192 : VK_LValue; 6193 6194 if (isFileScope) 6195 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6196 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6197 Expr *Init = ILE->getInit(i); 6198 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6199 } 6200 6201 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6202 VK, LiteralExpr, isFileScope); 6203 if (isFileScope) { 6204 if (!LiteralExpr->isTypeDependent() && 6205 !LiteralExpr->isValueDependent() && 6206 !literalType->isDependentType()) // C99 6.5.2.5p3 6207 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6208 return ExprError(); 6209 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6210 literalType.getAddressSpace() != LangAS::Default) { 6211 // Embedded-C extensions to C99 6.5.2.5: 6212 // "If the compound literal occurs inside the body of a function, the 6213 // type name shall not be qualified by an address-space qualifier." 6214 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6215 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6216 return ExprError(); 6217 } 6218 6219 // Compound literals that have automatic storage duration are destroyed at 6220 // the end of the scope. Emit diagnostics if it is or contains a C union type 6221 // that is non-trivial to destruct. 6222 if (!isFileScope) 6223 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6224 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6225 NTCUC_CompoundLiteral, NTCUK_Destruct); 6226 6227 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6228 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6229 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6230 E->getInitializer()->getExprLoc()); 6231 6232 return MaybeBindToTemporary(E); 6233 } 6234 6235 ExprResult 6236 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6237 SourceLocation RBraceLoc) { 6238 // Only produce each kind of designated initialization diagnostic once. 6239 SourceLocation FirstDesignator; 6240 bool DiagnosedArrayDesignator = false; 6241 bool DiagnosedNestedDesignator = false; 6242 bool DiagnosedMixedDesignator = false; 6243 6244 // Check that any designated initializers are syntactically valid in the 6245 // current language mode. 6246 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6247 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6248 if (FirstDesignator.isInvalid()) 6249 FirstDesignator = DIE->getBeginLoc(); 6250 6251 if (!getLangOpts().CPlusPlus) 6252 break; 6253 6254 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6255 DiagnosedNestedDesignator = true; 6256 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6257 << DIE->getDesignatorsSourceRange(); 6258 } 6259 6260 for (auto &Desig : DIE->designators()) { 6261 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6262 DiagnosedArrayDesignator = true; 6263 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6264 << Desig.getSourceRange(); 6265 } 6266 } 6267 6268 if (!DiagnosedMixedDesignator && 6269 !isa<DesignatedInitExpr>(InitArgList[0])) { 6270 DiagnosedMixedDesignator = true; 6271 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6272 << DIE->getSourceRange(); 6273 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6274 << InitArgList[0]->getSourceRange(); 6275 } 6276 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6277 isa<DesignatedInitExpr>(InitArgList[0])) { 6278 DiagnosedMixedDesignator = true; 6279 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6280 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6281 << DIE->getSourceRange(); 6282 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6283 << InitArgList[I]->getSourceRange(); 6284 } 6285 } 6286 6287 if (FirstDesignator.isValid()) { 6288 // Only diagnose designated initiaization as a C++20 extension if we didn't 6289 // already diagnose use of (non-C++20) C99 designator syntax. 6290 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6291 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6292 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6293 ? diag::warn_cxx17_compat_designated_init 6294 : diag::ext_cxx_designated_init); 6295 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6296 Diag(FirstDesignator, diag::ext_designated_init); 6297 } 6298 } 6299 6300 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6301 } 6302 6303 ExprResult 6304 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6305 SourceLocation RBraceLoc) { 6306 // Semantic analysis for initializers is done by ActOnDeclarator() and 6307 // CheckInitializer() - it requires knowledge of the object being initialized. 6308 6309 // Immediately handle non-overload placeholders. Overloads can be 6310 // resolved contextually, but everything else here can't. 6311 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6312 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6313 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6314 6315 // Ignore failures; dropping the entire initializer list because 6316 // of one failure would be terrible for indexing/etc. 6317 if (result.isInvalid()) continue; 6318 6319 InitArgList[I] = result.get(); 6320 } 6321 } 6322 6323 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6324 RBraceLoc); 6325 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6326 return E; 6327 } 6328 6329 /// Do an explicit extend of the given block pointer if we're in ARC. 6330 void Sema::maybeExtendBlockObject(ExprResult &E) { 6331 assert(E.get()->getType()->isBlockPointerType()); 6332 assert(E.get()->isRValue()); 6333 6334 // Only do this in an r-value context. 6335 if (!getLangOpts().ObjCAutoRefCount) return; 6336 6337 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6338 CK_ARCExtendBlockObject, E.get(), 6339 /*base path*/ nullptr, VK_RValue); 6340 Cleanup.setExprNeedsCleanups(true); 6341 } 6342 6343 /// Prepare a conversion of the given expression to an ObjC object 6344 /// pointer type. 6345 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6346 QualType type = E.get()->getType(); 6347 if (type->isObjCObjectPointerType()) { 6348 return CK_BitCast; 6349 } else if (type->isBlockPointerType()) { 6350 maybeExtendBlockObject(E); 6351 return CK_BlockPointerToObjCPointerCast; 6352 } else { 6353 assert(type->isPointerType()); 6354 return CK_CPointerToObjCPointerCast; 6355 } 6356 } 6357 6358 /// Prepares for a scalar cast, performing all the necessary stages 6359 /// except the final cast and returning the kind required. 6360 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6361 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6362 // Also, callers should have filtered out the invalid cases with 6363 // pointers. Everything else should be possible. 6364 6365 QualType SrcTy = Src.get()->getType(); 6366 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6367 return CK_NoOp; 6368 6369 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6370 case Type::STK_MemberPointer: 6371 llvm_unreachable("member pointer type in C"); 6372 6373 case Type::STK_CPointer: 6374 case Type::STK_BlockPointer: 6375 case Type::STK_ObjCObjectPointer: 6376 switch (DestTy->getScalarTypeKind()) { 6377 case Type::STK_CPointer: { 6378 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6379 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6380 if (SrcAS != DestAS) 6381 return CK_AddressSpaceConversion; 6382 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6383 return CK_NoOp; 6384 return CK_BitCast; 6385 } 6386 case Type::STK_BlockPointer: 6387 return (SrcKind == Type::STK_BlockPointer 6388 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6389 case Type::STK_ObjCObjectPointer: 6390 if (SrcKind == Type::STK_ObjCObjectPointer) 6391 return CK_BitCast; 6392 if (SrcKind == Type::STK_CPointer) 6393 return CK_CPointerToObjCPointerCast; 6394 maybeExtendBlockObject(Src); 6395 return CK_BlockPointerToObjCPointerCast; 6396 case Type::STK_Bool: 6397 return CK_PointerToBoolean; 6398 case Type::STK_Integral: 6399 return CK_PointerToIntegral; 6400 case Type::STK_Floating: 6401 case Type::STK_FloatingComplex: 6402 case Type::STK_IntegralComplex: 6403 case Type::STK_MemberPointer: 6404 case Type::STK_FixedPoint: 6405 llvm_unreachable("illegal cast from pointer"); 6406 } 6407 llvm_unreachable("Should have returned before this"); 6408 6409 case Type::STK_FixedPoint: 6410 switch (DestTy->getScalarTypeKind()) { 6411 case Type::STK_FixedPoint: 6412 return CK_FixedPointCast; 6413 case Type::STK_Bool: 6414 return CK_FixedPointToBoolean; 6415 case Type::STK_Integral: 6416 return CK_FixedPointToIntegral; 6417 case Type::STK_Floating: 6418 case Type::STK_IntegralComplex: 6419 case Type::STK_FloatingComplex: 6420 Diag(Src.get()->getExprLoc(), 6421 diag::err_unimplemented_conversion_with_fixed_point_type) 6422 << DestTy; 6423 return CK_IntegralCast; 6424 case Type::STK_CPointer: 6425 case Type::STK_ObjCObjectPointer: 6426 case Type::STK_BlockPointer: 6427 case Type::STK_MemberPointer: 6428 llvm_unreachable("illegal cast to pointer type"); 6429 } 6430 llvm_unreachable("Should have returned before this"); 6431 6432 case Type::STK_Bool: // casting from bool is like casting from an integer 6433 case Type::STK_Integral: 6434 switch (DestTy->getScalarTypeKind()) { 6435 case Type::STK_CPointer: 6436 case Type::STK_ObjCObjectPointer: 6437 case Type::STK_BlockPointer: 6438 if (Src.get()->isNullPointerConstant(Context, 6439 Expr::NPC_ValueDependentIsNull)) 6440 return CK_NullToPointer; 6441 return CK_IntegralToPointer; 6442 case Type::STK_Bool: 6443 return CK_IntegralToBoolean; 6444 case Type::STK_Integral: 6445 return CK_IntegralCast; 6446 case Type::STK_Floating: 6447 return CK_IntegralToFloating; 6448 case Type::STK_IntegralComplex: 6449 Src = ImpCastExprToType(Src.get(), 6450 DestTy->castAs<ComplexType>()->getElementType(), 6451 CK_IntegralCast); 6452 return CK_IntegralRealToComplex; 6453 case Type::STK_FloatingComplex: 6454 Src = ImpCastExprToType(Src.get(), 6455 DestTy->castAs<ComplexType>()->getElementType(), 6456 CK_IntegralToFloating); 6457 return CK_FloatingRealToComplex; 6458 case Type::STK_MemberPointer: 6459 llvm_unreachable("member pointer type in C"); 6460 case Type::STK_FixedPoint: 6461 return CK_IntegralToFixedPoint; 6462 } 6463 llvm_unreachable("Should have returned before this"); 6464 6465 case Type::STK_Floating: 6466 switch (DestTy->getScalarTypeKind()) { 6467 case Type::STK_Floating: 6468 return CK_FloatingCast; 6469 case Type::STK_Bool: 6470 return CK_FloatingToBoolean; 6471 case Type::STK_Integral: 6472 return CK_FloatingToIntegral; 6473 case Type::STK_FloatingComplex: 6474 Src = ImpCastExprToType(Src.get(), 6475 DestTy->castAs<ComplexType>()->getElementType(), 6476 CK_FloatingCast); 6477 return CK_FloatingRealToComplex; 6478 case Type::STK_IntegralComplex: 6479 Src = ImpCastExprToType(Src.get(), 6480 DestTy->castAs<ComplexType>()->getElementType(), 6481 CK_FloatingToIntegral); 6482 return CK_IntegralRealToComplex; 6483 case Type::STK_CPointer: 6484 case Type::STK_ObjCObjectPointer: 6485 case Type::STK_BlockPointer: 6486 llvm_unreachable("valid float->pointer cast?"); 6487 case Type::STK_MemberPointer: 6488 llvm_unreachable("member pointer type in C"); 6489 case Type::STK_FixedPoint: 6490 Diag(Src.get()->getExprLoc(), 6491 diag::err_unimplemented_conversion_with_fixed_point_type) 6492 << SrcTy; 6493 return CK_IntegralCast; 6494 } 6495 llvm_unreachable("Should have returned before this"); 6496 6497 case Type::STK_FloatingComplex: 6498 switch (DestTy->getScalarTypeKind()) { 6499 case Type::STK_FloatingComplex: 6500 return CK_FloatingComplexCast; 6501 case Type::STK_IntegralComplex: 6502 return CK_FloatingComplexToIntegralComplex; 6503 case Type::STK_Floating: { 6504 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6505 if (Context.hasSameType(ET, DestTy)) 6506 return CK_FloatingComplexToReal; 6507 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6508 return CK_FloatingCast; 6509 } 6510 case Type::STK_Bool: 6511 return CK_FloatingComplexToBoolean; 6512 case Type::STK_Integral: 6513 Src = ImpCastExprToType(Src.get(), 6514 SrcTy->castAs<ComplexType>()->getElementType(), 6515 CK_FloatingComplexToReal); 6516 return CK_FloatingToIntegral; 6517 case Type::STK_CPointer: 6518 case Type::STK_ObjCObjectPointer: 6519 case Type::STK_BlockPointer: 6520 llvm_unreachable("valid complex float->pointer cast?"); 6521 case Type::STK_MemberPointer: 6522 llvm_unreachable("member pointer type in C"); 6523 case Type::STK_FixedPoint: 6524 Diag(Src.get()->getExprLoc(), 6525 diag::err_unimplemented_conversion_with_fixed_point_type) 6526 << SrcTy; 6527 return CK_IntegralCast; 6528 } 6529 llvm_unreachable("Should have returned before this"); 6530 6531 case Type::STK_IntegralComplex: 6532 switch (DestTy->getScalarTypeKind()) { 6533 case Type::STK_FloatingComplex: 6534 return CK_IntegralComplexToFloatingComplex; 6535 case Type::STK_IntegralComplex: 6536 return CK_IntegralComplexCast; 6537 case Type::STK_Integral: { 6538 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6539 if (Context.hasSameType(ET, DestTy)) 6540 return CK_IntegralComplexToReal; 6541 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6542 return CK_IntegralCast; 6543 } 6544 case Type::STK_Bool: 6545 return CK_IntegralComplexToBoolean; 6546 case Type::STK_Floating: 6547 Src = ImpCastExprToType(Src.get(), 6548 SrcTy->castAs<ComplexType>()->getElementType(), 6549 CK_IntegralComplexToReal); 6550 return CK_IntegralToFloating; 6551 case Type::STK_CPointer: 6552 case Type::STK_ObjCObjectPointer: 6553 case Type::STK_BlockPointer: 6554 llvm_unreachable("valid complex int->pointer cast?"); 6555 case Type::STK_MemberPointer: 6556 llvm_unreachable("member pointer type in C"); 6557 case Type::STK_FixedPoint: 6558 Diag(Src.get()->getExprLoc(), 6559 diag::err_unimplemented_conversion_with_fixed_point_type) 6560 << SrcTy; 6561 return CK_IntegralCast; 6562 } 6563 llvm_unreachable("Should have returned before this"); 6564 } 6565 6566 llvm_unreachable("Unhandled scalar cast"); 6567 } 6568 6569 static bool breakDownVectorType(QualType type, uint64_t &len, 6570 QualType &eltType) { 6571 // Vectors are simple. 6572 if (const VectorType *vecType = type->getAs<VectorType>()) { 6573 len = vecType->getNumElements(); 6574 eltType = vecType->getElementType(); 6575 assert(eltType->isScalarType()); 6576 return true; 6577 } 6578 6579 // We allow lax conversion to and from non-vector types, but only if 6580 // they're real types (i.e. non-complex, non-pointer scalar types). 6581 if (!type->isRealType()) return false; 6582 6583 len = 1; 6584 eltType = type; 6585 return true; 6586 } 6587 6588 /// Are the two types lax-compatible vector types? That is, given 6589 /// that one of them is a vector, do they have equal storage sizes, 6590 /// where the storage size is the number of elements times the element 6591 /// size? 6592 /// 6593 /// This will also return false if either of the types is neither a 6594 /// vector nor a real type. 6595 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6596 assert(destTy->isVectorType() || srcTy->isVectorType()); 6597 6598 // Disallow lax conversions between scalars and ExtVectors (these 6599 // conversions are allowed for other vector types because common headers 6600 // depend on them). Most scalar OP ExtVector cases are handled by the 6601 // splat path anyway, which does what we want (convert, not bitcast). 6602 // What this rules out for ExtVectors is crazy things like char4*float. 6603 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6604 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6605 6606 uint64_t srcLen, destLen; 6607 QualType srcEltTy, destEltTy; 6608 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6609 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6610 6611 // ASTContext::getTypeSize will return the size rounded up to a 6612 // power of 2, so instead of using that, we need to use the raw 6613 // element size multiplied by the element count. 6614 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6615 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6616 6617 return (srcLen * srcEltSize == destLen * destEltSize); 6618 } 6619 6620 /// Is this a legal conversion between two types, one of which is 6621 /// known to be a vector type? 6622 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6623 assert(destTy->isVectorType() || srcTy->isVectorType()); 6624 6625 switch (Context.getLangOpts().getLaxVectorConversions()) { 6626 case LangOptions::LaxVectorConversionKind::None: 6627 return false; 6628 6629 case LangOptions::LaxVectorConversionKind::Integer: 6630 if (!srcTy->isIntegralOrEnumerationType()) { 6631 auto *Vec = srcTy->getAs<VectorType>(); 6632 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6633 return false; 6634 } 6635 if (!destTy->isIntegralOrEnumerationType()) { 6636 auto *Vec = destTy->getAs<VectorType>(); 6637 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6638 return false; 6639 } 6640 // OK, integer (vector) -> integer (vector) bitcast. 6641 break; 6642 6643 case LangOptions::LaxVectorConversionKind::All: 6644 break; 6645 } 6646 6647 return areLaxCompatibleVectorTypes(srcTy, destTy); 6648 } 6649 6650 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6651 CastKind &Kind) { 6652 assert(VectorTy->isVectorType() && "Not a vector type!"); 6653 6654 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6655 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6656 return Diag(R.getBegin(), 6657 Ty->isVectorType() ? 6658 diag::err_invalid_conversion_between_vectors : 6659 diag::err_invalid_conversion_between_vector_and_integer) 6660 << VectorTy << Ty << R; 6661 } else 6662 return Diag(R.getBegin(), 6663 diag::err_invalid_conversion_between_vector_and_scalar) 6664 << VectorTy << Ty << R; 6665 6666 Kind = CK_BitCast; 6667 return false; 6668 } 6669 6670 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6671 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6672 6673 if (DestElemTy == SplattedExpr->getType()) 6674 return SplattedExpr; 6675 6676 assert(DestElemTy->isFloatingType() || 6677 DestElemTy->isIntegralOrEnumerationType()); 6678 6679 CastKind CK; 6680 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6681 // OpenCL requires that we convert `true` boolean expressions to -1, but 6682 // only when splatting vectors. 6683 if (DestElemTy->isFloatingType()) { 6684 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6685 // in two steps: boolean to signed integral, then to floating. 6686 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6687 CK_BooleanToSignedIntegral); 6688 SplattedExpr = CastExprRes.get(); 6689 CK = CK_IntegralToFloating; 6690 } else { 6691 CK = CK_BooleanToSignedIntegral; 6692 } 6693 } else { 6694 ExprResult CastExprRes = SplattedExpr; 6695 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6696 if (CastExprRes.isInvalid()) 6697 return ExprError(); 6698 SplattedExpr = CastExprRes.get(); 6699 } 6700 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6701 } 6702 6703 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6704 Expr *CastExpr, CastKind &Kind) { 6705 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6706 6707 QualType SrcTy = CastExpr->getType(); 6708 6709 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6710 // an ExtVectorType. 6711 // In OpenCL, casts between vectors of different types are not allowed. 6712 // (See OpenCL 6.2). 6713 if (SrcTy->isVectorType()) { 6714 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6715 (getLangOpts().OpenCL && 6716 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6717 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6718 << DestTy << SrcTy << R; 6719 return ExprError(); 6720 } 6721 Kind = CK_BitCast; 6722 return CastExpr; 6723 } 6724 6725 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6726 // conversion will take place first from scalar to elt type, and then 6727 // splat from elt type to vector. 6728 if (SrcTy->isPointerType()) 6729 return Diag(R.getBegin(), 6730 diag::err_invalid_conversion_between_vector_and_scalar) 6731 << DestTy << SrcTy << R; 6732 6733 Kind = CK_VectorSplat; 6734 return prepareVectorSplat(DestTy, CastExpr); 6735 } 6736 6737 ExprResult 6738 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6739 Declarator &D, ParsedType &Ty, 6740 SourceLocation RParenLoc, Expr *CastExpr) { 6741 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6742 "ActOnCastExpr(): missing type or expr"); 6743 6744 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6745 if (D.isInvalidType()) 6746 return ExprError(); 6747 6748 if (getLangOpts().CPlusPlus) { 6749 // Check that there are no default arguments (C++ only). 6750 CheckExtraCXXDefaultArguments(D); 6751 } else { 6752 // Make sure any TypoExprs have been dealt with. 6753 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6754 if (!Res.isUsable()) 6755 return ExprError(); 6756 CastExpr = Res.get(); 6757 } 6758 6759 checkUnusedDeclAttributes(D); 6760 6761 QualType castType = castTInfo->getType(); 6762 Ty = CreateParsedType(castType, castTInfo); 6763 6764 bool isVectorLiteral = false; 6765 6766 // Check for an altivec or OpenCL literal, 6767 // i.e. all the elements are integer constants. 6768 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6769 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6770 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6771 && castType->isVectorType() && (PE || PLE)) { 6772 if (PLE && PLE->getNumExprs() == 0) { 6773 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6774 return ExprError(); 6775 } 6776 if (PE || PLE->getNumExprs() == 1) { 6777 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6778 if (!E->getType()->isVectorType()) 6779 isVectorLiteral = true; 6780 } 6781 else 6782 isVectorLiteral = true; 6783 } 6784 6785 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6786 // then handle it as such. 6787 if (isVectorLiteral) 6788 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6789 6790 // If the Expr being casted is a ParenListExpr, handle it specially. 6791 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6792 // sequence of BinOp comma operators. 6793 if (isa<ParenListExpr>(CastExpr)) { 6794 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6795 if (Result.isInvalid()) return ExprError(); 6796 CastExpr = Result.get(); 6797 } 6798 6799 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6800 !getSourceManager().isInSystemMacro(LParenLoc)) 6801 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6802 6803 CheckTollFreeBridgeCast(castType, CastExpr); 6804 6805 CheckObjCBridgeRelatedCast(castType, CastExpr); 6806 6807 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6808 6809 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6810 } 6811 6812 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6813 SourceLocation RParenLoc, Expr *E, 6814 TypeSourceInfo *TInfo) { 6815 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6816 "Expected paren or paren list expression"); 6817 6818 Expr **exprs; 6819 unsigned numExprs; 6820 Expr *subExpr; 6821 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6822 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6823 LiteralLParenLoc = PE->getLParenLoc(); 6824 LiteralRParenLoc = PE->getRParenLoc(); 6825 exprs = PE->getExprs(); 6826 numExprs = PE->getNumExprs(); 6827 } else { // isa<ParenExpr> by assertion at function entrance 6828 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6829 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6830 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6831 exprs = &subExpr; 6832 numExprs = 1; 6833 } 6834 6835 QualType Ty = TInfo->getType(); 6836 assert(Ty->isVectorType() && "Expected vector type"); 6837 6838 SmallVector<Expr *, 8> initExprs; 6839 const VectorType *VTy = Ty->castAs<VectorType>(); 6840 unsigned numElems = VTy->getNumElements(); 6841 6842 // '(...)' form of vector initialization in AltiVec: the number of 6843 // initializers must be one or must match the size of the vector. 6844 // If a single value is specified in the initializer then it will be 6845 // replicated to all the components of the vector 6846 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6847 // The number of initializers must be one or must match the size of the 6848 // vector. If a single value is specified in the initializer then it will 6849 // be replicated to all the components of the vector 6850 if (numExprs == 1) { 6851 QualType ElemTy = VTy->getElementType(); 6852 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6853 if (Literal.isInvalid()) 6854 return ExprError(); 6855 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6856 PrepareScalarCast(Literal, ElemTy)); 6857 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6858 } 6859 else if (numExprs < numElems) { 6860 Diag(E->getExprLoc(), 6861 diag::err_incorrect_number_of_vector_initializers); 6862 return ExprError(); 6863 } 6864 else 6865 initExprs.append(exprs, exprs + numExprs); 6866 } 6867 else { 6868 // For OpenCL, when the number of initializers is a single value, 6869 // it will be replicated to all components of the vector. 6870 if (getLangOpts().OpenCL && 6871 VTy->getVectorKind() == VectorType::GenericVector && 6872 numExprs == 1) { 6873 QualType ElemTy = VTy->getElementType(); 6874 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6875 if (Literal.isInvalid()) 6876 return ExprError(); 6877 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6878 PrepareScalarCast(Literal, ElemTy)); 6879 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6880 } 6881 6882 initExprs.append(exprs, exprs + numExprs); 6883 } 6884 // FIXME: This means that pretty-printing the final AST will produce curly 6885 // braces instead of the original commas. 6886 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6887 initExprs, LiteralRParenLoc); 6888 initE->setType(Ty); 6889 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6890 } 6891 6892 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6893 /// the ParenListExpr into a sequence of comma binary operators. 6894 ExprResult 6895 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6896 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6897 if (!E) 6898 return OrigExpr; 6899 6900 ExprResult Result(E->getExpr(0)); 6901 6902 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6903 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6904 E->getExpr(i)); 6905 6906 if (Result.isInvalid()) return ExprError(); 6907 6908 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6909 } 6910 6911 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6912 SourceLocation R, 6913 MultiExprArg Val) { 6914 return ParenListExpr::Create(Context, L, Val, R); 6915 } 6916 6917 /// Emit a specialized diagnostic when one expression is a null pointer 6918 /// constant and the other is not a pointer. Returns true if a diagnostic is 6919 /// emitted. 6920 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6921 SourceLocation QuestionLoc) { 6922 Expr *NullExpr = LHSExpr; 6923 Expr *NonPointerExpr = RHSExpr; 6924 Expr::NullPointerConstantKind NullKind = 6925 NullExpr->isNullPointerConstant(Context, 6926 Expr::NPC_ValueDependentIsNotNull); 6927 6928 if (NullKind == Expr::NPCK_NotNull) { 6929 NullExpr = RHSExpr; 6930 NonPointerExpr = LHSExpr; 6931 NullKind = 6932 NullExpr->isNullPointerConstant(Context, 6933 Expr::NPC_ValueDependentIsNotNull); 6934 } 6935 6936 if (NullKind == Expr::NPCK_NotNull) 6937 return false; 6938 6939 if (NullKind == Expr::NPCK_ZeroExpression) 6940 return false; 6941 6942 if (NullKind == Expr::NPCK_ZeroLiteral) { 6943 // In this case, check to make sure that we got here from a "NULL" 6944 // string in the source code. 6945 NullExpr = NullExpr->IgnoreParenImpCasts(); 6946 SourceLocation loc = NullExpr->getExprLoc(); 6947 if (!findMacroSpelling(loc, "NULL")) 6948 return false; 6949 } 6950 6951 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6952 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6953 << NonPointerExpr->getType() << DiagType 6954 << NonPointerExpr->getSourceRange(); 6955 return true; 6956 } 6957 6958 /// Return false if the condition expression is valid, true otherwise. 6959 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6960 QualType CondTy = Cond->getType(); 6961 6962 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6963 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6964 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6965 << CondTy << Cond->getSourceRange(); 6966 return true; 6967 } 6968 6969 // C99 6.5.15p2 6970 if (CondTy->isScalarType()) return false; 6971 6972 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6973 << CondTy << Cond->getSourceRange(); 6974 return true; 6975 } 6976 6977 /// Handle when one or both operands are void type. 6978 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6979 ExprResult &RHS) { 6980 Expr *LHSExpr = LHS.get(); 6981 Expr *RHSExpr = RHS.get(); 6982 6983 if (!LHSExpr->getType()->isVoidType()) 6984 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6985 << RHSExpr->getSourceRange(); 6986 if (!RHSExpr->getType()->isVoidType()) 6987 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6988 << LHSExpr->getSourceRange(); 6989 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6990 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6991 return S.Context.VoidTy; 6992 } 6993 6994 /// Return false if the NullExpr can be promoted to PointerTy, 6995 /// true otherwise. 6996 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6997 QualType PointerTy) { 6998 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6999 !NullExpr.get()->isNullPointerConstant(S.Context, 7000 Expr::NPC_ValueDependentIsNull)) 7001 return true; 7002 7003 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7004 return false; 7005 } 7006 7007 /// Checks compatibility between two pointers and return the resulting 7008 /// type. 7009 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7010 ExprResult &RHS, 7011 SourceLocation Loc) { 7012 QualType LHSTy = LHS.get()->getType(); 7013 QualType RHSTy = RHS.get()->getType(); 7014 7015 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7016 // Two identical pointers types are always compatible. 7017 return LHSTy; 7018 } 7019 7020 QualType lhptee, rhptee; 7021 7022 // Get the pointee types. 7023 bool IsBlockPointer = false; 7024 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7025 lhptee = LHSBTy->getPointeeType(); 7026 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7027 IsBlockPointer = true; 7028 } else { 7029 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7030 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7031 } 7032 7033 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7034 // differently qualified versions of compatible types, the result type is 7035 // a pointer to an appropriately qualified version of the composite 7036 // type. 7037 7038 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7039 // clause doesn't make sense for our extensions. E.g. address space 2 should 7040 // be incompatible with address space 3: they may live on different devices or 7041 // anything. 7042 Qualifiers lhQual = lhptee.getQualifiers(); 7043 Qualifiers rhQual = rhptee.getQualifiers(); 7044 7045 LangAS ResultAddrSpace = LangAS::Default; 7046 LangAS LAddrSpace = lhQual.getAddressSpace(); 7047 LangAS RAddrSpace = rhQual.getAddressSpace(); 7048 7049 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7050 // spaces is disallowed. 7051 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7052 ResultAddrSpace = LAddrSpace; 7053 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7054 ResultAddrSpace = RAddrSpace; 7055 else { 7056 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7057 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7058 << RHS.get()->getSourceRange(); 7059 return QualType(); 7060 } 7061 7062 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7063 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7064 lhQual.removeCVRQualifiers(); 7065 rhQual.removeCVRQualifiers(); 7066 7067 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7068 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7069 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7070 // qual types are compatible iff 7071 // * corresponded types are compatible 7072 // * CVR qualifiers are equal 7073 // * address spaces are equal 7074 // Thus for conditional operator we merge CVR and address space unqualified 7075 // pointees and if there is a composite type we return a pointer to it with 7076 // merged qualifiers. 7077 LHSCastKind = 7078 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7079 RHSCastKind = 7080 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7081 lhQual.removeAddressSpace(); 7082 rhQual.removeAddressSpace(); 7083 7084 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7085 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7086 7087 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7088 7089 if (CompositeTy.isNull()) { 7090 // In this situation, we assume void* type. No especially good 7091 // reason, but this is what gcc does, and we do have to pick 7092 // to get a consistent AST. 7093 QualType incompatTy; 7094 incompatTy = S.Context.getPointerType( 7095 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7096 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7097 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7098 7099 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7100 // for casts between types with incompatible address space qualifiers. 7101 // For the following code the compiler produces casts between global and 7102 // local address spaces of the corresponded innermost pointees: 7103 // local int *global *a; 7104 // global int *global *b; 7105 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7106 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7107 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7108 << RHS.get()->getSourceRange(); 7109 7110 return incompatTy; 7111 } 7112 7113 // The pointer types are compatible. 7114 // In case of OpenCL ResultTy should have the address space qualifier 7115 // which is a superset of address spaces of both the 2nd and the 3rd 7116 // operands of the conditional operator. 7117 QualType ResultTy = [&, ResultAddrSpace]() { 7118 if (S.getLangOpts().OpenCL) { 7119 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7120 CompositeQuals.setAddressSpace(ResultAddrSpace); 7121 return S.Context 7122 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7123 .withCVRQualifiers(MergedCVRQual); 7124 } 7125 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7126 }(); 7127 if (IsBlockPointer) 7128 ResultTy = S.Context.getBlockPointerType(ResultTy); 7129 else 7130 ResultTy = S.Context.getPointerType(ResultTy); 7131 7132 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7133 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7134 return ResultTy; 7135 } 7136 7137 /// Return the resulting type when the operands are both block pointers. 7138 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7139 ExprResult &LHS, 7140 ExprResult &RHS, 7141 SourceLocation Loc) { 7142 QualType LHSTy = LHS.get()->getType(); 7143 QualType RHSTy = RHS.get()->getType(); 7144 7145 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7146 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7147 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7148 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7149 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7150 return destType; 7151 } 7152 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7153 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7154 << RHS.get()->getSourceRange(); 7155 return QualType(); 7156 } 7157 7158 // We have 2 block pointer types. 7159 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7160 } 7161 7162 /// Return the resulting type when the operands are both pointers. 7163 static QualType 7164 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7165 ExprResult &RHS, 7166 SourceLocation Loc) { 7167 // get the pointer types 7168 QualType LHSTy = LHS.get()->getType(); 7169 QualType RHSTy = RHS.get()->getType(); 7170 7171 // get the "pointed to" types 7172 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7173 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7174 7175 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7176 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7177 // Figure out necessary qualifiers (C99 6.5.15p6) 7178 QualType destPointee 7179 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7180 QualType destType = S.Context.getPointerType(destPointee); 7181 // Add qualifiers if necessary. 7182 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7183 // Promote to void*. 7184 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7185 return destType; 7186 } 7187 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7188 QualType destPointee 7189 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7190 QualType destType = S.Context.getPointerType(destPointee); 7191 // Add qualifiers if necessary. 7192 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7193 // Promote to void*. 7194 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7195 return destType; 7196 } 7197 7198 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7199 } 7200 7201 /// Return false if the first expression is not an integer and the second 7202 /// expression is not a pointer, true otherwise. 7203 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7204 Expr* PointerExpr, SourceLocation Loc, 7205 bool IsIntFirstExpr) { 7206 if (!PointerExpr->getType()->isPointerType() || 7207 !Int.get()->getType()->isIntegerType()) 7208 return false; 7209 7210 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7211 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7212 7213 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7214 << Expr1->getType() << Expr2->getType() 7215 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7216 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7217 CK_IntegralToPointer); 7218 return true; 7219 } 7220 7221 /// Simple conversion between integer and floating point types. 7222 /// 7223 /// Used when handling the OpenCL conditional operator where the 7224 /// condition is a vector while the other operands are scalar. 7225 /// 7226 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7227 /// types are either integer or floating type. Between the two 7228 /// operands, the type with the higher rank is defined as the "result 7229 /// type". The other operand needs to be promoted to the same type. No 7230 /// other type promotion is allowed. We cannot use 7231 /// UsualArithmeticConversions() for this purpose, since it always 7232 /// promotes promotable types. 7233 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7234 ExprResult &RHS, 7235 SourceLocation QuestionLoc) { 7236 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7237 if (LHS.isInvalid()) 7238 return QualType(); 7239 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7240 if (RHS.isInvalid()) 7241 return QualType(); 7242 7243 // For conversion purposes, we ignore any qualifiers. 7244 // For example, "const float" and "float" are equivalent. 7245 QualType LHSType = 7246 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7247 QualType RHSType = 7248 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7249 7250 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7251 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7252 << LHSType << LHS.get()->getSourceRange(); 7253 return QualType(); 7254 } 7255 7256 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7257 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7258 << RHSType << RHS.get()->getSourceRange(); 7259 return QualType(); 7260 } 7261 7262 // If both types are identical, no conversion is needed. 7263 if (LHSType == RHSType) 7264 return LHSType; 7265 7266 // Now handle "real" floating types (i.e. float, double, long double). 7267 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7268 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7269 /*IsCompAssign = */ false); 7270 7271 // Finally, we have two differing integer types. 7272 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7273 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7274 } 7275 7276 /// Convert scalar operands to a vector that matches the 7277 /// condition in length. 7278 /// 7279 /// Used when handling the OpenCL conditional operator where the 7280 /// condition is a vector while the other operands are scalar. 7281 /// 7282 /// We first compute the "result type" for the scalar operands 7283 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7284 /// into a vector of that type where the length matches the condition 7285 /// vector type. s6.11.6 requires that the element types of the result 7286 /// and the condition must have the same number of bits. 7287 static QualType 7288 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7289 QualType CondTy, SourceLocation QuestionLoc) { 7290 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7291 if (ResTy.isNull()) return QualType(); 7292 7293 const VectorType *CV = CondTy->getAs<VectorType>(); 7294 assert(CV); 7295 7296 // Determine the vector result type 7297 unsigned NumElements = CV->getNumElements(); 7298 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7299 7300 // Ensure that all types have the same number of bits 7301 if (S.Context.getTypeSize(CV->getElementType()) 7302 != S.Context.getTypeSize(ResTy)) { 7303 // Since VectorTy is created internally, it does not pretty print 7304 // with an OpenCL name. Instead, we just print a description. 7305 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7306 SmallString<64> Str; 7307 llvm::raw_svector_ostream OS(Str); 7308 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7309 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7310 << CondTy << OS.str(); 7311 return QualType(); 7312 } 7313 7314 // Convert operands to the vector result type 7315 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7316 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7317 7318 return VectorTy; 7319 } 7320 7321 /// Return false if this is a valid OpenCL condition vector 7322 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7323 SourceLocation QuestionLoc) { 7324 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7325 // integral type. 7326 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7327 assert(CondTy); 7328 QualType EleTy = CondTy->getElementType(); 7329 if (EleTy->isIntegerType()) return false; 7330 7331 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7332 << Cond->getType() << Cond->getSourceRange(); 7333 return true; 7334 } 7335 7336 /// Return false if the vector condition type and the vector 7337 /// result type are compatible. 7338 /// 7339 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7340 /// number of elements, and their element types have the same number 7341 /// of bits. 7342 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7343 SourceLocation QuestionLoc) { 7344 const VectorType *CV = CondTy->getAs<VectorType>(); 7345 const VectorType *RV = VecResTy->getAs<VectorType>(); 7346 assert(CV && RV); 7347 7348 if (CV->getNumElements() != RV->getNumElements()) { 7349 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7350 << CondTy << VecResTy; 7351 return true; 7352 } 7353 7354 QualType CVE = CV->getElementType(); 7355 QualType RVE = RV->getElementType(); 7356 7357 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7358 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7359 << CondTy << VecResTy; 7360 return true; 7361 } 7362 7363 return false; 7364 } 7365 7366 /// Return the resulting type for the conditional operator in 7367 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7368 /// s6.3.i) when the condition is a vector type. 7369 static QualType 7370 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7371 ExprResult &LHS, ExprResult &RHS, 7372 SourceLocation QuestionLoc) { 7373 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7374 if (Cond.isInvalid()) 7375 return QualType(); 7376 QualType CondTy = Cond.get()->getType(); 7377 7378 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7379 return QualType(); 7380 7381 // If either operand is a vector then find the vector type of the 7382 // result as specified in OpenCL v1.1 s6.3.i. 7383 if (LHS.get()->getType()->isVectorType() || 7384 RHS.get()->getType()->isVectorType()) { 7385 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7386 /*isCompAssign*/false, 7387 /*AllowBothBool*/true, 7388 /*AllowBoolConversions*/false); 7389 if (VecResTy.isNull()) return QualType(); 7390 // The result type must match the condition type as specified in 7391 // OpenCL v1.1 s6.11.6. 7392 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7393 return QualType(); 7394 return VecResTy; 7395 } 7396 7397 // Both operands are scalar. 7398 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7399 } 7400 7401 /// Return true if the Expr is block type 7402 static bool checkBlockType(Sema &S, const Expr *E) { 7403 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7404 QualType Ty = CE->getCallee()->getType(); 7405 if (Ty->isBlockPointerType()) { 7406 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7407 return true; 7408 } 7409 } 7410 return false; 7411 } 7412 7413 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7414 /// In that case, LHS = cond. 7415 /// C99 6.5.15 7416 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7417 ExprResult &RHS, ExprValueKind &VK, 7418 ExprObjectKind &OK, 7419 SourceLocation QuestionLoc) { 7420 7421 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7422 if (!LHSResult.isUsable()) return QualType(); 7423 LHS = LHSResult; 7424 7425 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7426 if (!RHSResult.isUsable()) return QualType(); 7427 RHS = RHSResult; 7428 7429 // C++ is sufficiently different to merit its own checker. 7430 if (getLangOpts().CPlusPlus) 7431 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7432 7433 VK = VK_RValue; 7434 OK = OK_Ordinary; 7435 7436 // The OpenCL operator with a vector condition is sufficiently 7437 // different to merit its own checker. 7438 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7439 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7440 7441 // First, check the condition. 7442 Cond = UsualUnaryConversions(Cond.get()); 7443 if (Cond.isInvalid()) 7444 return QualType(); 7445 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7446 return QualType(); 7447 7448 // Now check the two expressions. 7449 if (LHS.get()->getType()->isVectorType() || 7450 RHS.get()->getType()->isVectorType()) 7451 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7452 /*AllowBothBool*/true, 7453 /*AllowBoolConversions*/false); 7454 7455 QualType ResTy = 7456 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7457 if (LHS.isInvalid() || RHS.isInvalid()) 7458 return QualType(); 7459 7460 QualType LHSTy = LHS.get()->getType(); 7461 QualType RHSTy = RHS.get()->getType(); 7462 7463 // Diagnose attempts to convert between __float128 and long double where 7464 // such conversions currently can't be handled. 7465 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7466 Diag(QuestionLoc, 7467 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7468 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7469 return QualType(); 7470 } 7471 7472 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7473 // selection operator (?:). 7474 if (getLangOpts().OpenCL && 7475 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7476 return QualType(); 7477 } 7478 7479 // If both operands have arithmetic type, do the usual arithmetic conversions 7480 // to find a common type: C99 6.5.15p3,5. 7481 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7482 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7483 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7484 7485 return ResTy; 7486 } 7487 7488 // If both operands are the same structure or union type, the result is that 7489 // type. 7490 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7491 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7492 if (LHSRT->getDecl() == RHSRT->getDecl()) 7493 // "If both the operands have structure or union type, the result has 7494 // that type." This implies that CV qualifiers are dropped. 7495 return LHSTy.getUnqualifiedType(); 7496 // FIXME: Type of conditional expression must be complete in C mode. 7497 } 7498 7499 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7500 // The following || allows only one side to be void (a GCC-ism). 7501 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7502 return checkConditionalVoidType(*this, LHS, RHS); 7503 } 7504 7505 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7506 // the type of the other operand." 7507 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7508 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7509 7510 // All objective-c pointer type analysis is done here. 7511 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7512 QuestionLoc); 7513 if (LHS.isInvalid() || RHS.isInvalid()) 7514 return QualType(); 7515 if (!compositeType.isNull()) 7516 return compositeType; 7517 7518 7519 // Handle block pointer types. 7520 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7521 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7522 QuestionLoc); 7523 7524 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7525 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7526 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7527 QuestionLoc); 7528 7529 // GCC compatibility: soften pointer/integer mismatch. Note that 7530 // null pointers have been filtered out by this point. 7531 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7532 /*IsIntFirstExpr=*/true)) 7533 return RHSTy; 7534 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7535 /*IsIntFirstExpr=*/false)) 7536 return LHSTy; 7537 7538 // Emit a better diagnostic if one of the expressions is a null pointer 7539 // constant and the other is not a pointer type. In this case, the user most 7540 // likely forgot to take the address of the other expression. 7541 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7542 return QualType(); 7543 7544 // Otherwise, the operands are not compatible. 7545 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7546 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7547 << RHS.get()->getSourceRange(); 7548 return QualType(); 7549 } 7550 7551 /// FindCompositeObjCPointerType - Helper method to find composite type of 7552 /// two objective-c pointer types of the two input expressions. 7553 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7554 SourceLocation QuestionLoc) { 7555 QualType LHSTy = LHS.get()->getType(); 7556 QualType RHSTy = RHS.get()->getType(); 7557 7558 // Handle things like Class and struct objc_class*. Here we case the result 7559 // to the pseudo-builtin, because that will be implicitly cast back to the 7560 // redefinition type if an attempt is made to access its fields. 7561 if (LHSTy->isObjCClassType() && 7562 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7563 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7564 return LHSTy; 7565 } 7566 if (RHSTy->isObjCClassType() && 7567 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7568 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7569 return RHSTy; 7570 } 7571 // And the same for struct objc_object* / id 7572 if (LHSTy->isObjCIdType() && 7573 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7574 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7575 return LHSTy; 7576 } 7577 if (RHSTy->isObjCIdType() && 7578 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7579 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7580 return RHSTy; 7581 } 7582 // And the same for struct objc_selector* / SEL 7583 if (Context.isObjCSelType(LHSTy) && 7584 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7585 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7586 return LHSTy; 7587 } 7588 if (Context.isObjCSelType(RHSTy) && 7589 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7590 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7591 return RHSTy; 7592 } 7593 // Check constraints for Objective-C object pointers types. 7594 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7595 7596 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7597 // Two identical object pointer types are always compatible. 7598 return LHSTy; 7599 } 7600 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7601 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7602 QualType compositeType = LHSTy; 7603 7604 // If both operands are interfaces and either operand can be 7605 // assigned to the other, use that type as the composite 7606 // type. This allows 7607 // xxx ? (A*) a : (B*) b 7608 // where B is a subclass of A. 7609 // 7610 // Additionally, as for assignment, if either type is 'id' 7611 // allow silent coercion. Finally, if the types are 7612 // incompatible then make sure to use 'id' as the composite 7613 // type so the result is acceptable for sending messages to. 7614 7615 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7616 // It could return the composite type. 7617 if (!(compositeType = 7618 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7619 // Nothing more to do. 7620 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7621 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7622 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7623 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7624 } else if ((LHSOPT->isObjCQualifiedIdType() || 7625 RHSOPT->isObjCQualifiedIdType()) && 7626 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7627 true)) { 7628 // Need to handle "id<xx>" explicitly. 7629 // GCC allows qualified id and any Objective-C type to devolve to 7630 // id. Currently localizing to here until clear this should be 7631 // part of ObjCQualifiedIdTypesAreCompatible. 7632 compositeType = Context.getObjCIdType(); 7633 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7634 compositeType = Context.getObjCIdType(); 7635 } else { 7636 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7637 << LHSTy << RHSTy 7638 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7639 QualType incompatTy = Context.getObjCIdType(); 7640 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7641 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7642 return incompatTy; 7643 } 7644 // The object pointer types are compatible. 7645 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7646 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7647 return compositeType; 7648 } 7649 // Check Objective-C object pointer types and 'void *' 7650 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7651 if (getLangOpts().ObjCAutoRefCount) { 7652 // ARC forbids the implicit conversion of object pointers to 'void *', 7653 // so these types are not compatible. 7654 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7655 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7656 LHS = RHS = true; 7657 return QualType(); 7658 } 7659 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7660 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7661 QualType destPointee 7662 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7663 QualType destType = Context.getPointerType(destPointee); 7664 // Add qualifiers if necessary. 7665 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7666 // Promote to void*. 7667 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7668 return destType; 7669 } 7670 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7671 if (getLangOpts().ObjCAutoRefCount) { 7672 // ARC forbids the implicit conversion of object pointers to 'void *', 7673 // so these types are not compatible. 7674 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7675 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7676 LHS = RHS = true; 7677 return QualType(); 7678 } 7679 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7680 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7681 QualType destPointee 7682 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7683 QualType destType = Context.getPointerType(destPointee); 7684 // Add qualifiers if necessary. 7685 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7686 // Promote to void*. 7687 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7688 return destType; 7689 } 7690 return QualType(); 7691 } 7692 7693 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7694 /// ParenRange in parentheses. 7695 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7696 const PartialDiagnostic &Note, 7697 SourceRange ParenRange) { 7698 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7699 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7700 EndLoc.isValid()) { 7701 Self.Diag(Loc, Note) 7702 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7703 << FixItHint::CreateInsertion(EndLoc, ")"); 7704 } else { 7705 // We can't display the parentheses, so just show the bare note. 7706 Self.Diag(Loc, Note) << ParenRange; 7707 } 7708 } 7709 7710 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7711 return BinaryOperator::isAdditiveOp(Opc) || 7712 BinaryOperator::isMultiplicativeOp(Opc) || 7713 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7714 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7715 // not any of the logical operators. Bitwise-xor is commonly used as a 7716 // logical-xor because there is no logical-xor operator. The logical 7717 // operators, including uses of xor, have a high false positive rate for 7718 // precedence warnings. 7719 } 7720 7721 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7722 /// expression, either using a built-in or overloaded operator, 7723 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7724 /// expression. 7725 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7726 Expr **RHSExprs) { 7727 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7728 E = E->IgnoreImpCasts(); 7729 E = E->IgnoreConversionOperator(); 7730 E = E->IgnoreImpCasts(); 7731 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7732 E = MTE->getSubExpr(); 7733 E = E->IgnoreImpCasts(); 7734 } 7735 7736 // Built-in binary operator. 7737 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7738 if (IsArithmeticOp(OP->getOpcode())) { 7739 *Opcode = OP->getOpcode(); 7740 *RHSExprs = OP->getRHS(); 7741 return true; 7742 } 7743 } 7744 7745 // Overloaded operator. 7746 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7747 if (Call->getNumArgs() != 2) 7748 return false; 7749 7750 // Make sure this is really a binary operator that is safe to pass into 7751 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7752 OverloadedOperatorKind OO = Call->getOperator(); 7753 if (OO < OO_Plus || OO > OO_Arrow || 7754 OO == OO_PlusPlus || OO == OO_MinusMinus) 7755 return false; 7756 7757 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7758 if (IsArithmeticOp(OpKind)) { 7759 *Opcode = OpKind; 7760 *RHSExprs = Call->getArg(1); 7761 return true; 7762 } 7763 } 7764 7765 return false; 7766 } 7767 7768 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7769 /// or is a logical expression such as (x==y) which has int type, but is 7770 /// commonly interpreted as boolean. 7771 static bool ExprLooksBoolean(Expr *E) { 7772 E = E->IgnoreParenImpCasts(); 7773 7774 if (E->getType()->isBooleanType()) 7775 return true; 7776 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7777 return OP->isComparisonOp() || OP->isLogicalOp(); 7778 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7779 return OP->getOpcode() == UO_LNot; 7780 if (E->getType()->isPointerType()) 7781 return true; 7782 // FIXME: What about overloaded operator calls returning "unspecified boolean 7783 // type"s (commonly pointer-to-members)? 7784 7785 return false; 7786 } 7787 7788 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7789 /// and binary operator are mixed in a way that suggests the programmer assumed 7790 /// the conditional operator has higher precedence, for example: 7791 /// "int x = a + someBinaryCondition ? 1 : 2". 7792 static void DiagnoseConditionalPrecedence(Sema &Self, 7793 SourceLocation OpLoc, 7794 Expr *Condition, 7795 Expr *LHSExpr, 7796 Expr *RHSExpr) { 7797 BinaryOperatorKind CondOpcode; 7798 Expr *CondRHS; 7799 7800 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7801 return; 7802 if (!ExprLooksBoolean(CondRHS)) 7803 return; 7804 7805 // The condition is an arithmetic binary expression, with a right- 7806 // hand side that looks boolean, so warn. 7807 7808 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7809 ? diag::warn_precedence_bitwise_conditional 7810 : diag::warn_precedence_conditional; 7811 7812 Self.Diag(OpLoc, DiagID) 7813 << Condition->getSourceRange() 7814 << BinaryOperator::getOpcodeStr(CondOpcode); 7815 7816 SuggestParentheses( 7817 Self, OpLoc, 7818 Self.PDiag(diag::note_precedence_silence) 7819 << BinaryOperator::getOpcodeStr(CondOpcode), 7820 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7821 7822 SuggestParentheses(Self, OpLoc, 7823 Self.PDiag(diag::note_precedence_conditional_first), 7824 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7825 } 7826 7827 /// Compute the nullability of a conditional expression. 7828 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7829 QualType LHSTy, QualType RHSTy, 7830 ASTContext &Ctx) { 7831 if (!ResTy->isAnyPointerType()) 7832 return ResTy; 7833 7834 auto GetNullability = [&Ctx](QualType Ty) { 7835 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7836 if (Kind) 7837 return *Kind; 7838 return NullabilityKind::Unspecified; 7839 }; 7840 7841 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7842 NullabilityKind MergedKind; 7843 7844 // Compute nullability of a binary conditional expression. 7845 if (IsBin) { 7846 if (LHSKind == NullabilityKind::NonNull) 7847 MergedKind = NullabilityKind::NonNull; 7848 else 7849 MergedKind = RHSKind; 7850 // Compute nullability of a normal conditional expression. 7851 } else { 7852 if (LHSKind == NullabilityKind::Nullable || 7853 RHSKind == NullabilityKind::Nullable) 7854 MergedKind = NullabilityKind::Nullable; 7855 else if (LHSKind == NullabilityKind::NonNull) 7856 MergedKind = RHSKind; 7857 else if (RHSKind == NullabilityKind::NonNull) 7858 MergedKind = LHSKind; 7859 else 7860 MergedKind = NullabilityKind::Unspecified; 7861 } 7862 7863 // Return if ResTy already has the correct nullability. 7864 if (GetNullability(ResTy) == MergedKind) 7865 return ResTy; 7866 7867 // Strip all nullability from ResTy. 7868 while (ResTy->getNullability(Ctx)) 7869 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7870 7871 // Create a new AttributedType with the new nullability kind. 7872 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7873 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7874 } 7875 7876 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7877 /// in the case of a the GNU conditional expr extension. 7878 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7879 SourceLocation ColonLoc, 7880 Expr *CondExpr, Expr *LHSExpr, 7881 Expr *RHSExpr) { 7882 if (!getLangOpts().CPlusPlus) { 7883 // C cannot handle TypoExpr nodes in the condition because it 7884 // doesn't handle dependent types properly, so make sure any TypoExprs have 7885 // been dealt with before checking the operands. 7886 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7887 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7888 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7889 7890 if (!CondResult.isUsable()) 7891 return ExprError(); 7892 7893 if (LHSExpr) { 7894 if (!LHSResult.isUsable()) 7895 return ExprError(); 7896 } 7897 7898 if (!RHSResult.isUsable()) 7899 return ExprError(); 7900 7901 CondExpr = CondResult.get(); 7902 LHSExpr = LHSResult.get(); 7903 RHSExpr = RHSResult.get(); 7904 } 7905 7906 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7907 // was the condition. 7908 OpaqueValueExpr *opaqueValue = nullptr; 7909 Expr *commonExpr = nullptr; 7910 if (!LHSExpr) { 7911 commonExpr = CondExpr; 7912 // Lower out placeholder types first. This is important so that we don't 7913 // try to capture a placeholder. This happens in few cases in C++; such 7914 // as Objective-C++'s dictionary subscripting syntax. 7915 if (commonExpr->hasPlaceholderType()) { 7916 ExprResult result = CheckPlaceholderExpr(commonExpr); 7917 if (!result.isUsable()) return ExprError(); 7918 commonExpr = result.get(); 7919 } 7920 // We usually want to apply unary conversions *before* saving, except 7921 // in the special case of a C++ l-value conditional. 7922 if (!(getLangOpts().CPlusPlus 7923 && !commonExpr->isTypeDependent() 7924 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7925 && commonExpr->isGLValue() 7926 && commonExpr->isOrdinaryOrBitFieldObject() 7927 && RHSExpr->isOrdinaryOrBitFieldObject() 7928 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7929 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7930 if (commonRes.isInvalid()) 7931 return ExprError(); 7932 commonExpr = commonRes.get(); 7933 } 7934 7935 // If the common expression is a class or array prvalue, materialize it 7936 // so that we can safely refer to it multiple times. 7937 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7938 commonExpr->getType()->isArrayType())) { 7939 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7940 if (MatExpr.isInvalid()) 7941 return ExprError(); 7942 commonExpr = MatExpr.get(); 7943 } 7944 7945 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7946 commonExpr->getType(), 7947 commonExpr->getValueKind(), 7948 commonExpr->getObjectKind(), 7949 commonExpr); 7950 LHSExpr = CondExpr = opaqueValue; 7951 } 7952 7953 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7954 ExprValueKind VK = VK_RValue; 7955 ExprObjectKind OK = OK_Ordinary; 7956 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7957 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7958 VK, OK, QuestionLoc); 7959 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7960 RHS.isInvalid()) 7961 return ExprError(); 7962 7963 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7964 RHS.get()); 7965 7966 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7967 7968 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7969 Context); 7970 7971 if (!commonExpr) 7972 return new (Context) 7973 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7974 RHS.get(), result, VK, OK); 7975 7976 return new (Context) BinaryConditionalOperator( 7977 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7978 ColonLoc, result, VK, OK); 7979 } 7980 7981 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7982 // being closely modeled after the C99 spec:-). The odd characteristic of this 7983 // routine is it effectively iqnores the qualifiers on the top level pointee. 7984 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7985 // FIXME: add a couple examples in this comment. 7986 static Sema::AssignConvertType 7987 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7988 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7989 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7990 7991 // get the "pointed to" type (ignoring qualifiers at the top level) 7992 const Type *lhptee, *rhptee; 7993 Qualifiers lhq, rhq; 7994 std::tie(lhptee, lhq) = 7995 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7996 std::tie(rhptee, rhq) = 7997 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7998 7999 Sema::AssignConvertType ConvTy = Sema::Compatible; 8000 8001 // C99 6.5.16.1p1: This following citation is common to constraints 8002 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8003 // qualifiers of the type *pointed to* by the right; 8004 8005 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8006 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8007 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8008 // Ignore lifetime for further calculation. 8009 lhq.removeObjCLifetime(); 8010 rhq.removeObjCLifetime(); 8011 } 8012 8013 if (!lhq.compatiblyIncludes(rhq)) { 8014 // Treat address-space mismatches as fatal. 8015 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8016 return Sema::IncompatiblePointerDiscardsQualifiers; 8017 8018 // It's okay to add or remove GC or lifetime qualifiers when converting to 8019 // and from void*. 8020 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8021 .compatiblyIncludes( 8022 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8023 && (lhptee->isVoidType() || rhptee->isVoidType())) 8024 ; // keep old 8025 8026 // Treat lifetime mismatches as fatal. 8027 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8028 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8029 8030 // For GCC/MS compatibility, other qualifier mismatches are treated 8031 // as still compatible in C. 8032 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8033 } 8034 8035 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8036 // incomplete type and the other is a pointer to a qualified or unqualified 8037 // version of void... 8038 if (lhptee->isVoidType()) { 8039 if (rhptee->isIncompleteOrObjectType()) 8040 return ConvTy; 8041 8042 // As an extension, we allow cast to/from void* to function pointer. 8043 assert(rhptee->isFunctionType()); 8044 return Sema::FunctionVoidPointer; 8045 } 8046 8047 if (rhptee->isVoidType()) { 8048 if (lhptee->isIncompleteOrObjectType()) 8049 return ConvTy; 8050 8051 // As an extension, we allow cast to/from void* to function pointer. 8052 assert(lhptee->isFunctionType()); 8053 return Sema::FunctionVoidPointer; 8054 } 8055 8056 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8057 // unqualified versions of compatible types, ... 8058 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8059 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8060 // Check if the pointee types are compatible ignoring the sign. 8061 // We explicitly check for char so that we catch "char" vs 8062 // "unsigned char" on systems where "char" is unsigned. 8063 if (lhptee->isCharType()) 8064 ltrans = S.Context.UnsignedCharTy; 8065 else if (lhptee->hasSignedIntegerRepresentation()) 8066 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8067 8068 if (rhptee->isCharType()) 8069 rtrans = S.Context.UnsignedCharTy; 8070 else if (rhptee->hasSignedIntegerRepresentation()) 8071 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8072 8073 if (ltrans == rtrans) { 8074 // Types are compatible ignoring the sign. Qualifier incompatibility 8075 // takes priority over sign incompatibility because the sign 8076 // warning can be disabled. 8077 if (ConvTy != Sema::Compatible) 8078 return ConvTy; 8079 8080 return Sema::IncompatiblePointerSign; 8081 } 8082 8083 // If we are a multi-level pointer, it's possible that our issue is simply 8084 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8085 // the eventual target type is the same and the pointers have the same 8086 // level of indirection, this must be the issue. 8087 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8088 do { 8089 std::tie(lhptee, lhq) = 8090 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8091 std::tie(rhptee, rhq) = 8092 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8093 8094 // Inconsistent address spaces at this point is invalid, even if the 8095 // address spaces would be compatible. 8096 // FIXME: This doesn't catch address space mismatches for pointers of 8097 // different nesting levels, like: 8098 // __local int *** a; 8099 // int ** b = a; 8100 // It's not clear how to actually determine when such pointers are 8101 // invalidly incompatible. 8102 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8103 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8104 8105 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8106 8107 if (lhptee == rhptee) 8108 return Sema::IncompatibleNestedPointerQualifiers; 8109 } 8110 8111 // General pointer incompatibility takes priority over qualifiers. 8112 return Sema::IncompatiblePointer; 8113 } 8114 if (!S.getLangOpts().CPlusPlus && 8115 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8116 return Sema::IncompatiblePointer; 8117 return ConvTy; 8118 } 8119 8120 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8121 /// block pointer types are compatible or whether a block and normal pointer 8122 /// are compatible. It is more restrict than comparing two function pointer 8123 // types. 8124 static Sema::AssignConvertType 8125 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8126 QualType RHSType) { 8127 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8128 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8129 8130 QualType lhptee, rhptee; 8131 8132 // get the "pointed to" type (ignoring qualifiers at the top level) 8133 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8134 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8135 8136 // In C++, the types have to match exactly. 8137 if (S.getLangOpts().CPlusPlus) 8138 return Sema::IncompatibleBlockPointer; 8139 8140 Sema::AssignConvertType ConvTy = Sema::Compatible; 8141 8142 // For blocks we enforce that qualifiers are identical. 8143 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8144 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8145 if (S.getLangOpts().OpenCL) { 8146 LQuals.removeAddressSpace(); 8147 RQuals.removeAddressSpace(); 8148 } 8149 if (LQuals != RQuals) 8150 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8151 8152 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8153 // assignment. 8154 // The current behavior is similar to C++ lambdas. A block might be 8155 // assigned to a variable iff its return type and parameters are compatible 8156 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8157 // an assignment. Presumably it should behave in way that a function pointer 8158 // assignment does in C, so for each parameter and return type: 8159 // * CVR and address space of LHS should be a superset of CVR and address 8160 // space of RHS. 8161 // * unqualified types should be compatible. 8162 if (S.getLangOpts().OpenCL) { 8163 if (!S.Context.typesAreBlockPointerCompatible( 8164 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8165 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8166 return Sema::IncompatibleBlockPointer; 8167 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8168 return Sema::IncompatibleBlockPointer; 8169 8170 return ConvTy; 8171 } 8172 8173 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8174 /// for assignment compatibility. 8175 static Sema::AssignConvertType 8176 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8177 QualType RHSType) { 8178 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8179 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8180 8181 if (LHSType->isObjCBuiltinType()) { 8182 // Class is not compatible with ObjC object pointers. 8183 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8184 !RHSType->isObjCQualifiedClassType()) 8185 return Sema::IncompatiblePointer; 8186 return Sema::Compatible; 8187 } 8188 if (RHSType->isObjCBuiltinType()) { 8189 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8190 !LHSType->isObjCQualifiedClassType()) 8191 return Sema::IncompatiblePointer; 8192 return Sema::Compatible; 8193 } 8194 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8195 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8196 8197 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8198 // make an exception for id<P> 8199 !LHSType->isObjCQualifiedIdType()) 8200 return Sema::CompatiblePointerDiscardsQualifiers; 8201 8202 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8203 return Sema::Compatible; 8204 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8205 return Sema::IncompatibleObjCQualifiedId; 8206 return Sema::IncompatiblePointer; 8207 } 8208 8209 Sema::AssignConvertType 8210 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8211 QualType LHSType, QualType RHSType) { 8212 // Fake up an opaque expression. We don't actually care about what 8213 // cast operations are required, so if CheckAssignmentConstraints 8214 // adds casts to this they'll be wasted, but fortunately that doesn't 8215 // usually happen on valid code. 8216 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8217 ExprResult RHSPtr = &RHSExpr; 8218 CastKind K; 8219 8220 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8221 } 8222 8223 /// This helper function returns true if QT is a vector type that has element 8224 /// type ElementType. 8225 static bool isVector(QualType QT, QualType ElementType) { 8226 if (const VectorType *VT = QT->getAs<VectorType>()) 8227 return VT->getElementType() == ElementType; 8228 return false; 8229 } 8230 8231 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8232 /// has code to accommodate several GCC extensions when type checking 8233 /// pointers. Here are some objectionable examples that GCC considers warnings: 8234 /// 8235 /// int a, *pint; 8236 /// short *pshort; 8237 /// struct foo *pfoo; 8238 /// 8239 /// pint = pshort; // warning: assignment from incompatible pointer type 8240 /// a = pint; // warning: assignment makes integer from pointer without a cast 8241 /// pint = a; // warning: assignment makes pointer from integer without a cast 8242 /// pint = pfoo; // warning: assignment from incompatible pointer type 8243 /// 8244 /// As a result, the code for dealing with pointers is more complex than the 8245 /// C99 spec dictates. 8246 /// 8247 /// Sets 'Kind' for any result kind except Incompatible. 8248 Sema::AssignConvertType 8249 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8250 CastKind &Kind, bool ConvertRHS) { 8251 QualType RHSType = RHS.get()->getType(); 8252 QualType OrigLHSType = LHSType; 8253 8254 // Get canonical types. We're not formatting these types, just comparing 8255 // them. 8256 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8257 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8258 8259 // Common case: no conversion required. 8260 if (LHSType == RHSType) { 8261 Kind = CK_NoOp; 8262 return Compatible; 8263 } 8264 8265 // If we have an atomic type, try a non-atomic assignment, then just add an 8266 // atomic qualification step. 8267 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8268 Sema::AssignConvertType result = 8269 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8270 if (result != Compatible) 8271 return result; 8272 if (Kind != CK_NoOp && ConvertRHS) 8273 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8274 Kind = CK_NonAtomicToAtomic; 8275 return Compatible; 8276 } 8277 8278 // If the left-hand side is a reference type, then we are in a 8279 // (rare!) case where we've allowed the use of references in C, 8280 // e.g., as a parameter type in a built-in function. In this case, 8281 // just make sure that the type referenced is compatible with the 8282 // right-hand side type. The caller is responsible for adjusting 8283 // LHSType so that the resulting expression does not have reference 8284 // type. 8285 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8286 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8287 Kind = CK_LValueBitCast; 8288 return Compatible; 8289 } 8290 return Incompatible; 8291 } 8292 8293 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8294 // to the same ExtVector type. 8295 if (LHSType->isExtVectorType()) { 8296 if (RHSType->isExtVectorType()) 8297 return Incompatible; 8298 if (RHSType->isArithmeticType()) { 8299 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8300 if (ConvertRHS) 8301 RHS = prepareVectorSplat(LHSType, RHS.get()); 8302 Kind = CK_VectorSplat; 8303 return Compatible; 8304 } 8305 } 8306 8307 // Conversions to or from vector type. 8308 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8309 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8310 // Allow assignments of an AltiVec vector type to an equivalent GCC 8311 // vector type and vice versa 8312 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8313 Kind = CK_BitCast; 8314 return Compatible; 8315 } 8316 8317 // If we are allowing lax vector conversions, and LHS and RHS are both 8318 // vectors, the total size only needs to be the same. This is a bitcast; 8319 // no bits are changed but the result type is different. 8320 if (isLaxVectorConversion(RHSType, LHSType)) { 8321 Kind = CK_BitCast; 8322 return IncompatibleVectors; 8323 } 8324 } 8325 8326 // When the RHS comes from another lax conversion (e.g. binops between 8327 // scalars and vectors) the result is canonicalized as a vector. When the 8328 // LHS is also a vector, the lax is allowed by the condition above. Handle 8329 // the case where LHS is a scalar. 8330 if (LHSType->isScalarType()) { 8331 const VectorType *VecType = RHSType->getAs<VectorType>(); 8332 if (VecType && VecType->getNumElements() == 1 && 8333 isLaxVectorConversion(RHSType, LHSType)) { 8334 ExprResult *VecExpr = &RHS; 8335 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8336 Kind = CK_BitCast; 8337 return Compatible; 8338 } 8339 } 8340 8341 return Incompatible; 8342 } 8343 8344 // Diagnose attempts to convert between __float128 and long double where 8345 // such conversions currently can't be handled. 8346 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8347 return Incompatible; 8348 8349 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8350 // discards the imaginary part. 8351 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8352 !LHSType->getAs<ComplexType>()) 8353 return Incompatible; 8354 8355 // Arithmetic conversions. 8356 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8357 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8358 if (ConvertRHS) 8359 Kind = PrepareScalarCast(RHS, LHSType); 8360 return Compatible; 8361 } 8362 8363 // Conversions to normal pointers. 8364 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8365 // U* -> T* 8366 if (isa<PointerType>(RHSType)) { 8367 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8368 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8369 if (AddrSpaceL != AddrSpaceR) 8370 Kind = CK_AddressSpaceConversion; 8371 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8372 Kind = CK_NoOp; 8373 else 8374 Kind = CK_BitCast; 8375 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8376 } 8377 8378 // int -> T* 8379 if (RHSType->isIntegerType()) { 8380 Kind = CK_IntegralToPointer; // FIXME: null? 8381 return IntToPointer; 8382 } 8383 8384 // C pointers are not compatible with ObjC object pointers, 8385 // with two exceptions: 8386 if (isa<ObjCObjectPointerType>(RHSType)) { 8387 // - conversions to void* 8388 if (LHSPointer->getPointeeType()->isVoidType()) { 8389 Kind = CK_BitCast; 8390 return Compatible; 8391 } 8392 8393 // - conversions from 'Class' to the redefinition type 8394 if (RHSType->isObjCClassType() && 8395 Context.hasSameType(LHSType, 8396 Context.getObjCClassRedefinitionType())) { 8397 Kind = CK_BitCast; 8398 return Compatible; 8399 } 8400 8401 Kind = CK_BitCast; 8402 return IncompatiblePointer; 8403 } 8404 8405 // U^ -> void* 8406 if (RHSType->getAs<BlockPointerType>()) { 8407 if (LHSPointer->getPointeeType()->isVoidType()) { 8408 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8409 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8410 ->getPointeeType() 8411 .getAddressSpace(); 8412 Kind = 8413 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8414 return Compatible; 8415 } 8416 } 8417 8418 return Incompatible; 8419 } 8420 8421 // Conversions to block pointers. 8422 if (isa<BlockPointerType>(LHSType)) { 8423 // U^ -> T^ 8424 if (RHSType->isBlockPointerType()) { 8425 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8426 ->getPointeeType() 8427 .getAddressSpace(); 8428 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8429 ->getPointeeType() 8430 .getAddressSpace(); 8431 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8432 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8433 } 8434 8435 // int or null -> T^ 8436 if (RHSType->isIntegerType()) { 8437 Kind = CK_IntegralToPointer; // FIXME: null 8438 return IntToBlockPointer; 8439 } 8440 8441 // id -> T^ 8442 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8443 Kind = CK_AnyPointerToBlockPointerCast; 8444 return Compatible; 8445 } 8446 8447 // void* -> T^ 8448 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8449 if (RHSPT->getPointeeType()->isVoidType()) { 8450 Kind = CK_AnyPointerToBlockPointerCast; 8451 return Compatible; 8452 } 8453 8454 return Incompatible; 8455 } 8456 8457 // Conversions to Objective-C pointers. 8458 if (isa<ObjCObjectPointerType>(LHSType)) { 8459 // A* -> B* 8460 if (RHSType->isObjCObjectPointerType()) { 8461 Kind = CK_BitCast; 8462 Sema::AssignConvertType result = 8463 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8464 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8465 result == Compatible && 8466 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8467 result = IncompatibleObjCWeakRef; 8468 return result; 8469 } 8470 8471 // int or null -> A* 8472 if (RHSType->isIntegerType()) { 8473 Kind = CK_IntegralToPointer; // FIXME: null 8474 return IntToPointer; 8475 } 8476 8477 // In general, C pointers are not compatible with ObjC object pointers, 8478 // with two exceptions: 8479 if (isa<PointerType>(RHSType)) { 8480 Kind = CK_CPointerToObjCPointerCast; 8481 8482 // - conversions from 'void*' 8483 if (RHSType->isVoidPointerType()) { 8484 return Compatible; 8485 } 8486 8487 // - conversions to 'Class' from its redefinition type 8488 if (LHSType->isObjCClassType() && 8489 Context.hasSameType(RHSType, 8490 Context.getObjCClassRedefinitionType())) { 8491 return Compatible; 8492 } 8493 8494 return IncompatiblePointer; 8495 } 8496 8497 // Only under strict condition T^ is compatible with an Objective-C pointer. 8498 if (RHSType->isBlockPointerType() && 8499 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8500 if (ConvertRHS) 8501 maybeExtendBlockObject(RHS); 8502 Kind = CK_BlockPointerToObjCPointerCast; 8503 return Compatible; 8504 } 8505 8506 return Incompatible; 8507 } 8508 8509 // Conversions from pointers that are not covered by the above. 8510 if (isa<PointerType>(RHSType)) { 8511 // T* -> _Bool 8512 if (LHSType == Context.BoolTy) { 8513 Kind = CK_PointerToBoolean; 8514 return Compatible; 8515 } 8516 8517 // T* -> int 8518 if (LHSType->isIntegerType()) { 8519 Kind = CK_PointerToIntegral; 8520 return PointerToInt; 8521 } 8522 8523 return Incompatible; 8524 } 8525 8526 // Conversions from Objective-C pointers that are not covered by the above. 8527 if (isa<ObjCObjectPointerType>(RHSType)) { 8528 // T* -> _Bool 8529 if (LHSType == Context.BoolTy) { 8530 Kind = CK_PointerToBoolean; 8531 return Compatible; 8532 } 8533 8534 // T* -> int 8535 if (LHSType->isIntegerType()) { 8536 Kind = CK_PointerToIntegral; 8537 return PointerToInt; 8538 } 8539 8540 return Incompatible; 8541 } 8542 8543 // struct A -> struct B 8544 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8545 if (Context.typesAreCompatible(LHSType, RHSType)) { 8546 Kind = CK_NoOp; 8547 return Compatible; 8548 } 8549 } 8550 8551 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8552 Kind = CK_IntToOCLSampler; 8553 return Compatible; 8554 } 8555 8556 return Incompatible; 8557 } 8558 8559 /// Constructs a transparent union from an expression that is 8560 /// used to initialize the transparent union. 8561 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8562 ExprResult &EResult, QualType UnionType, 8563 FieldDecl *Field) { 8564 // Build an initializer list that designates the appropriate member 8565 // of the transparent union. 8566 Expr *E = EResult.get(); 8567 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8568 E, SourceLocation()); 8569 Initializer->setType(UnionType); 8570 Initializer->setInitializedFieldInUnion(Field); 8571 8572 // Build a compound literal constructing a value of the transparent 8573 // union type from this initializer list. 8574 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8575 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8576 VK_RValue, Initializer, false); 8577 } 8578 8579 Sema::AssignConvertType 8580 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8581 ExprResult &RHS) { 8582 QualType RHSType = RHS.get()->getType(); 8583 8584 // If the ArgType is a Union type, we want to handle a potential 8585 // transparent_union GCC extension. 8586 const RecordType *UT = ArgType->getAsUnionType(); 8587 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8588 return Incompatible; 8589 8590 // The field to initialize within the transparent union. 8591 RecordDecl *UD = UT->getDecl(); 8592 FieldDecl *InitField = nullptr; 8593 // It's compatible if the expression matches any of the fields. 8594 for (auto *it : UD->fields()) { 8595 if (it->getType()->isPointerType()) { 8596 // If the transparent union contains a pointer type, we allow: 8597 // 1) void pointer 8598 // 2) null pointer constant 8599 if (RHSType->isPointerType()) 8600 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8601 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8602 InitField = it; 8603 break; 8604 } 8605 8606 if (RHS.get()->isNullPointerConstant(Context, 8607 Expr::NPC_ValueDependentIsNull)) { 8608 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8609 CK_NullToPointer); 8610 InitField = it; 8611 break; 8612 } 8613 } 8614 8615 CastKind Kind; 8616 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8617 == Compatible) { 8618 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8619 InitField = it; 8620 break; 8621 } 8622 } 8623 8624 if (!InitField) 8625 return Incompatible; 8626 8627 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8628 return Compatible; 8629 } 8630 8631 Sema::AssignConvertType 8632 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8633 bool Diagnose, 8634 bool DiagnoseCFAudited, 8635 bool ConvertRHS) { 8636 // We need to be able to tell the caller whether we diagnosed a problem, if 8637 // they ask us to issue diagnostics. 8638 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8639 8640 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8641 // we can't avoid *all* modifications at the moment, so we need some somewhere 8642 // to put the updated value. 8643 ExprResult LocalRHS = CallerRHS; 8644 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8645 8646 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8647 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8648 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8649 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8650 Diag(RHS.get()->getExprLoc(), 8651 diag::warn_noderef_to_dereferenceable_pointer) 8652 << RHS.get()->getSourceRange(); 8653 } 8654 } 8655 } 8656 8657 if (getLangOpts().CPlusPlus) { 8658 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8659 // C++ 5.17p3: If the left operand is not of class type, the 8660 // expression is implicitly converted (C++ 4) to the 8661 // cv-unqualified type of the left operand. 8662 QualType RHSType = RHS.get()->getType(); 8663 if (Diagnose) { 8664 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8665 AA_Assigning); 8666 } else { 8667 ImplicitConversionSequence ICS = 8668 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8669 /*SuppressUserConversions=*/false, 8670 /*AllowExplicit=*/false, 8671 /*InOverloadResolution=*/false, 8672 /*CStyle=*/false, 8673 /*AllowObjCWritebackConversion=*/false); 8674 if (ICS.isFailure()) 8675 return Incompatible; 8676 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8677 ICS, AA_Assigning); 8678 } 8679 if (RHS.isInvalid()) 8680 return Incompatible; 8681 Sema::AssignConvertType result = Compatible; 8682 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8683 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8684 result = IncompatibleObjCWeakRef; 8685 return result; 8686 } 8687 8688 // FIXME: Currently, we fall through and treat C++ classes like C 8689 // structures. 8690 // FIXME: We also fall through for atomics; not sure what should 8691 // happen there, though. 8692 } else if (RHS.get()->getType() == Context.OverloadTy) { 8693 // As a set of extensions to C, we support overloading on functions. These 8694 // functions need to be resolved here. 8695 DeclAccessPair DAP; 8696 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8697 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8698 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8699 else 8700 return Incompatible; 8701 } 8702 8703 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8704 // a null pointer constant. 8705 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8706 LHSType->isBlockPointerType()) && 8707 RHS.get()->isNullPointerConstant(Context, 8708 Expr::NPC_ValueDependentIsNull)) { 8709 if (Diagnose || ConvertRHS) { 8710 CastKind Kind; 8711 CXXCastPath Path; 8712 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8713 /*IgnoreBaseAccess=*/false, Diagnose); 8714 if (ConvertRHS) 8715 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8716 } 8717 return Compatible; 8718 } 8719 8720 // OpenCL queue_t type assignment. 8721 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8722 Context, Expr::NPC_ValueDependentIsNull)) { 8723 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8724 return Compatible; 8725 } 8726 8727 // This check seems unnatural, however it is necessary to ensure the proper 8728 // conversion of functions/arrays. If the conversion were done for all 8729 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8730 // expressions that suppress this implicit conversion (&, sizeof). 8731 // 8732 // Suppress this for references: C++ 8.5.3p5. 8733 if (!LHSType->isReferenceType()) { 8734 // FIXME: We potentially allocate here even if ConvertRHS is false. 8735 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8736 if (RHS.isInvalid()) 8737 return Incompatible; 8738 } 8739 CastKind Kind; 8740 Sema::AssignConvertType result = 8741 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8742 8743 // C99 6.5.16.1p2: The value of the right operand is converted to the 8744 // type of the assignment expression. 8745 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8746 // so that we can use references in built-in functions even in C. 8747 // The getNonReferenceType() call makes sure that the resulting expression 8748 // does not have reference type. 8749 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8750 QualType Ty = LHSType.getNonLValueExprType(Context); 8751 Expr *E = RHS.get(); 8752 8753 // Check for various Objective-C errors. If we are not reporting 8754 // diagnostics and just checking for errors, e.g., during overload 8755 // resolution, return Incompatible to indicate the failure. 8756 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8757 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8758 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8759 if (!Diagnose) 8760 return Incompatible; 8761 } 8762 if (getLangOpts().ObjC && 8763 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8764 E->getType(), E, Diagnose) || 8765 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8766 if (!Diagnose) 8767 return Incompatible; 8768 // Replace the expression with a corrected version and continue so we 8769 // can find further errors. 8770 RHS = E; 8771 return Compatible; 8772 } 8773 8774 if (ConvertRHS) 8775 RHS = ImpCastExprToType(E, Ty, Kind); 8776 } 8777 8778 return result; 8779 } 8780 8781 namespace { 8782 /// The original operand to an operator, prior to the application of the usual 8783 /// arithmetic conversions and converting the arguments of a builtin operator 8784 /// candidate. 8785 struct OriginalOperand { 8786 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8787 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8788 Op = MTE->getSubExpr(); 8789 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8790 Op = BTE->getSubExpr(); 8791 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8792 Orig = ICE->getSubExprAsWritten(); 8793 Conversion = ICE->getConversionFunction(); 8794 } 8795 } 8796 8797 QualType getType() const { return Orig->getType(); } 8798 8799 Expr *Orig; 8800 NamedDecl *Conversion; 8801 }; 8802 } 8803 8804 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8805 ExprResult &RHS) { 8806 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8807 8808 Diag(Loc, diag::err_typecheck_invalid_operands) 8809 << OrigLHS.getType() << OrigRHS.getType() 8810 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8811 8812 // If a user-defined conversion was applied to either of the operands prior 8813 // to applying the built-in operator rules, tell the user about it. 8814 if (OrigLHS.Conversion) { 8815 Diag(OrigLHS.Conversion->getLocation(), 8816 diag::note_typecheck_invalid_operands_converted) 8817 << 0 << LHS.get()->getType(); 8818 } 8819 if (OrigRHS.Conversion) { 8820 Diag(OrigRHS.Conversion->getLocation(), 8821 diag::note_typecheck_invalid_operands_converted) 8822 << 1 << RHS.get()->getType(); 8823 } 8824 8825 return QualType(); 8826 } 8827 8828 // Diagnose cases where a scalar was implicitly converted to a vector and 8829 // diagnose the underlying types. Otherwise, diagnose the error 8830 // as invalid vector logical operands for non-C++ cases. 8831 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8832 ExprResult &RHS) { 8833 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8834 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8835 8836 bool LHSNatVec = LHSType->isVectorType(); 8837 bool RHSNatVec = RHSType->isVectorType(); 8838 8839 if (!(LHSNatVec && RHSNatVec)) { 8840 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8841 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8842 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8843 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8844 << Vector->getSourceRange(); 8845 return QualType(); 8846 } 8847 8848 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8849 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8850 << RHS.get()->getSourceRange(); 8851 8852 return QualType(); 8853 } 8854 8855 /// Try to convert a value of non-vector type to a vector type by converting 8856 /// the type to the element type of the vector and then performing a splat. 8857 /// If the language is OpenCL, we only use conversions that promote scalar 8858 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8859 /// for float->int. 8860 /// 8861 /// OpenCL V2.0 6.2.6.p2: 8862 /// An error shall occur if any scalar operand type has greater rank 8863 /// than the type of the vector element. 8864 /// 8865 /// \param scalar - if non-null, actually perform the conversions 8866 /// \return true if the operation fails (but without diagnosing the failure) 8867 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8868 QualType scalarTy, 8869 QualType vectorEltTy, 8870 QualType vectorTy, 8871 unsigned &DiagID) { 8872 // The conversion to apply to the scalar before splatting it, 8873 // if necessary. 8874 CastKind scalarCast = CK_NoOp; 8875 8876 if (vectorEltTy->isIntegralType(S.Context)) { 8877 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8878 (scalarTy->isIntegerType() && 8879 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8880 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8881 return true; 8882 } 8883 if (!scalarTy->isIntegralType(S.Context)) 8884 return true; 8885 scalarCast = CK_IntegralCast; 8886 } else if (vectorEltTy->isRealFloatingType()) { 8887 if (scalarTy->isRealFloatingType()) { 8888 if (S.getLangOpts().OpenCL && 8889 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8890 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8891 return true; 8892 } 8893 scalarCast = CK_FloatingCast; 8894 } 8895 else if (scalarTy->isIntegralType(S.Context)) 8896 scalarCast = CK_IntegralToFloating; 8897 else 8898 return true; 8899 } else { 8900 return true; 8901 } 8902 8903 // Adjust scalar if desired. 8904 if (scalar) { 8905 if (scalarCast != CK_NoOp) 8906 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8907 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8908 } 8909 return false; 8910 } 8911 8912 /// Convert vector E to a vector with the same number of elements but different 8913 /// element type. 8914 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8915 const auto *VecTy = E->getType()->getAs<VectorType>(); 8916 assert(VecTy && "Expression E must be a vector"); 8917 QualType NewVecTy = S.Context.getVectorType(ElementType, 8918 VecTy->getNumElements(), 8919 VecTy->getVectorKind()); 8920 8921 // Look through the implicit cast. Return the subexpression if its type is 8922 // NewVecTy. 8923 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8924 if (ICE->getSubExpr()->getType() == NewVecTy) 8925 return ICE->getSubExpr(); 8926 8927 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8928 return S.ImpCastExprToType(E, NewVecTy, Cast); 8929 } 8930 8931 /// Test if a (constant) integer Int can be casted to another integer type 8932 /// IntTy without losing precision. 8933 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8934 QualType OtherIntTy) { 8935 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8936 8937 // Reject cases where the value of the Int is unknown as that would 8938 // possibly cause truncation, but accept cases where the scalar can be 8939 // demoted without loss of precision. 8940 Expr::EvalResult EVResult; 8941 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8942 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8943 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8944 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8945 8946 if (CstInt) { 8947 // If the scalar is constant and is of a higher order and has more active 8948 // bits that the vector element type, reject it. 8949 llvm::APSInt Result = EVResult.Val.getInt(); 8950 unsigned NumBits = IntSigned 8951 ? (Result.isNegative() ? Result.getMinSignedBits() 8952 : Result.getActiveBits()) 8953 : Result.getActiveBits(); 8954 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8955 return true; 8956 8957 // If the signedness of the scalar type and the vector element type 8958 // differs and the number of bits is greater than that of the vector 8959 // element reject it. 8960 return (IntSigned != OtherIntSigned && 8961 NumBits > S.Context.getIntWidth(OtherIntTy)); 8962 } 8963 8964 // Reject cases where the value of the scalar is not constant and it's 8965 // order is greater than that of the vector element type. 8966 return (Order < 0); 8967 } 8968 8969 /// Test if a (constant) integer Int can be casted to floating point type 8970 /// FloatTy without losing precision. 8971 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8972 QualType FloatTy) { 8973 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8974 8975 // Determine if the integer constant can be expressed as a floating point 8976 // number of the appropriate type. 8977 Expr::EvalResult EVResult; 8978 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8979 8980 uint64_t Bits = 0; 8981 if (CstInt) { 8982 // Reject constants that would be truncated if they were converted to 8983 // the floating point type. Test by simple to/from conversion. 8984 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8985 // could be avoided if there was a convertFromAPInt method 8986 // which could signal back if implicit truncation occurred. 8987 llvm::APSInt Result = EVResult.Val.getInt(); 8988 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8989 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8990 llvm::APFloat::rmTowardZero); 8991 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8992 !IntTy->hasSignedIntegerRepresentation()); 8993 bool Ignored = false; 8994 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8995 &Ignored); 8996 if (Result != ConvertBack) 8997 return true; 8998 } else { 8999 // Reject types that cannot be fully encoded into the mantissa of 9000 // the float. 9001 Bits = S.Context.getTypeSize(IntTy); 9002 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9003 S.Context.getFloatTypeSemantics(FloatTy)); 9004 if (Bits > FloatPrec) 9005 return true; 9006 } 9007 9008 return false; 9009 } 9010 9011 /// Attempt to convert and splat Scalar into a vector whose types matches 9012 /// Vector following GCC conversion rules. The rule is that implicit 9013 /// conversion can occur when Scalar can be casted to match Vector's element 9014 /// type without causing truncation of Scalar. 9015 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9016 ExprResult *Vector) { 9017 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9018 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9019 const VectorType *VT = VectorTy->getAs<VectorType>(); 9020 9021 assert(!isa<ExtVectorType>(VT) && 9022 "ExtVectorTypes should not be handled here!"); 9023 9024 QualType VectorEltTy = VT->getElementType(); 9025 9026 // Reject cases where the vector element type or the scalar element type are 9027 // not integral or floating point types. 9028 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9029 return true; 9030 9031 // The conversion to apply to the scalar before splatting it, 9032 // if necessary. 9033 CastKind ScalarCast = CK_NoOp; 9034 9035 // Accept cases where the vector elements are integers and the scalar is 9036 // an integer. 9037 // FIXME: Notionally if the scalar was a floating point value with a precise 9038 // integral representation, we could cast it to an appropriate integer 9039 // type and then perform the rest of the checks here. GCC will perform 9040 // this conversion in some cases as determined by the input language. 9041 // We should accept it on a language independent basis. 9042 if (VectorEltTy->isIntegralType(S.Context) && 9043 ScalarTy->isIntegralType(S.Context) && 9044 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9045 9046 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9047 return true; 9048 9049 ScalarCast = CK_IntegralCast; 9050 } else if (VectorEltTy->isIntegralType(S.Context) && 9051 ScalarTy->isRealFloatingType()) { 9052 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9053 ScalarCast = CK_FloatingToIntegral; 9054 else 9055 return true; 9056 } else if (VectorEltTy->isRealFloatingType()) { 9057 if (ScalarTy->isRealFloatingType()) { 9058 9059 // Reject cases where the scalar type is not a constant and has a higher 9060 // Order than the vector element type. 9061 llvm::APFloat Result(0.0); 9062 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 9063 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9064 if (!CstScalar && Order < 0) 9065 return true; 9066 9067 // If the scalar cannot be safely casted to the vector element type, 9068 // reject it. 9069 if (CstScalar) { 9070 bool Truncated = false; 9071 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9072 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9073 if (Truncated) 9074 return true; 9075 } 9076 9077 ScalarCast = CK_FloatingCast; 9078 } else if (ScalarTy->isIntegralType(S.Context)) { 9079 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9080 return true; 9081 9082 ScalarCast = CK_IntegralToFloating; 9083 } else 9084 return true; 9085 } 9086 9087 // Adjust scalar if desired. 9088 if (Scalar) { 9089 if (ScalarCast != CK_NoOp) 9090 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9091 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9092 } 9093 return false; 9094 } 9095 9096 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9097 SourceLocation Loc, bool IsCompAssign, 9098 bool AllowBothBool, 9099 bool AllowBoolConversions) { 9100 if (!IsCompAssign) { 9101 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9102 if (LHS.isInvalid()) 9103 return QualType(); 9104 } 9105 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9106 if (RHS.isInvalid()) 9107 return QualType(); 9108 9109 // For conversion purposes, we ignore any qualifiers. 9110 // For example, "const float" and "float" are equivalent. 9111 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9112 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9113 9114 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9115 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9116 assert(LHSVecType || RHSVecType); 9117 9118 // AltiVec-style "vector bool op vector bool" combinations are allowed 9119 // for some operators but not others. 9120 if (!AllowBothBool && 9121 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9122 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9123 return InvalidOperands(Loc, LHS, RHS); 9124 9125 // If the vector types are identical, return. 9126 if (Context.hasSameType(LHSType, RHSType)) 9127 return LHSType; 9128 9129 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9130 if (LHSVecType && RHSVecType && 9131 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9132 if (isa<ExtVectorType>(LHSVecType)) { 9133 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9134 return LHSType; 9135 } 9136 9137 if (!IsCompAssign) 9138 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9139 return RHSType; 9140 } 9141 9142 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9143 // can be mixed, with the result being the non-bool type. The non-bool 9144 // operand must have integer element type. 9145 if (AllowBoolConversions && LHSVecType && RHSVecType && 9146 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9147 (Context.getTypeSize(LHSVecType->getElementType()) == 9148 Context.getTypeSize(RHSVecType->getElementType()))) { 9149 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9150 LHSVecType->getElementType()->isIntegerType() && 9151 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9152 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9153 return LHSType; 9154 } 9155 if (!IsCompAssign && 9156 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9157 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9158 RHSVecType->getElementType()->isIntegerType()) { 9159 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9160 return RHSType; 9161 } 9162 } 9163 9164 // If there's a vector type and a scalar, try to convert the scalar to 9165 // the vector element type and splat. 9166 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9167 if (!RHSVecType) { 9168 if (isa<ExtVectorType>(LHSVecType)) { 9169 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9170 LHSVecType->getElementType(), LHSType, 9171 DiagID)) 9172 return LHSType; 9173 } else { 9174 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9175 return LHSType; 9176 } 9177 } 9178 if (!LHSVecType) { 9179 if (isa<ExtVectorType>(RHSVecType)) { 9180 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9181 LHSType, RHSVecType->getElementType(), 9182 RHSType, DiagID)) 9183 return RHSType; 9184 } else { 9185 if (LHS.get()->getValueKind() == VK_LValue || 9186 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9187 return RHSType; 9188 } 9189 } 9190 9191 // FIXME: The code below also handles conversion between vectors and 9192 // non-scalars, we should break this down into fine grained specific checks 9193 // and emit proper diagnostics. 9194 QualType VecType = LHSVecType ? LHSType : RHSType; 9195 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9196 QualType OtherType = LHSVecType ? RHSType : LHSType; 9197 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9198 if (isLaxVectorConversion(OtherType, VecType)) { 9199 // If we're allowing lax vector conversions, only the total (data) size 9200 // needs to be the same. For non compound assignment, if one of the types is 9201 // scalar, the result is always the vector type. 9202 if (!IsCompAssign) { 9203 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9204 return VecType; 9205 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9206 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9207 // type. Note that this is already done by non-compound assignments in 9208 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9209 // <1 x T> -> T. The result is also a vector type. 9210 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9211 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9212 ExprResult *RHSExpr = &RHS; 9213 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9214 return VecType; 9215 } 9216 } 9217 9218 // Okay, the expression is invalid. 9219 9220 // If there's a non-vector, non-real operand, diagnose that. 9221 if ((!RHSVecType && !RHSType->isRealType()) || 9222 (!LHSVecType && !LHSType->isRealType())) { 9223 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9224 << LHSType << RHSType 9225 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9226 return QualType(); 9227 } 9228 9229 // OpenCL V1.1 6.2.6.p1: 9230 // If the operands are of more than one vector type, then an error shall 9231 // occur. Implicit conversions between vector types are not permitted, per 9232 // section 6.2.1. 9233 if (getLangOpts().OpenCL && 9234 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9235 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9236 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9237 << RHSType; 9238 return QualType(); 9239 } 9240 9241 9242 // If there is a vector type that is not a ExtVector and a scalar, we reach 9243 // this point if scalar could not be converted to the vector's element type 9244 // without truncation. 9245 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9246 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9247 QualType Scalar = LHSVecType ? RHSType : LHSType; 9248 QualType Vector = LHSVecType ? LHSType : RHSType; 9249 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9250 Diag(Loc, 9251 diag::err_typecheck_vector_not_convertable_implict_truncation) 9252 << ScalarOrVector << Scalar << Vector; 9253 9254 return QualType(); 9255 } 9256 9257 // Otherwise, use the generic diagnostic. 9258 Diag(Loc, DiagID) 9259 << LHSType << RHSType 9260 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9261 return QualType(); 9262 } 9263 9264 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9265 // expression. These are mainly cases where the null pointer is used as an 9266 // integer instead of a pointer. 9267 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9268 SourceLocation Loc, bool IsCompare) { 9269 // The canonical way to check for a GNU null is with isNullPointerConstant, 9270 // but we use a bit of a hack here for speed; this is a relatively 9271 // hot path, and isNullPointerConstant is slow. 9272 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9273 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9274 9275 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9276 9277 // Avoid analyzing cases where the result will either be invalid (and 9278 // diagnosed as such) or entirely valid and not something to warn about. 9279 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9280 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9281 return; 9282 9283 // Comparison operations would not make sense with a null pointer no matter 9284 // what the other expression is. 9285 if (!IsCompare) { 9286 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9287 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9288 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9289 return; 9290 } 9291 9292 // The rest of the operations only make sense with a null pointer 9293 // if the other expression is a pointer. 9294 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9295 NonNullType->canDecayToPointerType()) 9296 return; 9297 9298 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9299 << LHSNull /* LHS is NULL */ << NonNullType 9300 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9301 } 9302 9303 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9304 SourceLocation Loc) { 9305 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9306 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9307 if (!LUE || !RUE) 9308 return; 9309 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9310 RUE->getKind() != UETT_SizeOf) 9311 return; 9312 9313 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9314 QualType LHSTy = LHSArg->getType(); 9315 QualType RHSTy; 9316 9317 if (RUE->isArgumentType()) 9318 RHSTy = RUE->getArgumentType(); 9319 else 9320 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9321 9322 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9323 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9324 return; 9325 9326 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9327 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9328 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9329 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9330 << LHSArgDecl; 9331 } 9332 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9333 QualType ArrayElemTy = ArrayTy->getElementType(); 9334 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9335 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9336 ArrayElemTy->isCharType() || 9337 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9338 return; 9339 S.Diag(Loc, diag::warn_division_sizeof_array) 9340 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9341 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9342 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9343 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9344 << LHSArgDecl; 9345 } 9346 9347 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9348 } 9349 } 9350 9351 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9352 ExprResult &RHS, 9353 SourceLocation Loc, bool IsDiv) { 9354 // Check for division/remainder by zero. 9355 Expr::EvalResult RHSValue; 9356 if (!RHS.get()->isValueDependent() && 9357 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9358 RHSValue.Val.getInt() == 0) 9359 S.DiagRuntimeBehavior(Loc, RHS.get(), 9360 S.PDiag(diag::warn_remainder_division_by_zero) 9361 << IsDiv << RHS.get()->getSourceRange()); 9362 } 9363 9364 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9365 SourceLocation Loc, 9366 bool IsCompAssign, bool IsDiv) { 9367 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9368 9369 if (LHS.get()->getType()->isVectorType() || 9370 RHS.get()->getType()->isVectorType()) 9371 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9372 /*AllowBothBool*/getLangOpts().AltiVec, 9373 /*AllowBoolConversions*/false); 9374 9375 QualType compType = UsualArithmeticConversions( 9376 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9377 if (LHS.isInvalid() || RHS.isInvalid()) 9378 return QualType(); 9379 9380 9381 if (compType.isNull() || !compType->isArithmeticType()) 9382 return InvalidOperands(Loc, LHS, RHS); 9383 if (IsDiv) { 9384 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9385 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9386 } 9387 return compType; 9388 } 9389 9390 QualType Sema::CheckRemainderOperands( 9391 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9392 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9393 9394 if (LHS.get()->getType()->isVectorType() || 9395 RHS.get()->getType()->isVectorType()) { 9396 if (LHS.get()->getType()->hasIntegerRepresentation() && 9397 RHS.get()->getType()->hasIntegerRepresentation()) 9398 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9399 /*AllowBothBool*/getLangOpts().AltiVec, 9400 /*AllowBoolConversions*/false); 9401 return InvalidOperands(Loc, LHS, RHS); 9402 } 9403 9404 QualType compType = UsualArithmeticConversions( 9405 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9406 if (LHS.isInvalid() || RHS.isInvalid()) 9407 return QualType(); 9408 9409 if (compType.isNull() || !compType->isIntegerType()) 9410 return InvalidOperands(Loc, LHS, RHS); 9411 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9412 return compType; 9413 } 9414 9415 /// Diagnose invalid arithmetic on two void pointers. 9416 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9417 Expr *LHSExpr, Expr *RHSExpr) { 9418 S.Diag(Loc, S.getLangOpts().CPlusPlus 9419 ? diag::err_typecheck_pointer_arith_void_type 9420 : diag::ext_gnu_void_ptr) 9421 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9422 << RHSExpr->getSourceRange(); 9423 } 9424 9425 /// Diagnose invalid arithmetic on a void pointer. 9426 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9427 Expr *Pointer) { 9428 S.Diag(Loc, S.getLangOpts().CPlusPlus 9429 ? diag::err_typecheck_pointer_arith_void_type 9430 : diag::ext_gnu_void_ptr) 9431 << 0 /* one pointer */ << Pointer->getSourceRange(); 9432 } 9433 9434 /// Diagnose invalid arithmetic on a null pointer. 9435 /// 9436 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9437 /// idiom, which we recognize as a GNU extension. 9438 /// 9439 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9440 Expr *Pointer, bool IsGNUIdiom) { 9441 if (IsGNUIdiom) 9442 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9443 << Pointer->getSourceRange(); 9444 else 9445 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9446 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9447 } 9448 9449 /// Diagnose invalid arithmetic on two function pointers. 9450 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9451 Expr *LHS, Expr *RHS) { 9452 assert(LHS->getType()->isAnyPointerType()); 9453 assert(RHS->getType()->isAnyPointerType()); 9454 S.Diag(Loc, S.getLangOpts().CPlusPlus 9455 ? diag::err_typecheck_pointer_arith_function_type 9456 : diag::ext_gnu_ptr_func_arith) 9457 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9458 // We only show the second type if it differs from the first. 9459 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9460 RHS->getType()) 9461 << RHS->getType()->getPointeeType() 9462 << LHS->getSourceRange() << RHS->getSourceRange(); 9463 } 9464 9465 /// Diagnose invalid arithmetic on a function pointer. 9466 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9467 Expr *Pointer) { 9468 assert(Pointer->getType()->isAnyPointerType()); 9469 S.Diag(Loc, S.getLangOpts().CPlusPlus 9470 ? diag::err_typecheck_pointer_arith_function_type 9471 : diag::ext_gnu_ptr_func_arith) 9472 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9473 << 0 /* one pointer, so only one type */ 9474 << Pointer->getSourceRange(); 9475 } 9476 9477 /// Emit error if Operand is incomplete pointer type 9478 /// 9479 /// \returns True if pointer has incomplete type 9480 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9481 Expr *Operand) { 9482 QualType ResType = Operand->getType(); 9483 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9484 ResType = ResAtomicType->getValueType(); 9485 9486 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9487 QualType PointeeTy = ResType->getPointeeType(); 9488 return S.RequireCompleteType(Loc, PointeeTy, 9489 diag::err_typecheck_arithmetic_incomplete_type, 9490 PointeeTy, Operand->getSourceRange()); 9491 } 9492 9493 /// Check the validity of an arithmetic pointer operand. 9494 /// 9495 /// If the operand has pointer type, this code will check for pointer types 9496 /// which are invalid in arithmetic operations. These will be diagnosed 9497 /// appropriately, including whether or not the use is supported as an 9498 /// extension. 9499 /// 9500 /// \returns True when the operand is valid to use (even if as an extension). 9501 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9502 Expr *Operand) { 9503 QualType ResType = Operand->getType(); 9504 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9505 ResType = ResAtomicType->getValueType(); 9506 9507 if (!ResType->isAnyPointerType()) return true; 9508 9509 QualType PointeeTy = ResType->getPointeeType(); 9510 if (PointeeTy->isVoidType()) { 9511 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9512 return !S.getLangOpts().CPlusPlus; 9513 } 9514 if (PointeeTy->isFunctionType()) { 9515 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9516 return !S.getLangOpts().CPlusPlus; 9517 } 9518 9519 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9520 9521 return true; 9522 } 9523 9524 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9525 /// operands. 9526 /// 9527 /// This routine will diagnose any invalid arithmetic on pointer operands much 9528 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9529 /// for emitting a single diagnostic even for operations where both LHS and RHS 9530 /// are (potentially problematic) pointers. 9531 /// 9532 /// \returns True when the operand is valid to use (even if as an extension). 9533 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9534 Expr *LHSExpr, Expr *RHSExpr) { 9535 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9536 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9537 if (!isLHSPointer && !isRHSPointer) return true; 9538 9539 QualType LHSPointeeTy, RHSPointeeTy; 9540 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9541 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9542 9543 // if both are pointers check if operation is valid wrt address spaces 9544 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9545 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9546 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9547 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9548 S.Diag(Loc, 9549 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9550 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9551 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9552 return false; 9553 } 9554 } 9555 9556 // Check for arithmetic on pointers to incomplete types. 9557 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9558 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9559 if (isLHSVoidPtr || isRHSVoidPtr) { 9560 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9561 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9562 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9563 9564 return !S.getLangOpts().CPlusPlus; 9565 } 9566 9567 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9568 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9569 if (isLHSFuncPtr || isRHSFuncPtr) { 9570 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9571 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9572 RHSExpr); 9573 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9574 9575 return !S.getLangOpts().CPlusPlus; 9576 } 9577 9578 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9579 return false; 9580 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9581 return false; 9582 9583 return true; 9584 } 9585 9586 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9587 /// literal. 9588 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9589 Expr *LHSExpr, Expr *RHSExpr) { 9590 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9591 Expr* IndexExpr = RHSExpr; 9592 if (!StrExpr) { 9593 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9594 IndexExpr = LHSExpr; 9595 } 9596 9597 bool IsStringPlusInt = StrExpr && 9598 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9599 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9600 return; 9601 9602 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9603 Self.Diag(OpLoc, diag::warn_string_plus_int) 9604 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9605 9606 // Only print a fixit for "str" + int, not for int + "str". 9607 if (IndexExpr == RHSExpr) { 9608 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9609 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9610 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9611 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9612 << FixItHint::CreateInsertion(EndLoc, "]"); 9613 } else 9614 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9615 } 9616 9617 /// Emit a warning when adding a char literal to a string. 9618 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9619 Expr *LHSExpr, Expr *RHSExpr) { 9620 const Expr *StringRefExpr = LHSExpr; 9621 const CharacterLiteral *CharExpr = 9622 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9623 9624 if (!CharExpr) { 9625 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9626 StringRefExpr = RHSExpr; 9627 } 9628 9629 if (!CharExpr || !StringRefExpr) 9630 return; 9631 9632 const QualType StringType = StringRefExpr->getType(); 9633 9634 // Return if not a PointerType. 9635 if (!StringType->isAnyPointerType()) 9636 return; 9637 9638 // Return if not a CharacterType. 9639 if (!StringType->getPointeeType()->isAnyCharacterType()) 9640 return; 9641 9642 ASTContext &Ctx = Self.getASTContext(); 9643 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9644 9645 const QualType CharType = CharExpr->getType(); 9646 if (!CharType->isAnyCharacterType() && 9647 CharType->isIntegerType() && 9648 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9649 Self.Diag(OpLoc, diag::warn_string_plus_char) 9650 << DiagRange << Ctx.CharTy; 9651 } else { 9652 Self.Diag(OpLoc, diag::warn_string_plus_char) 9653 << DiagRange << CharExpr->getType(); 9654 } 9655 9656 // Only print a fixit for str + char, not for char + str. 9657 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9658 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9659 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9660 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9661 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9662 << FixItHint::CreateInsertion(EndLoc, "]"); 9663 } else { 9664 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9665 } 9666 } 9667 9668 /// Emit error when two pointers are incompatible. 9669 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9670 Expr *LHSExpr, Expr *RHSExpr) { 9671 assert(LHSExpr->getType()->isAnyPointerType()); 9672 assert(RHSExpr->getType()->isAnyPointerType()); 9673 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9674 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9675 << RHSExpr->getSourceRange(); 9676 } 9677 9678 // C99 6.5.6 9679 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9680 SourceLocation Loc, BinaryOperatorKind Opc, 9681 QualType* CompLHSTy) { 9682 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9683 9684 if (LHS.get()->getType()->isVectorType() || 9685 RHS.get()->getType()->isVectorType()) { 9686 QualType compType = CheckVectorOperands( 9687 LHS, RHS, Loc, CompLHSTy, 9688 /*AllowBothBool*/getLangOpts().AltiVec, 9689 /*AllowBoolConversions*/getLangOpts().ZVector); 9690 if (CompLHSTy) *CompLHSTy = compType; 9691 return compType; 9692 } 9693 9694 QualType compType = UsualArithmeticConversions( 9695 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9696 if (LHS.isInvalid() || RHS.isInvalid()) 9697 return QualType(); 9698 9699 // Diagnose "string literal" '+' int and string '+' "char literal". 9700 if (Opc == BO_Add) { 9701 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9702 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9703 } 9704 9705 // handle the common case first (both operands are arithmetic). 9706 if (!compType.isNull() && compType->isArithmeticType()) { 9707 if (CompLHSTy) *CompLHSTy = compType; 9708 return compType; 9709 } 9710 9711 // Type-checking. Ultimately the pointer's going to be in PExp; 9712 // note that we bias towards the LHS being the pointer. 9713 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9714 9715 bool isObjCPointer; 9716 if (PExp->getType()->isPointerType()) { 9717 isObjCPointer = false; 9718 } else if (PExp->getType()->isObjCObjectPointerType()) { 9719 isObjCPointer = true; 9720 } else { 9721 std::swap(PExp, IExp); 9722 if (PExp->getType()->isPointerType()) { 9723 isObjCPointer = false; 9724 } else if (PExp->getType()->isObjCObjectPointerType()) { 9725 isObjCPointer = true; 9726 } else { 9727 return InvalidOperands(Loc, LHS, RHS); 9728 } 9729 } 9730 assert(PExp->getType()->isAnyPointerType()); 9731 9732 if (!IExp->getType()->isIntegerType()) 9733 return InvalidOperands(Loc, LHS, RHS); 9734 9735 // Adding to a null pointer results in undefined behavior. 9736 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9737 Context, Expr::NPC_ValueDependentIsNotNull)) { 9738 // In C++ adding zero to a null pointer is defined. 9739 Expr::EvalResult KnownVal; 9740 if (!getLangOpts().CPlusPlus || 9741 (!IExp->isValueDependent() && 9742 (!IExp->EvaluateAsInt(KnownVal, Context) || 9743 KnownVal.Val.getInt() != 0))) { 9744 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9745 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9746 Context, BO_Add, PExp, IExp); 9747 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9748 } 9749 } 9750 9751 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9752 return QualType(); 9753 9754 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9755 return QualType(); 9756 9757 // Check array bounds for pointer arithemtic 9758 CheckArrayAccess(PExp, IExp); 9759 9760 if (CompLHSTy) { 9761 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9762 if (LHSTy.isNull()) { 9763 LHSTy = LHS.get()->getType(); 9764 if (LHSTy->isPromotableIntegerType()) 9765 LHSTy = Context.getPromotedIntegerType(LHSTy); 9766 } 9767 *CompLHSTy = LHSTy; 9768 } 9769 9770 return PExp->getType(); 9771 } 9772 9773 // C99 6.5.6 9774 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9775 SourceLocation Loc, 9776 QualType* CompLHSTy) { 9777 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9778 9779 if (LHS.get()->getType()->isVectorType() || 9780 RHS.get()->getType()->isVectorType()) { 9781 QualType compType = CheckVectorOperands( 9782 LHS, RHS, Loc, CompLHSTy, 9783 /*AllowBothBool*/getLangOpts().AltiVec, 9784 /*AllowBoolConversions*/getLangOpts().ZVector); 9785 if (CompLHSTy) *CompLHSTy = compType; 9786 return compType; 9787 } 9788 9789 QualType compType = UsualArithmeticConversions( 9790 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9791 if (LHS.isInvalid() || RHS.isInvalid()) 9792 return QualType(); 9793 9794 // Enforce type constraints: C99 6.5.6p3. 9795 9796 // Handle the common case first (both operands are arithmetic). 9797 if (!compType.isNull() && compType->isArithmeticType()) { 9798 if (CompLHSTy) *CompLHSTy = compType; 9799 return compType; 9800 } 9801 9802 // Either ptr - int or ptr - ptr. 9803 if (LHS.get()->getType()->isAnyPointerType()) { 9804 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9805 9806 // Diagnose bad cases where we step over interface counts. 9807 if (LHS.get()->getType()->isObjCObjectPointerType() && 9808 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9809 return QualType(); 9810 9811 // The result type of a pointer-int computation is the pointer type. 9812 if (RHS.get()->getType()->isIntegerType()) { 9813 // Subtracting from a null pointer should produce a warning. 9814 // The last argument to the diagnose call says this doesn't match the 9815 // GNU int-to-pointer idiom. 9816 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9817 Expr::NPC_ValueDependentIsNotNull)) { 9818 // In C++ adding zero to a null pointer is defined. 9819 Expr::EvalResult KnownVal; 9820 if (!getLangOpts().CPlusPlus || 9821 (!RHS.get()->isValueDependent() && 9822 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9823 KnownVal.Val.getInt() != 0))) { 9824 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9825 } 9826 } 9827 9828 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9829 return QualType(); 9830 9831 // Check array bounds for pointer arithemtic 9832 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9833 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9834 9835 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9836 return LHS.get()->getType(); 9837 } 9838 9839 // Handle pointer-pointer subtractions. 9840 if (const PointerType *RHSPTy 9841 = RHS.get()->getType()->getAs<PointerType>()) { 9842 QualType rpointee = RHSPTy->getPointeeType(); 9843 9844 if (getLangOpts().CPlusPlus) { 9845 // Pointee types must be the same: C++ [expr.add] 9846 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9847 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9848 } 9849 } else { 9850 // Pointee types must be compatible C99 6.5.6p3 9851 if (!Context.typesAreCompatible( 9852 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9853 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9854 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9855 return QualType(); 9856 } 9857 } 9858 9859 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9860 LHS.get(), RHS.get())) 9861 return QualType(); 9862 9863 // FIXME: Add warnings for nullptr - ptr. 9864 9865 // The pointee type may have zero size. As an extension, a structure or 9866 // union may have zero size or an array may have zero length. In this 9867 // case subtraction does not make sense. 9868 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9869 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9870 if (ElementSize.isZero()) { 9871 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9872 << rpointee.getUnqualifiedType() 9873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9874 } 9875 } 9876 9877 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9878 return Context.getPointerDiffType(); 9879 } 9880 } 9881 9882 return InvalidOperands(Loc, LHS, RHS); 9883 } 9884 9885 static bool isScopedEnumerationType(QualType T) { 9886 if (const EnumType *ET = T->getAs<EnumType>()) 9887 return ET->getDecl()->isScoped(); 9888 return false; 9889 } 9890 9891 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9892 SourceLocation Loc, BinaryOperatorKind Opc, 9893 QualType LHSType) { 9894 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9895 // so skip remaining warnings as we don't want to modify values within Sema. 9896 if (S.getLangOpts().OpenCL) 9897 return; 9898 9899 // Check right/shifter operand 9900 Expr::EvalResult RHSResult; 9901 if (RHS.get()->isValueDependent() || 9902 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9903 return; 9904 llvm::APSInt Right = RHSResult.Val.getInt(); 9905 9906 if (Right.isNegative()) { 9907 S.DiagRuntimeBehavior(Loc, RHS.get(), 9908 S.PDiag(diag::warn_shift_negative) 9909 << RHS.get()->getSourceRange()); 9910 return; 9911 } 9912 llvm::APInt LeftBits(Right.getBitWidth(), 9913 S.Context.getTypeSize(LHS.get()->getType())); 9914 if (Right.uge(LeftBits)) { 9915 S.DiagRuntimeBehavior(Loc, RHS.get(), 9916 S.PDiag(diag::warn_shift_gt_typewidth) 9917 << RHS.get()->getSourceRange()); 9918 return; 9919 } 9920 if (Opc != BO_Shl) 9921 return; 9922 9923 // When left shifting an ICE which is signed, we can check for overflow which 9924 // according to C++ standards prior to C++2a has undefined behavior 9925 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 9926 // more than the maximum value representable in the result type, so never 9927 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 9928 // expression is still probably a bug.) 9929 Expr::EvalResult LHSResult; 9930 if (LHS.get()->isValueDependent() || 9931 LHSType->hasUnsignedIntegerRepresentation() || 9932 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9933 return; 9934 llvm::APSInt Left = LHSResult.Val.getInt(); 9935 9936 // If LHS does not have a signed type and non-negative value 9937 // then, the behavior is undefined before C++2a. Warn about it. 9938 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 9939 !S.getLangOpts().CPlusPlus2a) { 9940 S.DiagRuntimeBehavior(Loc, LHS.get(), 9941 S.PDiag(diag::warn_shift_lhs_negative) 9942 << LHS.get()->getSourceRange()); 9943 return; 9944 } 9945 9946 llvm::APInt ResultBits = 9947 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9948 if (LeftBits.uge(ResultBits)) 9949 return; 9950 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9951 Result = Result.shl(Right); 9952 9953 // Print the bit representation of the signed integer as an unsigned 9954 // hexadecimal number. 9955 SmallString<40> HexResult; 9956 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9957 9958 // If we are only missing a sign bit, this is less likely to result in actual 9959 // bugs -- if the result is cast back to an unsigned type, it will have the 9960 // expected value. Thus we place this behind a different warning that can be 9961 // turned off separately if needed. 9962 if (LeftBits == ResultBits - 1) { 9963 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9964 << HexResult << LHSType 9965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9966 return; 9967 } 9968 9969 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9970 << HexResult.str() << Result.getMinSignedBits() << LHSType 9971 << Left.getBitWidth() << LHS.get()->getSourceRange() 9972 << RHS.get()->getSourceRange(); 9973 } 9974 9975 /// Return the resulting type when a vector is shifted 9976 /// by a scalar or vector shift amount. 9977 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9978 SourceLocation Loc, bool IsCompAssign) { 9979 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9980 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9981 !LHS.get()->getType()->isVectorType()) { 9982 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9983 << RHS.get()->getType() << LHS.get()->getType() 9984 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9985 return QualType(); 9986 } 9987 9988 if (!IsCompAssign) { 9989 LHS = S.UsualUnaryConversions(LHS.get()); 9990 if (LHS.isInvalid()) return QualType(); 9991 } 9992 9993 RHS = S.UsualUnaryConversions(RHS.get()); 9994 if (RHS.isInvalid()) return QualType(); 9995 9996 QualType LHSType = LHS.get()->getType(); 9997 // Note that LHS might be a scalar because the routine calls not only in 9998 // OpenCL case. 9999 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10000 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10001 10002 // Note that RHS might not be a vector. 10003 QualType RHSType = RHS.get()->getType(); 10004 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10005 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10006 10007 // The operands need to be integers. 10008 if (!LHSEleType->isIntegerType()) { 10009 S.Diag(Loc, diag::err_typecheck_expect_int) 10010 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10011 return QualType(); 10012 } 10013 10014 if (!RHSEleType->isIntegerType()) { 10015 S.Diag(Loc, diag::err_typecheck_expect_int) 10016 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10017 return QualType(); 10018 } 10019 10020 if (!LHSVecTy) { 10021 assert(RHSVecTy); 10022 if (IsCompAssign) 10023 return RHSType; 10024 if (LHSEleType != RHSEleType) { 10025 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10026 LHSEleType = RHSEleType; 10027 } 10028 QualType VecTy = 10029 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10030 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10031 LHSType = VecTy; 10032 } else if (RHSVecTy) { 10033 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10034 // are applied component-wise. So if RHS is a vector, then ensure 10035 // that the number of elements is the same as LHS... 10036 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10037 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10038 << LHS.get()->getType() << RHS.get()->getType() 10039 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10040 return QualType(); 10041 } 10042 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10043 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10044 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10045 if (LHSBT != RHSBT && 10046 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10047 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10048 << LHS.get()->getType() << RHS.get()->getType() 10049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10050 } 10051 } 10052 } else { 10053 // ...else expand RHS to match the number of elements in LHS. 10054 QualType VecTy = 10055 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10056 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10057 } 10058 10059 return LHSType; 10060 } 10061 10062 // C99 6.5.7 10063 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10064 SourceLocation Loc, BinaryOperatorKind Opc, 10065 bool IsCompAssign) { 10066 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10067 10068 // Vector shifts promote their scalar inputs to vector type. 10069 if (LHS.get()->getType()->isVectorType() || 10070 RHS.get()->getType()->isVectorType()) { 10071 if (LangOpts.ZVector) { 10072 // The shift operators for the z vector extensions work basically 10073 // like general shifts, except that neither the LHS nor the RHS is 10074 // allowed to be a "vector bool". 10075 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10076 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10077 return InvalidOperands(Loc, LHS, RHS); 10078 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10079 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10080 return InvalidOperands(Loc, LHS, RHS); 10081 } 10082 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10083 } 10084 10085 // Shifts don't perform usual arithmetic conversions, they just do integer 10086 // promotions on each operand. C99 6.5.7p3 10087 10088 // For the LHS, do usual unary conversions, but then reset them away 10089 // if this is a compound assignment. 10090 ExprResult OldLHS = LHS; 10091 LHS = UsualUnaryConversions(LHS.get()); 10092 if (LHS.isInvalid()) 10093 return QualType(); 10094 QualType LHSType = LHS.get()->getType(); 10095 if (IsCompAssign) LHS = OldLHS; 10096 10097 // The RHS is simpler. 10098 RHS = UsualUnaryConversions(RHS.get()); 10099 if (RHS.isInvalid()) 10100 return QualType(); 10101 QualType RHSType = RHS.get()->getType(); 10102 10103 // C99 6.5.7p2: Each of the operands shall have integer type. 10104 if (!LHSType->hasIntegerRepresentation() || 10105 !RHSType->hasIntegerRepresentation()) 10106 return InvalidOperands(Loc, LHS, RHS); 10107 10108 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10109 // hasIntegerRepresentation() above instead of this. 10110 if (isScopedEnumerationType(LHSType) || 10111 isScopedEnumerationType(RHSType)) { 10112 return InvalidOperands(Loc, LHS, RHS); 10113 } 10114 // Sanity-check shift operands 10115 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10116 10117 // "The type of the result is that of the promoted left operand." 10118 return LHSType; 10119 } 10120 10121 /// Diagnose bad pointer comparisons. 10122 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10123 ExprResult &LHS, ExprResult &RHS, 10124 bool IsError) { 10125 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10126 : diag::ext_typecheck_comparison_of_distinct_pointers) 10127 << LHS.get()->getType() << RHS.get()->getType() 10128 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10129 } 10130 10131 /// Returns false if the pointers are converted to a composite type, 10132 /// true otherwise. 10133 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10134 ExprResult &LHS, ExprResult &RHS) { 10135 // C++ [expr.rel]p2: 10136 // [...] Pointer conversions (4.10) and qualification 10137 // conversions (4.4) are performed on pointer operands (or on 10138 // a pointer operand and a null pointer constant) to bring 10139 // them to their composite pointer type. [...] 10140 // 10141 // C++ [expr.eq]p1 uses the same notion for (in)equality 10142 // comparisons of pointers. 10143 10144 QualType LHSType = LHS.get()->getType(); 10145 QualType RHSType = RHS.get()->getType(); 10146 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10147 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10148 10149 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10150 if (T.isNull()) { 10151 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10152 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10153 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10154 else 10155 S.InvalidOperands(Loc, LHS, RHS); 10156 return true; 10157 } 10158 10159 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 10160 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 10161 return false; 10162 } 10163 10164 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10165 ExprResult &LHS, 10166 ExprResult &RHS, 10167 bool IsError) { 10168 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10169 : diag::ext_typecheck_comparison_of_fptr_to_void) 10170 << LHS.get()->getType() << RHS.get()->getType() 10171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10172 } 10173 10174 static bool isObjCObjectLiteral(ExprResult &E) { 10175 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10176 case Stmt::ObjCArrayLiteralClass: 10177 case Stmt::ObjCDictionaryLiteralClass: 10178 case Stmt::ObjCStringLiteralClass: 10179 case Stmt::ObjCBoxedExprClass: 10180 return true; 10181 default: 10182 // Note that ObjCBoolLiteral is NOT an object literal! 10183 return false; 10184 } 10185 } 10186 10187 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10188 const ObjCObjectPointerType *Type = 10189 LHS->getType()->getAs<ObjCObjectPointerType>(); 10190 10191 // If this is not actually an Objective-C object, bail out. 10192 if (!Type) 10193 return false; 10194 10195 // Get the LHS object's interface type. 10196 QualType InterfaceType = Type->getPointeeType(); 10197 10198 // If the RHS isn't an Objective-C object, bail out. 10199 if (!RHS->getType()->isObjCObjectPointerType()) 10200 return false; 10201 10202 // Try to find the -isEqual: method. 10203 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10204 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10205 InterfaceType, 10206 /*IsInstance=*/true); 10207 if (!Method) { 10208 if (Type->isObjCIdType()) { 10209 // For 'id', just check the global pool. 10210 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10211 /*receiverId=*/true); 10212 } else { 10213 // Check protocols. 10214 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10215 /*IsInstance=*/true); 10216 } 10217 } 10218 10219 if (!Method) 10220 return false; 10221 10222 QualType T = Method->parameters()[0]->getType(); 10223 if (!T->isObjCObjectPointerType()) 10224 return false; 10225 10226 QualType R = Method->getReturnType(); 10227 if (!R->isScalarType()) 10228 return false; 10229 10230 return true; 10231 } 10232 10233 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10234 FromE = FromE->IgnoreParenImpCasts(); 10235 switch (FromE->getStmtClass()) { 10236 default: 10237 break; 10238 case Stmt::ObjCStringLiteralClass: 10239 // "string literal" 10240 return LK_String; 10241 case Stmt::ObjCArrayLiteralClass: 10242 // "array literal" 10243 return LK_Array; 10244 case Stmt::ObjCDictionaryLiteralClass: 10245 // "dictionary literal" 10246 return LK_Dictionary; 10247 case Stmt::BlockExprClass: 10248 return LK_Block; 10249 case Stmt::ObjCBoxedExprClass: { 10250 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10251 switch (Inner->getStmtClass()) { 10252 case Stmt::IntegerLiteralClass: 10253 case Stmt::FloatingLiteralClass: 10254 case Stmt::CharacterLiteralClass: 10255 case Stmt::ObjCBoolLiteralExprClass: 10256 case Stmt::CXXBoolLiteralExprClass: 10257 // "numeric literal" 10258 return LK_Numeric; 10259 case Stmt::ImplicitCastExprClass: { 10260 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10261 // Boolean literals can be represented by implicit casts. 10262 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10263 return LK_Numeric; 10264 break; 10265 } 10266 default: 10267 break; 10268 } 10269 return LK_Boxed; 10270 } 10271 } 10272 return LK_None; 10273 } 10274 10275 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10276 ExprResult &LHS, ExprResult &RHS, 10277 BinaryOperator::Opcode Opc){ 10278 Expr *Literal; 10279 Expr *Other; 10280 if (isObjCObjectLiteral(LHS)) { 10281 Literal = LHS.get(); 10282 Other = RHS.get(); 10283 } else { 10284 Literal = RHS.get(); 10285 Other = LHS.get(); 10286 } 10287 10288 // Don't warn on comparisons against nil. 10289 Other = Other->IgnoreParenCasts(); 10290 if (Other->isNullPointerConstant(S.getASTContext(), 10291 Expr::NPC_ValueDependentIsNotNull)) 10292 return; 10293 10294 // This should be kept in sync with warn_objc_literal_comparison. 10295 // LK_String should always be after the other literals, since it has its own 10296 // warning flag. 10297 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10298 assert(LiteralKind != Sema::LK_Block); 10299 if (LiteralKind == Sema::LK_None) { 10300 llvm_unreachable("Unknown Objective-C object literal kind"); 10301 } 10302 10303 if (LiteralKind == Sema::LK_String) 10304 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10305 << Literal->getSourceRange(); 10306 else 10307 S.Diag(Loc, diag::warn_objc_literal_comparison) 10308 << LiteralKind << Literal->getSourceRange(); 10309 10310 if (BinaryOperator::isEqualityOp(Opc) && 10311 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10312 SourceLocation Start = LHS.get()->getBeginLoc(); 10313 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10314 CharSourceRange OpRange = 10315 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10316 10317 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10318 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10319 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10320 << FixItHint::CreateInsertion(End, "]"); 10321 } 10322 } 10323 10324 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10325 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10326 ExprResult &RHS, SourceLocation Loc, 10327 BinaryOperatorKind Opc) { 10328 // Check that left hand side is !something. 10329 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10330 if (!UO || UO->getOpcode() != UO_LNot) return; 10331 10332 // Only check if the right hand side is non-bool arithmetic type. 10333 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10334 10335 // Make sure that the something in !something is not bool. 10336 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10337 if (SubExpr->isKnownToHaveBooleanValue()) return; 10338 10339 // Emit warning. 10340 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10341 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10342 << Loc << IsBitwiseOp; 10343 10344 // First note suggest !(x < y) 10345 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10346 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10347 FirstClose = S.getLocForEndOfToken(FirstClose); 10348 if (FirstClose.isInvalid()) 10349 FirstOpen = SourceLocation(); 10350 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10351 << IsBitwiseOp 10352 << FixItHint::CreateInsertion(FirstOpen, "(") 10353 << FixItHint::CreateInsertion(FirstClose, ")"); 10354 10355 // Second note suggests (!x) < y 10356 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10357 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10358 SecondClose = S.getLocForEndOfToken(SecondClose); 10359 if (SecondClose.isInvalid()) 10360 SecondOpen = SourceLocation(); 10361 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10362 << FixItHint::CreateInsertion(SecondOpen, "(") 10363 << FixItHint::CreateInsertion(SecondClose, ")"); 10364 } 10365 10366 // Returns true if E refers to a non-weak array. 10367 static bool checkForArray(const Expr *E) { 10368 const ValueDecl *D = nullptr; 10369 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10370 D = DR->getDecl(); 10371 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10372 if (Mem->isImplicitAccess()) 10373 D = Mem->getMemberDecl(); 10374 } 10375 if (!D) 10376 return false; 10377 return D->getType()->isArrayType() && !D->isWeak(); 10378 } 10379 10380 /// Diagnose some forms of syntactically-obvious tautological comparison. 10381 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10382 Expr *LHS, Expr *RHS, 10383 BinaryOperatorKind Opc) { 10384 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10385 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10386 10387 QualType LHSType = LHS->getType(); 10388 QualType RHSType = RHS->getType(); 10389 if (LHSType->hasFloatingRepresentation() || 10390 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10391 S.inTemplateInstantiation()) 10392 return; 10393 10394 // Comparisons between two array types are ill-formed for operator<=>, so 10395 // we shouldn't emit any additional warnings about it. 10396 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10397 return; 10398 10399 // For non-floating point types, check for self-comparisons of the form 10400 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10401 // often indicate logic errors in the program. 10402 // 10403 // NOTE: Don't warn about comparison expressions resulting from macro 10404 // expansion. Also don't warn about comparisons which are only self 10405 // comparisons within a template instantiation. The warnings should catch 10406 // obvious cases in the definition of the template anyways. The idea is to 10407 // warn when the typed comparison operator will always evaluate to the same 10408 // result. 10409 10410 // Used for indexing into %select in warn_comparison_always 10411 enum { 10412 AlwaysConstant, 10413 AlwaysTrue, 10414 AlwaysFalse, 10415 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10416 }; 10417 10418 // C++2a [depr.array.comp]: 10419 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10420 // operands of array type are deprecated. 10421 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10422 RHSStripped->getType()->isArrayType()) { 10423 S.Diag(Loc, diag::warn_depr_array_comparison) 10424 << LHS->getSourceRange() << RHS->getSourceRange() 10425 << LHSStripped->getType() << RHSStripped->getType(); 10426 // Carry on to produce the tautological comparison warning, if this 10427 // expression is potentially-evaluated, we can resolve the array to a 10428 // non-weak declaration, and so on. 10429 } 10430 10431 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10432 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10433 unsigned Result; 10434 switch (Opc) { 10435 case BO_EQ: 10436 case BO_LE: 10437 case BO_GE: 10438 Result = AlwaysTrue; 10439 break; 10440 case BO_NE: 10441 case BO_LT: 10442 case BO_GT: 10443 Result = AlwaysFalse; 10444 break; 10445 case BO_Cmp: 10446 Result = AlwaysEqual; 10447 break; 10448 default: 10449 Result = AlwaysConstant; 10450 break; 10451 } 10452 S.DiagRuntimeBehavior(Loc, nullptr, 10453 S.PDiag(diag::warn_comparison_always) 10454 << 0 /*self-comparison*/ 10455 << Result); 10456 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10457 // What is it always going to evaluate to? 10458 unsigned Result; 10459 switch (Opc) { 10460 case BO_EQ: // e.g. array1 == array2 10461 Result = AlwaysFalse; 10462 break; 10463 case BO_NE: // e.g. array1 != array2 10464 Result = AlwaysTrue; 10465 break; 10466 default: // e.g. array1 <= array2 10467 // The best we can say is 'a constant' 10468 Result = AlwaysConstant; 10469 break; 10470 } 10471 S.DiagRuntimeBehavior(Loc, nullptr, 10472 S.PDiag(diag::warn_comparison_always) 10473 << 1 /*array comparison*/ 10474 << Result); 10475 } 10476 } 10477 10478 if (isa<CastExpr>(LHSStripped)) 10479 LHSStripped = LHSStripped->IgnoreParenCasts(); 10480 if (isa<CastExpr>(RHSStripped)) 10481 RHSStripped = RHSStripped->IgnoreParenCasts(); 10482 10483 // Warn about comparisons against a string constant (unless the other 10484 // operand is null); the user probably wants string comparison function. 10485 Expr *LiteralString = nullptr; 10486 Expr *LiteralStringStripped = nullptr; 10487 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10488 !RHSStripped->isNullPointerConstant(S.Context, 10489 Expr::NPC_ValueDependentIsNull)) { 10490 LiteralString = LHS; 10491 LiteralStringStripped = LHSStripped; 10492 } else if ((isa<StringLiteral>(RHSStripped) || 10493 isa<ObjCEncodeExpr>(RHSStripped)) && 10494 !LHSStripped->isNullPointerConstant(S.Context, 10495 Expr::NPC_ValueDependentIsNull)) { 10496 LiteralString = RHS; 10497 LiteralStringStripped = RHSStripped; 10498 } 10499 10500 if (LiteralString) { 10501 S.DiagRuntimeBehavior(Loc, nullptr, 10502 S.PDiag(diag::warn_stringcompare) 10503 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10504 << LiteralString->getSourceRange()); 10505 } 10506 } 10507 10508 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10509 switch (CK) { 10510 default: { 10511 #ifndef NDEBUG 10512 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10513 << "\n"; 10514 #endif 10515 llvm_unreachable("unhandled cast kind"); 10516 } 10517 case CK_UserDefinedConversion: 10518 return ICK_Identity; 10519 case CK_LValueToRValue: 10520 return ICK_Lvalue_To_Rvalue; 10521 case CK_ArrayToPointerDecay: 10522 return ICK_Array_To_Pointer; 10523 case CK_FunctionToPointerDecay: 10524 return ICK_Function_To_Pointer; 10525 case CK_IntegralCast: 10526 return ICK_Integral_Conversion; 10527 case CK_FloatingCast: 10528 return ICK_Floating_Conversion; 10529 case CK_IntegralToFloating: 10530 case CK_FloatingToIntegral: 10531 return ICK_Floating_Integral; 10532 case CK_IntegralComplexCast: 10533 case CK_FloatingComplexCast: 10534 case CK_FloatingComplexToIntegralComplex: 10535 case CK_IntegralComplexToFloatingComplex: 10536 return ICK_Complex_Conversion; 10537 case CK_FloatingComplexToReal: 10538 case CK_FloatingRealToComplex: 10539 case CK_IntegralComplexToReal: 10540 case CK_IntegralRealToComplex: 10541 return ICK_Complex_Real; 10542 } 10543 } 10544 10545 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10546 QualType FromType, 10547 SourceLocation Loc) { 10548 // Check for a narrowing implicit conversion. 10549 StandardConversionSequence SCS; 10550 SCS.setAsIdentityConversion(); 10551 SCS.setToType(0, FromType); 10552 SCS.setToType(1, ToType); 10553 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10554 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10555 10556 APValue PreNarrowingValue; 10557 QualType PreNarrowingType; 10558 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10559 PreNarrowingType, 10560 /*IgnoreFloatToIntegralConversion*/ true)) { 10561 case NK_Dependent_Narrowing: 10562 // Implicit conversion to a narrower type, but the expression is 10563 // value-dependent so we can't tell whether it's actually narrowing. 10564 case NK_Not_Narrowing: 10565 return false; 10566 10567 case NK_Constant_Narrowing: 10568 // Implicit conversion to a narrower type, and the value is not a constant 10569 // expression. 10570 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10571 << /*Constant*/ 1 10572 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10573 return true; 10574 10575 case NK_Variable_Narrowing: 10576 // Implicit conversion to a narrower type, and the value is not a constant 10577 // expression. 10578 case NK_Type_Narrowing: 10579 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10580 << /*Constant*/ 0 << FromType << ToType; 10581 // TODO: It's not a constant expression, but what if the user intended it 10582 // to be? Can we produce notes to help them figure out why it isn't? 10583 return true; 10584 } 10585 llvm_unreachable("unhandled case in switch"); 10586 } 10587 10588 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10589 ExprResult &LHS, 10590 ExprResult &RHS, 10591 SourceLocation Loc) { 10592 QualType LHSType = LHS.get()->getType(); 10593 QualType RHSType = RHS.get()->getType(); 10594 // Dig out the original argument type and expression before implicit casts 10595 // were applied. These are the types/expressions we need to check the 10596 // [expr.spaceship] requirements against. 10597 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10598 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10599 QualType LHSStrippedType = LHSStripped.get()->getType(); 10600 QualType RHSStrippedType = RHSStripped.get()->getType(); 10601 10602 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10603 // other is not, the program is ill-formed. 10604 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10605 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10606 return QualType(); 10607 } 10608 10609 // FIXME: Consider combining this with checkEnumArithmeticConversions. 10610 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10611 RHSStrippedType->isEnumeralType(); 10612 if (NumEnumArgs == 1) { 10613 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10614 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10615 if (OtherTy->hasFloatingRepresentation()) { 10616 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10617 return QualType(); 10618 } 10619 } 10620 if (NumEnumArgs == 2) { 10621 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10622 // type E, the operator yields the result of converting the operands 10623 // to the underlying type of E and applying <=> to the converted operands. 10624 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10625 S.InvalidOperands(Loc, LHS, RHS); 10626 return QualType(); 10627 } 10628 QualType IntType = 10629 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10630 assert(IntType->isArithmeticType()); 10631 10632 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10633 // promote the boolean type, and all other promotable integer types, to 10634 // avoid this. 10635 if (IntType->isPromotableIntegerType()) 10636 IntType = S.Context.getPromotedIntegerType(IntType); 10637 10638 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10639 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10640 LHSType = RHSType = IntType; 10641 } 10642 10643 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10644 // usual arithmetic conversions are applied to the operands. 10645 QualType Type = 10646 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10647 if (LHS.isInvalid() || RHS.isInvalid()) 10648 return QualType(); 10649 if (Type.isNull()) 10650 return S.InvalidOperands(Loc, LHS, RHS); 10651 10652 Optional<ComparisonCategoryType> CCT = 10653 getComparisonCategoryForBuiltinCmp(Type); 10654 if (!CCT) 10655 return S.InvalidOperands(Loc, LHS, RHS); 10656 10657 bool HasNarrowing = checkThreeWayNarrowingConversion( 10658 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10659 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10660 RHS.get()->getBeginLoc()); 10661 if (HasNarrowing) 10662 return QualType(); 10663 10664 assert(!Type.isNull() && "composite type for <=> has not been set"); 10665 10666 return S.CheckComparisonCategoryType( 10667 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 10668 } 10669 10670 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10671 ExprResult &RHS, 10672 SourceLocation Loc, 10673 BinaryOperatorKind Opc) { 10674 if (Opc == BO_Cmp) 10675 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10676 10677 // C99 6.5.8p3 / C99 6.5.9p4 10678 QualType Type = 10679 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10680 if (LHS.isInvalid() || RHS.isInvalid()) 10681 return QualType(); 10682 if (Type.isNull()) 10683 return S.InvalidOperands(Loc, LHS, RHS); 10684 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10685 10686 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10687 return S.InvalidOperands(Loc, LHS, RHS); 10688 10689 // Check for comparisons of floating point operands using != and ==. 10690 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10691 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10692 10693 // The result of comparisons is 'bool' in C++, 'int' in C. 10694 return S.Context.getLogicalOperationType(); 10695 } 10696 10697 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10698 if (!NullE.get()->getType()->isAnyPointerType()) 10699 return; 10700 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10701 if (!E.get()->getType()->isAnyPointerType() && 10702 E.get()->isNullPointerConstant(Context, 10703 Expr::NPC_ValueDependentIsNotNull) == 10704 Expr::NPCK_ZeroExpression) { 10705 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10706 if (CL->getValue() == 0) 10707 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10708 << NullValue 10709 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10710 NullValue ? "NULL" : "(void *)0"); 10711 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10712 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10713 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10714 if (T == Context.CharTy) 10715 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10716 << NullValue 10717 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10718 NullValue ? "NULL" : "(void *)0"); 10719 } 10720 } 10721 } 10722 10723 // C99 6.5.8, C++ [expr.rel] 10724 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10725 SourceLocation Loc, 10726 BinaryOperatorKind Opc) { 10727 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10728 bool IsThreeWay = Opc == BO_Cmp; 10729 bool IsOrdered = IsRelational || IsThreeWay; 10730 auto IsAnyPointerType = [](ExprResult E) { 10731 QualType Ty = E.get()->getType(); 10732 return Ty->isPointerType() || Ty->isMemberPointerType(); 10733 }; 10734 10735 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10736 // type, array-to-pointer, ..., conversions are performed on both operands to 10737 // bring them to their composite type. 10738 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10739 // any type-related checks. 10740 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10741 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10742 if (LHS.isInvalid()) 10743 return QualType(); 10744 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10745 if (RHS.isInvalid()) 10746 return QualType(); 10747 } else { 10748 LHS = DefaultLvalueConversion(LHS.get()); 10749 if (LHS.isInvalid()) 10750 return QualType(); 10751 RHS = DefaultLvalueConversion(RHS.get()); 10752 if (RHS.isInvalid()) 10753 return QualType(); 10754 } 10755 10756 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10757 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10758 CheckPtrComparisonWithNullChar(LHS, RHS); 10759 CheckPtrComparisonWithNullChar(RHS, LHS); 10760 } 10761 10762 // Handle vector comparisons separately. 10763 if (LHS.get()->getType()->isVectorType() || 10764 RHS.get()->getType()->isVectorType()) 10765 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10766 10767 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10768 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10769 10770 QualType LHSType = LHS.get()->getType(); 10771 QualType RHSType = RHS.get()->getType(); 10772 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10773 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10774 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10775 10776 const Expr::NullPointerConstantKind LHSNullKind = 10777 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10778 const Expr::NullPointerConstantKind RHSNullKind = 10779 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10780 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10781 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10782 10783 auto computeResultTy = [&]() { 10784 if (Opc != BO_Cmp) 10785 return Context.getLogicalOperationType(); 10786 assert(getLangOpts().CPlusPlus); 10787 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10788 10789 QualType CompositeTy = LHS.get()->getType(); 10790 assert(!CompositeTy->isReferenceType()); 10791 10792 Optional<ComparisonCategoryType> CCT = 10793 getComparisonCategoryForBuiltinCmp(CompositeTy); 10794 if (!CCT) 10795 return InvalidOperands(Loc, LHS, RHS); 10796 10797 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 10798 // P0946R0: Comparisons between a null pointer constant and an object 10799 // pointer result in std::strong_equality, which is ill-formed under 10800 // P1959R0. 10801 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 10802 << (LHSIsNull ? LHS.get()->getSourceRange() 10803 : RHS.get()->getSourceRange()); 10804 return QualType(); 10805 } 10806 10807 return CheckComparisonCategoryType( 10808 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 10809 }; 10810 10811 if (!IsOrdered && LHSIsNull != RHSIsNull) { 10812 bool IsEquality = Opc == BO_EQ; 10813 if (RHSIsNull) 10814 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10815 RHS.get()->getSourceRange()); 10816 else 10817 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10818 LHS.get()->getSourceRange()); 10819 } 10820 10821 if ((LHSType->isIntegerType() && !LHSIsNull) || 10822 (RHSType->isIntegerType() && !RHSIsNull)) { 10823 // Skip normal pointer conversion checks in this case; we have better 10824 // diagnostics for this below. 10825 } else if (getLangOpts().CPlusPlus) { 10826 // Equality comparison of a function pointer to a void pointer is invalid, 10827 // but we allow it as an extension. 10828 // FIXME: If we really want to allow this, should it be part of composite 10829 // pointer type computation so it works in conditionals too? 10830 if (!IsOrdered && 10831 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10832 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10833 // This is a gcc extension compatibility comparison. 10834 // In a SFINAE context, we treat this as a hard error to maintain 10835 // conformance with the C++ standard. 10836 diagnoseFunctionPointerToVoidComparison( 10837 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10838 10839 if (isSFINAEContext()) 10840 return QualType(); 10841 10842 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10843 return computeResultTy(); 10844 } 10845 10846 // C++ [expr.eq]p2: 10847 // If at least one operand is a pointer [...] bring them to their 10848 // composite pointer type. 10849 // C++ [expr.spaceship]p6 10850 // If at least one of the operands is of pointer type, [...] bring them 10851 // to their composite pointer type. 10852 // C++ [expr.rel]p2: 10853 // If both operands are pointers, [...] bring them to their composite 10854 // pointer type. 10855 // For <=>, the only valid non-pointer types are arrays and functions, and 10856 // we already decayed those, so this is really the same as the relational 10857 // comparison rule. 10858 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10859 (IsOrdered ? 2 : 1) && 10860 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10861 RHSType->isObjCObjectPointerType()))) { 10862 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10863 return QualType(); 10864 return computeResultTy(); 10865 } 10866 } else if (LHSType->isPointerType() && 10867 RHSType->isPointerType()) { // C99 6.5.8p2 10868 // All of the following pointer-related warnings are GCC extensions, except 10869 // when handling null pointer constants. 10870 QualType LCanPointeeTy = 10871 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10872 QualType RCanPointeeTy = 10873 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10874 10875 // C99 6.5.9p2 and C99 6.5.8p2 10876 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10877 RCanPointeeTy.getUnqualifiedType())) { 10878 // Valid unless a relational comparison of function pointers 10879 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10880 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10881 << LHSType << RHSType << LHS.get()->getSourceRange() 10882 << RHS.get()->getSourceRange(); 10883 } 10884 } else if (!IsRelational && 10885 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10886 // Valid unless comparison between non-null pointer and function pointer 10887 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10888 && !LHSIsNull && !RHSIsNull) 10889 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10890 /*isError*/false); 10891 } else { 10892 // Invalid 10893 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10894 } 10895 if (LCanPointeeTy != RCanPointeeTy) { 10896 // Treat NULL constant as a special case in OpenCL. 10897 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10898 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 10899 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 10900 Diag(Loc, 10901 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10902 << LHSType << RHSType << 0 /* comparison */ 10903 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10904 } 10905 } 10906 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10907 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10908 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10909 : CK_BitCast; 10910 if (LHSIsNull && !RHSIsNull) 10911 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10912 else 10913 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10914 } 10915 return computeResultTy(); 10916 } 10917 10918 if (getLangOpts().CPlusPlus) { 10919 // C++ [expr.eq]p4: 10920 // Two operands of type std::nullptr_t or one operand of type 10921 // std::nullptr_t and the other a null pointer constant compare equal. 10922 if (!IsOrdered && LHSIsNull && RHSIsNull) { 10923 if (LHSType->isNullPtrType()) { 10924 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10925 return computeResultTy(); 10926 } 10927 if (RHSType->isNullPtrType()) { 10928 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10929 return computeResultTy(); 10930 } 10931 } 10932 10933 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10934 // These aren't covered by the composite pointer type rules. 10935 if (!IsOrdered && RHSType->isNullPtrType() && 10936 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10937 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10938 return computeResultTy(); 10939 } 10940 if (!IsOrdered && LHSType->isNullPtrType() && 10941 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10942 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10943 return computeResultTy(); 10944 } 10945 10946 if (IsRelational && 10947 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10948 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10949 // HACK: Relational comparison of nullptr_t against a pointer type is 10950 // invalid per DR583, but we allow it within std::less<> and friends, 10951 // since otherwise common uses of it break. 10952 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10953 // friends to have std::nullptr_t overload candidates. 10954 DeclContext *DC = CurContext; 10955 if (isa<FunctionDecl>(DC)) 10956 DC = DC->getParent(); 10957 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10958 if (CTSD->isInStdNamespace() && 10959 llvm::StringSwitch<bool>(CTSD->getName()) 10960 .Cases("less", "less_equal", "greater", "greater_equal", true) 10961 .Default(false)) { 10962 if (RHSType->isNullPtrType()) 10963 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10964 else 10965 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10966 return computeResultTy(); 10967 } 10968 } 10969 } 10970 10971 // C++ [expr.eq]p2: 10972 // If at least one operand is a pointer to member, [...] bring them to 10973 // their composite pointer type. 10974 if (!IsOrdered && 10975 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10976 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10977 return QualType(); 10978 else 10979 return computeResultTy(); 10980 } 10981 } 10982 10983 // Handle block pointer types. 10984 if (!IsOrdered && LHSType->isBlockPointerType() && 10985 RHSType->isBlockPointerType()) { 10986 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10987 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10988 10989 if (!LHSIsNull && !RHSIsNull && 10990 !Context.typesAreCompatible(lpointee, rpointee)) { 10991 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10992 << LHSType << RHSType << LHS.get()->getSourceRange() 10993 << RHS.get()->getSourceRange(); 10994 } 10995 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10996 return computeResultTy(); 10997 } 10998 10999 // Allow block pointers to be compared with null pointer constants. 11000 if (!IsOrdered 11001 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11002 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11003 if (!LHSIsNull && !RHSIsNull) { 11004 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11005 ->getPointeeType()->isVoidType()) 11006 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11007 ->getPointeeType()->isVoidType()))) 11008 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11009 << LHSType << RHSType << LHS.get()->getSourceRange() 11010 << RHS.get()->getSourceRange(); 11011 } 11012 if (LHSIsNull && !RHSIsNull) 11013 LHS = ImpCastExprToType(LHS.get(), RHSType, 11014 RHSType->isPointerType() ? CK_BitCast 11015 : CK_AnyPointerToBlockPointerCast); 11016 else 11017 RHS = ImpCastExprToType(RHS.get(), LHSType, 11018 LHSType->isPointerType() ? CK_BitCast 11019 : CK_AnyPointerToBlockPointerCast); 11020 return computeResultTy(); 11021 } 11022 11023 if (LHSType->isObjCObjectPointerType() || 11024 RHSType->isObjCObjectPointerType()) { 11025 const PointerType *LPT = LHSType->getAs<PointerType>(); 11026 const PointerType *RPT = RHSType->getAs<PointerType>(); 11027 if (LPT || RPT) { 11028 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11029 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11030 11031 if (!LPtrToVoid && !RPtrToVoid && 11032 !Context.typesAreCompatible(LHSType, RHSType)) { 11033 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11034 /*isError*/false); 11035 } 11036 if (LHSIsNull && !RHSIsNull) { 11037 Expr *E = LHS.get(); 11038 if (getLangOpts().ObjCAutoRefCount) 11039 CheckObjCConversion(SourceRange(), RHSType, E, 11040 CCK_ImplicitConversion); 11041 LHS = ImpCastExprToType(E, RHSType, 11042 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11043 } 11044 else { 11045 Expr *E = RHS.get(); 11046 if (getLangOpts().ObjCAutoRefCount) 11047 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11048 /*Diagnose=*/true, 11049 /*DiagnoseCFAudited=*/false, Opc); 11050 RHS = ImpCastExprToType(E, LHSType, 11051 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11052 } 11053 return computeResultTy(); 11054 } 11055 if (LHSType->isObjCObjectPointerType() && 11056 RHSType->isObjCObjectPointerType()) { 11057 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11058 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11059 /*isError*/false); 11060 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11061 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11062 11063 if (LHSIsNull && !RHSIsNull) 11064 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11065 else 11066 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11067 return computeResultTy(); 11068 } 11069 11070 if (!IsOrdered && LHSType->isBlockPointerType() && 11071 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11072 LHS = ImpCastExprToType(LHS.get(), RHSType, 11073 CK_BlockPointerToObjCPointerCast); 11074 return computeResultTy(); 11075 } else if (!IsOrdered && 11076 LHSType->isBlockCompatibleObjCPointerType(Context) && 11077 RHSType->isBlockPointerType()) { 11078 RHS = ImpCastExprToType(RHS.get(), LHSType, 11079 CK_BlockPointerToObjCPointerCast); 11080 return computeResultTy(); 11081 } 11082 } 11083 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11084 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11085 unsigned DiagID = 0; 11086 bool isError = false; 11087 if (LangOpts.DebuggerSupport) { 11088 // Under a debugger, allow the comparison of pointers to integers, 11089 // since users tend to want to compare addresses. 11090 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11091 (RHSIsNull && RHSType->isIntegerType())) { 11092 if (IsOrdered) { 11093 isError = getLangOpts().CPlusPlus; 11094 DiagID = 11095 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11096 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11097 } 11098 } else if (getLangOpts().CPlusPlus) { 11099 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11100 isError = true; 11101 } else if (IsOrdered) 11102 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11103 else 11104 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11105 11106 if (DiagID) { 11107 Diag(Loc, DiagID) 11108 << LHSType << RHSType << LHS.get()->getSourceRange() 11109 << RHS.get()->getSourceRange(); 11110 if (isError) 11111 return QualType(); 11112 } 11113 11114 if (LHSType->isIntegerType()) 11115 LHS = ImpCastExprToType(LHS.get(), RHSType, 11116 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11117 else 11118 RHS = ImpCastExprToType(RHS.get(), LHSType, 11119 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11120 return computeResultTy(); 11121 } 11122 11123 // Handle block pointers. 11124 if (!IsOrdered && RHSIsNull 11125 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11126 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11127 return computeResultTy(); 11128 } 11129 if (!IsOrdered && LHSIsNull 11130 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11131 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11132 return computeResultTy(); 11133 } 11134 11135 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11136 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11137 return computeResultTy(); 11138 } 11139 11140 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11141 return computeResultTy(); 11142 } 11143 11144 if (LHSIsNull && RHSType->isQueueT()) { 11145 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11146 return computeResultTy(); 11147 } 11148 11149 if (LHSType->isQueueT() && RHSIsNull) { 11150 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11151 return computeResultTy(); 11152 } 11153 } 11154 11155 return InvalidOperands(Loc, LHS, RHS); 11156 } 11157 11158 // Return a signed ext_vector_type that is of identical size and number of 11159 // elements. For floating point vectors, return an integer type of identical 11160 // size and number of elements. In the non ext_vector_type case, search from 11161 // the largest type to the smallest type to avoid cases where long long == long, 11162 // where long gets picked over long long. 11163 QualType Sema::GetSignedVectorType(QualType V) { 11164 const VectorType *VTy = V->castAs<VectorType>(); 11165 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11166 11167 if (isa<ExtVectorType>(VTy)) { 11168 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11169 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11170 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11171 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11172 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11173 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11174 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11175 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11176 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11177 "Unhandled vector element size in vector compare"); 11178 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11179 } 11180 11181 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11182 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11183 VectorType::GenericVector); 11184 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11185 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11186 VectorType::GenericVector); 11187 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11188 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11189 VectorType::GenericVector); 11190 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11191 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11192 VectorType::GenericVector); 11193 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11194 "Unhandled vector element size in vector compare"); 11195 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11196 VectorType::GenericVector); 11197 } 11198 11199 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11200 /// operates on extended vector types. Instead of producing an IntTy result, 11201 /// like a scalar comparison, a vector comparison produces a vector of integer 11202 /// types. 11203 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11204 SourceLocation Loc, 11205 BinaryOperatorKind Opc) { 11206 if (Opc == BO_Cmp) { 11207 Diag(Loc, diag::err_three_way_vector_comparison); 11208 return QualType(); 11209 } 11210 11211 // Check to make sure we're operating on vectors of the same type and width, 11212 // Allowing one side to be a scalar of element type. 11213 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11214 /*AllowBothBool*/true, 11215 /*AllowBoolConversions*/getLangOpts().ZVector); 11216 if (vType.isNull()) 11217 return vType; 11218 11219 QualType LHSType = LHS.get()->getType(); 11220 11221 // If AltiVec, the comparison results in a numeric type, i.e. 11222 // bool for C++, int for C 11223 if (getLangOpts().AltiVec && 11224 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11225 return Context.getLogicalOperationType(); 11226 11227 // For non-floating point types, check for self-comparisons of the form 11228 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11229 // often indicate logic errors in the program. 11230 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11231 11232 // Check for comparisons of floating point operands using != and ==. 11233 if (BinaryOperator::isEqualityOp(Opc) && 11234 LHSType->hasFloatingRepresentation()) { 11235 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11236 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11237 } 11238 11239 // Return a signed type for the vector. 11240 return GetSignedVectorType(vType); 11241 } 11242 11243 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11244 const ExprResult &XorRHS, 11245 const SourceLocation Loc) { 11246 // Do not diagnose macros. 11247 if (Loc.isMacroID()) 11248 return; 11249 11250 bool Negative = false; 11251 bool ExplicitPlus = false; 11252 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11253 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11254 11255 if (!LHSInt) 11256 return; 11257 if (!RHSInt) { 11258 // Check negative literals. 11259 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11260 UnaryOperatorKind Opc = UO->getOpcode(); 11261 if (Opc != UO_Minus && Opc != UO_Plus) 11262 return; 11263 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11264 if (!RHSInt) 11265 return; 11266 Negative = (Opc == UO_Minus); 11267 ExplicitPlus = !Negative; 11268 } else { 11269 return; 11270 } 11271 } 11272 11273 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11274 llvm::APInt RightSideValue = RHSInt->getValue(); 11275 if (LeftSideValue != 2 && LeftSideValue != 10) 11276 return; 11277 11278 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11279 return; 11280 11281 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11282 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11283 llvm::StringRef ExprStr = 11284 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11285 11286 CharSourceRange XorRange = 11287 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11288 llvm::StringRef XorStr = 11289 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11290 // Do not diagnose if xor keyword/macro is used. 11291 if (XorStr == "xor") 11292 return; 11293 11294 std::string LHSStr = Lexer::getSourceText( 11295 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11296 S.getSourceManager(), S.getLangOpts()); 11297 std::string RHSStr = Lexer::getSourceText( 11298 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11299 S.getSourceManager(), S.getLangOpts()); 11300 11301 if (Negative) { 11302 RightSideValue = -RightSideValue; 11303 RHSStr = "-" + RHSStr; 11304 } else if (ExplicitPlus) { 11305 RHSStr = "+" + RHSStr; 11306 } 11307 11308 StringRef LHSStrRef = LHSStr; 11309 StringRef RHSStrRef = RHSStr; 11310 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11311 // literals. 11312 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11313 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11314 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11315 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11316 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11317 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11318 LHSStrRef.find('\'') != StringRef::npos || 11319 RHSStrRef.find('\'') != StringRef::npos) 11320 return; 11321 11322 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11323 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11324 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11325 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11326 std::string SuggestedExpr = "1 << " + RHSStr; 11327 bool Overflow = false; 11328 llvm::APInt One = (LeftSideValue - 1); 11329 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11330 if (Overflow) { 11331 if (RightSideIntValue < 64) 11332 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11333 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11334 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11335 else if (RightSideIntValue == 64) 11336 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11337 else 11338 return; 11339 } else { 11340 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11341 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11342 << PowValue.toString(10, true) 11343 << FixItHint::CreateReplacement( 11344 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11345 } 11346 11347 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11348 } else if (LeftSideValue == 10) { 11349 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11350 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11351 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11352 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11353 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11354 } 11355 } 11356 11357 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11358 SourceLocation Loc) { 11359 // Ensure that either both operands are of the same vector type, or 11360 // one operand is of a vector type and the other is of its element type. 11361 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11362 /*AllowBothBool*/true, 11363 /*AllowBoolConversions*/false); 11364 if (vType.isNull()) 11365 return InvalidOperands(Loc, LHS, RHS); 11366 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11367 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11368 return InvalidOperands(Loc, LHS, RHS); 11369 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11370 // usage of the logical operators && and || with vectors in C. This 11371 // check could be notionally dropped. 11372 if (!getLangOpts().CPlusPlus && 11373 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11374 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11375 11376 return GetSignedVectorType(LHS.get()->getType()); 11377 } 11378 11379 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11380 SourceLocation Loc, 11381 BinaryOperatorKind Opc) { 11382 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11383 11384 bool IsCompAssign = 11385 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11386 11387 if (LHS.get()->getType()->isVectorType() || 11388 RHS.get()->getType()->isVectorType()) { 11389 if (LHS.get()->getType()->hasIntegerRepresentation() && 11390 RHS.get()->getType()->hasIntegerRepresentation()) 11391 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11392 /*AllowBothBool*/true, 11393 /*AllowBoolConversions*/getLangOpts().ZVector); 11394 return InvalidOperands(Loc, LHS, RHS); 11395 } 11396 11397 if (Opc == BO_And) 11398 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11399 11400 if (LHS.get()->getType()->hasFloatingRepresentation() || 11401 RHS.get()->getType()->hasFloatingRepresentation()) 11402 return InvalidOperands(Loc, LHS, RHS); 11403 11404 ExprResult LHSResult = LHS, RHSResult = RHS; 11405 QualType compType = UsualArithmeticConversions( 11406 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11407 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11408 return QualType(); 11409 LHS = LHSResult.get(); 11410 RHS = RHSResult.get(); 11411 11412 if (Opc == BO_Xor) 11413 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11414 11415 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11416 return compType; 11417 return InvalidOperands(Loc, LHS, RHS); 11418 } 11419 11420 // C99 6.5.[13,14] 11421 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11422 SourceLocation Loc, 11423 BinaryOperatorKind Opc) { 11424 // Check vector operands differently. 11425 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11426 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11427 11428 bool EnumConstantInBoolContext = false; 11429 for (const ExprResult &HS : {LHS, RHS}) { 11430 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11431 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11432 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11433 EnumConstantInBoolContext = true; 11434 } 11435 } 11436 11437 if (EnumConstantInBoolContext) 11438 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11439 11440 // Diagnose cases where the user write a logical and/or but probably meant a 11441 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11442 // is a constant. 11443 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11444 !LHS.get()->getType()->isBooleanType() && 11445 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11446 // Don't warn in macros or template instantiations. 11447 !Loc.isMacroID() && !inTemplateInstantiation()) { 11448 // If the RHS can be constant folded, and if it constant folds to something 11449 // that isn't 0 or 1 (which indicate a potential logical operation that 11450 // happened to fold to true/false) then warn. 11451 // Parens on the RHS are ignored. 11452 Expr::EvalResult EVResult; 11453 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11454 llvm::APSInt Result = EVResult.Val.getInt(); 11455 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11456 !RHS.get()->getExprLoc().isMacroID()) || 11457 (Result != 0 && Result != 1)) { 11458 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11459 << RHS.get()->getSourceRange() 11460 << (Opc == BO_LAnd ? "&&" : "||"); 11461 // Suggest replacing the logical operator with the bitwise version 11462 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11463 << (Opc == BO_LAnd ? "&" : "|") 11464 << FixItHint::CreateReplacement(SourceRange( 11465 Loc, getLocForEndOfToken(Loc)), 11466 Opc == BO_LAnd ? "&" : "|"); 11467 if (Opc == BO_LAnd) 11468 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11469 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11470 << FixItHint::CreateRemoval( 11471 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11472 RHS.get()->getEndLoc())); 11473 } 11474 } 11475 } 11476 11477 if (!Context.getLangOpts().CPlusPlus) { 11478 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11479 // not operate on the built-in scalar and vector float types. 11480 if (Context.getLangOpts().OpenCL && 11481 Context.getLangOpts().OpenCLVersion < 120) { 11482 if (LHS.get()->getType()->isFloatingType() || 11483 RHS.get()->getType()->isFloatingType()) 11484 return InvalidOperands(Loc, LHS, RHS); 11485 } 11486 11487 LHS = UsualUnaryConversions(LHS.get()); 11488 if (LHS.isInvalid()) 11489 return QualType(); 11490 11491 RHS = UsualUnaryConversions(RHS.get()); 11492 if (RHS.isInvalid()) 11493 return QualType(); 11494 11495 if (!LHS.get()->getType()->isScalarType() || 11496 !RHS.get()->getType()->isScalarType()) 11497 return InvalidOperands(Loc, LHS, RHS); 11498 11499 return Context.IntTy; 11500 } 11501 11502 // The following is safe because we only use this method for 11503 // non-overloadable operands. 11504 11505 // C++ [expr.log.and]p1 11506 // C++ [expr.log.or]p1 11507 // The operands are both contextually converted to type bool. 11508 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11509 if (LHSRes.isInvalid()) 11510 return InvalidOperands(Loc, LHS, RHS); 11511 LHS = LHSRes; 11512 11513 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11514 if (RHSRes.isInvalid()) 11515 return InvalidOperands(Loc, LHS, RHS); 11516 RHS = RHSRes; 11517 11518 // C++ [expr.log.and]p2 11519 // C++ [expr.log.or]p2 11520 // The result is a bool. 11521 return Context.BoolTy; 11522 } 11523 11524 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11525 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11526 if (!ME) return false; 11527 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11528 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11529 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11530 if (!Base) return false; 11531 return Base->getMethodDecl() != nullptr; 11532 } 11533 11534 /// Is the given expression (which must be 'const') a reference to a 11535 /// variable which was originally non-const, but which has become 11536 /// 'const' due to being captured within a block? 11537 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11538 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11539 assert(E->isLValue() && E->getType().isConstQualified()); 11540 E = E->IgnoreParens(); 11541 11542 // Must be a reference to a declaration from an enclosing scope. 11543 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11544 if (!DRE) return NCCK_None; 11545 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11546 11547 // The declaration must be a variable which is not declared 'const'. 11548 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11549 if (!var) return NCCK_None; 11550 if (var->getType().isConstQualified()) return NCCK_None; 11551 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11552 11553 // Decide whether the first capture was for a block or a lambda. 11554 DeclContext *DC = S.CurContext, *Prev = nullptr; 11555 // Decide whether the first capture was for a block or a lambda. 11556 while (DC) { 11557 // For init-capture, it is possible that the variable belongs to the 11558 // template pattern of the current context. 11559 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11560 if (var->isInitCapture() && 11561 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11562 break; 11563 if (DC == var->getDeclContext()) 11564 break; 11565 Prev = DC; 11566 DC = DC->getParent(); 11567 } 11568 // Unless we have an init-capture, we've gone one step too far. 11569 if (!var->isInitCapture()) 11570 DC = Prev; 11571 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11572 } 11573 11574 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11575 Ty = Ty.getNonReferenceType(); 11576 if (IsDereference && Ty->isPointerType()) 11577 Ty = Ty->getPointeeType(); 11578 return !Ty.isConstQualified(); 11579 } 11580 11581 // Update err_typecheck_assign_const and note_typecheck_assign_const 11582 // when this enum is changed. 11583 enum { 11584 ConstFunction, 11585 ConstVariable, 11586 ConstMember, 11587 ConstMethod, 11588 NestedConstMember, 11589 ConstUnknown, // Keep as last element 11590 }; 11591 11592 /// Emit the "read-only variable not assignable" error and print notes to give 11593 /// more information about why the variable is not assignable, such as pointing 11594 /// to the declaration of a const variable, showing that a method is const, or 11595 /// that the function is returning a const reference. 11596 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11597 SourceLocation Loc) { 11598 SourceRange ExprRange = E->getSourceRange(); 11599 11600 // Only emit one error on the first const found. All other consts will emit 11601 // a note to the error. 11602 bool DiagnosticEmitted = false; 11603 11604 // Track if the current expression is the result of a dereference, and if the 11605 // next checked expression is the result of a dereference. 11606 bool IsDereference = false; 11607 bool NextIsDereference = false; 11608 11609 // Loop to process MemberExpr chains. 11610 while (true) { 11611 IsDereference = NextIsDereference; 11612 11613 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11614 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11615 NextIsDereference = ME->isArrow(); 11616 const ValueDecl *VD = ME->getMemberDecl(); 11617 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11618 // Mutable fields can be modified even if the class is const. 11619 if (Field->isMutable()) { 11620 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11621 break; 11622 } 11623 11624 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11625 if (!DiagnosticEmitted) { 11626 S.Diag(Loc, diag::err_typecheck_assign_const) 11627 << ExprRange << ConstMember << false /*static*/ << Field 11628 << Field->getType(); 11629 DiagnosticEmitted = true; 11630 } 11631 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11632 << ConstMember << false /*static*/ << Field << Field->getType() 11633 << Field->getSourceRange(); 11634 } 11635 E = ME->getBase(); 11636 continue; 11637 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11638 if (VDecl->getType().isConstQualified()) { 11639 if (!DiagnosticEmitted) { 11640 S.Diag(Loc, diag::err_typecheck_assign_const) 11641 << ExprRange << ConstMember << true /*static*/ << VDecl 11642 << VDecl->getType(); 11643 DiagnosticEmitted = true; 11644 } 11645 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11646 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11647 << VDecl->getSourceRange(); 11648 } 11649 // Static fields do not inherit constness from parents. 11650 break; 11651 } 11652 break; // End MemberExpr 11653 } else if (const ArraySubscriptExpr *ASE = 11654 dyn_cast<ArraySubscriptExpr>(E)) { 11655 E = ASE->getBase()->IgnoreParenImpCasts(); 11656 continue; 11657 } else if (const ExtVectorElementExpr *EVE = 11658 dyn_cast<ExtVectorElementExpr>(E)) { 11659 E = EVE->getBase()->IgnoreParenImpCasts(); 11660 continue; 11661 } 11662 break; 11663 } 11664 11665 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11666 // Function calls 11667 const FunctionDecl *FD = CE->getDirectCallee(); 11668 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11669 if (!DiagnosticEmitted) { 11670 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11671 << ConstFunction << FD; 11672 DiagnosticEmitted = true; 11673 } 11674 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11675 diag::note_typecheck_assign_const) 11676 << ConstFunction << FD << FD->getReturnType() 11677 << FD->getReturnTypeSourceRange(); 11678 } 11679 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11680 // Point to variable declaration. 11681 if (const ValueDecl *VD = DRE->getDecl()) { 11682 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11683 if (!DiagnosticEmitted) { 11684 S.Diag(Loc, diag::err_typecheck_assign_const) 11685 << ExprRange << ConstVariable << VD << VD->getType(); 11686 DiagnosticEmitted = true; 11687 } 11688 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11689 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11690 } 11691 } 11692 } else if (isa<CXXThisExpr>(E)) { 11693 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11694 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11695 if (MD->isConst()) { 11696 if (!DiagnosticEmitted) { 11697 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11698 << ConstMethod << MD; 11699 DiagnosticEmitted = true; 11700 } 11701 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11702 << ConstMethod << MD << MD->getSourceRange(); 11703 } 11704 } 11705 } 11706 } 11707 11708 if (DiagnosticEmitted) 11709 return; 11710 11711 // Can't determine a more specific message, so display the generic error. 11712 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11713 } 11714 11715 enum OriginalExprKind { 11716 OEK_Variable, 11717 OEK_Member, 11718 OEK_LValue 11719 }; 11720 11721 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11722 const RecordType *Ty, 11723 SourceLocation Loc, SourceRange Range, 11724 OriginalExprKind OEK, 11725 bool &DiagnosticEmitted) { 11726 std::vector<const RecordType *> RecordTypeList; 11727 RecordTypeList.push_back(Ty); 11728 unsigned NextToCheckIndex = 0; 11729 // We walk the record hierarchy breadth-first to ensure that we print 11730 // diagnostics in field nesting order. 11731 while (RecordTypeList.size() > NextToCheckIndex) { 11732 bool IsNested = NextToCheckIndex > 0; 11733 for (const FieldDecl *Field : 11734 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11735 // First, check every field for constness. 11736 QualType FieldTy = Field->getType(); 11737 if (FieldTy.isConstQualified()) { 11738 if (!DiagnosticEmitted) { 11739 S.Diag(Loc, diag::err_typecheck_assign_const) 11740 << Range << NestedConstMember << OEK << VD 11741 << IsNested << Field; 11742 DiagnosticEmitted = true; 11743 } 11744 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11745 << NestedConstMember << IsNested << Field 11746 << FieldTy << Field->getSourceRange(); 11747 } 11748 11749 // Then we append it to the list to check next in order. 11750 FieldTy = FieldTy.getCanonicalType(); 11751 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11752 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11753 RecordTypeList.push_back(FieldRecTy); 11754 } 11755 } 11756 ++NextToCheckIndex; 11757 } 11758 } 11759 11760 /// Emit an error for the case where a record we are trying to assign to has a 11761 /// const-qualified field somewhere in its hierarchy. 11762 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11763 SourceLocation Loc) { 11764 QualType Ty = E->getType(); 11765 assert(Ty->isRecordType() && "lvalue was not record?"); 11766 SourceRange Range = E->getSourceRange(); 11767 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11768 bool DiagEmitted = false; 11769 11770 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11771 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11772 Range, OEK_Member, DiagEmitted); 11773 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11774 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11775 Range, OEK_Variable, DiagEmitted); 11776 else 11777 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11778 Range, OEK_LValue, DiagEmitted); 11779 if (!DiagEmitted) 11780 DiagnoseConstAssignment(S, E, Loc); 11781 } 11782 11783 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11784 /// emit an error and return true. If so, return false. 11785 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11786 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11787 11788 S.CheckShadowingDeclModification(E, Loc); 11789 11790 SourceLocation OrigLoc = Loc; 11791 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11792 &Loc); 11793 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11794 IsLV = Expr::MLV_InvalidMessageExpression; 11795 if (IsLV == Expr::MLV_Valid) 11796 return false; 11797 11798 unsigned DiagID = 0; 11799 bool NeedType = false; 11800 switch (IsLV) { // C99 6.5.16p2 11801 case Expr::MLV_ConstQualified: 11802 // Use a specialized diagnostic when we're assigning to an object 11803 // from an enclosing function or block. 11804 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11805 if (NCCK == NCCK_Block) 11806 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11807 else 11808 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11809 break; 11810 } 11811 11812 // In ARC, use some specialized diagnostics for occasions where we 11813 // infer 'const'. These are always pseudo-strong variables. 11814 if (S.getLangOpts().ObjCAutoRefCount) { 11815 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11816 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11817 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11818 11819 // Use the normal diagnostic if it's pseudo-__strong but the 11820 // user actually wrote 'const'. 11821 if (var->isARCPseudoStrong() && 11822 (!var->getTypeSourceInfo() || 11823 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11824 // There are three pseudo-strong cases: 11825 // - self 11826 ObjCMethodDecl *method = S.getCurMethodDecl(); 11827 if (method && var == method->getSelfDecl()) { 11828 DiagID = method->isClassMethod() 11829 ? diag::err_typecheck_arc_assign_self_class_method 11830 : diag::err_typecheck_arc_assign_self; 11831 11832 // - Objective-C externally_retained attribute. 11833 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11834 isa<ParmVarDecl>(var)) { 11835 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11836 11837 // - fast enumeration variables 11838 } else { 11839 DiagID = diag::err_typecheck_arr_assign_enumeration; 11840 } 11841 11842 SourceRange Assign; 11843 if (Loc != OrigLoc) 11844 Assign = SourceRange(OrigLoc, OrigLoc); 11845 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11846 // We need to preserve the AST regardless, so migration tool 11847 // can do its job. 11848 return false; 11849 } 11850 } 11851 } 11852 11853 // If none of the special cases above are triggered, then this is a 11854 // simple const assignment. 11855 if (DiagID == 0) { 11856 DiagnoseConstAssignment(S, E, Loc); 11857 return true; 11858 } 11859 11860 break; 11861 case Expr::MLV_ConstAddrSpace: 11862 DiagnoseConstAssignment(S, E, Loc); 11863 return true; 11864 case Expr::MLV_ConstQualifiedField: 11865 DiagnoseRecursiveConstFields(S, E, Loc); 11866 return true; 11867 case Expr::MLV_ArrayType: 11868 case Expr::MLV_ArrayTemporary: 11869 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11870 NeedType = true; 11871 break; 11872 case Expr::MLV_NotObjectType: 11873 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11874 NeedType = true; 11875 break; 11876 case Expr::MLV_LValueCast: 11877 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11878 break; 11879 case Expr::MLV_Valid: 11880 llvm_unreachable("did not take early return for MLV_Valid"); 11881 case Expr::MLV_InvalidExpression: 11882 case Expr::MLV_MemberFunction: 11883 case Expr::MLV_ClassTemporary: 11884 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11885 break; 11886 case Expr::MLV_IncompleteType: 11887 case Expr::MLV_IncompleteVoidType: 11888 return S.RequireCompleteType(Loc, E->getType(), 11889 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11890 case Expr::MLV_DuplicateVectorComponents: 11891 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11892 break; 11893 case Expr::MLV_NoSetterProperty: 11894 llvm_unreachable("readonly properties should be processed differently"); 11895 case Expr::MLV_InvalidMessageExpression: 11896 DiagID = diag::err_readonly_message_assignment; 11897 break; 11898 case Expr::MLV_SubObjCPropertySetting: 11899 DiagID = diag::err_no_subobject_property_setting; 11900 break; 11901 } 11902 11903 SourceRange Assign; 11904 if (Loc != OrigLoc) 11905 Assign = SourceRange(OrigLoc, OrigLoc); 11906 if (NeedType) 11907 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11908 else 11909 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11910 return true; 11911 } 11912 11913 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11914 SourceLocation Loc, 11915 Sema &Sema) { 11916 if (Sema.inTemplateInstantiation()) 11917 return; 11918 if (Sema.isUnevaluatedContext()) 11919 return; 11920 if (Loc.isInvalid() || Loc.isMacroID()) 11921 return; 11922 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11923 return; 11924 11925 // C / C++ fields 11926 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11927 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11928 if (ML && MR) { 11929 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11930 return; 11931 const ValueDecl *LHSDecl = 11932 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11933 const ValueDecl *RHSDecl = 11934 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11935 if (LHSDecl != RHSDecl) 11936 return; 11937 if (LHSDecl->getType().isVolatileQualified()) 11938 return; 11939 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11940 if (RefTy->getPointeeType().isVolatileQualified()) 11941 return; 11942 11943 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11944 } 11945 11946 // Objective-C instance variables 11947 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11948 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11949 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11950 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11951 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11952 if (RL && RR && RL->getDecl() == RR->getDecl()) 11953 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11954 } 11955 } 11956 11957 // C99 6.5.16.1 11958 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11959 SourceLocation Loc, 11960 QualType CompoundType) { 11961 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11962 11963 // Verify that LHS is a modifiable lvalue, and emit error if not. 11964 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11965 return QualType(); 11966 11967 QualType LHSType = LHSExpr->getType(); 11968 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11969 CompoundType; 11970 // OpenCL v1.2 s6.1.1.1 p2: 11971 // The half data type can only be used to declare a pointer to a buffer that 11972 // contains half values 11973 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11974 LHSType->isHalfType()) { 11975 Diag(Loc, diag::err_opencl_half_load_store) << 1 11976 << LHSType.getUnqualifiedType(); 11977 return QualType(); 11978 } 11979 11980 AssignConvertType ConvTy; 11981 if (CompoundType.isNull()) { 11982 Expr *RHSCheck = RHS.get(); 11983 11984 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11985 11986 QualType LHSTy(LHSType); 11987 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11988 if (RHS.isInvalid()) 11989 return QualType(); 11990 // Special case of NSObject attributes on c-style pointer types. 11991 if (ConvTy == IncompatiblePointer && 11992 ((Context.isObjCNSObjectType(LHSType) && 11993 RHSType->isObjCObjectPointerType()) || 11994 (Context.isObjCNSObjectType(RHSType) && 11995 LHSType->isObjCObjectPointerType()))) 11996 ConvTy = Compatible; 11997 11998 if (ConvTy == Compatible && 11999 LHSType->isObjCObjectType()) 12000 Diag(Loc, diag::err_objc_object_assignment) 12001 << LHSType; 12002 12003 // If the RHS is a unary plus or minus, check to see if they = and + are 12004 // right next to each other. If so, the user may have typo'd "x =+ 4" 12005 // instead of "x += 4". 12006 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12007 RHSCheck = ICE->getSubExpr(); 12008 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12009 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12010 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12011 // Only if the two operators are exactly adjacent. 12012 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12013 // And there is a space or other character before the subexpr of the 12014 // unary +/-. We don't want to warn on "x=-1". 12015 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12016 UO->getSubExpr()->getBeginLoc().isFileID()) { 12017 Diag(Loc, diag::warn_not_compound_assign) 12018 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12019 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12020 } 12021 } 12022 12023 if (ConvTy == Compatible) { 12024 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12025 // Warn about retain cycles where a block captures the LHS, but 12026 // not if the LHS is a simple variable into which the block is 12027 // being stored...unless that variable can be captured by reference! 12028 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12029 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12030 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12031 checkRetainCycles(LHSExpr, RHS.get()); 12032 } 12033 12034 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12035 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12036 // It is safe to assign a weak reference into a strong variable. 12037 // Although this code can still have problems: 12038 // id x = self.weakProp; 12039 // id y = self.weakProp; 12040 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12041 // paths through the function. This should be revisited if 12042 // -Wrepeated-use-of-weak is made flow-sensitive. 12043 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12044 // variable, which will be valid for the current autorelease scope. 12045 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12046 RHS.get()->getBeginLoc())) 12047 getCurFunction()->markSafeWeakUse(RHS.get()); 12048 12049 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12050 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12051 } 12052 } 12053 } else { 12054 // Compound assignment "x += y" 12055 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12056 } 12057 12058 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12059 RHS.get(), AA_Assigning)) 12060 return QualType(); 12061 12062 CheckForNullPointerDereference(*this, LHSExpr); 12063 12064 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12065 if (CompoundType.isNull()) { 12066 // C++2a [expr.ass]p5: 12067 // A simple-assignment whose left operand is of a volatile-qualified 12068 // type is deprecated unless the assignment is either a discarded-value 12069 // expression or an unevaluated operand 12070 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12071 } else { 12072 // C++2a [expr.ass]p6: 12073 // [Compound-assignment] expressions are deprecated if E1 has 12074 // volatile-qualified type 12075 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12076 } 12077 } 12078 12079 // C99 6.5.16p3: The type of an assignment expression is the type of the 12080 // left operand unless the left operand has qualified type, in which case 12081 // it is the unqualified version of the type of the left operand. 12082 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12083 // is converted to the type of the assignment expression (above). 12084 // C++ 5.17p1: the type of the assignment expression is that of its left 12085 // operand. 12086 return (getLangOpts().CPlusPlus 12087 ? LHSType : LHSType.getUnqualifiedType()); 12088 } 12089 12090 // Only ignore explicit casts to void. 12091 static bool IgnoreCommaOperand(const Expr *E) { 12092 E = E->IgnoreParens(); 12093 12094 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12095 if (CE->getCastKind() == CK_ToVoid) { 12096 return true; 12097 } 12098 12099 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12100 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12101 CE->getSubExpr()->getType()->isDependentType()) { 12102 return true; 12103 } 12104 } 12105 12106 return false; 12107 } 12108 12109 // Look for instances where it is likely the comma operator is confused with 12110 // another operator. There is a whitelist of acceptable expressions for the 12111 // left hand side of the comma operator, otherwise emit a warning. 12112 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12113 // No warnings in macros 12114 if (Loc.isMacroID()) 12115 return; 12116 12117 // Don't warn in template instantiations. 12118 if (inTemplateInstantiation()) 12119 return; 12120 12121 // Scope isn't fine-grained enough to whitelist the specific cases, so 12122 // instead, skip more than needed, then call back into here with the 12123 // CommaVisitor in SemaStmt.cpp. 12124 // The whitelisted locations are the initialization and increment portions 12125 // of a for loop. The additional checks are on the condition of 12126 // if statements, do/while loops, and for loops. 12127 // Differences in scope flags for C89 mode requires the extra logic. 12128 const unsigned ForIncrementFlags = 12129 getLangOpts().C99 || getLangOpts().CPlusPlus 12130 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12131 : Scope::ContinueScope | Scope::BreakScope; 12132 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12133 const unsigned ScopeFlags = getCurScope()->getFlags(); 12134 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12135 (ScopeFlags & ForInitFlags) == ForInitFlags) 12136 return; 12137 12138 // If there are multiple comma operators used together, get the RHS of the 12139 // of the comma operator as the LHS. 12140 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12141 if (BO->getOpcode() != BO_Comma) 12142 break; 12143 LHS = BO->getRHS(); 12144 } 12145 12146 // Only allow some expressions on LHS to not warn. 12147 if (IgnoreCommaOperand(LHS)) 12148 return; 12149 12150 Diag(Loc, diag::warn_comma_operator); 12151 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12152 << LHS->getSourceRange() 12153 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12154 LangOpts.CPlusPlus ? "static_cast<void>(" 12155 : "(void)(") 12156 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12157 ")"); 12158 } 12159 12160 // C99 6.5.17 12161 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12162 SourceLocation Loc) { 12163 LHS = S.CheckPlaceholderExpr(LHS.get()); 12164 RHS = S.CheckPlaceholderExpr(RHS.get()); 12165 if (LHS.isInvalid() || RHS.isInvalid()) 12166 return QualType(); 12167 12168 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12169 // operands, but not unary promotions. 12170 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12171 12172 // So we treat the LHS as a ignored value, and in C++ we allow the 12173 // containing site to determine what should be done with the RHS. 12174 LHS = S.IgnoredValueConversions(LHS.get()); 12175 if (LHS.isInvalid()) 12176 return QualType(); 12177 12178 S.DiagnoseUnusedExprResult(LHS.get()); 12179 12180 if (!S.getLangOpts().CPlusPlus) { 12181 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12182 if (RHS.isInvalid()) 12183 return QualType(); 12184 if (!RHS.get()->getType()->isVoidType()) 12185 S.RequireCompleteType(Loc, RHS.get()->getType(), 12186 diag::err_incomplete_type); 12187 } 12188 12189 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12190 S.DiagnoseCommaOperator(LHS.get(), Loc); 12191 12192 return RHS.get()->getType(); 12193 } 12194 12195 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12196 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12197 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12198 ExprValueKind &VK, 12199 ExprObjectKind &OK, 12200 SourceLocation OpLoc, 12201 bool IsInc, bool IsPrefix) { 12202 if (Op->isTypeDependent()) 12203 return S.Context.DependentTy; 12204 12205 QualType ResType = Op->getType(); 12206 // Atomic types can be used for increment / decrement where the non-atomic 12207 // versions can, so ignore the _Atomic() specifier for the purpose of 12208 // checking. 12209 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12210 ResType = ResAtomicType->getValueType(); 12211 12212 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12213 12214 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12215 // Decrement of bool is not allowed. 12216 if (!IsInc) { 12217 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12218 return QualType(); 12219 } 12220 // Increment of bool sets it to true, but is deprecated. 12221 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12222 : diag::warn_increment_bool) 12223 << Op->getSourceRange(); 12224 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12225 // Error on enum increments and decrements in C++ mode 12226 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12227 return QualType(); 12228 } else if (ResType->isRealType()) { 12229 // OK! 12230 } else if (ResType->isPointerType()) { 12231 // C99 6.5.2.4p2, 6.5.6p2 12232 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12233 return QualType(); 12234 } else if (ResType->isObjCObjectPointerType()) { 12235 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12236 // Otherwise, we just need a complete type. 12237 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12238 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12239 return QualType(); 12240 } else if (ResType->isAnyComplexType()) { 12241 // C99 does not support ++/-- on complex types, we allow as an extension. 12242 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12243 << ResType << Op->getSourceRange(); 12244 } else if (ResType->isPlaceholderType()) { 12245 ExprResult PR = S.CheckPlaceholderExpr(Op); 12246 if (PR.isInvalid()) return QualType(); 12247 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12248 IsInc, IsPrefix); 12249 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12250 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12251 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12252 (ResType->castAs<VectorType>()->getVectorKind() != 12253 VectorType::AltiVecBool)) { 12254 // The z vector extensions allow ++ and -- for non-bool vectors. 12255 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12256 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12257 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12258 } else { 12259 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12260 << ResType << int(IsInc) << Op->getSourceRange(); 12261 return QualType(); 12262 } 12263 // At this point, we know we have a real, complex or pointer type. 12264 // Now make sure the operand is a modifiable lvalue. 12265 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12266 return QualType(); 12267 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12268 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12269 // An operand with volatile-qualified type is deprecated 12270 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12271 << IsInc << ResType; 12272 } 12273 // In C++, a prefix increment is the same type as the operand. Otherwise 12274 // (in C or with postfix), the increment is the unqualified type of the 12275 // operand. 12276 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12277 VK = VK_LValue; 12278 OK = Op->getObjectKind(); 12279 return ResType; 12280 } else { 12281 VK = VK_RValue; 12282 return ResType.getUnqualifiedType(); 12283 } 12284 } 12285 12286 12287 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12288 /// This routine allows us to typecheck complex/recursive expressions 12289 /// where the declaration is needed for type checking. We only need to 12290 /// handle cases when the expression references a function designator 12291 /// or is an lvalue. Here are some examples: 12292 /// - &(x) => x 12293 /// - &*****f => f for f a function designator. 12294 /// - &s.xx => s 12295 /// - &s.zz[1].yy -> s, if zz is an array 12296 /// - *(x + 1) -> x, if x is an array 12297 /// - &"123"[2] -> 0 12298 /// - & __real__ x -> x 12299 static ValueDecl *getPrimaryDecl(Expr *E) { 12300 switch (E->getStmtClass()) { 12301 case Stmt::DeclRefExprClass: 12302 return cast<DeclRefExpr>(E)->getDecl(); 12303 case Stmt::MemberExprClass: 12304 // If this is an arrow operator, the address is an offset from 12305 // the base's value, so the object the base refers to is 12306 // irrelevant. 12307 if (cast<MemberExpr>(E)->isArrow()) 12308 return nullptr; 12309 // Otherwise, the expression refers to a part of the base 12310 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12311 case Stmt::ArraySubscriptExprClass: { 12312 // FIXME: This code shouldn't be necessary! We should catch the implicit 12313 // promotion of register arrays earlier. 12314 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12315 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12316 if (ICE->getSubExpr()->getType()->isArrayType()) 12317 return getPrimaryDecl(ICE->getSubExpr()); 12318 } 12319 return nullptr; 12320 } 12321 case Stmt::UnaryOperatorClass: { 12322 UnaryOperator *UO = cast<UnaryOperator>(E); 12323 12324 switch(UO->getOpcode()) { 12325 case UO_Real: 12326 case UO_Imag: 12327 case UO_Extension: 12328 return getPrimaryDecl(UO->getSubExpr()); 12329 default: 12330 return nullptr; 12331 } 12332 } 12333 case Stmt::ParenExprClass: 12334 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12335 case Stmt::ImplicitCastExprClass: 12336 // If the result of an implicit cast is an l-value, we care about 12337 // the sub-expression; otherwise, the result here doesn't matter. 12338 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12339 default: 12340 return nullptr; 12341 } 12342 } 12343 12344 namespace { 12345 enum { 12346 AO_Bit_Field = 0, 12347 AO_Vector_Element = 1, 12348 AO_Property_Expansion = 2, 12349 AO_Register_Variable = 3, 12350 AO_No_Error = 4 12351 }; 12352 } 12353 /// Diagnose invalid operand for address of operations. 12354 /// 12355 /// \param Type The type of operand which cannot have its address taken. 12356 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12357 Expr *E, unsigned Type) { 12358 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12359 } 12360 12361 /// CheckAddressOfOperand - The operand of & must be either a function 12362 /// designator or an lvalue designating an object. If it is an lvalue, the 12363 /// object cannot be declared with storage class register or be a bit field. 12364 /// Note: The usual conversions are *not* applied to the operand of the & 12365 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12366 /// In C++, the operand might be an overloaded function name, in which case 12367 /// we allow the '&' but retain the overloaded-function type. 12368 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12369 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12370 if (PTy->getKind() == BuiltinType::Overload) { 12371 Expr *E = OrigOp.get()->IgnoreParens(); 12372 if (!isa<OverloadExpr>(E)) { 12373 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12374 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12375 << OrigOp.get()->getSourceRange(); 12376 return QualType(); 12377 } 12378 12379 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12380 if (isa<UnresolvedMemberExpr>(Ovl)) 12381 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12382 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12383 << OrigOp.get()->getSourceRange(); 12384 return QualType(); 12385 } 12386 12387 return Context.OverloadTy; 12388 } 12389 12390 if (PTy->getKind() == BuiltinType::UnknownAny) 12391 return Context.UnknownAnyTy; 12392 12393 if (PTy->getKind() == BuiltinType::BoundMember) { 12394 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12395 << OrigOp.get()->getSourceRange(); 12396 return QualType(); 12397 } 12398 12399 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12400 if (OrigOp.isInvalid()) return QualType(); 12401 } 12402 12403 if (OrigOp.get()->isTypeDependent()) 12404 return Context.DependentTy; 12405 12406 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12407 12408 // Make sure to ignore parentheses in subsequent checks 12409 Expr *op = OrigOp.get()->IgnoreParens(); 12410 12411 // In OpenCL captures for blocks called as lambda functions 12412 // are located in the private address space. Blocks used in 12413 // enqueue_kernel can be located in a different address space 12414 // depending on a vendor implementation. Thus preventing 12415 // taking an address of the capture to avoid invalid AS casts. 12416 if (LangOpts.OpenCL) { 12417 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12418 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12419 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12420 return QualType(); 12421 } 12422 } 12423 12424 if (getLangOpts().C99) { 12425 // Implement C99-only parts of addressof rules. 12426 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12427 if (uOp->getOpcode() == UO_Deref) 12428 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12429 // (assuming the deref expression is valid). 12430 return uOp->getSubExpr()->getType(); 12431 } 12432 // Technically, there should be a check for array subscript 12433 // expressions here, but the result of one is always an lvalue anyway. 12434 } 12435 ValueDecl *dcl = getPrimaryDecl(op); 12436 12437 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12438 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12439 op->getBeginLoc())) 12440 return QualType(); 12441 12442 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12443 unsigned AddressOfError = AO_No_Error; 12444 12445 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12446 bool sfinae = (bool)isSFINAEContext(); 12447 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12448 : diag::ext_typecheck_addrof_temporary) 12449 << op->getType() << op->getSourceRange(); 12450 if (sfinae) 12451 return QualType(); 12452 // Materialize the temporary as an lvalue so that we can take its address. 12453 OrigOp = op = 12454 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12455 } else if (isa<ObjCSelectorExpr>(op)) { 12456 return Context.getPointerType(op->getType()); 12457 } else if (lval == Expr::LV_MemberFunction) { 12458 // If it's an instance method, make a member pointer. 12459 // The expression must have exactly the form &A::foo. 12460 12461 // If the underlying expression isn't a decl ref, give up. 12462 if (!isa<DeclRefExpr>(op)) { 12463 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12464 << OrigOp.get()->getSourceRange(); 12465 return QualType(); 12466 } 12467 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12468 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12469 12470 // The id-expression was parenthesized. 12471 if (OrigOp.get() != DRE) { 12472 Diag(OpLoc, diag::err_parens_pointer_member_function) 12473 << OrigOp.get()->getSourceRange(); 12474 12475 // The method was named without a qualifier. 12476 } else if (!DRE->getQualifier()) { 12477 if (MD->getParent()->getName().empty()) 12478 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12479 << op->getSourceRange(); 12480 else { 12481 SmallString<32> Str; 12482 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12483 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12484 << op->getSourceRange() 12485 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12486 } 12487 } 12488 12489 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12490 if (isa<CXXDestructorDecl>(MD)) 12491 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12492 12493 QualType MPTy = Context.getMemberPointerType( 12494 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12495 // Under the MS ABI, lock down the inheritance model now. 12496 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12497 (void)isCompleteType(OpLoc, MPTy); 12498 return MPTy; 12499 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12500 // C99 6.5.3.2p1 12501 // The operand must be either an l-value or a function designator 12502 if (!op->getType()->isFunctionType()) { 12503 // Use a special diagnostic for loads from property references. 12504 if (isa<PseudoObjectExpr>(op)) { 12505 AddressOfError = AO_Property_Expansion; 12506 } else { 12507 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12508 << op->getType() << op->getSourceRange(); 12509 return QualType(); 12510 } 12511 } 12512 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12513 // The operand cannot be a bit-field 12514 AddressOfError = AO_Bit_Field; 12515 } else if (op->getObjectKind() == OK_VectorComponent) { 12516 // The operand cannot be an element of a vector 12517 AddressOfError = AO_Vector_Element; 12518 } else if (dcl) { // C99 6.5.3.2p1 12519 // We have an lvalue with a decl. Make sure the decl is not declared 12520 // with the register storage-class specifier. 12521 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12522 // in C++ it is not error to take address of a register 12523 // variable (c++03 7.1.1P3) 12524 if (vd->getStorageClass() == SC_Register && 12525 !getLangOpts().CPlusPlus) { 12526 AddressOfError = AO_Register_Variable; 12527 } 12528 } else if (isa<MSPropertyDecl>(dcl)) { 12529 AddressOfError = AO_Property_Expansion; 12530 } else if (isa<FunctionTemplateDecl>(dcl)) { 12531 return Context.OverloadTy; 12532 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12533 // Okay: we can take the address of a field. 12534 // Could be a pointer to member, though, if there is an explicit 12535 // scope qualifier for the class. 12536 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12537 DeclContext *Ctx = dcl->getDeclContext(); 12538 if (Ctx && Ctx->isRecord()) { 12539 if (dcl->getType()->isReferenceType()) { 12540 Diag(OpLoc, 12541 diag::err_cannot_form_pointer_to_member_of_reference_type) 12542 << dcl->getDeclName() << dcl->getType(); 12543 return QualType(); 12544 } 12545 12546 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12547 Ctx = Ctx->getParent(); 12548 12549 QualType MPTy = Context.getMemberPointerType( 12550 op->getType(), 12551 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12552 // Under the MS ABI, lock down the inheritance model now. 12553 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12554 (void)isCompleteType(OpLoc, MPTy); 12555 return MPTy; 12556 } 12557 } 12558 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12559 !isa<BindingDecl>(dcl)) 12560 llvm_unreachable("Unknown/unexpected decl type"); 12561 } 12562 12563 if (AddressOfError != AO_No_Error) { 12564 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12565 return QualType(); 12566 } 12567 12568 if (lval == Expr::LV_IncompleteVoidType) { 12569 // Taking the address of a void variable is technically illegal, but we 12570 // allow it in cases which are otherwise valid. 12571 // Example: "extern void x; void* y = &x;". 12572 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12573 } 12574 12575 // If the operand has type "type", the result has type "pointer to type". 12576 if (op->getType()->isObjCObjectType()) 12577 return Context.getObjCObjectPointerType(op->getType()); 12578 12579 CheckAddressOfPackedMember(op); 12580 12581 return Context.getPointerType(op->getType()); 12582 } 12583 12584 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12585 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12586 if (!DRE) 12587 return; 12588 const Decl *D = DRE->getDecl(); 12589 if (!D) 12590 return; 12591 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12592 if (!Param) 12593 return; 12594 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12595 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12596 return; 12597 if (FunctionScopeInfo *FD = S.getCurFunction()) 12598 if (!FD->ModifiedNonNullParams.count(Param)) 12599 FD->ModifiedNonNullParams.insert(Param); 12600 } 12601 12602 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12603 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12604 SourceLocation OpLoc) { 12605 if (Op->isTypeDependent()) 12606 return S.Context.DependentTy; 12607 12608 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12609 if (ConvResult.isInvalid()) 12610 return QualType(); 12611 Op = ConvResult.get(); 12612 QualType OpTy = Op->getType(); 12613 QualType Result; 12614 12615 if (isa<CXXReinterpretCastExpr>(Op)) { 12616 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12617 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12618 Op->getSourceRange()); 12619 } 12620 12621 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12622 { 12623 Result = PT->getPointeeType(); 12624 } 12625 else if (const ObjCObjectPointerType *OPT = 12626 OpTy->getAs<ObjCObjectPointerType>()) 12627 Result = OPT->getPointeeType(); 12628 else { 12629 ExprResult PR = S.CheckPlaceholderExpr(Op); 12630 if (PR.isInvalid()) return QualType(); 12631 if (PR.get() != Op) 12632 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12633 } 12634 12635 if (Result.isNull()) { 12636 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12637 << OpTy << Op->getSourceRange(); 12638 return QualType(); 12639 } 12640 12641 // Note that per both C89 and C99, indirection is always legal, even if Result 12642 // is an incomplete type or void. It would be possible to warn about 12643 // dereferencing a void pointer, but it's completely well-defined, and such a 12644 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12645 // for pointers to 'void' but is fine for any other pointer type: 12646 // 12647 // C++ [expr.unary.op]p1: 12648 // [...] the expression to which [the unary * operator] is applied shall 12649 // be a pointer to an object type, or a pointer to a function type 12650 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12651 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12652 << OpTy << Op->getSourceRange(); 12653 12654 // Dereferences are usually l-values... 12655 VK = VK_LValue; 12656 12657 // ...except that certain expressions are never l-values in C. 12658 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12659 VK = VK_RValue; 12660 12661 return Result; 12662 } 12663 12664 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12665 BinaryOperatorKind Opc; 12666 switch (Kind) { 12667 default: llvm_unreachable("Unknown binop!"); 12668 case tok::periodstar: Opc = BO_PtrMemD; break; 12669 case tok::arrowstar: Opc = BO_PtrMemI; break; 12670 case tok::star: Opc = BO_Mul; break; 12671 case tok::slash: Opc = BO_Div; break; 12672 case tok::percent: Opc = BO_Rem; break; 12673 case tok::plus: Opc = BO_Add; break; 12674 case tok::minus: Opc = BO_Sub; break; 12675 case tok::lessless: Opc = BO_Shl; break; 12676 case tok::greatergreater: Opc = BO_Shr; break; 12677 case tok::lessequal: Opc = BO_LE; break; 12678 case tok::less: Opc = BO_LT; break; 12679 case tok::greaterequal: Opc = BO_GE; break; 12680 case tok::greater: Opc = BO_GT; break; 12681 case tok::exclaimequal: Opc = BO_NE; break; 12682 case tok::equalequal: Opc = BO_EQ; break; 12683 case tok::spaceship: Opc = BO_Cmp; break; 12684 case tok::amp: Opc = BO_And; break; 12685 case tok::caret: Opc = BO_Xor; break; 12686 case tok::pipe: Opc = BO_Or; break; 12687 case tok::ampamp: Opc = BO_LAnd; break; 12688 case tok::pipepipe: Opc = BO_LOr; break; 12689 case tok::equal: Opc = BO_Assign; break; 12690 case tok::starequal: Opc = BO_MulAssign; break; 12691 case tok::slashequal: Opc = BO_DivAssign; break; 12692 case tok::percentequal: Opc = BO_RemAssign; break; 12693 case tok::plusequal: Opc = BO_AddAssign; break; 12694 case tok::minusequal: Opc = BO_SubAssign; break; 12695 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12696 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12697 case tok::ampequal: Opc = BO_AndAssign; break; 12698 case tok::caretequal: Opc = BO_XorAssign; break; 12699 case tok::pipeequal: Opc = BO_OrAssign; break; 12700 case tok::comma: Opc = BO_Comma; break; 12701 } 12702 return Opc; 12703 } 12704 12705 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12706 tok::TokenKind Kind) { 12707 UnaryOperatorKind Opc; 12708 switch (Kind) { 12709 default: llvm_unreachable("Unknown unary op!"); 12710 case tok::plusplus: Opc = UO_PreInc; break; 12711 case tok::minusminus: Opc = UO_PreDec; break; 12712 case tok::amp: Opc = UO_AddrOf; break; 12713 case tok::star: Opc = UO_Deref; break; 12714 case tok::plus: Opc = UO_Plus; break; 12715 case tok::minus: Opc = UO_Minus; break; 12716 case tok::tilde: Opc = UO_Not; break; 12717 case tok::exclaim: Opc = UO_LNot; break; 12718 case tok::kw___real: Opc = UO_Real; break; 12719 case tok::kw___imag: Opc = UO_Imag; break; 12720 case tok::kw___extension__: Opc = UO_Extension; break; 12721 } 12722 return Opc; 12723 } 12724 12725 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12726 /// This warning suppressed in the event of macro expansions. 12727 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12728 SourceLocation OpLoc, bool IsBuiltin) { 12729 if (S.inTemplateInstantiation()) 12730 return; 12731 if (S.isUnevaluatedContext()) 12732 return; 12733 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12734 return; 12735 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12736 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12737 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12738 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12739 if (!LHSDeclRef || !RHSDeclRef || 12740 LHSDeclRef->getLocation().isMacroID() || 12741 RHSDeclRef->getLocation().isMacroID()) 12742 return; 12743 const ValueDecl *LHSDecl = 12744 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12745 const ValueDecl *RHSDecl = 12746 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12747 if (LHSDecl != RHSDecl) 12748 return; 12749 if (LHSDecl->getType().isVolatileQualified()) 12750 return; 12751 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12752 if (RefTy->getPointeeType().isVolatileQualified()) 12753 return; 12754 12755 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12756 : diag::warn_self_assignment_overloaded) 12757 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12758 << RHSExpr->getSourceRange(); 12759 } 12760 12761 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12762 /// is usually indicative of introspection within the Objective-C pointer. 12763 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12764 SourceLocation OpLoc) { 12765 if (!S.getLangOpts().ObjC) 12766 return; 12767 12768 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12769 const Expr *LHS = L.get(); 12770 const Expr *RHS = R.get(); 12771 12772 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12773 ObjCPointerExpr = LHS; 12774 OtherExpr = RHS; 12775 } 12776 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12777 ObjCPointerExpr = RHS; 12778 OtherExpr = LHS; 12779 } 12780 12781 // This warning is deliberately made very specific to reduce false 12782 // positives with logic that uses '&' for hashing. This logic mainly 12783 // looks for code trying to introspect into tagged pointers, which 12784 // code should generally never do. 12785 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12786 unsigned Diag = diag::warn_objc_pointer_masking; 12787 // Determine if we are introspecting the result of performSelectorXXX. 12788 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12789 // Special case messages to -performSelector and friends, which 12790 // can return non-pointer values boxed in a pointer value. 12791 // Some clients may wish to silence warnings in this subcase. 12792 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12793 Selector S = ME->getSelector(); 12794 StringRef SelArg0 = S.getNameForSlot(0); 12795 if (SelArg0.startswith("performSelector")) 12796 Diag = diag::warn_objc_pointer_masking_performSelector; 12797 } 12798 12799 S.Diag(OpLoc, Diag) 12800 << ObjCPointerExpr->getSourceRange(); 12801 } 12802 } 12803 12804 static NamedDecl *getDeclFromExpr(Expr *E) { 12805 if (!E) 12806 return nullptr; 12807 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12808 return DRE->getDecl(); 12809 if (auto *ME = dyn_cast<MemberExpr>(E)) 12810 return ME->getMemberDecl(); 12811 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12812 return IRE->getDecl(); 12813 return nullptr; 12814 } 12815 12816 // This helper function promotes a binary operator's operands (which are of a 12817 // half vector type) to a vector of floats and then truncates the result to 12818 // a vector of either half or short. 12819 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12820 BinaryOperatorKind Opc, QualType ResultTy, 12821 ExprValueKind VK, ExprObjectKind OK, 12822 bool IsCompAssign, SourceLocation OpLoc, 12823 FPOptions FPFeatures) { 12824 auto &Context = S.getASTContext(); 12825 assert((isVector(ResultTy, Context.HalfTy) || 12826 isVector(ResultTy, Context.ShortTy)) && 12827 "Result must be a vector of half or short"); 12828 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12829 isVector(RHS.get()->getType(), Context.HalfTy) && 12830 "both operands expected to be a half vector"); 12831 12832 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12833 QualType BinOpResTy = RHS.get()->getType(); 12834 12835 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12836 // change BinOpResTy to a vector of ints. 12837 if (isVector(ResultTy, Context.ShortTy)) 12838 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12839 12840 if (IsCompAssign) 12841 return new (Context) CompoundAssignOperator( 12842 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12843 OpLoc, FPFeatures); 12844 12845 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12846 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12847 VK, OK, OpLoc, FPFeatures); 12848 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 12849 } 12850 12851 static std::pair<ExprResult, ExprResult> 12852 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12853 Expr *RHSExpr) { 12854 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12855 if (!S.getLangOpts().CPlusPlus) { 12856 // C cannot handle TypoExpr nodes on either side of a binop because it 12857 // doesn't handle dependent types properly, so make sure any TypoExprs have 12858 // been dealt with before checking the operands. 12859 LHS = S.CorrectDelayedTyposInExpr(LHS); 12860 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12861 if (Opc != BO_Assign) 12862 return ExprResult(E); 12863 // Avoid correcting the RHS to the same Expr as the LHS. 12864 Decl *D = getDeclFromExpr(E); 12865 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12866 }); 12867 } 12868 return std::make_pair(LHS, RHS); 12869 } 12870 12871 /// Returns true if conversion between vectors of halfs and vectors of floats 12872 /// is needed. 12873 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12874 QualType SrcType) { 12875 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12876 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12877 isVector(SrcType, Ctx.HalfTy); 12878 } 12879 12880 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12881 /// operator @p Opc at location @c TokLoc. This routine only supports 12882 /// built-in operations; ActOnBinOp handles overloaded operators. 12883 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12884 BinaryOperatorKind Opc, 12885 Expr *LHSExpr, Expr *RHSExpr) { 12886 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12887 // The syntax only allows initializer lists on the RHS of assignment, 12888 // so we don't need to worry about accepting invalid code for 12889 // non-assignment operators. 12890 // C++11 5.17p9: 12891 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12892 // of x = {} is x = T(). 12893 InitializationKind Kind = InitializationKind::CreateDirectList( 12894 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12895 InitializedEntity Entity = 12896 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12897 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12898 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12899 if (Init.isInvalid()) 12900 return Init; 12901 RHSExpr = Init.get(); 12902 } 12903 12904 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12905 QualType ResultTy; // Result type of the binary operator. 12906 // The following two variables are used for compound assignment operators 12907 QualType CompLHSTy; // Type of LHS after promotions for computation 12908 QualType CompResultTy; // Type of computation result 12909 ExprValueKind VK = VK_RValue; 12910 ExprObjectKind OK = OK_Ordinary; 12911 bool ConvertHalfVec = false; 12912 12913 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12914 if (!LHS.isUsable() || !RHS.isUsable()) 12915 return ExprError(); 12916 12917 if (getLangOpts().OpenCL) { 12918 QualType LHSTy = LHSExpr->getType(); 12919 QualType RHSTy = RHSExpr->getType(); 12920 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12921 // the ATOMIC_VAR_INIT macro. 12922 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12923 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12924 if (BO_Assign == Opc) 12925 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12926 else 12927 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12928 return ExprError(); 12929 } 12930 12931 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12932 // only with a builtin functions and therefore should be disallowed here. 12933 if (LHSTy->isImageType() || RHSTy->isImageType() || 12934 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12935 LHSTy->isPipeType() || RHSTy->isPipeType() || 12936 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12937 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12938 return ExprError(); 12939 } 12940 } 12941 12942 // Diagnose operations on the unsupported types for OpenMP device compilation. 12943 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 12944 if (Opc != BO_Assign && Opc != BO_Comma) { 12945 checkOpenMPDeviceExpr(LHSExpr); 12946 checkOpenMPDeviceExpr(RHSExpr); 12947 } 12948 } 12949 12950 switch (Opc) { 12951 case BO_Assign: 12952 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12953 if (getLangOpts().CPlusPlus && 12954 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12955 VK = LHS.get()->getValueKind(); 12956 OK = LHS.get()->getObjectKind(); 12957 } 12958 if (!ResultTy.isNull()) { 12959 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12960 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12961 12962 // Avoid copying a block to the heap if the block is assigned to a local 12963 // auto variable that is declared in the same scope as the block. This 12964 // optimization is unsafe if the local variable is declared in an outer 12965 // scope. For example: 12966 // 12967 // BlockTy b; 12968 // { 12969 // b = ^{...}; 12970 // } 12971 // // It is unsafe to invoke the block here if it wasn't copied to the 12972 // // heap. 12973 // b(); 12974 12975 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 12976 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 12977 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 12978 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 12979 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12980 12981 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12982 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 12983 NTCUC_Assignment, NTCUK_Copy); 12984 } 12985 RecordModifiableNonNullParam(*this, LHS.get()); 12986 break; 12987 case BO_PtrMemD: 12988 case BO_PtrMemI: 12989 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12990 Opc == BO_PtrMemI); 12991 break; 12992 case BO_Mul: 12993 case BO_Div: 12994 ConvertHalfVec = true; 12995 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12996 Opc == BO_Div); 12997 break; 12998 case BO_Rem: 12999 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13000 break; 13001 case BO_Add: 13002 ConvertHalfVec = true; 13003 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13004 break; 13005 case BO_Sub: 13006 ConvertHalfVec = true; 13007 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13008 break; 13009 case BO_Shl: 13010 case BO_Shr: 13011 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13012 break; 13013 case BO_LE: 13014 case BO_LT: 13015 case BO_GE: 13016 case BO_GT: 13017 ConvertHalfVec = true; 13018 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13019 break; 13020 case BO_EQ: 13021 case BO_NE: 13022 ConvertHalfVec = true; 13023 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13024 break; 13025 case BO_Cmp: 13026 ConvertHalfVec = true; 13027 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13028 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13029 break; 13030 case BO_And: 13031 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13032 LLVM_FALLTHROUGH; 13033 case BO_Xor: 13034 case BO_Or: 13035 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13036 break; 13037 case BO_LAnd: 13038 case BO_LOr: 13039 ConvertHalfVec = true; 13040 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13041 break; 13042 case BO_MulAssign: 13043 case BO_DivAssign: 13044 ConvertHalfVec = true; 13045 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13046 Opc == BO_DivAssign); 13047 CompLHSTy = CompResultTy; 13048 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13049 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13050 break; 13051 case BO_RemAssign: 13052 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13053 CompLHSTy = CompResultTy; 13054 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13055 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13056 break; 13057 case BO_AddAssign: 13058 ConvertHalfVec = true; 13059 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13060 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13061 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13062 break; 13063 case BO_SubAssign: 13064 ConvertHalfVec = true; 13065 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13066 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13067 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13068 break; 13069 case BO_ShlAssign: 13070 case BO_ShrAssign: 13071 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13072 CompLHSTy = CompResultTy; 13073 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13074 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13075 break; 13076 case BO_AndAssign: 13077 case BO_OrAssign: // fallthrough 13078 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13079 LLVM_FALLTHROUGH; 13080 case BO_XorAssign: 13081 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13082 CompLHSTy = CompResultTy; 13083 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13084 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13085 break; 13086 case BO_Comma: 13087 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13088 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13089 VK = RHS.get()->getValueKind(); 13090 OK = RHS.get()->getObjectKind(); 13091 } 13092 break; 13093 } 13094 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13095 return ExprError(); 13096 13097 if (ResultTy->isRealFloatingType() && 13098 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13099 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13100 // Mark the current function as usng floating point constrained intrinsics 13101 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13102 F->setUsesFPIntrin(true); 13103 } 13104 13105 // Some of the binary operations require promoting operands of half vector to 13106 // float vectors and truncating the result back to half vector. For now, we do 13107 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13108 // arm64). 13109 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13110 isVector(LHS.get()->getType(), Context.HalfTy) && 13111 "both sides are half vectors or neither sides are"); 13112 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 13113 LHS.get()->getType()); 13114 13115 // Check for array bounds violations for both sides of the BinaryOperator 13116 CheckArrayAccess(LHS.get()); 13117 CheckArrayAccess(RHS.get()); 13118 13119 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13120 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13121 &Context.Idents.get("object_setClass"), 13122 SourceLocation(), LookupOrdinaryName); 13123 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13124 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13125 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13126 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13127 "object_setClass(") 13128 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13129 ",") 13130 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13131 } 13132 else 13133 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13134 } 13135 else if (const ObjCIvarRefExpr *OIRE = 13136 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13137 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13138 13139 // Opc is not a compound assignment if CompResultTy is null. 13140 if (CompResultTy.isNull()) { 13141 if (ConvertHalfVec) 13142 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13143 OpLoc, FPFeatures); 13144 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13145 OK, OpLoc, FPFeatures); 13146 } 13147 13148 // Handle compound assignments. 13149 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13150 OK_ObjCProperty) { 13151 VK = VK_LValue; 13152 OK = LHS.get()->getObjectKind(); 13153 } 13154 13155 if (ConvertHalfVec) 13156 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13157 OpLoc, FPFeatures); 13158 13159 return new (Context) CompoundAssignOperator( 13160 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13161 OpLoc, FPFeatures); 13162 } 13163 13164 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13165 /// operators are mixed in a way that suggests that the programmer forgot that 13166 /// comparison operators have higher precedence. The most typical example of 13167 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13168 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13169 SourceLocation OpLoc, Expr *LHSExpr, 13170 Expr *RHSExpr) { 13171 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13172 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13173 13174 // Check that one of the sides is a comparison operator and the other isn't. 13175 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13176 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13177 if (isLeftComp == isRightComp) 13178 return; 13179 13180 // Bitwise operations are sometimes used as eager logical ops. 13181 // Don't diagnose this. 13182 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13183 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13184 if (isLeftBitwise || isRightBitwise) 13185 return; 13186 13187 SourceRange DiagRange = isLeftComp 13188 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13189 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13190 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13191 SourceRange ParensRange = 13192 isLeftComp 13193 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13194 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13195 13196 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13197 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13198 SuggestParentheses(Self, OpLoc, 13199 Self.PDiag(diag::note_precedence_silence) << OpStr, 13200 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13201 SuggestParentheses(Self, OpLoc, 13202 Self.PDiag(diag::note_precedence_bitwise_first) 13203 << BinaryOperator::getOpcodeStr(Opc), 13204 ParensRange); 13205 } 13206 13207 /// It accepts a '&&' expr that is inside a '||' one. 13208 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13209 /// in parentheses. 13210 static void 13211 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13212 BinaryOperator *Bop) { 13213 assert(Bop->getOpcode() == BO_LAnd); 13214 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13215 << Bop->getSourceRange() << OpLoc; 13216 SuggestParentheses(Self, Bop->getOperatorLoc(), 13217 Self.PDiag(diag::note_precedence_silence) 13218 << Bop->getOpcodeStr(), 13219 Bop->getSourceRange()); 13220 } 13221 13222 /// Returns true if the given expression can be evaluated as a constant 13223 /// 'true'. 13224 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13225 bool Res; 13226 return !E->isValueDependent() && 13227 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13228 } 13229 13230 /// Returns true if the given expression can be evaluated as a constant 13231 /// 'false'. 13232 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13233 bool Res; 13234 return !E->isValueDependent() && 13235 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13236 } 13237 13238 /// Look for '&&' in the left hand of a '||' expr. 13239 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13240 Expr *LHSExpr, Expr *RHSExpr) { 13241 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13242 if (Bop->getOpcode() == BO_LAnd) { 13243 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13244 if (EvaluatesAsFalse(S, RHSExpr)) 13245 return; 13246 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13247 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13248 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13249 } else if (Bop->getOpcode() == BO_LOr) { 13250 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13251 // If it's "a || b && 1 || c" we didn't warn earlier for 13252 // "a || b && 1", but warn now. 13253 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13254 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13255 } 13256 } 13257 } 13258 } 13259 13260 /// Look for '&&' in the right hand of a '||' expr. 13261 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13262 Expr *LHSExpr, Expr *RHSExpr) { 13263 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13264 if (Bop->getOpcode() == BO_LAnd) { 13265 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13266 if (EvaluatesAsFalse(S, LHSExpr)) 13267 return; 13268 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13269 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13270 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13271 } 13272 } 13273 } 13274 13275 /// Look for bitwise op in the left or right hand of a bitwise op with 13276 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13277 /// the '&' expression in parentheses. 13278 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13279 SourceLocation OpLoc, Expr *SubExpr) { 13280 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13281 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13282 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13283 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13284 << Bop->getSourceRange() << OpLoc; 13285 SuggestParentheses(S, Bop->getOperatorLoc(), 13286 S.PDiag(diag::note_precedence_silence) 13287 << Bop->getOpcodeStr(), 13288 Bop->getSourceRange()); 13289 } 13290 } 13291 } 13292 13293 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13294 Expr *SubExpr, StringRef Shift) { 13295 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13296 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13297 StringRef Op = Bop->getOpcodeStr(); 13298 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13299 << Bop->getSourceRange() << OpLoc << Shift << Op; 13300 SuggestParentheses(S, Bop->getOperatorLoc(), 13301 S.PDiag(diag::note_precedence_silence) << Op, 13302 Bop->getSourceRange()); 13303 } 13304 } 13305 } 13306 13307 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13308 Expr *LHSExpr, Expr *RHSExpr) { 13309 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13310 if (!OCE) 13311 return; 13312 13313 FunctionDecl *FD = OCE->getDirectCallee(); 13314 if (!FD || !FD->isOverloadedOperator()) 13315 return; 13316 13317 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13318 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13319 return; 13320 13321 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13322 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13323 << (Kind == OO_LessLess); 13324 SuggestParentheses(S, OCE->getOperatorLoc(), 13325 S.PDiag(diag::note_precedence_silence) 13326 << (Kind == OO_LessLess ? "<<" : ">>"), 13327 OCE->getSourceRange()); 13328 SuggestParentheses( 13329 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13330 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13331 } 13332 13333 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13334 /// precedence. 13335 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13336 SourceLocation OpLoc, Expr *LHSExpr, 13337 Expr *RHSExpr){ 13338 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13339 if (BinaryOperator::isBitwiseOp(Opc)) 13340 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13341 13342 // Diagnose "arg1 & arg2 | arg3" 13343 if ((Opc == BO_Or || Opc == BO_Xor) && 13344 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13345 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13346 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13347 } 13348 13349 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13350 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13351 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13352 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13353 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13354 } 13355 13356 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13357 || Opc == BO_Shr) { 13358 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13359 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13360 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13361 } 13362 13363 // Warn on overloaded shift operators and comparisons, such as: 13364 // cout << 5 == 4; 13365 if (BinaryOperator::isComparisonOp(Opc)) 13366 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13367 } 13368 13369 // Binary Operators. 'Tok' is the token for the operator. 13370 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13371 tok::TokenKind Kind, 13372 Expr *LHSExpr, Expr *RHSExpr) { 13373 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13374 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13375 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13376 13377 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13378 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13379 13380 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13381 } 13382 13383 /// Build an overloaded binary operator expression in the given scope. 13384 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13385 BinaryOperatorKind Opc, 13386 Expr *LHS, Expr *RHS) { 13387 switch (Opc) { 13388 case BO_Assign: 13389 case BO_DivAssign: 13390 case BO_RemAssign: 13391 case BO_SubAssign: 13392 case BO_AndAssign: 13393 case BO_OrAssign: 13394 case BO_XorAssign: 13395 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13396 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13397 break; 13398 default: 13399 break; 13400 } 13401 13402 // Find all of the overloaded operators visible from this 13403 // point. We perform both an operator-name lookup from the local 13404 // scope and an argument-dependent lookup based on the types of 13405 // the arguments. 13406 UnresolvedSet<16> Functions; 13407 OverloadedOperatorKind OverOp 13408 = BinaryOperator::getOverloadedOperator(Opc); 13409 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13410 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13411 RHS->getType(), Functions); 13412 13413 // In C++20 onwards, we may have a second operator to look up. 13414 if (S.getLangOpts().CPlusPlus2a) { 13415 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13416 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13417 RHS->getType(), Functions); 13418 } 13419 13420 // Build the (potentially-overloaded, potentially-dependent) 13421 // binary operation. 13422 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13423 } 13424 13425 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13426 BinaryOperatorKind Opc, 13427 Expr *LHSExpr, Expr *RHSExpr) { 13428 ExprResult LHS, RHS; 13429 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13430 if (!LHS.isUsable() || !RHS.isUsable()) 13431 return ExprError(); 13432 LHSExpr = LHS.get(); 13433 RHSExpr = RHS.get(); 13434 13435 // We want to end up calling one of checkPseudoObjectAssignment 13436 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13437 // both expressions are overloadable or either is type-dependent), 13438 // or CreateBuiltinBinOp (in any other case). We also want to get 13439 // any placeholder types out of the way. 13440 13441 // Handle pseudo-objects in the LHS. 13442 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13443 // Assignments with a pseudo-object l-value need special analysis. 13444 if (pty->getKind() == BuiltinType::PseudoObject && 13445 BinaryOperator::isAssignmentOp(Opc)) 13446 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13447 13448 // Don't resolve overloads if the other type is overloadable. 13449 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13450 // We can't actually test that if we still have a placeholder, 13451 // though. Fortunately, none of the exceptions we see in that 13452 // code below are valid when the LHS is an overload set. Note 13453 // that an overload set can be dependently-typed, but it never 13454 // instantiates to having an overloadable type. 13455 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13456 if (resolvedRHS.isInvalid()) return ExprError(); 13457 RHSExpr = resolvedRHS.get(); 13458 13459 if (RHSExpr->isTypeDependent() || 13460 RHSExpr->getType()->isOverloadableType()) 13461 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13462 } 13463 13464 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13465 // template, diagnose the missing 'template' keyword instead of diagnosing 13466 // an invalid use of a bound member function. 13467 // 13468 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13469 // to C++1z [over.over]/1.4, but we already checked for that case above. 13470 if (Opc == BO_LT && inTemplateInstantiation() && 13471 (pty->getKind() == BuiltinType::BoundMember || 13472 pty->getKind() == BuiltinType::Overload)) { 13473 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13474 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13475 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13476 return isa<FunctionTemplateDecl>(ND); 13477 })) { 13478 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13479 : OE->getNameLoc(), 13480 diag::err_template_kw_missing) 13481 << OE->getName().getAsString() << ""; 13482 return ExprError(); 13483 } 13484 } 13485 13486 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13487 if (LHS.isInvalid()) return ExprError(); 13488 LHSExpr = LHS.get(); 13489 } 13490 13491 // Handle pseudo-objects in the RHS. 13492 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13493 // An overload in the RHS can potentially be resolved by the type 13494 // being assigned to. 13495 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13496 if (getLangOpts().CPlusPlus && 13497 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13498 LHSExpr->getType()->isOverloadableType())) 13499 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13500 13501 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13502 } 13503 13504 // Don't resolve overloads if the other type is overloadable. 13505 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13506 LHSExpr->getType()->isOverloadableType()) 13507 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13508 13509 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13510 if (!resolvedRHS.isUsable()) return ExprError(); 13511 RHSExpr = resolvedRHS.get(); 13512 } 13513 13514 if (getLangOpts().CPlusPlus) { 13515 // If either expression is type-dependent, always build an 13516 // overloaded op. 13517 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13518 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13519 13520 // Otherwise, build an overloaded op if either expression has an 13521 // overloadable type. 13522 if (LHSExpr->getType()->isOverloadableType() || 13523 RHSExpr->getType()->isOverloadableType()) 13524 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13525 } 13526 13527 // Build a built-in binary operation. 13528 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13529 } 13530 13531 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13532 if (T.isNull() || T->isDependentType()) 13533 return false; 13534 13535 if (!T->isPromotableIntegerType()) 13536 return true; 13537 13538 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13539 } 13540 13541 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13542 UnaryOperatorKind Opc, 13543 Expr *InputExpr) { 13544 ExprResult Input = InputExpr; 13545 ExprValueKind VK = VK_RValue; 13546 ExprObjectKind OK = OK_Ordinary; 13547 QualType resultType; 13548 bool CanOverflow = false; 13549 13550 bool ConvertHalfVec = false; 13551 if (getLangOpts().OpenCL) { 13552 QualType Ty = InputExpr->getType(); 13553 // The only legal unary operation for atomics is '&'. 13554 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13555 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13556 // only with a builtin functions and therefore should be disallowed here. 13557 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13558 || Ty->isBlockPointerType())) { 13559 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13560 << InputExpr->getType() 13561 << Input.get()->getSourceRange()); 13562 } 13563 } 13564 // Diagnose operations on the unsupported types for OpenMP device compilation. 13565 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13566 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13567 UnaryOperator::isArithmeticOp(Opc)) 13568 checkOpenMPDeviceExpr(InputExpr); 13569 } 13570 13571 switch (Opc) { 13572 case UO_PreInc: 13573 case UO_PreDec: 13574 case UO_PostInc: 13575 case UO_PostDec: 13576 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13577 OpLoc, 13578 Opc == UO_PreInc || 13579 Opc == UO_PostInc, 13580 Opc == UO_PreInc || 13581 Opc == UO_PreDec); 13582 CanOverflow = isOverflowingIntegerType(Context, resultType); 13583 break; 13584 case UO_AddrOf: 13585 resultType = CheckAddressOfOperand(Input, OpLoc); 13586 CheckAddressOfNoDeref(InputExpr); 13587 RecordModifiableNonNullParam(*this, InputExpr); 13588 break; 13589 case UO_Deref: { 13590 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13591 if (Input.isInvalid()) return ExprError(); 13592 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13593 break; 13594 } 13595 case UO_Plus: 13596 case UO_Minus: 13597 CanOverflow = Opc == UO_Minus && 13598 isOverflowingIntegerType(Context, Input.get()->getType()); 13599 Input = UsualUnaryConversions(Input.get()); 13600 if (Input.isInvalid()) return ExprError(); 13601 // Unary plus and minus require promoting an operand of half vector to a 13602 // float vector and truncating the result back to a half vector. For now, we 13603 // do this only when HalfArgsAndReturns is set (that is, when the target is 13604 // arm or arm64). 13605 ConvertHalfVec = 13606 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 13607 13608 // If the operand is a half vector, promote it to a float vector. 13609 if (ConvertHalfVec) 13610 Input = convertVector(Input.get(), Context.FloatTy, *this); 13611 resultType = Input.get()->getType(); 13612 if (resultType->isDependentType()) 13613 break; 13614 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13615 break; 13616 else if (resultType->isVectorType() && 13617 // The z vector extensions don't allow + or - with bool vectors. 13618 (!Context.getLangOpts().ZVector || 13619 resultType->castAs<VectorType>()->getVectorKind() != 13620 VectorType::AltiVecBool)) 13621 break; 13622 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13623 Opc == UO_Plus && 13624 resultType->isPointerType()) 13625 break; 13626 13627 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13628 << resultType << Input.get()->getSourceRange()); 13629 13630 case UO_Not: // bitwise complement 13631 Input = UsualUnaryConversions(Input.get()); 13632 if (Input.isInvalid()) 13633 return ExprError(); 13634 resultType = Input.get()->getType(); 13635 if (resultType->isDependentType()) 13636 break; 13637 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13638 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13639 // C99 does not support '~' for complex conjugation. 13640 Diag(OpLoc, diag::ext_integer_complement_complex) 13641 << resultType << Input.get()->getSourceRange(); 13642 else if (resultType->hasIntegerRepresentation()) 13643 break; 13644 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13645 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13646 // on vector float types. 13647 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13648 if (!T->isIntegerType()) 13649 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13650 << resultType << Input.get()->getSourceRange()); 13651 } else { 13652 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13653 << resultType << Input.get()->getSourceRange()); 13654 } 13655 break; 13656 13657 case UO_LNot: // logical negation 13658 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13659 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13660 if (Input.isInvalid()) return ExprError(); 13661 resultType = Input.get()->getType(); 13662 13663 // Though we still have to promote half FP to float... 13664 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13665 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13666 resultType = Context.FloatTy; 13667 } 13668 13669 if (resultType->isDependentType()) 13670 break; 13671 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13672 // C99 6.5.3.3p1: ok, fallthrough; 13673 if (Context.getLangOpts().CPlusPlus) { 13674 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13675 // operand contextually converted to bool. 13676 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13677 ScalarTypeToBooleanCastKind(resultType)); 13678 } else if (Context.getLangOpts().OpenCL && 13679 Context.getLangOpts().OpenCLVersion < 120) { 13680 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13681 // operate on scalar float types. 13682 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13684 << resultType << Input.get()->getSourceRange()); 13685 } 13686 } else if (resultType->isExtVectorType()) { 13687 if (Context.getLangOpts().OpenCL && 13688 Context.getLangOpts().OpenCLVersion < 120 && 13689 !Context.getLangOpts().OpenCLCPlusPlus) { 13690 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13691 // operate on vector float types. 13692 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13693 if (!T->isIntegerType()) 13694 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13695 << resultType << Input.get()->getSourceRange()); 13696 } 13697 // Vector logical not returns the signed variant of the operand type. 13698 resultType = GetSignedVectorType(resultType); 13699 break; 13700 } else { 13701 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13702 // type in C++. We should allow that here too. 13703 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13704 << resultType << Input.get()->getSourceRange()); 13705 } 13706 13707 // LNot always has type int. C99 6.5.3.3p5. 13708 // In C++, it's bool. C++ 5.3.1p8 13709 resultType = Context.getLogicalOperationType(); 13710 break; 13711 case UO_Real: 13712 case UO_Imag: 13713 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13714 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13715 // complex l-values to ordinary l-values and all other values to r-values. 13716 if (Input.isInvalid()) return ExprError(); 13717 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13718 if (Input.get()->getValueKind() != VK_RValue && 13719 Input.get()->getObjectKind() == OK_Ordinary) 13720 VK = Input.get()->getValueKind(); 13721 } else if (!getLangOpts().CPlusPlus) { 13722 // In C, a volatile scalar is read by __imag. In C++, it is not. 13723 Input = DefaultLvalueConversion(Input.get()); 13724 } 13725 break; 13726 case UO_Extension: 13727 resultType = Input.get()->getType(); 13728 VK = Input.get()->getValueKind(); 13729 OK = Input.get()->getObjectKind(); 13730 break; 13731 case UO_Coawait: 13732 // It's unnecessary to represent the pass-through operator co_await in the 13733 // AST; just return the input expression instead. 13734 assert(!Input.get()->getType()->isDependentType() && 13735 "the co_await expression must be non-dependant before " 13736 "building operator co_await"); 13737 return Input; 13738 } 13739 if (resultType.isNull() || Input.isInvalid()) 13740 return ExprError(); 13741 13742 // Check for array bounds violations in the operand of the UnaryOperator, 13743 // except for the '*' and '&' operators that have to be handled specially 13744 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13745 // that are explicitly defined as valid by the standard). 13746 if (Opc != UO_AddrOf && Opc != UO_Deref) 13747 CheckArrayAccess(Input.get()); 13748 13749 auto *UO = new (Context) 13750 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13751 13752 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13753 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13754 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13755 13756 // Convert the result back to a half vector. 13757 if (ConvertHalfVec) 13758 return convertVector(UO, Context.HalfTy, *this); 13759 return UO; 13760 } 13761 13762 /// Determine whether the given expression is a qualified member 13763 /// access expression, of a form that could be turned into a pointer to member 13764 /// with the address-of operator. 13765 bool Sema::isQualifiedMemberAccess(Expr *E) { 13766 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13767 if (!DRE->getQualifier()) 13768 return false; 13769 13770 ValueDecl *VD = DRE->getDecl(); 13771 if (!VD->isCXXClassMember()) 13772 return false; 13773 13774 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13775 return true; 13776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13777 return Method->isInstance(); 13778 13779 return false; 13780 } 13781 13782 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13783 if (!ULE->getQualifier()) 13784 return false; 13785 13786 for (NamedDecl *D : ULE->decls()) { 13787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13788 if (Method->isInstance()) 13789 return true; 13790 } else { 13791 // Overload set does not contain methods. 13792 break; 13793 } 13794 } 13795 13796 return false; 13797 } 13798 13799 return false; 13800 } 13801 13802 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13803 UnaryOperatorKind Opc, Expr *Input) { 13804 // First things first: handle placeholders so that the 13805 // overloaded-operator check considers the right type. 13806 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13807 // Increment and decrement of pseudo-object references. 13808 if (pty->getKind() == BuiltinType::PseudoObject && 13809 UnaryOperator::isIncrementDecrementOp(Opc)) 13810 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13811 13812 // extension is always a builtin operator. 13813 if (Opc == UO_Extension) 13814 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13815 13816 // & gets special logic for several kinds of placeholder. 13817 // The builtin code knows what to do. 13818 if (Opc == UO_AddrOf && 13819 (pty->getKind() == BuiltinType::Overload || 13820 pty->getKind() == BuiltinType::UnknownAny || 13821 pty->getKind() == BuiltinType::BoundMember)) 13822 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13823 13824 // Anything else needs to be handled now. 13825 ExprResult Result = CheckPlaceholderExpr(Input); 13826 if (Result.isInvalid()) return ExprError(); 13827 Input = Result.get(); 13828 } 13829 13830 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13831 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13832 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13833 // Find all of the overloaded operators visible from this 13834 // point. We perform both an operator-name lookup from the local 13835 // scope and an argument-dependent lookup based on the types of 13836 // the arguments. 13837 UnresolvedSet<16> Functions; 13838 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13839 if (S && OverOp != OO_None) 13840 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13841 Functions); 13842 13843 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13844 } 13845 13846 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13847 } 13848 13849 // Unary Operators. 'Tok' is the token for the operator. 13850 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13851 tok::TokenKind Op, Expr *Input) { 13852 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13853 } 13854 13855 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13856 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13857 LabelDecl *TheDecl) { 13858 TheDecl->markUsed(Context); 13859 // Create the AST node. The address of a label always has type 'void*'. 13860 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13861 Context.getPointerType(Context.VoidTy)); 13862 } 13863 13864 void Sema::ActOnStartStmtExpr() { 13865 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13866 } 13867 13868 void Sema::ActOnStmtExprError() { 13869 // Note that function is also called by TreeTransform when leaving a 13870 // StmtExpr scope without rebuilding anything. 13871 13872 DiscardCleanupsInEvaluationContext(); 13873 PopExpressionEvaluationContext(); 13874 } 13875 13876 ExprResult 13877 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13878 SourceLocation RPLoc) { // "({..})" 13879 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13880 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13881 13882 if (hasAnyUnrecoverableErrorsInThisFunction()) 13883 DiscardCleanupsInEvaluationContext(); 13884 assert(!Cleanup.exprNeedsCleanups() && 13885 "cleanups within StmtExpr not correctly bound!"); 13886 PopExpressionEvaluationContext(); 13887 13888 // FIXME: there are a variety of strange constraints to enforce here, for 13889 // example, it is not possible to goto into a stmt expression apparently. 13890 // More semantic analysis is needed. 13891 13892 // If there are sub-stmts in the compound stmt, take the type of the last one 13893 // as the type of the stmtexpr. 13894 QualType Ty = Context.VoidTy; 13895 bool StmtExprMayBindToTemp = false; 13896 if (!Compound->body_empty()) { 13897 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 13898 if (const auto *LastStmt = 13899 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 13900 if (const Expr *Value = LastStmt->getExprStmt()) { 13901 StmtExprMayBindToTemp = true; 13902 Ty = Value->getType(); 13903 } 13904 } 13905 } 13906 13907 // FIXME: Check that expression type is complete/non-abstract; statement 13908 // expressions are not lvalues. 13909 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13910 if (StmtExprMayBindToTemp) 13911 return MaybeBindToTemporary(ResStmtExpr); 13912 return ResStmtExpr; 13913 } 13914 13915 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 13916 if (ER.isInvalid()) 13917 return ExprError(); 13918 13919 // Do function/array conversion on the last expression, but not 13920 // lvalue-to-rvalue. However, initialize an unqualified type. 13921 ER = DefaultFunctionArrayConversion(ER.get()); 13922 if (ER.isInvalid()) 13923 return ExprError(); 13924 Expr *E = ER.get(); 13925 13926 if (E->isTypeDependent()) 13927 return E; 13928 13929 // In ARC, if the final expression ends in a consume, splice 13930 // the consume out and bind it later. In the alternate case 13931 // (when dealing with a retainable type), the result 13932 // initialization will create a produce. In both cases the 13933 // result will be +1, and we'll need to balance that out with 13934 // a bind. 13935 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 13936 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 13937 return Cast->getSubExpr(); 13938 13939 // FIXME: Provide a better location for the initialization. 13940 return PerformCopyInitialization( 13941 InitializedEntity::InitializeStmtExprResult( 13942 E->getBeginLoc(), E->getType().getUnqualifiedType()), 13943 SourceLocation(), E); 13944 } 13945 13946 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13947 TypeSourceInfo *TInfo, 13948 ArrayRef<OffsetOfComponent> Components, 13949 SourceLocation RParenLoc) { 13950 QualType ArgTy = TInfo->getType(); 13951 bool Dependent = ArgTy->isDependentType(); 13952 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13953 13954 // We must have at least one component that refers to the type, and the first 13955 // one is known to be a field designator. Verify that the ArgTy represents 13956 // a struct/union/class. 13957 if (!Dependent && !ArgTy->isRecordType()) 13958 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13959 << ArgTy << TypeRange); 13960 13961 // Type must be complete per C99 7.17p3 because a declaring a variable 13962 // with an incomplete type would be ill-formed. 13963 if (!Dependent 13964 && RequireCompleteType(BuiltinLoc, ArgTy, 13965 diag::err_offsetof_incomplete_type, TypeRange)) 13966 return ExprError(); 13967 13968 bool DidWarnAboutNonPOD = false; 13969 QualType CurrentType = ArgTy; 13970 SmallVector<OffsetOfNode, 4> Comps; 13971 SmallVector<Expr*, 4> Exprs; 13972 for (const OffsetOfComponent &OC : Components) { 13973 if (OC.isBrackets) { 13974 // Offset of an array sub-field. TODO: Should we allow vector elements? 13975 if (!CurrentType->isDependentType()) { 13976 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13977 if(!AT) 13978 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13979 << CurrentType); 13980 CurrentType = AT->getElementType(); 13981 } else 13982 CurrentType = Context.DependentTy; 13983 13984 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13985 if (IdxRval.isInvalid()) 13986 return ExprError(); 13987 Expr *Idx = IdxRval.get(); 13988 13989 // The expression must be an integral expression. 13990 // FIXME: An integral constant expression? 13991 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13992 !Idx->getType()->isIntegerType()) 13993 return ExprError( 13994 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13995 << Idx->getSourceRange()); 13996 13997 // Record this array index. 13998 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13999 Exprs.push_back(Idx); 14000 continue; 14001 } 14002 14003 // Offset of a field. 14004 if (CurrentType->isDependentType()) { 14005 // We have the offset of a field, but we can't look into the dependent 14006 // type. Just record the identifier of the field. 14007 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14008 CurrentType = Context.DependentTy; 14009 continue; 14010 } 14011 14012 // We need to have a complete type to look into. 14013 if (RequireCompleteType(OC.LocStart, CurrentType, 14014 diag::err_offsetof_incomplete_type)) 14015 return ExprError(); 14016 14017 // Look for the designated field. 14018 const RecordType *RC = CurrentType->getAs<RecordType>(); 14019 if (!RC) 14020 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14021 << CurrentType); 14022 RecordDecl *RD = RC->getDecl(); 14023 14024 // C++ [lib.support.types]p5: 14025 // The macro offsetof accepts a restricted set of type arguments in this 14026 // International Standard. type shall be a POD structure or a POD union 14027 // (clause 9). 14028 // C++11 [support.types]p4: 14029 // If type is not a standard-layout class (Clause 9), the results are 14030 // undefined. 14031 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14032 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14033 unsigned DiagID = 14034 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14035 : diag::ext_offsetof_non_pod_type; 14036 14037 if (!IsSafe && !DidWarnAboutNonPOD && 14038 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14039 PDiag(DiagID) 14040 << SourceRange(Components[0].LocStart, OC.LocEnd) 14041 << CurrentType)) 14042 DidWarnAboutNonPOD = true; 14043 } 14044 14045 // Look for the field. 14046 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14047 LookupQualifiedName(R, RD); 14048 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14049 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14050 if (!MemberDecl) { 14051 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14052 MemberDecl = IndirectMemberDecl->getAnonField(); 14053 } 14054 14055 if (!MemberDecl) 14056 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14057 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14058 OC.LocEnd)); 14059 14060 // C99 7.17p3: 14061 // (If the specified member is a bit-field, the behavior is undefined.) 14062 // 14063 // We diagnose this as an error. 14064 if (MemberDecl->isBitField()) { 14065 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14066 << MemberDecl->getDeclName() 14067 << SourceRange(BuiltinLoc, RParenLoc); 14068 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14069 return ExprError(); 14070 } 14071 14072 RecordDecl *Parent = MemberDecl->getParent(); 14073 if (IndirectMemberDecl) 14074 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14075 14076 // If the member was found in a base class, introduce OffsetOfNodes for 14077 // the base class indirections. 14078 CXXBasePaths Paths; 14079 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14080 Paths)) { 14081 if (Paths.getDetectedVirtual()) { 14082 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14083 << MemberDecl->getDeclName() 14084 << SourceRange(BuiltinLoc, RParenLoc); 14085 return ExprError(); 14086 } 14087 14088 CXXBasePath &Path = Paths.front(); 14089 for (const CXXBasePathElement &B : Path) 14090 Comps.push_back(OffsetOfNode(B.Base)); 14091 } 14092 14093 if (IndirectMemberDecl) { 14094 for (auto *FI : IndirectMemberDecl->chain()) { 14095 assert(isa<FieldDecl>(FI)); 14096 Comps.push_back(OffsetOfNode(OC.LocStart, 14097 cast<FieldDecl>(FI), OC.LocEnd)); 14098 } 14099 } else 14100 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14101 14102 CurrentType = MemberDecl->getType().getNonReferenceType(); 14103 } 14104 14105 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14106 Comps, Exprs, RParenLoc); 14107 } 14108 14109 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14110 SourceLocation BuiltinLoc, 14111 SourceLocation TypeLoc, 14112 ParsedType ParsedArgTy, 14113 ArrayRef<OffsetOfComponent> Components, 14114 SourceLocation RParenLoc) { 14115 14116 TypeSourceInfo *ArgTInfo; 14117 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14118 if (ArgTy.isNull()) 14119 return ExprError(); 14120 14121 if (!ArgTInfo) 14122 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14123 14124 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14125 } 14126 14127 14128 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14129 Expr *CondExpr, 14130 Expr *LHSExpr, Expr *RHSExpr, 14131 SourceLocation RPLoc) { 14132 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14133 14134 ExprValueKind VK = VK_RValue; 14135 ExprObjectKind OK = OK_Ordinary; 14136 QualType resType; 14137 bool ValueDependent = false; 14138 bool CondIsTrue = false; 14139 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14140 resType = Context.DependentTy; 14141 ValueDependent = true; 14142 } else { 14143 // The conditional expression is required to be a constant expression. 14144 llvm::APSInt condEval(32); 14145 ExprResult CondICE 14146 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14147 diag::err_typecheck_choose_expr_requires_constant, false); 14148 if (CondICE.isInvalid()) 14149 return ExprError(); 14150 CondExpr = CondICE.get(); 14151 CondIsTrue = condEval.getZExtValue(); 14152 14153 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14154 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14155 14156 resType = ActiveExpr->getType(); 14157 ValueDependent = ActiveExpr->isValueDependent(); 14158 VK = ActiveExpr->getValueKind(); 14159 OK = ActiveExpr->getObjectKind(); 14160 } 14161 14162 return new (Context) 14163 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 14164 CondIsTrue, resType->isDependentType(), ValueDependent); 14165 } 14166 14167 //===----------------------------------------------------------------------===// 14168 // Clang Extensions. 14169 //===----------------------------------------------------------------------===// 14170 14171 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14172 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14173 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14174 14175 if (LangOpts.CPlusPlus) { 14176 MangleNumberingContext *MCtx; 14177 Decl *ManglingContextDecl; 14178 std::tie(MCtx, ManglingContextDecl) = 14179 getCurrentMangleNumberContext(Block->getDeclContext()); 14180 if (MCtx) { 14181 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14182 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14183 } 14184 } 14185 14186 PushBlockScope(CurScope, Block); 14187 CurContext->addDecl(Block); 14188 if (CurScope) 14189 PushDeclContext(CurScope, Block); 14190 else 14191 CurContext = Block; 14192 14193 getCurBlock()->HasImplicitReturnType = true; 14194 14195 // Enter a new evaluation context to insulate the block from any 14196 // cleanups from the enclosing full-expression. 14197 PushExpressionEvaluationContext( 14198 ExpressionEvaluationContext::PotentiallyEvaluated); 14199 } 14200 14201 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14202 Scope *CurScope) { 14203 assert(ParamInfo.getIdentifier() == nullptr && 14204 "block-id should have no identifier!"); 14205 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14206 BlockScopeInfo *CurBlock = getCurBlock(); 14207 14208 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14209 QualType T = Sig->getType(); 14210 14211 // FIXME: We should allow unexpanded parameter packs here, but that would, 14212 // in turn, make the block expression contain unexpanded parameter packs. 14213 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14214 // Drop the parameters. 14215 FunctionProtoType::ExtProtoInfo EPI; 14216 EPI.HasTrailingReturn = false; 14217 EPI.TypeQuals.addConst(); 14218 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14219 Sig = Context.getTrivialTypeSourceInfo(T); 14220 } 14221 14222 // GetTypeForDeclarator always produces a function type for a block 14223 // literal signature. Furthermore, it is always a FunctionProtoType 14224 // unless the function was written with a typedef. 14225 assert(T->isFunctionType() && 14226 "GetTypeForDeclarator made a non-function block signature"); 14227 14228 // Look for an explicit signature in that function type. 14229 FunctionProtoTypeLoc ExplicitSignature; 14230 14231 if ((ExplicitSignature = Sig->getTypeLoc() 14232 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14233 14234 // Check whether that explicit signature was synthesized by 14235 // GetTypeForDeclarator. If so, don't save that as part of the 14236 // written signature. 14237 if (ExplicitSignature.getLocalRangeBegin() == 14238 ExplicitSignature.getLocalRangeEnd()) { 14239 // This would be much cheaper if we stored TypeLocs instead of 14240 // TypeSourceInfos. 14241 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14242 unsigned Size = Result.getFullDataSize(); 14243 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14244 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14245 14246 ExplicitSignature = FunctionProtoTypeLoc(); 14247 } 14248 } 14249 14250 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14251 CurBlock->FunctionType = T; 14252 14253 const FunctionType *Fn = T->getAs<FunctionType>(); 14254 QualType RetTy = Fn->getReturnType(); 14255 bool isVariadic = 14256 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14257 14258 CurBlock->TheDecl->setIsVariadic(isVariadic); 14259 14260 // Context.DependentTy is used as a placeholder for a missing block 14261 // return type. TODO: what should we do with declarators like: 14262 // ^ * { ... } 14263 // If the answer is "apply template argument deduction".... 14264 if (RetTy != Context.DependentTy) { 14265 CurBlock->ReturnType = RetTy; 14266 CurBlock->TheDecl->setBlockMissingReturnType(false); 14267 CurBlock->HasImplicitReturnType = false; 14268 } 14269 14270 // Push block parameters from the declarator if we had them. 14271 SmallVector<ParmVarDecl*, 8> Params; 14272 if (ExplicitSignature) { 14273 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14274 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14275 if (Param->getIdentifier() == nullptr && 14276 !Param->isImplicit() && 14277 !Param->isInvalidDecl() && 14278 !getLangOpts().CPlusPlus) 14279 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14280 Params.push_back(Param); 14281 } 14282 14283 // Fake up parameter variables if we have a typedef, like 14284 // ^ fntype { ... } 14285 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14286 for (const auto &I : Fn->param_types()) { 14287 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14288 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14289 Params.push_back(Param); 14290 } 14291 } 14292 14293 // Set the parameters on the block decl. 14294 if (!Params.empty()) { 14295 CurBlock->TheDecl->setParams(Params); 14296 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14297 /*CheckParameterNames=*/false); 14298 } 14299 14300 // Finally we can process decl attributes. 14301 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14302 14303 // Put the parameter variables in scope. 14304 for (auto AI : CurBlock->TheDecl->parameters()) { 14305 AI->setOwningFunction(CurBlock->TheDecl); 14306 14307 // If this has an identifier, add it to the scope stack. 14308 if (AI->getIdentifier()) { 14309 CheckShadow(CurBlock->TheScope, AI); 14310 14311 PushOnScopeChains(AI, CurBlock->TheScope); 14312 } 14313 } 14314 } 14315 14316 /// ActOnBlockError - If there is an error parsing a block, this callback 14317 /// is invoked to pop the information about the block from the action impl. 14318 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14319 // Leave the expression-evaluation context. 14320 DiscardCleanupsInEvaluationContext(); 14321 PopExpressionEvaluationContext(); 14322 14323 // Pop off CurBlock, handle nested blocks. 14324 PopDeclContext(); 14325 PopFunctionScopeInfo(); 14326 } 14327 14328 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14329 /// literal was successfully completed. ^(int x){...} 14330 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14331 Stmt *Body, Scope *CurScope) { 14332 // If blocks are disabled, emit an error. 14333 if (!LangOpts.Blocks) 14334 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14335 14336 // Leave the expression-evaluation context. 14337 if (hasAnyUnrecoverableErrorsInThisFunction()) 14338 DiscardCleanupsInEvaluationContext(); 14339 assert(!Cleanup.exprNeedsCleanups() && 14340 "cleanups within block not correctly bound!"); 14341 PopExpressionEvaluationContext(); 14342 14343 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14344 BlockDecl *BD = BSI->TheDecl; 14345 14346 if (BSI->HasImplicitReturnType) 14347 deduceClosureReturnType(*BSI); 14348 14349 QualType RetTy = Context.VoidTy; 14350 if (!BSI->ReturnType.isNull()) 14351 RetTy = BSI->ReturnType; 14352 14353 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14354 QualType BlockTy; 14355 14356 // If the user wrote a function type in some form, try to use that. 14357 if (!BSI->FunctionType.isNull()) { 14358 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14359 14360 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14361 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14362 14363 // Turn protoless block types into nullary block types. 14364 if (isa<FunctionNoProtoType>(FTy)) { 14365 FunctionProtoType::ExtProtoInfo EPI; 14366 EPI.ExtInfo = Ext; 14367 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14368 14369 // Otherwise, if we don't need to change anything about the function type, 14370 // preserve its sugar structure. 14371 } else if (FTy->getReturnType() == RetTy && 14372 (!NoReturn || FTy->getNoReturnAttr())) { 14373 BlockTy = BSI->FunctionType; 14374 14375 // Otherwise, make the minimal modifications to the function type. 14376 } else { 14377 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14378 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14379 EPI.TypeQuals = Qualifiers(); 14380 EPI.ExtInfo = Ext; 14381 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14382 } 14383 14384 // If we don't have a function type, just build one from nothing. 14385 } else { 14386 FunctionProtoType::ExtProtoInfo EPI; 14387 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14388 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14389 } 14390 14391 DiagnoseUnusedParameters(BD->parameters()); 14392 BlockTy = Context.getBlockPointerType(BlockTy); 14393 14394 // If needed, diagnose invalid gotos and switches in the block. 14395 if (getCurFunction()->NeedsScopeChecking() && 14396 !PP.isCodeCompletionEnabled()) 14397 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14398 14399 BD->setBody(cast<CompoundStmt>(Body)); 14400 14401 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14402 DiagnoseUnguardedAvailabilityViolations(BD); 14403 14404 // Try to apply the named return value optimization. We have to check again 14405 // if we can do this, though, because blocks keep return statements around 14406 // to deduce an implicit return type. 14407 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14408 !BD->isDependentContext()) 14409 computeNRVO(Body, BSI); 14410 14411 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14412 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14413 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14414 NTCUK_Destruct|NTCUK_Copy); 14415 14416 PopDeclContext(); 14417 14418 // Pop the block scope now but keep it alive to the end of this function. 14419 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14420 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14421 14422 // Set the captured variables on the block. 14423 SmallVector<BlockDecl::Capture, 4> Captures; 14424 for (Capture &Cap : BSI->Captures) { 14425 if (Cap.isInvalid() || Cap.isThisCapture()) 14426 continue; 14427 14428 VarDecl *Var = Cap.getVariable(); 14429 Expr *CopyExpr = nullptr; 14430 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14431 if (const RecordType *Record = 14432 Cap.getCaptureType()->getAs<RecordType>()) { 14433 // The capture logic needs the destructor, so make sure we mark it. 14434 // Usually this is unnecessary because most local variables have 14435 // their destructors marked at declaration time, but parameters are 14436 // an exception because it's technically only the call site that 14437 // actually requires the destructor. 14438 if (isa<ParmVarDecl>(Var)) 14439 FinalizeVarWithDestructor(Var, Record); 14440 14441 // Enter a separate potentially-evaluated context while building block 14442 // initializers to isolate their cleanups from those of the block 14443 // itself. 14444 // FIXME: Is this appropriate even when the block itself occurs in an 14445 // unevaluated operand? 14446 EnterExpressionEvaluationContext EvalContext( 14447 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14448 14449 SourceLocation Loc = Cap.getLocation(); 14450 14451 ExprResult Result = BuildDeclarationNameExpr( 14452 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14453 14454 // According to the blocks spec, the capture of a variable from 14455 // the stack requires a const copy constructor. This is not true 14456 // of the copy/move done to move a __block variable to the heap. 14457 if (!Result.isInvalid() && 14458 !Result.get()->getType().isConstQualified()) { 14459 Result = ImpCastExprToType(Result.get(), 14460 Result.get()->getType().withConst(), 14461 CK_NoOp, VK_LValue); 14462 } 14463 14464 if (!Result.isInvalid()) { 14465 Result = PerformCopyInitialization( 14466 InitializedEntity::InitializeBlock(Var->getLocation(), 14467 Cap.getCaptureType(), false), 14468 Loc, Result.get()); 14469 } 14470 14471 // Build a full-expression copy expression if initialization 14472 // succeeded and used a non-trivial constructor. Recover from 14473 // errors by pretending that the copy isn't necessary. 14474 if (!Result.isInvalid() && 14475 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14476 ->isTrivial()) { 14477 Result = MaybeCreateExprWithCleanups(Result); 14478 CopyExpr = Result.get(); 14479 } 14480 } 14481 } 14482 14483 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14484 CopyExpr); 14485 Captures.push_back(NewCap); 14486 } 14487 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14488 14489 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14490 14491 // If the block isn't obviously global, i.e. it captures anything at 14492 // all, then we need to do a few things in the surrounding context: 14493 if (Result->getBlockDecl()->hasCaptures()) { 14494 // First, this expression has a new cleanup object. 14495 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14496 Cleanup.setExprNeedsCleanups(true); 14497 14498 // It also gets a branch-protected scope if any of the captured 14499 // variables needs destruction. 14500 for (const auto &CI : Result->getBlockDecl()->captures()) { 14501 const VarDecl *var = CI.getVariable(); 14502 if (var->getType().isDestructedType() != QualType::DK_none) { 14503 setFunctionHasBranchProtectedScope(); 14504 break; 14505 } 14506 } 14507 } 14508 14509 if (getCurFunction()) 14510 getCurFunction()->addBlock(BD); 14511 14512 return Result; 14513 } 14514 14515 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14516 SourceLocation RPLoc) { 14517 TypeSourceInfo *TInfo; 14518 GetTypeFromParser(Ty, &TInfo); 14519 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14520 } 14521 14522 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14523 Expr *E, TypeSourceInfo *TInfo, 14524 SourceLocation RPLoc) { 14525 Expr *OrigExpr = E; 14526 bool IsMS = false; 14527 14528 // CUDA device code does not support varargs. 14529 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14530 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14531 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14532 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14533 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14534 } 14535 } 14536 14537 // NVPTX does not support va_arg expression. 14538 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14539 Context.getTargetInfo().getTriple().isNVPTX()) 14540 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14541 14542 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14543 // as Microsoft ABI on an actual Microsoft platform, where 14544 // __builtin_ms_va_list and __builtin_va_list are the same.) 14545 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14546 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14547 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14548 if (Context.hasSameType(MSVaListType, E->getType())) { 14549 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14550 return ExprError(); 14551 IsMS = true; 14552 } 14553 } 14554 14555 // Get the va_list type 14556 QualType VaListType = Context.getBuiltinVaListType(); 14557 if (!IsMS) { 14558 if (VaListType->isArrayType()) { 14559 // Deal with implicit array decay; for example, on x86-64, 14560 // va_list is an array, but it's supposed to decay to 14561 // a pointer for va_arg. 14562 VaListType = Context.getArrayDecayedType(VaListType); 14563 // Make sure the input expression also decays appropriately. 14564 ExprResult Result = UsualUnaryConversions(E); 14565 if (Result.isInvalid()) 14566 return ExprError(); 14567 E = Result.get(); 14568 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14569 // If va_list is a record type and we are compiling in C++ mode, 14570 // check the argument using reference binding. 14571 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14572 Context, Context.getLValueReferenceType(VaListType), false); 14573 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14574 if (Init.isInvalid()) 14575 return ExprError(); 14576 E = Init.getAs<Expr>(); 14577 } else { 14578 // Otherwise, the va_list argument must be an l-value because 14579 // it is modified by va_arg. 14580 if (!E->isTypeDependent() && 14581 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14582 return ExprError(); 14583 } 14584 } 14585 14586 if (!IsMS && !E->isTypeDependent() && 14587 !Context.hasSameType(VaListType, E->getType())) 14588 return ExprError( 14589 Diag(E->getBeginLoc(), 14590 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14591 << OrigExpr->getType() << E->getSourceRange()); 14592 14593 if (!TInfo->getType()->isDependentType()) { 14594 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14595 diag::err_second_parameter_to_va_arg_incomplete, 14596 TInfo->getTypeLoc())) 14597 return ExprError(); 14598 14599 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14600 TInfo->getType(), 14601 diag::err_second_parameter_to_va_arg_abstract, 14602 TInfo->getTypeLoc())) 14603 return ExprError(); 14604 14605 if (!TInfo->getType().isPODType(Context)) { 14606 Diag(TInfo->getTypeLoc().getBeginLoc(), 14607 TInfo->getType()->isObjCLifetimeType() 14608 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14609 : diag::warn_second_parameter_to_va_arg_not_pod) 14610 << TInfo->getType() 14611 << TInfo->getTypeLoc().getSourceRange(); 14612 } 14613 14614 // Check for va_arg where arguments of the given type will be promoted 14615 // (i.e. this va_arg is guaranteed to have undefined behavior). 14616 QualType PromoteType; 14617 if (TInfo->getType()->isPromotableIntegerType()) { 14618 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14619 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14620 PromoteType = QualType(); 14621 } 14622 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14623 PromoteType = Context.DoubleTy; 14624 if (!PromoteType.isNull()) 14625 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14626 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14627 << TInfo->getType() 14628 << PromoteType 14629 << TInfo->getTypeLoc().getSourceRange()); 14630 } 14631 14632 QualType T = TInfo->getType().getNonLValueExprType(Context); 14633 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14634 } 14635 14636 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14637 // The type of __null will be int or long, depending on the size of 14638 // pointers on the target. 14639 QualType Ty; 14640 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14641 if (pw == Context.getTargetInfo().getIntWidth()) 14642 Ty = Context.IntTy; 14643 else if (pw == Context.getTargetInfo().getLongWidth()) 14644 Ty = Context.LongTy; 14645 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14646 Ty = Context.LongLongTy; 14647 else { 14648 llvm_unreachable("I don't know size of pointer!"); 14649 } 14650 14651 return new (Context) GNUNullExpr(Ty, TokenLoc); 14652 } 14653 14654 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14655 SourceLocation BuiltinLoc, 14656 SourceLocation RPLoc) { 14657 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14658 } 14659 14660 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14661 SourceLocation BuiltinLoc, 14662 SourceLocation RPLoc, 14663 DeclContext *ParentContext) { 14664 return new (Context) 14665 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14666 } 14667 14668 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14669 bool Diagnose) { 14670 if (!getLangOpts().ObjC) 14671 return false; 14672 14673 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14674 if (!PT) 14675 return false; 14676 14677 if (!PT->isObjCIdType()) { 14678 // Check if the destination is the 'NSString' interface. 14679 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14680 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14681 return false; 14682 } 14683 14684 // Ignore any parens, implicit casts (should only be 14685 // array-to-pointer decays), and not-so-opaque values. The last is 14686 // important for making this trigger for property assignments. 14687 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14688 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14689 if (OV->getSourceExpr()) 14690 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14691 14692 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14693 if (!SL || !SL->isAscii()) 14694 return false; 14695 if (Diagnose) { 14696 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14697 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14698 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14699 } 14700 return true; 14701 } 14702 14703 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14704 const Expr *SrcExpr) { 14705 if (!DstType->isFunctionPointerType() || 14706 !SrcExpr->getType()->isFunctionType()) 14707 return false; 14708 14709 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14710 if (!DRE) 14711 return false; 14712 14713 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14714 if (!FD) 14715 return false; 14716 14717 return !S.checkAddressOfFunctionIsAvailable(FD, 14718 /*Complain=*/true, 14719 SrcExpr->getBeginLoc()); 14720 } 14721 14722 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14723 SourceLocation Loc, 14724 QualType DstType, QualType SrcType, 14725 Expr *SrcExpr, AssignmentAction Action, 14726 bool *Complained) { 14727 if (Complained) 14728 *Complained = false; 14729 14730 // Decode the result (notice that AST's are still created for extensions). 14731 bool CheckInferredResultType = false; 14732 bool isInvalid = false; 14733 unsigned DiagKind = 0; 14734 FixItHint Hint; 14735 ConversionFixItGenerator ConvHints; 14736 bool MayHaveConvFixit = false; 14737 bool MayHaveFunctionDiff = false; 14738 const ObjCInterfaceDecl *IFace = nullptr; 14739 const ObjCProtocolDecl *PDecl = nullptr; 14740 14741 switch (ConvTy) { 14742 case Compatible: 14743 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14744 return false; 14745 14746 case PointerToInt: 14747 DiagKind = diag::ext_typecheck_convert_pointer_int; 14748 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14749 MayHaveConvFixit = true; 14750 break; 14751 case IntToPointer: 14752 DiagKind = diag::ext_typecheck_convert_int_pointer; 14753 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14754 MayHaveConvFixit = true; 14755 break; 14756 case IncompatiblePointer: 14757 if (Action == AA_Passing_CFAudited) 14758 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14759 else if (SrcType->isFunctionPointerType() && 14760 DstType->isFunctionPointerType()) 14761 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14762 else 14763 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14764 14765 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14766 SrcType->isObjCObjectPointerType(); 14767 if (Hint.isNull() && !CheckInferredResultType) { 14768 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14769 } 14770 else if (CheckInferredResultType) { 14771 SrcType = SrcType.getUnqualifiedType(); 14772 DstType = DstType.getUnqualifiedType(); 14773 } 14774 MayHaveConvFixit = true; 14775 break; 14776 case IncompatiblePointerSign: 14777 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14778 break; 14779 case FunctionVoidPointer: 14780 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14781 break; 14782 case IncompatiblePointerDiscardsQualifiers: { 14783 // Perform array-to-pointer decay if necessary. 14784 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14785 14786 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14787 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14788 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14789 DiagKind = diag::err_typecheck_incompatible_address_space; 14790 break; 14791 14792 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14793 DiagKind = diag::err_typecheck_incompatible_ownership; 14794 break; 14795 } 14796 14797 llvm_unreachable("unknown error case for discarding qualifiers!"); 14798 // fallthrough 14799 } 14800 case CompatiblePointerDiscardsQualifiers: 14801 // If the qualifiers lost were because we were applying the 14802 // (deprecated) C++ conversion from a string literal to a char* 14803 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 14804 // Ideally, this check would be performed in 14805 // checkPointerTypesForAssignment. However, that would require a 14806 // bit of refactoring (so that the second argument is an 14807 // expression, rather than a type), which should be done as part 14808 // of a larger effort to fix checkPointerTypesForAssignment for 14809 // C++ semantics. 14810 if (getLangOpts().CPlusPlus && 14811 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 14812 return false; 14813 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 14814 break; 14815 case IncompatibleNestedPointerQualifiers: 14816 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 14817 break; 14818 case IncompatibleNestedPointerAddressSpaceMismatch: 14819 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 14820 break; 14821 case IntToBlockPointer: 14822 DiagKind = diag::err_int_to_block_pointer; 14823 break; 14824 case IncompatibleBlockPointer: 14825 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14826 break; 14827 case IncompatibleObjCQualifiedId: { 14828 if (SrcType->isObjCQualifiedIdType()) { 14829 const ObjCObjectPointerType *srcOPT = 14830 SrcType->castAs<ObjCObjectPointerType>(); 14831 for (auto *srcProto : srcOPT->quals()) { 14832 PDecl = srcProto; 14833 break; 14834 } 14835 if (const ObjCInterfaceType *IFaceT = 14836 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14837 IFace = IFaceT->getDecl(); 14838 } 14839 else if (DstType->isObjCQualifiedIdType()) { 14840 const ObjCObjectPointerType *dstOPT = 14841 DstType->castAs<ObjCObjectPointerType>(); 14842 for (auto *dstProto : dstOPT->quals()) { 14843 PDecl = dstProto; 14844 break; 14845 } 14846 if (const ObjCInterfaceType *IFaceT = 14847 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 14848 IFace = IFaceT->getDecl(); 14849 } 14850 DiagKind = diag::warn_incompatible_qualified_id; 14851 break; 14852 } 14853 case IncompatibleVectors: 14854 DiagKind = diag::warn_incompatible_vectors; 14855 break; 14856 case IncompatibleObjCWeakRef: 14857 DiagKind = diag::err_arc_weak_unavailable_assign; 14858 break; 14859 case Incompatible: 14860 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14861 if (Complained) 14862 *Complained = true; 14863 return true; 14864 } 14865 14866 DiagKind = diag::err_typecheck_convert_incompatible; 14867 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14868 MayHaveConvFixit = true; 14869 isInvalid = true; 14870 MayHaveFunctionDiff = true; 14871 break; 14872 } 14873 14874 QualType FirstType, SecondType; 14875 switch (Action) { 14876 case AA_Assigning: 14877 case AA_Initializing: 14878 // The destination type comes first. 14879 FirstType = DstType; 14880 SecondType = SrcType; 14881 break; 14882 14883 case AA_Returning: 14884 case AA_Passing: 14885 case AA_Passing_CFAudited: 14886 case AA_Converting: 14887 case AA_Sending: 14888 case AA_Casting: 14889 // The source type comes first. 14890 FirstType = SrcType; 14891 SecondType = DstType; 14892 break; 14893 } 14894 14895 PartialDiagnostic FDiag = PDiag(DiagKind); 14896 if (Action == AA_Passing_CFAudited) 14897 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14898 else 14899 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14900 14901 // If we can fix the conversion, suggest the FixIts. 14902 assert(ConvHints.isNull() || Hint.isNull()); 14903 if (!ConvHints.isNull()) { 14904 for (FixItHint &H : ConvHints.Hints) 14905 FDiag << H; 14906 } else { 14907 FDiag << Hint; 14908 } 14909 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14910 14911 if (MayHaveFunctionDiff) 14912 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14913 14914 Diag(Loc, FDiag); 14915 if (DiagKind == diag::warn_incompatible_qualified_id && 14916 PDecl && IFace && !IFace->hasDefinition()) 14917 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14918 << IFace << PDecl; 14919 14920 if (SecondType == Context.OverloadTy) 14921 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14922 FirstType, /*TakingAddress=*/true); 14923 14924 if (CheckInferredResultType) 14925 EmitRelatedResultTypeNote(SrcExpr); 14926 14927 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14928 EmitRelatedResultTypeNoteForReturn(DstType); 14929 14930 if (Complained) 14931 *Complained = true; 14932 return isInvalid; 14933 } 14934 14935 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14936 llvm::APSInt *Result) { 14937 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14938 public: 14939 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14940 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14941 } 14942 } Diagnoser; 14943 14944 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14945 } 14946 14947 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14948 llvm::APSInt *Result, 14949 unsigned DiagID, 14950 bool AllowFold) { 14951 class IDDiagnoser : public VerifyICEDiagnoser { 14952 unsigned DiagID; 14953 14954 public: 14955 IDDiagnoser(unsigned DiagID) 14956 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14957 14958 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14959 S.Diag(Loc, DiagID) << SR; 14960 } 14961 } Diagnoser(DiagID); 14962 14963 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14964 } 14965 14966 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14967 SourceRange SR) { 14968 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14969 } 14970 14971 ExprResult 14972 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14973 VerifyICEDiagnoser &Diagnoser, 14974 bool AllowFold) { 14975 SourceLocation DiagLoc = E->getBeginLoc(); 14976 14977 if (getLangOpts().CPlusPlus11) { 14978 // C++11 [expr.const]p5: 14979 // If an expression of literal class type is used in a context where an 14980 // integral constant expression is required, then that class type shall 14981 // have a single non-explicit conversion function to an integral or 14982 // unscoped enumeration type 14983 ExprResult Converted; 14984 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14985 public: 14986 CXX11ConvertDiagnoser(bool Silent) 14987 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14988 Silent, true) {} 14989 14990 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14991 QualType T) override { 14992 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14993 } 14994 14995 SemaDiagnosticBuilder diagnoseIncomplete( 14996 Sema &S, SourceLocation Loc, QualType T) override { 14997 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14998 } 14999 15000 SemaDiagnosticBuilder diagnoseExplicitConv( 15001 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15002 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15003 } 15004 15005 SemaDiagnosticBuilder noteExplicitConv( 15006 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15007 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15008 << ConvTy->isEnumeralType() << ConvTy; 15009 } 15010 15011 SemaDiagnosticBuilder diagnoseAmbiguous( 15012 Sema &S, SourceLocation Loc, QualType T) override { 15013 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15014 } 15015 15016 SemaDiagnosticBuilder noteAmbiguous( 15017 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15018 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15019 << ConvTy->isEnumeralType() << ConvTy; 15020 } 15021 15022 SemaDiagnosticBuilder diagnoseConversion( 15023 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15024 llvm_unreachable("conversion functions are permitted"); 15025 } 15026 } ConvertDiagnoser(Diagnoser.Suppress); 15027 15028 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15029 ConvertDiagnoser); 15030 if (Converted.isInvalid()) 15031 return Converted; 15032 E = Converted.get(); 15033 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15034 return ExprError(); 15035 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15036 // An ICE must be of integral or unscoped enumeration type. 15037 if (!Diagnoser.Suppress) 15038 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15039 return ExprError(); 15040 } 15041 15042 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15043 // in the non-ICE case. 15044 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15045 if (Result) 15046 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15047 if (!isa<ConstantExpr>(E)) 15048 E = ConstantExpr::Create(Context, E); 15049 return E; 15050 } 15051 15052 Expr::EvalResult EvalResult; 15053 SmallVector<PartialDiagnosticAt, 8> Notes; 15054 EvalResult.Diag = &Notes; 15055 15056 // Try to evaluate the expression, and produce diagnostics explaining why it's 15057 // not a constant expression as a side-effect. 15058 bool Folded = 15059 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15060 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15061 15062 if (!isa<ConstantExpr>(E)) 15063 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15064 15065 // In C++11, we can rely on diagnostics being produced for any expression 15066 // which is not a constant expression. If no diagnostics were produced, then 15067 // this is a constant expression. 15068 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15069 if (Result) 15070 *Result = EvalResult.Val.getInt(); 15071 return E; 15072 } 15073 15074 // If our only note is the usual "invalid subexpression" note, just point 15075 // the caret at its location rather than producing an essentially 15076 // redundant note. 15077 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15078 diag::note_invalid_subexpr_in_const_expr) { 15079 DiagLoc = Notes[0].first; 15080 Notes.clear(); 15081 } 15082 15083 if (!Folded || !AllowFold) { 15084 if (!Diagnoser.Suppress) { 15085 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15086 for (const PartialDiagnosticAt &Note : Notes) 15087 Diag(Note.first, Note.second); 15088 } 15089 15090 return ExprError(); 15091 } 15092 15093 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15094 for (const PartialDiagnosticAt &Note : Notes) 15095 Diag(Note.first, Note.second); 15096 15097 if (Result) 15098 *Result = EvalResult.Val.getInt(); 15099 return E; 15100 } 15101 15102 namespace { 15103 // Handle the case where we conclude a expression which we speculatively 15104 // considered to be unevaluated is actually evaluated. 15105 class TransformToPE : public TreeTransform<TransformToPE> { 15106 typedef TreeTransform<TransformToPE> BaseTransform; 15107 15108 public: 15109 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15110 15111 // Make sure we redo semantic analysis 15112 bool AlwaysRebuild() { return true; } 15113 bool ReplacingOriginal() { return true; } 15114 15115 // We need to special-case DeclRefExprs referring to FieldDecls which 15116 // are not part of a member pointer formation; normal TreeTransforming 15117 // doesn't catch this case because of the way we represent them in the AST. 15118 // FIXME: This is a bit ugly; is it really the best way to handle this 15119 // case? 15120 // 15121 // Error on DeclRefExprs referring to FieldDecls. 15122 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15123 if (isa<FieldDecl>(E->getDecl()) && 15124 !SemaRef.isUnevaluatedContext()) 15125 return SemaRef.Diag(E->getLocation(), 15126 diag::err_invalid_non_static_member_use) 15127 << E->getDecl() << E->getSourceRange(); 15128 15129 return BaseTransform::TransformDeclRefExpr(E); 15130 } 15131 15132 // Exception: filter out member pointer formation 15133 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15134 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15135 return E; 15136 15137 return BaseTransform::TransformUnaryOperator(E); 15138 } 15139 15140 // The body of a lambda-expression is in a separate expression evaluation 15141 // context so never needs to be transformed. 15142 // FIXME: Ideally we wouldn't transform the closure type either, and would 15143 // just recreate the capture expressions and lambda expression. 15144 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15145 return SkipLambdaBody(E, Body); 15146 } 15147 }; 15148 } 15149 15150 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15151 assert(isUnevaluatedContext() && 15152 "Should only transform unevaluated expressions"); 15153 ExprEvalContexts.back().Context = 15154 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15155 if (isUnevaluatedContext()) 15156 return E; 15157 return TransformToPE(*this).TransformExpr(E); 15158 } 15159 15160 void 15161 Sema::PushExpressionEvaluationContext( 15162 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15163 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15164 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15165 LambdaContextDecl, ExprContext); 15166 Cleanup.reset(); 15167 if (!MaybeODRUseExprs.empty()) 15168 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15169 } 15170 15171 void 15172 Sema::PushExpressionEvaluationContext( 15173 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15174 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15175 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15176 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15177 } 15178 15179 namespace { 15180 15181 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15182 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15183 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15184 if (E->getOpcode() == UO_Deref) 15185 return CheckPossibleDeref(S, E->getSubExpr()); 15186 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15187 return CheckPossibleDeref(S, E->getBase()); 15188 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15189 return CheckPossibleDeref(S, E->getBase()); 15190 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15191 QualType Inner; 15192 QualType Ty = E->getType(); 15193 if (const auto *Ptr = Ty->getAs<PointerType>()) 15194 Inner = Ptr->getPointeeType(); 15195 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15196 Inner = Arr->getElementType(); 15197 else 15198 return nullptr; 15199 15200 if (Inner->hasAttr(attr::NoDeref)) 15201 return E; 15202 } 15203 return nullptr; 15204 } 15205 15206 } // namespace 15207 15208 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15209 for (const Expr *E : Rec.PossibleDerefs) { 15210 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15211 if (DeclRef) { 15212 const ValueDecl *Decl = DeclRef->getDecl(); 15213 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15214 << Decl->getName() << E->getSourceRange(); 15215 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15216 } else { 15217 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15218 << E->getSourceRange(); 15219 } 15220 } 15221 Rec.PossibleDerefs.clear(); 15222 } 15223 15224 /// Check whether E, which is either a discarded-value expression or an 15225 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15226 /// and if so, remove it from the list of volatile-qualified assignments that 15227 /// we are going to warn are deprecated. 15228 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15229 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15230 return; 15231 15232 // Note: ignoring parens here is not justified by the standard rules, but 15233 // ignoring parentheses seems like a more reasonable approach, and this only 15234 // drives a deprecation warning so doesn't affect conformance. 15235 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15236 if (BO->getOpcode() == BO_Assign) { 15237 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15238 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15239 LHSs.end()); 15240 } 15241 } 15242 } 15243 15244 void Sema::PopExpressionEvaluationContext() { 15245 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15246 unsigned NumTypos = Rec.NumTypos; 15247 15248 if (!Rec.Lambdas.empty()) { 15249 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15250 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15251 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15252 unsigned D; 15253 if (Rec.isUnevaluated()) { 15254 // C++11 [expr.prim.lambda]p2: 15255 // A lambda-expression shall not appear in an unevaluated operand 15256 // (Clause 5). 15257 D = diag::err_lambda_unevaluated_operand; 15258 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15259 // C++1y [expr.const]p2: 15260 // A conditional-expression e is a core constant expression unless the 15261 // evaluation of e, following the rules of the abstract machine, would 15262 // evaluate [...] a lambda-expression. 15263 D = diag::err_lambda_in_constant_expression; 15264 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15265 // C++17 [expr.prim.lamda]p2: 15266 // A lambda-expression shall not appear [...] in a template-argument. 15267 D = diag::err_lambda_in_invalid_context; 15268 } else 15269 llvm_unreachable("Couldn't infer lambda error message."); 15270 15271 for (const auto *L : Rec.Lambdas) 15272 Diag(L->getBeginLoc(), D); 15273 } 15274 } 15275 15276 WarnOnPendingNoDerefs(Rec); 15277 15278 // Warn on any volatile-qualified simple-assignments that are not discarded- 15279 // value expressions nor unevaluated operands (those cases get removed from 15280 // this list by CheckUnusedVolatileAssignment). 15281 for (auto *BO : Rec.VolatileAssignmentLHSs) 15282 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15283 << BO->getType(); 15284 15285 // When are coming out of an unevaluated context, clear out any 15286 // temporaries that we may have created as part of the evaluation of 15287 // the expression in that context: they aren't relevant because they 15288 // will never be constructed. 15289 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15290 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15291 ExprCleanupObjects.end()); 15292 Cleanup = Rec.ParentCleanup; 15293 CleanupVarDeclMarking(); 15294 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15295 // Otherwise, merge the contexts together. 15296 } else { 15297 Cleanup.mergeFrom(Rec.ParentCleanup); 15298 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15299 Rec.SavedMaybeODRUseExprs.end()); 15300 } 15301 15302 // Pop the current expression evaluation context off the stack. 15303 ExprEvalContexts.pop_back(); 15304 15305 // The global expression evaluation context record is never popped. 15306 ExprEvalContexts.back().NumTypos += NumTypos; 15307 } 15308 15309 void Sema::DiscardCleanupsInEvaluationContext() { 15310 ExprCleanupObjects.erase( 15311 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15312 ExprCleanupObjects.end()); 15313 Cleanup.reset(); 15314 MaybeODRUseExprs.clear(); 15315 } 15316 15317 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15318 ExprResult Result = CheckPlaceholderExpr(E); 15319 if (Result.isInvalid()) 15320 return ExprError(); 15321 E = Result.get(); 15322 if (!E->getType()->isVariablyModifiedType()) 15323 return E; 15324 return TransformToPotentiallyEvaluated(E); 15325 } 15326 15327 /// Are we in a context that is potentially constant evaluated per C++20 15328 /// [expr.const]p12? 15329 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15330 /// C++2a [expr.const]p12: 15331 // An expression or conversion is potentially constant evaluated if it is 15332 switch (SemaRef.ExprEvalContexts.back().Context) { 15333 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15334 // -- a manifestly constant-evaluated expression, 15335 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15336 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15337 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15338 // -- a potentially-evaluated expression, 15339 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15340 // -- an immediate subexpression of a braced-init-list, 15341 15342 // -- [FIXME] an expression of the form & cast-expression that occurs 15343 // within a templated entity 15344 // -- a subexpression of one of the above that is not a subexpression of 15345 // a nested unevaluated operand. 15346 return true; 15347 15348 case Sema::ExpressionEvaluationContext::Unevaluated: 15349 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15350 // Expressions in this context are never evaluated. 15351 return false; 15352 } 15353 llvm_unreachable("Invalid context"); 15354 } 15355 15356 /// Return true if this function has a calling convention that requires mangling 15357 /// in the size of the parameter pack. 15358 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15359 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15360 // we don't need parameter type sizes. 15361 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15362 if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 && 15363 TT.getArch() != llvm::Triple::x86_64)) 15364 return false; 15365 15366 // If this is C++ and this isn't an extern "C" function, parameters do not 15367 // need to be complete. In this case, C++ mangling will apply, which doesn't 15368 // use the size of the parameters. 15369 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15370 return false; 15371 15372 // Stdcall, fastcall, and vectorcall need this special treatment. 15373 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15374 switch (CC) { 15375 case CC_X86StdCall: 15376 case CC_X86FastCall: 15377 case CC_X86VectorCall: 15378 return true; 15379 default: 15380 break; 15381 } 15382 return false; 15383 } 15384 15385 /// Require that all of the parameter types of function be complete. Normally, 15386 /// parameter types are only required to be complete when a function is called 15387 /// or defined, but to mangle functions with certain calling conventions, the 15388 /// mangler needs to know the size of the parameter list. In this situation, 15389 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15390 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15391 /// result in a linker error. Clang doesn't implement this behavior, and instead 15392 /// attempts to error at compile time. 15393 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15394 SourceLocation Loc) { 15395 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15396 FunctionDecl *FD; 15397 ParmVarDecl *Param; 15398 15399 public: 15400 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15401 : FD(FD), Param(Param) {} 15402 15403 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15404 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15405 StringRef CCName; 15406 switch (CC) { 15407 case CC_X86StdCall: 15408 CCName = "stdcall"; 15409 break; 15410 case CC_X86FastCall: 15411 CCName = "fastcall"; 15412 break; 15413 case CC_X86VectorCall: 15414 CCName = "vectorcall"; 15415 break; 15416 default: 15417 llvm_unreachable("CC does not need mangling"); 15418 } 15419 15420 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15421 << Param->getDeclName() << FD->getDeclName() << CCName; 15422 } 15423 }; 15424 15425 for (ParmVarDecl *Param : FD->parameters()) { 15426 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15427 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15428 } 15429 } 15430 15431 namespace { 15432 enum class OdrUseContext { 15433 /// Declarations in this context are not odr-used. 15434 None, 15435 /// Declarations in this context are formally odr-used, but this is a 15436 /// dependent context. 15437 Dependent, 15438 /// Declarations in this context are odr-used but not actually used (yet). 15439 FormallyOdrUsed, 15440 /// Declarations in this context are used. 15441 Used 15442 }; 15443 } 15444 15445 /// Are we within a context in which references to resolved functions or to 15446 /// variables result in odr-use? 15447 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15448 OdrUseContext Result; 15449 15450 switch (SemaRef.ExprEvalContexts.back().Context) { 15451 case Sema::ExpressionEvaluationContext::Unevaluated: 15452 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15453 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15454 return OdrUseContext::None; 15455 15456 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15457 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15458 Result = OdrUseContext::Used; 15459 break; 15460 15461 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15462 Result = OdrUseContext::FormallyOdrUsed; 15463 break; 15464 15465 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15466 // A default argument formally results in odr-use, but doesn't actually 15467 // result in a use in any real sense until it itself is used. 15468 Result = OdrUseContext::FormallyOdrUsed; 15469 break; 15470 } 15471 15472 if (SemaRef.CurContext->isDependentContext()) 15473 return OdrUseContext::Dependent; 15474 15475 return Result; 15476 } 15477 15478 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15479 return Func->isConstexpr() && 15480 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15481 } 15482 15483 /// Mark a function referenced, and check whether it is odr-used 15484 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15485 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15486 bool MightBeOdrUse) { 15487 assert(Func && "No function?"); 15488 15489 Func->setReferenced(); 15490 15491 // Recursive functions aren't really used until they're used from some other 15492 // context. 15493 bool IsRecursiveCall = CurContext == Func; 15494 15495 // C++11 [basic.def.odr]p3: 15496 // A function whose name appears as a potentially-evaluated expression is 15497 // odr-used if it is the unique lookup result or the selected member of a 15498 // set of overloaded functions [...]. 15499 // 15500 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15501 // can just check that here. 15502 OdrUseContext OdrUse = 15503 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15504 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15505 OdrUse = OdrUseContext::FormallyOdrUsed; 15506 15507 // Trivial default constructors and destructors are never actually used. 15508 // FIXME: What about other special members? 15509 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15510 OdrUse == OdrUseContext::Used) { 15511 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15512 if (Constructor->isDefaultConstructor()) 15513 OdrUse = OdrUseContext::FormallyOdrUsed; 15514 if (isa<CXXDestructorDecl>(Func)) 15515 OdrUse = OdrUseContext::FormallyOdrUsed; 15516 } 15517 15518 // C++20 [expr.const]p12: 15519 // A function [...] is needed for constant evaluation if it is [...] a 15520 // constexpr function that is named by an expression that is potentially 15521 // constant evaluated 15522 bool NeededForConstantEvaluation = 15523 isPotentiallyConstantEvaluatedContext(*this) && 15524 isImplicitlyDefinableConstexprFunction(Func); 15525 15526 // Determine whether we require a function definition to exist, per 15527 // C++11 [temp.inst]p3: 15528 // Unless a function template specialization has been explicitly 15529 // instantiated or explicitly specialized, the function template 15530 // specialization is implicitly instantiated when the specialization is 15531 // referenced in a context that requires a function definition to exist. 15532 // C++20 [temp.inst]p7: 15533 // The existence of a definition of a [...] function is considered to 15534 // affect the semantics of the program if the [...] function is needed for 15535 // constant evaluation by an expression 15536 // C++20 [basic.def.odr]p10: 15537 // Every program shall contain exactly one definition of every non-inline 15538 // function or variable that is odr-used in that program outside of a 15539 // discarded statement 15540 // C++20 [special]p1: 15541 // The implementation will implicitly define [defaulted special members] 15542 // if they are odr-used or needed for constant evaluation. 15543 // 15544 // Note that we skip the implicit instantiation of templates that are only 15545 // used in unused default arguments or by recursive calls to themselves. 15546 // This is formally non-conforming, but seems reasonable in practice. 15547 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15548 NeededForConstantEvaluation); 15549 15550 // C++14 [temp.expl.spec]p6: 15551 // If a template [...] is explicitly specialized then that specialization 15552 // shall be declared before the first use of that specialization that would 15553 // cause an implicit instantiation to take place, in every translation unit 15554 // in which such a use occurs 15555 if (NeedDefinition && 15556 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15557 Func->getMemberSpecializationInfo())) 15558 checkSpecializationVisibility(Loc, Func); 15559 15560 if (getLangOpts().CUDA) 15561 CheckCUDACall(Loc, Func); 15562 15563 // If we need a definition, try to create one. 15564 if (NeedDefinition && !Func->getBody()) { 15565 runWithSufficientStackSpace(Loc, [&] { 15566 if (CXXConstructorDecl *Constructor = 15567 dyn_cast<CXXConstructorDecl>(Func)) { 15568 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15569 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15570 if (Constructor->isDefaultConstructor()) { 15571 if (Constructor->isTrivial() && 15572 !Constructor->hasAttr<DLLExportAttr>()) 15573 return; 15574 DefineImplicitDefaultConstructor(Loc, Constructor); 15575 } else if (Constructor->isCopyConstructor()) { 15576 DefineImplicitCopyConstructor(Loc, Constructor); 15577 } else if (Constructor->isMoveConstructor()) { 15578 DefineImplicitMoveConstructor(Loc, Constructor); 15579 } 15580 } else if (Constructor->getInheritedConstructor()) { 15581 DefineInheritingConstructor(Loc, Constructor); 15582 } 15583 } else if (CXXDestructorDecl *Destructor = 15584 dyn_cast<CXXDestructorDecl>(Func)) { 15585 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 15586 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 15587 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 15588 return; 15589 DefineImplicitDestructor(Loc, Destructor); 15590 } 15591 if (Destructor->isVirtual() && getLangOpts().AppleKext) 15592 MarkVTableUsed(Loc, Destructor->getParent()); 15593 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 15594 if (MethodDecl->isOverloadedOperator() && 15595 MethodDecl->getOverloadedOperator() == OO_Equal) { 15596 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 15597 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 15598 if (MethodDecl->isCopyAssignmentOperator()) 15599 DefineImplicitCopyAssignment(Loc, MethodDecl); 15600 else if (MethodDecl->isMoveAssignmentOperator()) 15601 DefineImplicitMoveAssignment(Loc, MethodDecl); 15602 } 15603 } else if (isa<CXXConversionDecl>(MethodDecl) && 15604 MethodDecl->getParent()->isLambda()) { 15605 CXXConversionDecl *Conversion = 15606 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 15607 if (Conversion->isLambdaToBlockPointerConversion()) 15608 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 15609 else 15610 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 15611 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 15612 MarkVTableUsed(Loc, MethodDecl->getParent()); 15613 } 15614 15615 if (Func->isDefaulted() && !Func->isDeleted()) { 15616 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 15617 if (DCK != DefaultedComparisonKind::None) 15618 DefineDefaultedComparison(Loc, Func, DCK); 15619 } 15620 15621 // Implicit instantiation of function templates and member functions of 15622 // class templates. 15623 if (Func->isImplicitlyInstantiable()) { 15624 TemplateSpecializationKind TSK = 15625 Func->getTemplateSpecializationKindForInstantiation(); 15626 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 15627 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15628 if (FirstInstantiation) { 15629 PointOfInstantiation = Loc; 15630 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15631 } else if (TSK != TSK_ImplicitInstantiation) { 15632 // Use the point of use as the point of instantiation, instead of the 15633 // point of explicit instantiation (which we track as the actual point 15634 // of instantiation). This gives better backtraces in diagnostics. 15635 PointOfInstantiation = Loc; 15636 } 15637 15638 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 15639 Func->isConstexpr()) { 15640 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 15641 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 15642 CodeSynthesisContexts.size()) 15643 PendingLocalImplicitInstantiations.push_back( 15644 std::make_pair(Func, PointOfInstantiation)); 15645 else if (Func->isConstexpr()) 15646 // Do not defer instantiations of constexpr functions, to avoid the 15647 // expression evaluator needing to call back into Sema if it sees a 15648 // call to such a function. 15649 InstantiateFunctionDefinition(PointOfInstantiation, Func); 15650 else { 15651 Func->setInstantiationIsPending(true); 15652 PendingInstantiations.push_back( 15653 std::make_pair(Func, PointOfInstantiation)); 15654 // Notify the consumer that a function was implicitly instantiated. 15655 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 15656 } 15657 } 15658 } else { 15659 // Walk redefinitions, as some of them may be instantiable. 15660 for (auto i : Func->redecls()) { 15661 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 15662 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 15663 } 15664 } 15665 }); 15666 } 15667 15668 // C++14 [except.spec]p17: 15669 // An exception-specification is considered to be needed when: 15670 // - the function is odr-used or, if it appears in an unevaluated operand, 15671 // would be odr-used if the expression were potentially-evaluated; 15672 // 15673 // Note, we do this even if MightBeOdrUse is false. That indicates that the 15674 // function is a pure virtual function we're calling, and in that case the 15675 // function was selected by overload resolution and we need to resolve its 15676 // exception specification for a different reason. 15677 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 15678 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 15679 ResolveExceptionSpec(Loc, FPT); 15680 15681 // If this is the first "real" use, act on that. 15682 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 15683 // Keep track of used but undefined functions. 15684 if (!Func->isDefined()) { 15685 if (mightHaveNonExternalLinkage(Func)) 15686 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15687 else if (Func->getMostRecentDecl()->isInlined() && 15688 !LangOpts.GNUInline && 15689 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 15690 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15691 else if (isExternalWithNoLinkageType(Func)) 15692 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 15693 } 15694 15695 // Some x86 Windows calling conventions mangle the size of the parameter 15696 // pack into the name. Computing the size of the parameters requires the 15697 // parameter types to be complete. Check that now. 15698 if (funcHasParameterSizeMangling(*this, Func)) 15699 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 15700 15701 Func->markUsed(Context); 15702 } 15703 15704 if (LangOpts.OpenMP) { 15705 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse); 15706 if (LangOpts.OpenMPIsDevice) 15707 checkOpenMPDeviceFunction(Loc, Func); 15708 else 15709 checkOpenMPHostFunction(Loc, Func); 15710 } 15711 } 15712 15713 /// Directly mark a variable odr-used. Given a choice, prefer to use 15714 /// MarkVariableReferenced since it does additional checks and then 15715 /// calls MarkVarDeclODRUsed. 15716 /// If the variable must be captured: 15717 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 15718 /// - else capture it in the DeclContext that maps to the 15719 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 15720 static void 15721 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 15722 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 15723 // Keep track of used but undefined variables. 15724 // FIXME: We shouldn't suppress this warning for static data members. 15725 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 15726 (!Var->isExternallyVisible() || Var->isInline() || 15727 SemaRef.isExternalWithNoLinkageType(Var)) && 15728 !(Var->isStaticDataMember() && Var->hasInit())) { 15729 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 15730 if (old.isInvalid()) 15731 old = Loc; 15732 } 15733 QualType CaptureType, DeclRefType; 15734 if (SemaRef.LangOpts.OpenMP) 15735 SemaRef.tryCaptureOpenMPLambdas(Var); 15736 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 15737 /*EllipsisLoc*/ SourceLocation(), 15738 /*BuildAndDiagnose*/ true, 15739 CaptureType, DeclRefType, 15740 FunctionScopeIndexToStopAt); 15741 15742 Var->markUsed(SemaRef.Context); 15743 } 15744 15745 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 15746 SourceLocation Loc, 15747 unsigned CapturingScopeIndex) { 15748 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 15749 } 15750 15751 static void 15752 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 15753 ValueDecl *var, DeclContext *DC) { 15754 DeclContext *VarDC = var->getDeclContext(); 15755 15756 // If the parameter still belongs to the translation unit, then 15757 // we're actually just using one parameter in the declaration of 15758 // the next. 15759 if (isa<ParmVarDecl>(var) && 15760 isa<TranslationUnitDecl>(VarDC)) 15761 return; 15762 15763 // For C code, don't diagnose about capture if we're not actually in code 15764 // right now; it's impossible to write a non-constant expression outside of 15765 // function context, so we'll get other (more useful) diagnostics later. 15766 // 15767 // For C++, things get a bit more nasty... it would be nice to suppress this 15768 // diagnostic for certain cases like using a local variable in an array bound 15769 // for a member of a local class, but the correct predicate is not obvious. 15770 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 15771 return; 15772 15773 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 15774 unsigned ContextKind = 3; // unknown 15775 if (isa<CXXMethodDecl>(VarDC) && 15776 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 15777 ContextKind = 2; 15778 } else if (isa<FunctionDecl>(VarDC)) { 15779 ContextKind = 0; 15780 } else if (isa<BlockDecl>(VarDC)) { 15781 ContextKind = 1; 15782 } 15783 15784 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 15785 << var << ValueKind << ContextKind << VarDC; 15786 S.Diag(var->getLocation(), diag::note_entity_declared_at) 15787 << var; 15788 15789 // FIXME: Add additional diagnostic info about class etc. which prevents 15790 // capture. 15791 } 15792 15793 15794 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 15795 bool &SubCapturesAreNested, 15796 QualType &CaptureType, 15797 QualType &DeclRefType) { 15798 // Check whether we've already captured it. 15799 if (CSI->CaptureMap.count(Var)) { 15800 // If we found a capture, any subcaptures are nested. 15801 SubCapturesAreNested = true; 15802 15803 // Retrieve the capture type for this variable. 15804 CaptureType = CSI->getCapture(Var).getCaptureType(); 15805 15806 // Compute the type of an expression that refers to this variable. 15807 DeclRefType = CaptureType.getNonReferenceType(); 15808 15809 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 15810 // are mutable in the sense that user can change their value - they are 15811 // private instances of the captured declarations. 15812 const Capture &Cap = CSI->getCapture(Var); 15813 if (Cap.isCopyCapture() && 15814 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 15815 !(isa<CapturedRegionScopeInfo>(CSI) && 15816 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 15817 DeclRefType.addConst(); 15818 return true; 15819 } 15820 return false; 15821 } 15822 15823 // Only block literals, captured statements, and lambda expressions can 15824 // capture; other scopes don't work. 15825 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 15826 SourceLocation Loc, 15827 const bool Diagnose, Sema &S) { 15828 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 15829 return getLambdaAwareParentOfDeclContext(DC); 15830 else if (Var->hasLocalStorage()) { 15831 if (Diagnose) 15832 diagnoseUncapturableValueReference(S, Loc, Var, DC); 15833 } 15834 return nullptr; 15835 } 15836 15837 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15838 // certain types of variables (unnamed, variably modified types etc.) 15839 // so check for eligibility. 15840 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 15841 SourceLocation Loc, 15842 const bool Diagnose, Sema &S) { 15843 15844 bool IsBlock = isa<BlockScopeInfo>(CSI); 15845 bool IsLambda = isa<LambdaScopeInfo>(CSI); 15846 15847 // Lambdas are not allowed to capture unnamed variables 15848 // (e.g. anonymous unions). 15849 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 15850 // assuming that's the intent. 15851 if (IsLambda && !Var->getDeclName()) { 15852 if (Diagnose) { 15853 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 15854 S.Diag(Var->getLocation(), diag::note_declared_at); 15855 } 15856 return false; 15857 } 15858 15859 // Prohibit variably-modified types in blocks; they're difficult to deal with. 15860 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 15861 if (Diagnose) { 15862 S.Diag(Loc, diag::err_ref_vm_type); 15863 S.Diag(Var->getLocation(), diag::note_previous_decl) 15864 << Var->getDeclName(); 15865 } 15866 return false; 15867 } 15868 // Prohibit structs with flexible array members too. 15869 // We cannot capture what is in the tail end of the struct. 15870 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 15871 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 15872 if (Diagnose) { 15873 if (IsBlock) 15874 S.Diag(Loc, diag::err_ref_flexarray_type); 15875 else 15876 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 15877 << Var->getDeclName(); 15878 S.Diag(Var->getLocation(), diag::note_previous_decl) 15879 << Var->getDeclName(); 15880 } 15881 return false; 15882 } 15883 } 15884 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15885 // Lambdas and captured statements are not allowed to capture __block 15886 // variables; they don't support the expected semantics. 15887 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 15888 if (Diagnose) { 15889 S.Diag(Loc, diag::err_capture_block_variable) 15890 << Var->getDeclName() << !IsLambda; 15891 S.Diag(Var->getLocation(), diag::note_previous_decl) 15892 << Var->getDeclName(); 15893 } 15894 return false; 15895 } 15896 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 15897 if (S.getLangOpts().OpenCL && IsBlock && 15898 Var->getType()->isBlockPointerType()) { 15899 if (Diagnose) 15900 S.Diag(Loc, diag::err_opencl_block_ref_block); 15901 return false; 15902 } 15903 15904 return true; 15905 } 15906 15907 // Returns true if the capture by block was successful. 15908 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 15909 SourceLocation Loc, 15910 const bool BuildAndDiagnose, 15911 QualType &CaptureType, 15912 QualType &DeclRefType, 15913 const bool Nested, 15914 Sema &S, bool Invalid) { 15915 bool ByRef = false; 15916 15917 // Blocks are not allowed to capture arrays, excepting OpenCL. 15918 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 15919 // (decayed to pointers). 15920 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 15921 if (BuildAndDiagnose) { 15922 S.Diag(Loc, diag::err_ref_array_type); 15923 S.Diag(Var->getLocation(), diag::note_previous_decl) 15924 << Var->getDeclName(); 15925 Invalid = true; 15926 } else { 15927 return false; 15928 } 15929 } 15930 15931 // Forbid the block-capture of autoreleasing variables. 15932 if (!Invalid && 15933 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15934 if (BuildAndDiagnose) { 15935 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 15936 << /*block*/ 0; 15937 S.Diag(Var->getLocation(), diag::note_previous_decl) 15938 << Var->getDeclName(); 15939 Invalid = true; 15940 } else { 15941 return false; 15942 } 15943 } 15944 15945 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 15946 if (const auto *PT = CaptureType->getAs<PointerType>()) { 15947 QualType PointeeTy = PT->getPointeeType(); 15948 15949 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 15950 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 15951 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 15952 if (BuildAndDiagnose) { 15953 SourceLocation VarLoc = Var->getLocation(); 15954 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 15955 S.Diag(VarLoc, diag::note_declare_parameter_strong); 15956 } 15957 } 15958 } 15959 15960 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 15961 if (HasBlocksAttr || CaptureType->isReferenceType() || 15962 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 15963 // Block capture by reference does not change the capture or 15964 // declaration reference types. 15965 ByRef = true; 15966 } else { 15967 // Block capture by copy introduces 'const'. 15968 CaptureType = CaptureType.getNonReferenceType().withConst(); 15969 DeclRefType = CaptureType; 15970 } 15971 15972 // Actually capture the variable. 15973 if (BuildAndDiagnose) 15974 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 15975 CaptureType, Invalid); 15976 15977 return !Invalid; 15978 } 15979 15980 15981 /// Capture the given variable in the captured region. 15982 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 15983 VarDecl *Var, 15984 SourceLocation Loc, 15985 const bool BuildAndDiagnose, 15986 QualType &CaptureType, 15987 QualType &DeclRefType, 15988 const bool RefersToCapturedVariable, 15989 Sema &S, bool Invalid) { 15990 // By default, capture variables by reference. 15991 bool ByRef = true; 15992 // Using an LValue reference type is consistent with Lambdas (see below). 15993 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 15994 if (S.isOpenMPCapturedDecl(Var)) { 15995 bool HasConst = DeclRefType.isConstQualified(); 15996 DeclRefType = DeclRefType.getUnqualifiedType(); 15997 // Don't lose diagnostics about assignments to const. 15998 if (HasConst) 15999 DeclRefType.addConst(); 16000 } 16001 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16002 RSI->OpenMPCaptureLevel); 16003 } 16004 16005 if (ByRef) 16006 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16007 else 16008 CaptureType = DeclRefType; 16009 16010 // Actually capture the variable. 16011 if (BuildAndDiagnose) 16012 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16013 Loc, SourceLocation(), CaptureType, Invalid); 16014 16015 return !Invalid; 16016 } 16017 16018 /// Capture the given variable in the lambda. 16019 static bool captureInLambda(LambdaScopeInfo *LSI, 16020 VarDecl *Var, 16021 SourceLocation Loc, 16022 const bool BuildAndDiagnose, 16023 QualType &CaptureType, 16024 QualType &DeclRefType, 16025 const bool RefersToCapturedVariable, 16026 const Sema::TryCaptureKind Kind, 16027 SourceLocation EllipsisLoc, 16028 const bool IsTopScope, 16029 Sema &S, bool Invalid) { 16030 // Determine whether we are capturing by reference or by value. 16031 bool ByRef = false; 16032 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16033 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16034 } else { 16035 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16036 } 16037 16038 // Compute the type of the field that will capture this variable. 16039 if (ByRef) { 16040 // C++11 [expr.prim.lambda]p15: 16041 // An entity is captured by reference if it is implicitly or 16042 // explicitly captured but not captured by copy. It is 16043 // unspecified whether additional unnamed non-static data 16044 // members are declared in the closure type for entities 16045 // captured by reference. 16046 // 16047 // FIXME: It is not clear whether we want to build an lvalue reference 16048 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16049 // to do the former, while EDG does the latter. Core issue 1249 will 16050 // clarify, but for now we follow GCC because it's a more permissive and 16051 // easily defensible position. 16052 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16053 } else { 16054 // C++11 [expr.prim.lambda]p14: 16055 // For each entity captured by copy, an unnamed non-static 16056 // data member is declared in the closure type. The 16057 // declaration order of these members is unspecified. The type 16058 // of such a data member is the type of the corresponding 16059 // captured entity if the entity is not a reference to an 16060 // object, or the referenced type otherwise. [Note: If the 16061 // captured entity is a reference to a function, the 16062 // corresponding data member is also a reference to a 16063 // function. - end note ] 16064 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16065 if (!RefType->getPointeeType()->isFunctionType()) 16066 CaptureType = RefType->getPointeeType(); 16067 } 16068 16069 // Forbid the lambda copy-capture of autoreleasing variables. 16070 if (!Invalid && 16071 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16072 if (BuildAndDiagnose) { 16073 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16074 S.Diag(Var->getLocation(), diag::note_previous_decl) 16075 << Var->getDeclName(); 16076 Invalid = true; 16077 } else { 16078 return false; 16079 } 16080 } 16081 16082 // Make sure that by-copy captures are of a complete and non-abstract type. 16083 if (!Invalid && BuildAndDiagnose) { 16084 if (!CaptureType->isDependentType() && 16085 S.RequireCompleteType(Loc, CaptureType, 16086 diag::err_capture_of_incomplete_type, 16087 Var->getDeclName())) 16088 Invalid = true; 16089 else if (S.RequireNonAbstractType(Loc, CaptureType, 16090 diag::err_capture_of_abstract_type)) 16091 Invalid = true; 16092 } 16093 } 16094 16095 // Compute the type of a reference to this captured variable. 16096 if (ByRef) 16097 DeclRefType = CaptureType.getNonReferenceType(); 16098 else { 16099 // C++ [expr.prim.lambda]p5: 16100 // The closure type for a lambda-expression has a public inline 16101 // function call operator [...]. This function call operator is 16102 // declared const (9.3.1) if and only if the lambda-expression's 16103 // parameter-declaration-clause is not followed by mutable. 16104 DeclRefType = CaptureType.getNonReferenceType(); 16105 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16106 DeclRefType.addConst(); 16107 } 16108 16109 // Add the capture. 16110 if (BuildAndDiagnose) 16111 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16112 Loc, EllipsisLoc, CaptureType, Invalid); 16113 16114 return !Invalid; 16115 } 16116 16117 bool Sema::tryCaptureVariable( 16118 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16119 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16120 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16121 // An init-capture is notionally from the context surrounding its 16122 // declaration, but its parent DC is the lambda class. 16123 DeclContext *VarDC = Var->getDeclContext(); 16124 if (Var->isInitCapture()) 16125 VarDC = VarDC->getParent(); 16126 16127 DeclContext *DC = CurContext; 16128 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16129 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16130 // We need to sync up the Declaration Context with the 16131 // FunctionScopeIndexToStopAt 16132 if (FunctionScopeIndexToStopAt) { 16133 unsigned FSIndex = FunctionScopes.size() - 1; 16134 while (FSIndex != MaxFunctionScopesIndex) { 16135 DC = getLambdaAwareParentOfDeclContext(DC); 16136 --FSIndex; 16137 } 16138 } 16139 16140 16141 // If the variable is declared in the current context, there is no need to 16142 // capture it. 16143 if (VarDC == DC) return true; 16144 16145 // Capture global variables if it is required to use private copy of this 16146 // variable. 16147 bool IsGlobal = !Var->hasLocalStorage(); 16148 if (IsGlobal && 16149 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16150 MaxFunctionScopesIndex))) 16151 return true; 16152 Var = Var->getCanonicalDecl(); 16153 16154 // Walk up the stack to determine whether we can capture the variable, 16155 // performing the "simple" checks that don't depend on type. We stop when 16156 // we've either hit the declared scope of the variable or find an existing 16157 // capture of that variable. We start from the innermost capturing-entity 16158 // (the DC) and ensure that all intervening capturing-entities 16159 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16160 // declcontext can either capture the variable or have already captured 16161 // the variable. 16162 CaptureType = Var->getType(); 16163 DeclRefType = CaptureType.getNonReferenceType(); 16164 bool Nested = false; 16165 bool Explicit = (Kind != TryCapture_Implicit); 16166 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16167 do { 16168 // Only block literals, captured statements, and lambda expressions can 16169 // capture; other scopes don't work. 16170 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16171 ExprLoc, 16172 BuildAndDiagnose, 16173 *this); 16174 // We need to check for the parent *first* because, if we *have* 16175 // private-captured a global variable, we need to recursively capture it in 16176 // intermediate blocks, lambdas, etc. 16177 if (!ParentDC) { 16178 if (IsGlobal) { 16179 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16180 break; 16181 } 16182 return true; 16183 } 16184 16185 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16186 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16187 16188 16189 // Check whether we've already captured it. 16190 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16191 DeclRefType)) { 16192 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16193 break; 16194 } 16195 // If we are instantiating a generic lambda call operator body, 16196 // we do not want to capture new variables. What was captured 16197 // during either a lambdas transformation or initial parsing 16198 // should be used. 16199 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16200 if (BuildAndDiagnose) { 16201 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16202 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16203 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16204 Diag(Var->getLocation(), diag::note_previous_decl) 16205 << Var->getDeclName(); 16206 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16207 } else 16208 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16209 } 16210 return true; 16211 } 16212 16213 // Try to capture variable-length arrays types. 16214 if (Var->getType()->isVariablyModifiedType()) { 16215 // We're going to walk down into the type and look for VLA 16216 // expressions. 16217 QualType QTy = Var->getType(); 16218 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16219 QTy = PVD->getOriginalType(); 16220 captureVariablyModifiedType(Context, QTy, CSI); 16221 } 16222 16223 if (getLangOpts().OpenMP) { 16224 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16225 // OpenMP private variables should not be captured in outer scope, so 16226 // just break here. Similarly, global variables that are captured in a 16227 // target region should not be captured outside the scope of the region. 16228 if (RSI->CapRegionKind == CR_OpenMP) { 16229 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 16230 // If the variable is private (i.e. not captured) and has variably 16231 // modified type, we still need to capture the type for correct 16232 // codegen in all regions, associated with the construct. Currently, 16233 // it is captured in the innermost captured region only. 16234 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) { 16235 QualType QTy = Var->getType(); 16236 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16237 QTy = PVD->getOriginalType(); 16238 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16239 I < E; ++I) { 16240 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16241 FunctionScopes[FunctionScopesIndex - I]); 16242 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16243 "Wrong number of captured regions associated with the " 16244 "OpenMP construct."); 16245 captureVariablyModifiedType(Context, QTy, OuterRSI); 16246 } 16247 } 16248 bool IsTargetCap = !IsOpenMPPrivateDecl && 16249 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 16250 // When we detect target captures we are looking from inside the 16251 // target region, therefore we need to propagate the capture from the 16252 // enclosing region. Therefore, the capture is not initially nested. 16253 if (IsTargetCap) 16254 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16255 16256 if (IsTargetCap || IsOpenMPPrivateDecl) { 16257 Nested = !IsTargetCap; 16258 DeclRefType = DeclRefType.getUnqualifiedType(); 16259 CaptureType = Context.getLValueReferenceType(DeclRefType); 16260 break; 16261 } 16262 } 16263 } 16264 } 16265 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16266 // No capture-default, and this is not an explicit capture 16267 // so cannot capture this variable. 16268 if (BuildAndDiagnose) { 16269 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16270 Diag(Var->getLocation(), diag::note_previous_decl) 16271 << Var->getDeclName(); 16272 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16273 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16274 diag::note_lambda_decl); 16275 // FIXME: If we error out because an outer lambda can not implicitly 16276 // capture a variable that an inner lambda explicitly captures, we 16277 // should have the inner lambda do the explicit capture - because 16278 // it makes for cleaner diagnostics later. This would purely be done 16279 // so that the diagnostic does not misleadingly claim that a variable 16280 // can not be captured by a lambda implicitly even though it is captured 16281 // explicitly. Suggestion: 16282 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16283 // at the function head 16284 // - cache the StartingDeclContext - this must be a lambda 16285 // - captureInLambda in the innermost lambda the variable. 16286 } 16287 return true; 16288 } 16289 16290 FunctionScopesIndex--; 16291 DC = ParentDC; 16292 Explicit = false; 16293 } while (!VarDC->Equals(DC)); 16294 16295 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16296 // computing the type of the capture at each step, checking type-specific 16297 // requirements, and adding captures if requested. 16298 // If the variable had already been captured previously, we start capturing 16299 // at the lambda nested within that one. 16300 bool Invalid = false; 16301 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16302 ++I) { 16303 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16304 16305 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16306 // certain types of variables (unnamed, variably modified types etc.) 16307 // so check for eligibility. 16308 if (!Invalid) 16309 Invalid = 16310 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16311 16312 // After encountering an error, if we're actually supposed to capture, keep 16313 // capturing in nested contexts to suppress any follow-on diagnostics. 16314 if (Invalid && !BuildAndDiagnose) 16315 return true; 16316 16317 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16318 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16319 DeclRefType, Nested, *this, Invalid); 16320 Nested = true; 16321 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16322 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16323 CaptureType, DeclRefType, Nested, 16324 *this, Invalid); 16325 Nested = true; 16326 } else { 16327 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16328 Invalid = 16329 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16330 DeclRefType, Nested, Kind, EllipsisLoc, 16331 /*IsTopScope*/ I == N - 1, *this, Invalid); 16332 Nested = true; 16333 } 16334 16335 if (Invalid && !BuildAndDiagnose) 16336 return true; 16337 } 16338 return Invalid; 16339 } 16340 16341 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16342 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16343 QualType CaptureType; 16344 QualType DeclRefType; 16345 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16346 /*BuildAndDiagnose=*/true, CaptureType, 16347 DeclRefType, nullptr); 16348 } 16349 16350 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16351 QualType CaptureType; 16352 QualType DeclRefType; 16353 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16354 /*BuildAndDiagnose=*/false, CaptureType, 16355 DeclRefType, nullptr); 16356 } 16357 16358 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16359 QualType CaptureType; 16360 QualType DeclRefType; 16361 16362 // Determine whether we can capture this variable. 16363 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16364 /*BuildAndDiagnose=*/false, CaptureType, 16365 DeclRefType, nullptr)) 16366 return QualType(); 16367 16368 return DeclRefType; 16369 } 16370 16371 namespace { 16372 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16373 // The produced TemplateArgumentListInfo* points to data stored within this 16374 // object, so should only be used in contexts where the pointer will not be 16375 // used after the CopiedTemplateArgs object is destroyed. 16376 class CopiedTemplateArgs { 16377 bool HasArgs; 16378 TemplateArgumentListInfo TemplateArgStorage; 16379 public: 16380 template<typename RefExpr> 16381 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16382 if (HasArgs) 16383 E->copyTemplateArgumentsInto(TemplateArgStorage); 16384 } 16385 operator TemplateArgumentListInfo*() 16386 #ifdef __has_cpp_attribute 16387 #if __has_cpp_attribute(clang::lifetimebound) 16388 [[clang::lifetimebound]] 16389 #endif 16390 #endif 16391 { 16392 return HasArgs ? &TemplateArgStorage : nullptr; 16393 } 16394 }; 16395 } 16396 16397 /// Walk the set of potential results of an expression and mark them all as 16398 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16399 /// 16400 /// \return A new expression if we found any potential results, ExprEmpty() if 16401 /// not, and ExprError() if we diagnosed an error. 16402 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16403 NonOdrUseReason NOUR) { 16404 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16405 // an object that satisfies the requirements for appearing in a 16406 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16407 // is immediately applied." This function handles the lvalue-to-rvalue 16408 // conversion part. 16409 // 16410 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16411 // transform it into the relevant kind of non-odr-use node and rebuild the 16412 // tree of nodes leading to it. 16413 // 16414 // This is a mini-TreeTransform that only transforms a restricted subset of 16415 // nodes (and only certain operands of them). 16416 16417 // Rebuild a subexpression. 16418 auto Rebuild = [&](Expr *Sub) { 16419 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16420 }; 16421 16422 // Check whether a potential result satisfies the requirements of NOUR. 16423 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16424 // Any entity other than a VarDecl is always odr-used whenever it's named 16425 // in a potentially-evaluated expression. 16426 auto *VD = dyn_cast<VarDecl>(D); 16427 if (!VD) 16428 return true; 16429 16430 // C++2a [basic.def.odr]p4: 16431 // A variable x whose name appears as a potentially-evalauted expression 16432 // e is odr-used by e unless 16433 // -- x is a reference that is usable in constant expressions, or 16434 // -- x is a variable of non-reference type that is usable in constant 16435 // expressions and has no mutable subobjects, and e is an element of 16436 // the set of potential results of an expression of 16437 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16438 // conversion is applied, or 16439 // -- x is a variable of non-reference type, and e is an element of the 16440 // set of potential results of a discarded-value expression to which 16441 // the lvalue-to-rvalue conversion is not applied 16442 // 16443 // We check the first bullet and the "potentially-evaluated" condition in 16444 // BuildDeclRefExpr. We check the type requirements in the second bullet 16445 // in CheckLValueToRValueConversionOperand below. 16446 switch (NOUR) { 16447 case NOUR_None: 16448 case NOUR_Unevaluated: 16449 llvm_unreachable("unexpected non-odr-use-reason"); 16450 16451 case NOUR_Constant: 16452 // Constant references were handled when they were built. 16453 if (VD->getType()->isReferenceType()) 16454 return true; 16455 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16456 if (RD->hasMutableFields()) 16457 return true; 16458 if (!VD->isUsableInConstantExpressions(S.Context)) 16459 return true; 16460 break; 16461 16462 case NOUR_Discarded: 16463 if (VD->getType()->isReferenceType()) 16464 return true; 16465 break; 16466 } 16467 return false; 16468 }; 16469 16470 // Mark that this expression does not constitute an odr-use. 16471 auto MarkNotOdrUsed = [&] { 16472 S.MaybeODRUseExprs.erase(E); 16473 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16474 LSI->markVariableExprAsNonODRUsed(E); 16475 }; 16476 16477 // C++2a [basic.def.odr]p2: 16478 // The set of potential results of an expression e is defined as follows: 16479 switch (E->getStmtClass()) { 16480 // -- If e is an id-expression, ... 16481 case Expr::DeclRefExprClass: { 16482 auto *DRE = cast<DeclRefExpr>(E); 16483 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16484 break; 16485 16486 // Rebuild as a non-odr-use DeclRefExpr. 16487 MarkNotOdrUsed(); 16488 return DeclRefExpr::Create( 16489 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16490 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16491 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16492 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16493 } 16494 16495 case Expr::FunctionParmPackExprClass: { 16496 auto *FPPE = cast<FunctionParmPackExpr>(E); 16497 // If any of the declarations in the pack is odr-used, then the expression 16498 // as a whole constitutes an odr-use. 16499 for (VarDecl *D : *FPPE) 16500 if (IsPotentialResultOdrUsed(D)) 16501 return ExprEmpty(); 16502 16503 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16504 // nothing cares about whether we marked this as an odr-use, but it might 16505 // be useful for non-compiler tools. 16506 MarkNotOdrUsed(); 16507 break; 16508 } 16509 16510 // -- If e is a subscripting operation with an array operand... 16511 case Expr::ArraySubscriptExprClass: { 16512 auto *ASE = cast<ArraySubscriptExpr>(E); 16513 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16514 if (!OldBase->getType()->isArrayType()) 16515 break; 16516 ExprResult Base = Rebuild(OldBase); 16517 if (!Base.isUsable()) 16518 return Base; 16519 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16520 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16521 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16522 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16523 ASE->getRBracketLoc()); 16524 } 16525 16526 case Expr::MemberExprClass: { 16527 auto *ME = cast<MemberExpr>(E); 16528 // -- If e is a class member access expression [...] naming a non-static 16529 // data member... 16530 if (isa<FieldDecl>(ME->getMemberDecl())) { 16531 ExprResult Base = Rebuild(ME->getBase()); 16532 if (!Base.isUsable()) 16533 return Base; 16534 return MemberExpr::Create( 16535 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16536 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16537 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16538 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16539 ME->getObjectKind(), ME->isNonOdrUse()); 16540 } 16541 16542 if (ME->getMemberDecl()->isCXXInstanceMember()) 16543 break; 16544 16545 // -- If e is a class member access expression naming a static data member, 16546 // ... 16547 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16548 break; 16549 16550 // Rebuild as a non-odr-use MemberExpr. 16551 MarkNotOdrUsed(); 16552 return MemberExpr::Create( 16553 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16554 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16555 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16556 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16557 return ExprEmpty(); 16558 } 16559 16560 case Expr::BinaryOperatorClass: { 16561 auto *BO = cast<BinaryOperator>(E); 16562 Expr *LHS = BO->getLHS(); 16563 Expr *RHS = BO->getRHS(); 16564 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16565 if (BO->getOpcode() == BO_PtrMemD) { 16566 ExprResult Sub = Rebuild(LHS); 16567 if (!Sub.isUsable()) 16568 return Sub; 16569 LHS = Sub.get(); 16570 // -- If e is a comma expression, ... 16571 } else if (BO->getOpcode() == BO_Comma) { 16572 ExprResult Sub = Rebuild(RHS); 16573 if (!Sub.isUsable()) 16574 return Sub; 16575 RHS = Sub.get(); 16576 } else { 16577 break; 16578 } 16579 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 16580 LHS, RHS); 16581 } 16582 16583 // -- If e has the form (e1)... 16584 case Expr::ParenExprClass: { 16585 auto *PE = cast<ParenExpr>(E); 16586 ExprResult Sub = Rebuild(PE->getSubExpr()); 16587 if (!Sub.isUsable()) 16588 return Sub; 16589 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 16590 } 16591 16592 // -- If e is a glvalue conditional expression, ... 16593 // We don't apply this to a binary conditional operator. FIXME: Should we? 16594 case Expr::ConditionalOperatorClass: { 16595 auto *CO = cast<ConditionalOperator>(E); 16596 ExprResult LHS = Rebuild(CO->getLHS()); 16597 if (LHS.isInvalid()) 16598 return ExprError(); 16599 ExprResult RHS = Rebuild(CO->getRHS()); 16600 if (RHS.isInvalid()) 16601 return ExprError(); 16602 if (!LHS.isUsable() && !RHS.isUsable()) 16603 return ExprEmpty(); 16604 if (!LHS.isUsable()) 16605 LHS = CO->getLHS(); 16606 if (!RHS.isUsable()) 16607 RHS = CO->getRHS(); 16608 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 16609 CO->getCond(), LHS.get(), RHS.get()); 16610 } 16611 16612 // [Clang extension] 16613 // -- If e has the form __extension__ e1... 16614 case Expr::UnaryOperatorClass: { 16615 auto *UO = cast<UnaryOperator>(E); 16616 if (UO->getOpcode() != UO_Extension) 16617 break; 16618 ExprResult Sub = Rebuild(UO->getSubExpr()); 16619 if (!Sub.isUsable()) 16620 return Sub; 16621 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 16622 Sub.get()); 16623 } 16624 16625 // [Clang extension] 16626 // -- If e has the form _Generic(...), the set of potential results is the 16627 // union of the sets of potential results of the associated expressions. 16628 case Expr::GenericSelectionExprClass: { 16629 auto *GSE = cast<GenericSelectionExpr>(E); 16630 16631 SmallVector<Expr *, 4> AssocExprs; 16632 bool AnyChanged = false; 16633 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 16634 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 16635 if (AssocExpr.isInvalid()) 16636 return ExprError(); 16637 if (AssocExpr.isUsable()) { 16638 AssocExprs.push_back(AssocExpr.get()); 16639 AnyChanged = true; 16640 } else { 16641 AssocExprs.push_back(OrigAssocExpr); 16642 } 16643 } 16644 16645 return AnyChanged ? S.CreateGenericSelectionExpr( 16646 GSE->getGenericLoc(), GSE->getDefaultLoc(), 16647 GSE->getRParenLoc(), GSE->getControllingExpr(), 16648 GSE->getAssocTypeSourceInfos(), AssocExprs) 16649 : ExprEmpty(); 16650 } 16651 16652 // [Clang extension] 16653 // -- If e has the form __builtin_choose_expr(...), the set of potential 16654 // results is the union of the sets of potential results of the 16655 // second and third subexpressions. 16656 case Expr::ChooseExprClass: { 16657 auto *CE = cast<ChooseExpr>(E); 16658 16659 ExprResult LHS = Rebuild(CE->getLHS()); 16660 if (LHS.isInvalid()) 16661 return ExprError(); 16662 16663 ExprResult RHS = Rebuild(CE->getLHS()); 16664 if (RHS.isInvalid()) 16665 return ExprError(); 16666 16667 if (!LHS.get() && !RHS.get()) 16668 return ExprEmpty(); 16669 if (!LHS.isUsable()) 16670 LHS = CE->getLHS(); 16671 if (!RHS.isUsable()) 16672 RHS = CE->getRHS(); 16673 16674 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 16675 RHS.get(), CE->getRParenLoc()); 16676 } 16677 16678 // Step through non-syntactic nodes. 16679 case Expr::ConstantExprClass: { 16680 auto *CE = cast<ConstantExpr>(E); 16681 ExprResult Sub = Rebuild(CE->getSubExpr()); 16682 if (!Sub.isUsable()) 16683 return Sub; 16684 return ConstantExpr::Create(S.Context, Sub.get()); 16685 } 16686 16687 // We could mostly rely on the recursive rebuilding to rebuild implicit 16688 // casts, but not at the top level, so rebuild them here. 16689 case Expr::ImplicitCastExprClass: { 16690 auto *ICE = cast<ImplicitCastExpr>(E); 16691 // Only step through the narrow set of cast kinds we expect to encounter. 16692 // Anything else suggests we've left the region in which potential results 16693 // can be found. 16694 switch (ICE->getCastKind()) { 16695 case CK_NoOp: 16696 case CK_DerivedToBase: 16697 case CK_UncheckedDerivedToBase: { 16698 ExprResult Sub = Rebuild(ICE->getSubExpr()); 16699 if (!Sub.isUsable()) 16700 return Sub; 16701 CXXCastPath Path(ICE->path()); 16702 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 16703 ICE->getValueKind(), &Path); 16704 } 16705 16706 default: 16707 break; 16708 } 16709 break; 16710 } 16711 16712 default: 16713 break; 16714 } 16715 16716 // Can't traverse through this node. Nothing to do. 16717 return ExprEmpty(); 16718 } 16719 16720 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 16721 // Check whether the operand is or contains an object of non-trivial C union 16722 // type. 16723 if (E->getType().isVolatileQualified() && 16724 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 16725 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 16726 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 16727 Sema::NTCUC_LValueToRValueVolatile, 16728 NTCUK_Destruct|NTCUK_Copy); 16729 16730 // C++2a [basic.def.odr]p4: 16731 // [...] an expression of non-volatile-qualified non-class type to which 16732 // the lvalue-to-rvalue conversion is applied [...] 16733 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 16734 return E; 16735 16736 ExprResult Result = 16737 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 16738 if (Result.isInvalid()) 16739 return ExprError(); 16740 return Result.get() ? Result : E; 16741 } 16742 16743 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 16744 Res = CorrectDelayedTyposInExpr(Res); 16745 16746 if (!Res.isUsable()) 16747 return Res; 16748 16749 // If a constant-expression is a reference to a variable where we delay 16750 // deciding whether it is an odr-use, just assume we will apply the 16751 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 16752 // (a non-type template argument), we have special handling anyway. 16753 return CheckLValueToRValueConversionOperand(Res.get()); 16754 } 16755 16756 void Sema::CleanupVarDeclMarking() { 16757 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 16758 // call. 16759 MaybeODRUseExprSet LocalMaybeODRUseExprs; 16760 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 16761 16762 for (Expr *E : LocalMaybeODRUseExprs) { 16763 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 16764 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 16765 DRE->getLocation(), *this); 16766 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 16767 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 16768 *this); 16769 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 16770 for (VarDecl *VD : *FP) 16771 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 16772 } else { 16773 llvm_unreachable("Unexpected expression"); 16774 } 16775 } 16776 16777 assert(MaybeODRUseExprs.empty() && 16778 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 16779 } 16780 16781 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 16782 VarDecl *Var, Expr *E) { 16783 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 16784 isa<FunctionParmPackExpr>(E)) && 16785 "Invalid Expr argument to DoMarkVarDeclReferenced"); 16786 Var->setReferenced(); 16787 16788 if (Var->isInvalidDecl()) 16789 return; 16790 16791 auto *MSI = Var->getMemberSpecializationInfo(); 16792 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 16793 : Var->getTemplateSpecializationKind(); 16794 16795 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 16796 bool UsableInConstantExpr = 16797 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 16798 16799 // C++20 [expr.const]p12: 16800 // A variable [...] is needed for constant evaluation if it is [...] a 16801 // variable whose name appears as a potentially constant evaluated 16802 // expression that is either a contexpr variable or is of non-volatile 16803 // const-qualified integral type or of reference type 16804 bool NeededForConstantEvaluation = 16805 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 16806 16807 bool NeedDefinition = 16808 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 16809 16810 VarTemplateSpecializationDecl *VarSpec = 16811 dyn_cast<VarTemplateSpecializationDecl>(Var); 16812 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 16813 "Can't instantiate a partial template specialization."); 16814 16815 // If this might be a member specialization of a static data member, check 16816 // the specialization is visible. We already did the checks for variable 16817 // template specializations when we created them. 16818 if (NeedDefinition && TSK != TSK_Undeclared && 16819 !isa<VarTemplateSpecializationDecl>(Var)) 16820 SemaRef.checkSpecializationVisibility(Loc, Var); 16821 16822 // Perform implicit instantiation of static data members, static data member 16823 // templates of class templates, and variable template specializations. Delay 16824 // instantiations of variable templates, except for those that could be used 16825 // in a constant expression. 16826 if (NeedDefinition && isTemplateInstantiation(TSK)) { 16827 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 16828 // instantiation declaration if a variable is usable in a constant 16829 // expression (among other cases). 16830 bool TryInstantiating = 16831 TSK == TSK_ImplicitInstantiation || 16832 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 16833 16834 if (TryInstantiating) { 16835 SourceLocation PointOfInstantiation = 16836 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 16837 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16838 if (FirstInstantiation) { 16839 PointOfInstantiation = Loc; 16840 if (MSI) 16841 MSI->setPointOfInstantiation(PointOfInstantiation); 16842 else 16843 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16844 } 16845 16846 bool InstantiationDependent = false; 16847 bool IsNonDependent = 16848 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 16849 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 16850 : true; 16851 16852 // Do not instantiate specializations that are still type-dependent. 16853 if (IsNonDependent) { 16854 if (UsableInConstantExpr) { 16855 // Do not defer instantiations of variables that could be used in a 16856 // constant expression. 16857 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 16858 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 16859 }); 16860 } else if (FirstInstantiation || 16861 isa<VarTemplateSpecializationDecl>(Var)) { 16862 // FIXME: For a specialization of a variable template, we don't 16863 // distinguish between "declaration and type implicitly instantiated" 16864 // and "implicit instantiation of definition requested", so we have 16865 // no direct way to avoid enqueueing the pending instantiation 16866 // multiple times. 16867 SemaRef.PendingInstantiations 16868 .push_back(std::make_pair(Var, PointOfInstantiation)); 16869 } 16870 } 16871 } 16872 } 16873 16874 // C++2a [basic.def.odr]p4: 16875 // A variable x whose name appears as a potentially-evaluated expression e 16876 // is odr-used by e unless 16877 // -- x is a reference that is usable in constant expressions 16878 // -- x is a variable of non-reference type that is usable in constant 16879 // expressions and has no mutable subobjects [FIXME], and e is an 16880 // element of the set of potential results of an expression of 16881 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16882 // conversion is applied 16883 // -- x is a variable of non-reference type, and e is an element of the set 16884 // of potential results of a discarded-value expression to which the 16885 // lvalue-to-rvalue conversion is not applied [FIXME] 16886 // 16887 // We check the first part of the second bullet here, and 16888 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 16889 // FIXME: To get the third bullet right, we need to delay this even for 16890 // variables that are not usable in constant expressions. 16891 16892 // If we already know this isn't an odr-use, there's nothing more to do. 16893 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 16894 if (DRE->isNonOdrUse()) 16895 return; 16896 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 16897 if (ME->isNonOdrUse()) 16898 return; 16899 16900 switch (OdrUse) { 16901 case OdrUseContext::None: 16902 assert((!E || isa<FunctionParmPackExpr>(E)) && 16903 "missing non-odr-use marking for unevaluated decl ref"); 16904 break; 16905 16906 case OdrUseContext::FormallyOdrUsed: 16907 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 16908 // behavior. 16909 break; 16910 16911 case OdrUseContext::Used: 16912 // If we might later find that this expression isn't actually an odr-use, 16913 // delay the marking. 16914 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 16915 SemaRef.MaybeODRUseExprs.insert(E); 16916 else 16917 MarkVarDeclODRUsed(Var, Loc, SemaRef); 16918 break; 16919 16920 case OdrUseContext::Dependent: 16921 // If this is a dependent context, we don't need to mark variables as 16922 // odr-used, but we may still need to track them for lambda capture. 16923 // FIXME: Do we also need to do this inside dependent typeid expressions 16924 // (which are modeled as unevaluated at this point)? 16925 const bool RefersToEnclosingScope = 16926 (SemaRef.CurContext != Var->getDeclContext() && 16927 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 16928 if (RefersToEnclosingScope) { 16929 LambdaScopeInfo *const LSI = 16930 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 16931 if (LSI && (!LSI->CallOperator || 16932 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 16933 // If a variable could potentially be odr-used, defer marking it so 16934 // until we finish analyzing the full expression for any 16935 // lvalue-to-rvalue 16936 // or discarded value conversions that would obviate odr-use. 16937 // Add it to the list of potential captures that will be analyzed 16938 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 16939 // unless the variable is a reference that was initialized by a constant 16940 // expression (this will never need to be captured or odr-used). 16941 // 16942 // FIXME: We can simplify this a lot after implementing P0588R1. 16943 assert(E && "Capture variable should be used in an expression."); 16944 if (!Var->getType()->isReferenceType() || 16945 !Var->isUsableInConstantExpressions(SemaRef.Context)) 16946 LSI->addPotentialCapture(E->IgnoreParens()); 16947 } 16948 } 16949 break; 16950 } 16951 } 16952 16953 /// Mark a variable referenced, and check whether it is odr-used 16954 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 16955 /// used directly for normal expressions referring to VarDecl. 16956 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 16957 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 16958 } 16959 16960 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 16961 Decl *D, Expr *E, bool MightBeOdrUse) { 16962 if (SemaRef.isInOpenMPDeclareTargetContext()) 16963 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 16964 16965 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 16966 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 16967 return; 16968 } 16969 16970 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 16971 16972 // If this is a call to a method via a cast, also mark the method in the 16973 // derived class used in case codegen can devirtualize the call. 16974 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 16975 if (!ME) 16976 return; 16977 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 16978 if (!MD) 16979 return; 16980 // Only attempt to devirtualize if this is truly a virtual call. 16981 bool IsVirtualCall = MD->isVirtual() && 16982 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 16983 if (!IsVirtualCall) 16984 return; 16985 16986 // If it's possible to devirtualize the call, mark the called function 16987 // referenced. 16988 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 16989 ME->getBase(), SemaRef.getLangOpts().AppleKext); 16990 if (DM) 16991 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 16992 } 16993 16994 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 16995 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 16996 // TODO: update this with DR# once a defect report is filed. 16997 // C++11 defect. The address of a pure member should not be an ODR use, even 16998 // if it's a qualified reference. 16999 bool OdrUse = true; 17000 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17001 if (Method->isVirtual() && 17002 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17003 OdrUse = false; 17004 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17005 } 17006 17007 /// Perform reference-marking and odr-use handling for a MemberExpr. 17008 void Sema::MarkMemberReferenced(MemberExpr *E) { 17009 // C++11 [basic.def.odr]p2: 17010 // A non-overloaded function whose name appears as a potentially-evaluated 17011 // expression or a member of a set of candidate functions, if selected by 17012 // overload resolution when referred to from a potentially-evaluated 17013 // expression, is odr-used, unless it is a pure virtual function and its 17014 // name is not explicitly qualified. 17015 bool MightBeOdrUse = true; 17016 if (E->performsVirtualDispatch(getLangOpts())) { 17017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17018 if (Method->isPure()) 17019 MightBeOdrUse = false; 17020 } 17021 SourceLocation Loc = 17022 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17023 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17024 } 17025 17026 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17027 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17028 for (VarDecl *VD : *E) 17029 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17030 } 17031 17032 /// Perform marking for a reference to an arbitrary declaration. It 17033 /// marks the declaration referenced, and performs odr-use checking for 17034 /// functions and variables. This method should not be used when building a 17035 /// normal expression which refers to a variable. 17036 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17037 bool MightBeOdrUse) { 17038 if (MightBeOdrUse) { 17039 if (auto *VD = dyn_cast<VarDecl>(D)) { 17040 MarkVariableReferenced(Loc, VD); 17041 return; 17042 } 17043 } 17044 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17045 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17046 return; 17047 } 17048 D->setReferenced(); 17049 } 17050 17051 namespace { 17052 // Mark all of the declarations used by a type as referenced. 17053 // FIXME: Not fully implemented yet! We need to have a better understanding 17054 // of when we're entering a context we should not recurse into. 17055 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17056 // TreeTransforms rebuilding the type in a new context. Rather than 17057 // duplicating the TreeTransform logic, we should consider reusing it here. 17058 // Currently that causes problems when rebuilding LambdaExprs. 17059 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17060 Sema &S; 17061 SourceLocation Loc; 17062 17063 public: 17064 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17065 17066 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17067 17068 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17069 }; 17070 } 17071 17072 bool MarkReferencedDecls::TraverseTemplateArgument( 17073 const TemplateArgument &Arg) { 17074 { 17075 // A non-type template argument is a constant-evaluated context. 17076 EnterExpressionEvaluationContext Evaluated( 17077 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17078 if (Arg.getKind() == TemplateArgument::Declaration) { 17079 if (Decl *D = Arg.getAsDecl()) 17080 S.MarkAnyDeclReferenced(Loc, D, true); 17081 } else if (Arg.getKind() == TemplateArgument::Expression) { 17082 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17083 } 17084 } 17085 17086 return Inherited::TraverseTemplateArgument(Arg); 17087 } 17088 17089 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17090 MarkReferencedDecls Marker(*this, Loc); 17091 Marker.TraverseType(T); 17092 } 17093 17094 namespace { 17095 /// Helper class that marks all of the declarations referenced by 17096 /// potentially-evaluated subexpressions as "referenced". 17097 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 17098 Sema &S; 17099 bool SkipLocalVariables; 17100 17101 public: 17102 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 17103 17104 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17105 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 17106 17107 void VisitDeclRefExpr(DeclRefExpr *E) { 17108 // If we were asked not to visit local variables, don't. 17109 if (SkipLocalVariables) { 17110 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17111 if (VD->hasLocalStorage()) 17112 return; 17113 } 17114 17115 S.MarkDeclRefReferenced(E); 17116 } 17117 17118 void VisitMemberExpr(MemberExpr *E) { 17119 S.MarkMemberReferenced(E); 17120 Inherited::VisitMemberExpr(E); 17121 } 17122 17123 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 17124 S.MarkFunctionReferenced( 17125 E->getBeginLoc(), 17126 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 17127 Visit(E->getSubExpr()); 17128 } 17129 17130 void VisitCXXNewExpr(CXXNewExpr *E) { 17131 if (E->getOperatorNew()) 17132 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 17133 if (E->getOperatorDelete()) 17134 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17135 Inherited::VisitCXXNewExpr(E); 17136 } 17137 17138 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17139 if (E->getOperatorDelete()) 17140 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 17141 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 17142 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 17143 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 17144 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 17145 } 17146 17147 Inherited::VisitCXXDeleteExpr(E); 17148 } 17149 17150 void VisitCXXConstructExpr(CXXConstructExpr *E) { 17151 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 17152 Inherited::VisitCXXConstructExpr(E); 17153 } 17154 17155 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 17156 Visit(E->getExpr()); 17157 } 17158 }; 17159 } 17160 17161 /// Mark any declarations that appear within this expression or any 17162 /// potentially-evaluated subexpressions as "referenced". 17163 /// 17164 /// \param SkipLocalVariables If true, don't mark local variables as 17165 /// 'referenced'. 17166 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17167 bool SkipLocalVariables) { 17168 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17169 } 17170 17171 /// Emit a diagnostic that describes an effect on the run-time behavior 17172 /// of the program being compiled. 17173 /// 17174 /// This routine emits the given diagnostic when the code currently being 17175 /// type-checked is "potentially evaluated", meaning that there is a 17176 /// possibility that the code will actually be executable. Code in sizeof() 17177 /// expressions, code used only during overload resolution, etc., are not 17178 /// potentially evaluated. This routine will suppress such diagnostics or, 17179 /// in the absolutely nutty case of potentially potentially evaluated 17180 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17181 /// later. 17182 /// 17183 /// This routine should be used for all diagnostics that describe the run-time 17184 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17185 /// Failure to do so will likely result in spurious diagnostics or failures 17186 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17187 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17188 const PartialDiagnostic &PD) { 17189 switch (ExprEvalContexts.back().Context) { 17190 case ExpressionEvaluationContext::Unevaluated: 17191 case ExpressionEvaluationContext::UnevaluatedList: 17192 case ExpressionEvaluationContext::UnevaluatedAbstract: 17193 case ExpressionEvaluationContext::DiscardedStatement: 17194 // The argument will never be evaluated, so don't complain. 17195 break; 17196 17197 case ExpressionEvaluationContext::ConstantEvaluated: 17198 // Relevant diagnostics should be produced by constant evaluation. 17199 break; 17200 17201 case ExpressionEvaluationContext::PotentiallyEvaluated: 17202 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17203 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17204 FunctionScopes.back()->PossiblyUnreachableDiags. 17205 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17206 return true; 17207 } 17208 17209 // The initializer of a constexpr variable or of the first declaration of a 17210 // static data member is not syntactically a constant evaluated constant, 17211 // but nonetheless is always required to be a constant expression, so we 17212 // can skip diagnosing. 17213 // FIXME: Using the mangling context here is a hack. 17214 if (auto *VD = dyn_cast_or_null<VarDecl>( 17215 ExprEvalContexts.back().ManglingContextDecl)) { 17216 if (VD->isConstexpr() || 17217 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17218 break; 17219 // FIXME: For any other kind of variable, we should build a CFG for its 17220 // initializer and check whether the context in question is reachable. 17221 } 17222 17223 Diag(Loc, PD); 17224 return true; 17225 } 17226 17227 return false; 17228 } 17229 17230 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17231 const PartialDiagnostic &PD) { 17232 return DiagRuntimeBehavior( 17233 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17234 } 17235 17236 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17237 CallExpr *CE, FunctionDecl *FD) { 17238 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17239 return false; 17240 17241 // If we're inside a decltype's expression, don't check for a valid return 17242 // type or construct temporaries until we know whether this is the last call. 17243 if (ExprEvalContexts.back().ExprContext == 17244 ExpressionEvaluationContextRecord::EK_Decltype) { 17245 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17246 return false; 17247 } 17248 17249 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17250 FunctionDecl *FD; 17251 CallExpr *CE; 17252 17253 public: 17254 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17255 : FD(FD), CE(CE) { } 17256 17257 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17258 if (!FD) { 17259 S.Diag(Loc, diag::err_call_incomplete_return) 17260 << T << CE->getSourceRange(); 17261 return; 17262 } 17263 17264 S.Diag(Loc, diag::err_call_function_incomplete_return) 17265 << CE->getSourceRange() << FD->getDeclName() << T; 17266 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17267 << FD->getDeclName(); 17268 } 17269 } Diagnoser(FD, CE); 17270 17271 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17272 return true; 17273 17274 return false; 17275 } 17276 17277 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17278 // will prevent this condition from triggering, which is what we want. 17279 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17280 SourceLocation Loc; 17281 17282 unsigned diagnostic = diag::warn_condition_is_assignment; 17283 bool IsOrAssign = false; 17284 17285 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17286 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17287 return; 17288 17289 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17290 17291 // Greylist some idioms by putting them into a warning subcategory. 17292 if (ObjCMessageExpr *ME 17293 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17294 Selector Sel = ME->getSelector(); 17295 17296 // self = [<foo> init...] 17297 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17298 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17299 17300 // <foo> = [<bar> nextObject] 17301 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17302 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17303 } 17304 17305 Loc = Op->getOperatorLoc(); 17306 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17307 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17308 return; 17309 17310 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17311 Loc = Op->getOperatorLoc(); 17312 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17313 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17314 else { 17315 // Not an assignment. 17316 return; 17317 } 17318 17319 Diag(Loc, diagnostic) << E->getSourceRange(); 17320 17321 SourceLocation Open = E->getBeginLoc(); 17322 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17323 Diag(Loc, diag::note_condition_assign_silence) 17324 << FixItHint::CreateInsertion(Open, "(") 17325 << FixItHint::CreateInsertion(Close, ")"); 17326 17327 if (IsOrAssign) 17328 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17329 << FixItHint::CreateReplacement(Loc, "!="); 17330 else 17331 Diag(Loc, diag::note_condition_assign_to_comparison) 17332 << FixItHint::CreateReplacement(Loc, "=="); 17333 } 17334 17335 /// Redundant parentheses over an equality comparison can indicate 17336 /// that the user intended an assignment used as condition. 17337 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17338 // Don't warn if the parens came from a macro. 17339 SourceLocation parenLoc = ParenE->getBeginLoc(); 17340 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17341 return; 17342 // Don't warn for dependent expressions. 17343 if (ParenE->isTypeDependent()) 17344 return; 17345 17346 Expr *E = ParenE->IgnoreParens(); 17347 17348 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17349 if (opE->getOpcode() == BO_EQ && 17350 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17351 == Expr::MLV_Valid) { 17352 SourceLocation Loc = opE->getOperatorLoc(); 17353 17354 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17355 SourceRange ParenERange = ParenE->getSourceRange(); 17356 Diag(Loc, diag::note_equality_comparison_silence) 17357 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17358 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17359 Diag(Loc, diag::note_equality_comparison_to_assign) 17360 << FixItHint::CreateReplacement(Loc, "="); 17361 } 17362 } 17363 17364 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17365 bool IsConstexpr) { 17366 DiagnoseAssignmentAsCondition(E); 17367 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17368 DiagnoseEqualityWithExtraParens(parenE); 17369 17370 ExprResult result = CheckPlaceholderExpr(E); 17371 if (result.isInvalid()) return ExprError(); 17372 E = result.get(); 17373 17374 if (!E->isTypeDependent()) { 17375 if (getLangOpts().CPlusPlus) 17376 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17377 17378 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17379 if (ERes.isInvalid()) 17380 return ExprError(); 17381 E = ERes.get(); 17382 17383 QualType T = E->getType(); 17384 if (!T->isScalarType()) { // C99 6.8.4.1p1 17385 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17386 << T << E->getSourceRange(); 17387 return ExprError(); 17388 } 17389 CheckBoolLikeConversion(E, Loc); 17390 } 17391 17392 return E; 17393 } 17394 17395 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17396 Expr *SubExpr, ConditionKind CK) { 17397 // Empty conditions are valid in for-statements. 17398 if (!SubExpr) 17399 return ConditionResult(); 17400 17401 ExprResult Cond; 17402 switch (CK) { 17403 case ConditionKind::Boolean: 17404 Cond = CheckBooleanCondition(Loc, SubExpr); 17405 break; 17406 17407 case ConditionKind::ConstexprIf: 17408 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17409 break; 17410 17411 case ConditionKind::Switch: 17412 Cond = CheckSwitchCondition(Loc, SubExpr); 17413 break; 17414 } 17415 if (Cond.isInvalid()) 17416 return ConditionError(); 17417 17418 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17419 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17420 if (!FullExpr.get()) 17421 return ConditionError(); 17422 17423 return ConditionResult(*this, nullptr, FullExpr, 17424 CK == ConditionKind::ConstexprIf); 17425 } 17426 17427 namespace { 17428 /// A visitor for rebuilding a call to an __unknown_any expression 17429 /// to have an appropriate type. 17430 struct RebuildUnknownAnyFunction 17431 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17432 17433 Sema &S; 17434 17435 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17436 17437 ExprResult VisitStmt(Stmt *S) { 17438 llvm_unreachable("unexpected statement!"); 17439 } 17440 17441 ExprResult VisitExpr(Expr *E) { 17442 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17443 << E->getSourceRange(); 17444 return ExprError(); 17445 } 17446 17447 /// Rebuild an expression which simply semantically wraps another 17448 /// expression which it shares the type and value kind of. 17449 template <class T> ExprResult rebuildSugarExpr(T *E) { 17450 ExprResult SubResult = Visit(E->getSubExpr()); 17451 if (SubResult.isInvalid()) return ExprError(); 17452 17453 Expr *SubExpr = SubResult.get(); 17454 E->setSubExpr(SubExpr); 17455 E->setType(SubExpr->getType()); 17456 E->setValueKind(SubExpr->getValueKind()); 17457 assert(E->getObjectKind() == OK_Ordinary); 17458 return E; 17459 } 17460 17461 ExprResult VisitParenExpr(ParenExpr *E) { 17462 return rebuildSugarExpr(E); 17463 } 17464 17465 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17466 return rebuildSugarExpr(E); 17467 } 17468 17469 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17470 ExprResult SubResult = Visit(E->getSubExpr()); 17471 if (SubResult.isInvalid()) return ExprError(); 17472 17473 Expr *SubExpr = SubResult.get(); 17474 E->setSubExpr(SubExpr); 17475 E->setType(S.Context.getPointerType(SubExpr->getType())); 17476 assert(E->getValueKind() == VK_RValue); 17477 assert(E->getObjectKind() == OK_Ordinary); 17478 return E; 17479 } 17480 17481 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17482 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17483 17484 E->setType(VD->getType()); 17485 17486 assert(E->getValueKind() == VK_RValue); 17487 if (S.getLangOpts().CPlusPlus && 17488 !(isa<CXXMethodDecl>(VD) && 17489 cast<CXXMethodDecl>(VD)->isInstance())) 17490 E->setValueKind(VK_LValue); 17491 17492 return E; 17493 } 17494 17495 ExprResult VisitMemberExpr(MemberExpr *E) { 17496 return resolveDecl(E, E->getMemberDecl()); 17497 } 17498 17499 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17500 return resolveDecl(E, E->getDecl()); 17501 } 17502 }; 17503 } 17504 17505 /// Given a function expression of unknown-any type, try to rebuild it 17506 /// to have a function type. 17507 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17508 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17509 if (Result.isInvalid()) return ExprError(); 17510 return S.DefaultFunctionArrayConversion(Result.get()); 17511 } 17512 17513 namespace { 17514 /// A visitor for rebuilding an expression of type __unknown_anytype 17515 /// into one which resolves the type directly on the referring 17516 /// expression. Strict preservation of the original source 17517 /// structure is not a goal. 17518 struct RebuildUnknownAnyExpr 17519 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17520 17521 Sema &S; 17522 17523 /// The current destination type. 17524 QualType DestType; 17525 17526 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17527 : S(S), DestType(CastType) {} 17528 17529 ExprResult VisitStmt(Stmt *S) { 17530 llvm_unreachable("unexpected statement!"); 17531 } 17532 17533 ExprResult VisitExpr(Expr *E) { 17534 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17535 << E->getSourceRange(); 17536 return ExprError(); 17537 } 17538 17539 ExprResult VisitCallExpr(CallExpr *E); 17540 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17541 17542 /// Rebuild an expression which simply semantically wraps another 17543 /// expression which it shares the type and value kind of. 17544 template <class T> ExprResult rebuildSugarExpr(T *E) { 17545 ExprResult SubResult = Visit(E->getSubExpr()); 17546 if (SubResult.isInvalid()) return ExprError(); 17547 Expr *SubExpr = SubResult.get(); 17548 E->setSubExpr(SubExpr); 17549 E->setType(SubExpr->getType()); 17550 E->setValueKind(SubExpr->getValueKind()); 17551 assert(E->getObjectKind() == OK_Ordinary); 17552 return E; 17553 } 17554 17555 ExprResult VisitParenExpr(ParenExpr *E) { 17556 return rebuildSugarExpr(E); 17557 } 17558 17559 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17560 return rebuildSugarExpr(E); 17561 } 17562 17563 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17564 const PointerType *Ptr = DestType->getAs<PointerType>(); 17565 if (!Ptr) { 17566 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17567 << E->getSourceRange(); 17568 return ExprError(); 17569 } 17570 17571 if (isa<CallExpr>(E->getSubExpr())) { 17572 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17573 << E->getSourceRange(); 17574 return ExprError(); 17575 } 17576 17577 assert(E->getValueKind() == VK_RValue); 17578 assert(E->getObjectKind() == OK_Ordinary); 17579 E->setType(DestType); 17580 17581 // Build the sub-expression as if it were an object of the pointee type. 17582 DestType = Ptr->getPointeeType(); 17583 ExprResult SubResult = Visit(E->getSubExpr()); 17584 if (SubResult.isInvalid()) return ExprError(); 17585 E->setSubExpr(SubResult.get()); 17586 return E; 17587 } 17588 17589 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17590 17591 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17592 17593 ExprResult VisitMemberExpr(MemberExpr *E) { 17594 return resolveDecl(E, E->getMemberDecl()); 17595 } 17596 17597 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17598 return resolveDecl(E, E->getDecl()); 17599 } 17600 }; 17601 } 17602 17603 /// Rebuilds a call expression which yielded __unknown_anytype. 17604 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17605 Expr *CalleeExpr = E->getCallee(); 17606 17607 enum FnKind { 17608 FK_MemberFunction, 17609 FK_FunctionPointer, 17610 FK_BlockPointer 17611 }; 17612 17613 FnKind Kind; 17614 QualType CalleeType = CalleeExpr->getType(); 17615 if (CalleeType == S.Context.BoundMemberTy) { 17616 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 17617 Kind = FK_MemberFunction; 17618 CalleeType = Expr::findBoundMemberType(CalleeExpr); 17619 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 17620 CalleeType = Ptr->getPointeeType(); 17621 Kind = FK_FunctionPointer; 17622 } else { 17623 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 17624 Kind = FK_BlockPointer; 17625 } 17626 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 17627 17628 // Verify that this is a legal result type of a function. 17629 if (DestType->isArrayType() || DestType->isFunctionType()) { 17630 unsigned diagID = diag::err_func_returning_array_function; 17631 if (Kind == FK_BlockPointer) 17632 diagID = diag::err_block_returning_array_function; 17633 17634 S.Diag(E->getExprLoc(), diagID) 17635 << DestType->isFunctionType() << DestType; 17636 return ExprError(); 17637 } 17638 17639 // Otherwise, go ahead and set DestType as the call's result. 17640 E->setType(DestType.getNonLValueExprType(S.Context)); 17641 E->setValueKind(Expr::getValueKindForType(DestType)); 17642 assert(E->getObjectKind() == OK_Ordinary); 17643 17644 // Rebuild the function type, replacing the result type with DestType. 17645 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 17646 if (Proto) { 17647 // __unknown_anytype(...) is a special case used by the debugger when 17648 // it has no idea what a function's signature is. 17649 // 17650 // We want to build this call essentially under the K&R 17651 // unprototyped rules, but making a FunctionNoProtoType in C++ 17652 // would foul up all sorts of assumptions. However, we cannot 17653 // simply pass all arguments as variadic arguments, nor can we 17654 // portably just call the function under a non-variadic type; see 17655 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 17656 // However, it turns out that in practice it is generally safe to 17657 // call a function declared as "A foo(B,C,D);" under the prototype 17658 // "A foo(B,C,D,...);". The only known exception is with the 17659 // Windows ABI, where any variadic function is implicitly cdecl 17660 // regardless of its normal CC. Therefore we change the parameter 17661 // types to match the types of the arguments. 17662 // 17663 // This is a hack, but it is far superior to moving the 17664 // corresponding target-specific code from IR-gen to Sema/AST. 17665 17666 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 17667 SmallVector<QualType, 8> ArgTypes; 17668 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 17669 ArgTypes.reserve(E->getNumArgs()); 17670 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 17671 Expr *Arg = E->getArg(i); 17672 QualType ArgType = Arg->getType(); 17673 if (E->isLValue()) { 17674 ArgType = S.Context.getLValueReferenceType(ArgType); 17675 } else if (E->isXValue()) { 17676 ArgType = S.Context.getRValueReferenceType(ArgType); 17677 } 17678 ArgTypes.push_back(ArgType); 17679 } 17680 ParamTypes = ArgTypes; 17681 } 17682 DestType = S.Context.getFunctionType(DestType, ParamTypes, 17683 Proto->getExtProtoInfo()); 17684 } else { 17685 DestType = S.Context.getFunctionNoProtoType(DestType, 17686 FnType->getExtInfo()); 17687 } 17688 17689 // Rebuild the appropriate pointer-to-function type. 17690 switch (Kind) { 17691 case FK_MemberFunction: 17692 // Nothing to do. 17693 break; 17694 17695 case FK_FunctionPointer: 17696 DestType = S.Context.getPointerType(DestType); 17697 break; 17698 17699 case FK_BlockPointer: 17700 DestType = S.Context.getBlockPointerType(DestType); 17701 break; 17702 } 17703 17704 // Finally, we can recurse. 17705 ExprResult CalleeResult = Visit(CalleeExpr); 17706 if (!CalleeResult.isUsable()) return ExprError(); 17707 E->setCallee(CalleeResult.get()); 17708 17709 // Bind a temporary if necessary. 17710 return S.MaybeBindToTemporary(E); 17711 } 17712 17713 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 17714 // Verify that this is a legal result type of a call. 17715 if (DestType->isArrayType() || DestType->isFunctionType()) { 17716 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 17717 << DestType->isFunctionType() << DestType; 17718 return ExprError(); 17719 } 17720 17721 // Rewrite the method result type if available. 17722 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 17723 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 17724 Method->setReturnType(DestType); 17725 } 17726 17727 // Change the type of the message. 17728 E->setType(DestType.getNonReferenceType()); 17729 E->setValueKind(Expr::getValueKindForType(DestType)); 17730 17731 return S.MaybeBindToTemporary(E); 17732 } 17733 17734 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 17735 // The only case we should ever see here is a function-to-pointer decay. 17736 if (E->getCastKind() == CK_FunctionToPointerDecay) { 17737 assert(E->getValueKind() == VK_RValue); 17738 assert(E->getObjectKind() == OK_Ordinary); 17739 17740 E->setType(DestType); 17741 17742 // Rebuild the sub-expression as the pointee (function) type. 17743 DestType = DestType->castAs<PointerType>()->getPointeeType(); 17744 17745 ExprResult Result = Visit(E->getSubExpr()); 17746 if (!Result.isUsable()) return ExprError(); 17747 17748 E->setSubExpr(Result.get()); 17749 return E; 17750 } else if (E->getCastKind() == CK_LValueToRValue) { 17751 assert(E->getValueKind() == VK_RValue); 17752 assert(E->getObjectKind() == OK_Ordinary); 17753 17754 assert(isa<BlockPointerType>(E->getType())); 17755 17756 E->setType(DestType); 17757 17758 // The sub-expression has to be a lvalue reference, so rebuild it as such. 17759 DestType = S.Context.getLValueReferenceType(DestType); 17760 17761 ExprResult Result = Visit(E->getSubExpr()); 17762 if (!Result.isUsable()) return ExprError(); 17763 17764 E->setSubExpr(Result.get()); 17765 return E; 17766 } else { 17767 llvm_unreachable("Unhandled cast type!"); 17768 } 17769 } 17770 17771 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 17772 ExprValueKind ValueKind = VK_LValue; 17773 QualType Type = DestType; 17774 17775 // We know how to make this work for certain kinds of decls: 17776 17777 // - functions 17778 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 17779 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 17780 DestType = Ptr->getPointeeType(); 17781 ExprResult Result = resolveDecl(E, VD); 17782 if (Result.isInvalid()) return ExprError(); 17783 return S.ImpCastExprToType(Result.get(), Type, 17784 CK_FunctionToPointerDecay, VK_RValue); 17785 } 17786 17787 if (!Type->isFunctionType()) { 17788 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 17789 << VD << E->getSourceRange(); 17790 return ExprError(); 17791 } 17792 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 17793 // We must match the FunctionDecl's type to the hack introduced in 17794 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 17795 // type. See the lengthy commentary in that routine. 17796 QualType FDT = FD->getType(); 17797 const FunctionType *FnType = FDT->castAs<FunctionType>(); 17798 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 17799 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 17800 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 17801 SourceLocation Loc = FD->getLocation(); 17802 FunctionDecl *NewFD = FunctionDecl::Create( 17803 S.Context, FD->getDeclContext(), Loc, Loc, 17804 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 17805 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 17806 /*ConstexprKind*/ CSK_unspecified); 17807 17808 if (FD->getQualifier()) 17809 NewFD->setQualifierInfo(FD->getQualifierLoc()); 17810 17811 SmallVector<ParmVarDecl*, 16> Params; 17812 for (const auto &AI : FT->param_types()) { 17813 ParmVarDecl *Param = 17814 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 17815 Param->setScopeInfo(0, Params.size()); 17816 Params.push_back(Param); 17817 } 17818 NewFD->setParams(Params); 17819 DRE->setDecl(NewFD); 17820 VD = DRE->getDecl(); 17821 } 17822 } 17823 17824 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 17825 if (MD->isInstance()) { 17826 ValueKind = VK_RValue; 17827 Type = S.Context.BoundMemberTy; 17828 } 17829 17830 // Function references aren't l-values in C. 17831 if (!S.getLangOpts().CPlusPlus) 17832 ValueKind = VK_RValue; 17833 17834 // - variables 17835 } else if (isa<VarDecl>(VD)) { 17836 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 17837 Type = RefTy->getPointeeType(); 17838 } else if (Type->isFunctionType()) { 17839 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 17840 << VD << E->getSourceRange(); 17841 return ExprError(); 17842 } 17843 17844 // - nothing else 17845 } else { 17846 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 17847 << VD << E->getSourceRange(); 17848 return ExprError(); 17849 } 17850 17851 // Modifying the declaration like this is friendly to IR-gen but 17852 // also really dangerous. 17853 VD->setType(DestType); 17854 E->setType(Type); 17855 E->setValueKind(ValueKind); 17856 return E; 17857 } 17858 17859 /// Check a cast of an unknown-any type. We intentionally only 17860 /// trigger this for C-style casts. 17861 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 17862 Expr *CastExpr, CastKind &CastKind, 17863 ExprValueKind &VK, CXXCastPath &Path) { 17864 // The type we're casting to must be either void or complete. 17865 if (!CastType->isVoidType() && 17866 RequireCompleteType(TypeRange.getBegin(), CastType, 17867 diag::err_typecheck_cast_to_incomplete)) 17868 return ExprError(); 17869 17870 // Rewrite the casted expression from scratch. 17871 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 17872 if (!result.isUsable()) return ExprError(); 17873 17874 CastExpr = result.get(); 17875 VK = CastExpr->getValueKind(); 17876 CastKind = CK_NoOp; 17877 17878 return CastExpr; 17879 } 17880 17881 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 17882 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 17883 } 17884 17885 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 17886 Expr *arg, QualType ¶mType) { 17887 // If the syntactic form of the argument is not an explicit cast of 17888 // any sort, just do default argument promotion. 17889 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 17890 if (!castArg) { 17891 ExprResult result = DefaultArgumentPromotion(arg); 17892 if (result.isInvalid()) return ExprError(); 17893 paramType = result.get()->getType(); 17894 return result; 17895 } 17896 17897 // Otherwise, use the type that was written in the explicit cast. 17898 assert(!arg->hasPlaceholderType()); 17899 paramType = castArg->getTypeAsWritten(); 17900 17901 // Copy-initialize a parameter of that type. 17902 InitializedEntity entity = 17903 InitializedEntity::InitializeParameter(Context, paramType, 17904 /*consumed*/ false); 17905 return PerformCopyInitialization(entity, callLoc, arg); 17906 } 17907 17908 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 17909 Expr *orig = E; 17910 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 17911 while (true) { 17912 E = E->IgnoreParenImpCasts(); 17913 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 17914 E = call->getCallee(); 17915 diagID = diag::err_uncasted_call_of_unknown_any; 17916 } else { 17917 break; 17918 } 17919 } 17920 17921 SourceLocation loc; 17922 NamedDecl *d; 17923 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 17924 loc = ref->getLocation(); 17925 d = ref->getDecl(); 17926 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 17927 loc = mem->getMemberLoc(); 17928 d = mem->getMemberDecl(); 17929 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 17930 diagID = diag::err_uncasted_call_of_unknown_any; 17931 loc = msg->getSelectorStartLoc(); 17932 d = msg->getMethodDecl(); 17933 if (!d) { 17934 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 17935 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 17936 << orig->getSourceRange(); 17937 return ExprError(); 17938 } 17939 } else { 17940 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17941 << E->getSourceRange(); 17942 return ExprError(); 17943 } 17944 17945 S.Diag(loc, diagID) << d << orig->getSourceRange(); 17946 17947 // Never recoverable. 17948 return ExprError(); 17949 } 17950 17951 /// Check for operands with placeholder types and complain if found. 17952 /// Returns ExprError() if there was an error and no recovery was possible. 17953 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 17954 if (!getLangOpts().CPlusPlus) { 17955 // C cannot handle TypoExpr nodes on either side of a binop because it 17956 // doesn't handle dependent types properly, so make sure any TypoExprs have 17957 // been dealt with before checking the operands. 17958 ExprResult Result = CorrectDelayedTyposInExpr(E); 17959 if (!Result.isUsable()) return ExprError(); 17960 E = Result.get(); 17961 } 17962 17963 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 17964 if (!placeholderType) return E; 17965 17966 switch (placeholderType->getKind()) { 17967 17968 // Overloaded expressions. 17969 case BuiltinType::Overload: { 17970 // Try to resolve a single function template specialization. 17971 // This is obligatory. 17972 ExprResult Result = E; 17973 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 17974 return Result; 17975 17976 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 17977 // leaves Result unchanged on failure. 17978 Result = E; 17979 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 17980 return Result; 17981 17982 // If that failed, try to recover with a call. 17983 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 17984 /*complain*/ true); 17985 return Result; 17986 } 17987 17988 // Bound member functions. 17989 case BuiltinType::BoundMember: { 17990 ExprResult result = E; 17991 const Expr *BME = E->IgnoreParens(); 17992 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 17993 // Try to give a nicer diagnostic if it is a bound member that we recognize. 17994 if (isa<CXXPseudoDestructorExpr>(BME)) { 17995 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 17996 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 17997 if (ME->getMemberNameInfo().getName().getNameKind() == 17998 DeclarationName::CXXDestructorName) 17999 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18000 } 18001 tryToRecoverWithCall(result, PD, 18002 /*complain*/ true); 18003 return result; 18004 } 18005 18006 // ARC unbridged casts. 18007 case BuiltinType::ARCUnbridgedCast: { 18008 Expr *realCast = stripARCUnbridgedCast(E); 18009 diagnoseARCUnbridgedCast(realCast); 18010 return realCast; 18011 } 18012 18013 // Expressions of unknown type. 18014 case BuiltinType::UnknownAny: 18015 return diagnoseUnknownAnyExpr(*this, E); 18016 18017 // Pseudo-objects. 18018 case BuiltinType::PseudoObject: 18019 return checkPseudoObjectRValue(E); 18020 18021 case BuiltinType::BuiltinFn: { 18022 // Accept __noop without parens by implicitly converting it to a call expr. 18023 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18024 if (DRE) { 18025 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18026 if (FD->getBuiltinID() == Builtin::BI__noop) { 18027 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18028 CK_BuiltinFnToFnPtr) 18029 .get(); 18030 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18031 VK_RValue, SourceLocation()); 18032 } 18033 } 18034 18035 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18036 return ExprError(); 18037 } 18038 18039 // Expressions of unknown type. 18040 case BuiltinType::OMPArraySection: 18041 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18042 return ExprError(); 18043 18044 // Everything else should be impossible. 18045 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18046 case BuiltinType::Id: 18047 #include "clang/Basic/OpenCLImageTypes.def" 18048 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18049 case BuiltinType::Id: 18050 #include "clang/Basic/OpenCLExtensionTypes.def" 18051 #define SVE_TYPE(Name, Id, SingletonId) \ 18052 case BuiltinType::Id: 18053 #include "clang/Basic/AArch64SVEACLETypes.def" 18054 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18055 #define PLACEHOLDER_TYPE(Id, SingletonId) 18056 #include "clang/AST/BuiltinTypes.def" 18057 break; 18058 } 18059 18060 llvm_unreachable("invalid placeholder type!"); 18061 } 18062 18063 bool Sema::CheckCaseExpression(Expr *E) { 18064 if (E->isTypeDependent()) 18065 return true; 18066 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18067 return E->getType()->isIntegralOrEnumerationType(); 18068 return false; 18069 } 18070 18071 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18072 ExprResult 18073 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18074 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18075 "Unknown Objective-C Boolean value!"); 18076 QualType BoolT = Context.ObjCBuiltinBoolTy; 18077 if (!Context.getBOOLDecl()) { 18078 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18079 Sema::LookupOrdinaryName); 18080 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18081 NamedDecl *ND = Result.getFoundDecl(); 18082 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18083 Context.setBOOLDecl(TD); 18084 } 18085 } 18086 if (Context.getBOOLDecl()) 18087 BoolT = Context.getBOOLType(); 18088 return new (Context) 18089 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18090 } 18091 18092 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18093 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18094 SourceLocation RParen) { 18095 18096 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18097 18098 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18099 return Spec.getPlatform() == Platform; 18100 }); 18101 18102 VersionTuple Version; 18103 if (Spec != AvailSpecs.end()) 18104 Version = Spec->getVersion(); 18105 18106 // The use of `@available` in the enclosing function should be analyzed to 18107 // warn when it's used inappropriately (i.e. not if(@available)). 18108 if (getCurFunctionOrMethodDecl()) 18109 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18110 else if (getCurBlock() || getCurLambda()) 18111 getCurFunction()->HasPotentialAvailabilityViolations = true; 18112 18113 return new (Context) 18114 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18115 } 18116