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 "UsedDeclVisitor.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/FixedPoint.h" 31 #include "clang/Basic/PartialDiagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Lex/LiteralSupport.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Sema/AnalysisBasedWarnings.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Designator.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/Overload.h" 43 #include "clang/Sema/ParsedTemplate.h" 44 #include "clang/Sema/Scope.h" 45 #include "clang/Sema/ScopeInfo.h" 46 #include "clang/Sema/SemaFixItUtils.h" 47 #include "clang/Sema/SemaInternal.h" 48 #include "clang/Sema/Template.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/SaveAndRestore.h" 51 using namespace clang; 52 using namespace sema; 53 54 /// Determine whether the use of this declaration is valid, without 55 /// emitting diagnostics. 56 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 57 // See if this is an auto-typed variable whose initializer we are parsing. 58 if (ParsingInitForAutoVars.count(D)) 59 return false; 60 61 // See if this is a deleted function. 62 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 63 if (FD->isDeleted()) 64 return false; 65 66 // If the function has a deduced return type, and we can't deduce it, 67 // then we can't use it either. 68 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 69 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 70 return false; 71 72 // See if this is an aligned allocation/deallocation function that is 73 // unavailable. 74 if (TreatUnavailableAsInvalid && 75 isUnavailableAlignedAllocationFunction(*FD)) 76 return false; 77 } 78 79 // See if this function is unavailable. 80 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 81 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 82 return false; 83 84 return true; 85 } 86 87 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 88 // Warn if this is used but marked unused. 89 if (const auto *A = D->getAttr<UnusedAttr>()) { 90 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 91 // should diagnose them. 92 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 93 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 94 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 95 if (DC && !DC->hasAttr<UnusedAttr>()) 96 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 97 } 98 } 99 } 100 101 /// Emit a note explaining that this function is deleted. 102 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 103 assert(Decl && Decl->isDeleted()); 104 105 if (Decl->isDefaulted()) { 106 // If the method was explicitly defaulted, point at that declaration. 107 if (!Decl->isImplicit()) 108 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 109 110 // Try to diagnose why this special member function was implicitly 111 // deleted. This might fail, if that reason no longer applies. 112 DiagnoseDeletedDefaultedFunction(Decl); 113 return; 114 } 115 116 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 117 if (Ctor && Ctor->isInheritingConstructor()) 118 return NoteDeletedInheritingConstructor(Ctor); 119 120 Diag(Decl->getLocation(), diag::note_availability_specified_here) 121 << Decl << 1; 122 } 123 124 /// Determine whether a FunctionDecl was ever declared with an 125 /// explicit storage class. 126 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 127 for (auto I : D->redecls()) { 128 if (I->getStorageClass() != SC_None) 129 return true; 130 } 131 return false; 132 } 133 134 /// Check whether we're in an extern inline function and referring to a 135 /// variable or function with internal linkage (C11 6.7.4p3). 136 /// 137 /// This is only a warning because we used to silently accept this code, but 138 /// in many cases it will not behave correctly. This is not enabled in C++ mode 139 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 140 /// and so while there may still be user mistakes, most of the time we can't 141 /// prove that there are errors. 142 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 143 const NamedDecl *D, 144 SourceLocation Loc) { 145 // This is disabled under C++; there are too many ways for this to fire in 146 // contexts where the warning is a false positive, or where it is technically 147 // correct but benign. 148 if (S.getLangOpts().CPlusPlus) 149 return; 150 151 // Check if this is an inlined function or method. 152 FunctionDecl *Current = S.getCurFunctionDecl(); 153 if (!Current) 154 return; 155 if (!Current->isInlined()) 156 return; 157 if (!Current->isExternallyVisible()) 158 return; 159 160 // Check if the decl has internal linkage. 161 if (D->getFormalLinkage() != InternalLinkage) 162 return; 163 164 // Downgrade from ExtWarn to Extension if 165 // (1) the supposedly external inline function is in the main file, 166 // and probably won't be included anywhere else. 167 // (2) the thing we're referencing is a pure function. 168 // (3) the thing we're referencing is another inline function. 169 // This last can give us false negatives, but it's better than warning on 170 // wrappers for simple C library functions. 171 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 172 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 173 if (!DowngradeWarning && UsedFn) 174 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 175 176 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 177 : diag::ext_internal_in_extern_inline) 178 << /*IsVar=*/!UsedFn << D; 179 180 S.MaybeSuggestAddingStaticToDecl(Current); 181 182 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 183 << D; 184 } 185 186 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 187 const FunctionDecl *First = Cur->getFirstDecl(); 188 189 // Suggest "static" on the function, if possible. 190 if (!hasAnyExplicitStorageClass(First)) { 191 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 192 Diag(DeclBegin, diag::note_convert_inline_to_static) 193 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 194 } 195 } 196 197 /// Determine whether the use of this declaration is valid, and 198 /// emit any corresponding diagnostics. 199 /// 200 /// This routine diagnoses various problems with referencing 201 /// declarations that can occur when using a declaration. For example, 202 /// it might warn if a deprecated or unavailable declaration is being 203 /// used, or produce an error (and return true) if a C++0x deleted 204 /// function is being used. 205 /// 206 /// \returns true if there was an error (this declaration cannot be 207 /// referenced), false otherwise. 208 /// 209 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 210 const ObjCInterfaceDecl *UnknownObjCClass, 211 bool ObjCPropertyAccess, 212 bool AvoidPartialAvailabilityChecks, 213 ObjCInterfaceDecl *ClassReceiver) { 214 SourceLocation Loc = Locs.front(); 215 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 216 // If there were any diagnostics suppressed by template argument deduction, 217 // emit them now. 218 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 219 if (Pos != SuppressedDiagnostics.end()) { 220 for (const PartialDiagnosticAt &Suppressed : Pos->second) 221 Diag(Suppressed.first, Suppressed.second); 222 223 // Clear out the list of suppressed diagnostics, so that we don't emit 224 // them again for this specialization. However, we don't obsolete this 225 // entry from the table, because we want to avoid ever emitting these 226 // diagnostics again. 227 Pos->second.clear(); 228 } 229 230 // C++ [basic.start.main]p3: 231 // The function 'main' shall not be used within a program. 232 if (cast<FunctionDecl>(D)->isMain()) 233 Diag(Loc, diag::ext_main_used); 234 235 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 236 } 237 238 // See if this is an auto-typed variable whose initializer we are parsing. 239 if (ParsingInitForAutoVars.count(D)) { 240 if (isa<BindingDecl>(D)) { 241 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 242 << D->getDeclName(); 243 } else { 244 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 245 << D->getDeclName() << cast<VarDecl>(D)->getType(); 246 } 247 return true; 248 } 249 250 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 251 // See if this is a deleted function. 252 if (FD->isDeleted()) { 253 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 254 if (Ctor && Ctor->isInheritingConstructor()) 255 Diag(Loc, diag::err_deleted_inherited_ctor_use) 256 << Ctor->getParent() 257 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 258 else 259 Diag(Loc, diag::err_deleted_function_use); 260 NoteDeletedFunction(FD); 261 return true; 262 } 263 264 // [expr.prim.id]p4 265 // A program that refers explicitly or implicitly to a function with a 266 // trailing requires-clause whose constraint-expression is not satisfied, 267 // other than to declare it, is ill-formed. [...] 268 // 269 // See if this is a function with constraints that need to be satisfied. 270 // Check this before deducing the return type, as it might instantiate the 271 // definition. 272 if (FD->getTrailingRequiresClause()) { 273 ConstraintSatisfaction Satisfaction; 274 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 275 // A diagnostic will have already been generated (non-constant 276 // constraint expression, for example) 277 return true; 278 if (!Satisfaction.IsSatisfied) { 279 Diag(Loc, 280 diag::err_reference_to_function_with_unsatisfied_constraints) 281 << D; 282 DiagnoseUnsatisfiedConstraint(Satisfaction); 283 return true; 284 } 285 } 286 287 // If the function has a deduced return type, and we can't deduce it, 288 // then we can't use it either. 289 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 290 DeduceReturnType(FD, Loc)) 291 return true; 292 293 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 294 return true; 295 } 296 297 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 298 // Lambdas are only default-constructible or assignable in C++2a onwards. 299 if (MD->getParent()->isLambda() && 300 ((isa<CXXConstructorDecl>(MD) && 301 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 302 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 303 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 304 << !isa<CXXConstructorDecl>(MD); 305 } 306 } 307 308 auto getReferencedObjCProp = [](const NamedDecl *D) -> 309 const ObjCPropertyDecl * { 310 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 311 return MD->findPropertyDecl(); 312 return nullptr; 313 }; 314 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 315 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 316 return true; 317 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 318 return true; 319 } 320 321 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 322 // Only the variables omp_in and omp_out are allowed in the combiner. 323 // Only the variables omp_priv and omp_orig are allowed in the 324 // initializer-clause. 325 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 326 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 327 isa<VarDecl>(D)) { 328 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 329 << getCurFunction()->HasOMPDeclareReductionCombiner; 330 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 331 return true; 332 } 333 334 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 335 // List-items in map clauses on this construct may only refer to the declared 336 // variable var and entities that could be referenced by a procedure defined 337 // at the same location 338 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext); 339 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) && 340 isa<VarDecl>(D)) { 341 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 342 << DMD->getVarName().getAsString(); 343 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 344 return true; 345 } 346 347 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 348 AvoidPartialAvailabilityChecks, ClassReceiver); 349 350 DiagnoseUnusedOfDecl(*this, D, Loc); 351 352 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 353 354 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 355 !isUnevaluatedContext()) { 356 // C++ [expr.prim.req.nested] p3 357 // A local parameter shall only appear as an unevaluated operand 358 // (Clause 8) within the constraint-expression. 359 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 360 << D; 361 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 362 return true; 363 } 364 365 return false; 366 } 367 368 /// DiagnoseSentinelCalls - This routine checks whether a call or 369 /// message-send is to a declaration with the sentinel attribute, and 370 /// if so, it checks that the requirements of the sentinel are 371 /// satisfied. 372 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 373 ArrayRef<Expr *> Args) { 374 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 375 if (!attr) 376 return; 377 378 // The number of formal parameters of the declaration. 379 unsigned numFormalParams; 380 381 // The kind of declaration. This is also an index into a %select in 382 // the diagnostic. 383 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 384 385 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 386 numFormalParams = MD->param_size(); 387 calleeType = CT_Method; 388 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 389 numFormalParams = FD->param_size(); 390 calleeType = CT_Function; 391 } else if (isa<VarDecl>(D)) { 392 QualType type = cast<ValueDecl>(D)->getType(); 393 const FunctionType *fn = nullptr; 394 if (const PointerType *ptr = type->getAs<PointerType>()) { 395 fn = ptr->getPointeeType()->getAs<FunctionType>(); 396 if (!fn) return; 397 calleeType = CT_Function; 398 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 399 fn = ptr->getPointeeType()->castAs<FunctionType>(); 400 calleeType = CT_Block; 401 } else { 402 return; 403 } 404 405 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 406 numFormalParams = proto->getNumParams(); 407 } else { 408 numFormalParams = 0; 409 } 410 } else { 411 return; 412 } 413 414 // "nullPos" is the number of formal parameters at the end which 415 // effectively count as part of the variadic arguments. This is 416 // useful if you would prefer to not have *any* formal parameters, 417 // but the language forces you to have at least one. 418 unsigned nullPos = attr->getNullPos(); 419 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 420 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 421 422 // The number of arguments which should follow the sentinel. 423 unsigned numArgsAfterSentinel = attr->getSentinel(); 424 425 // If there aren't enough arguments for all the formal parameters, 426 // the sentinel, and the args after the sentinel, complain. 427 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 428 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 429 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 430 return; 431 } 432 433 // Otherwise, find the sentinel expression. 434 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 435 if (!sentinelExpr) return; 436 if (sentinelExpr->isValueDependent()) return; 437 if (Context.isSentinelNullExpr(sentinelExpr)) return; 438 439 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 440 // or 'NULL' if those are actually defined in the context. Only use 441 // 'nil' for ObjC methods, where it's much more likely that the 442 // variadic arguments form a list of object pointers. 443 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 444 std::string NullValue; 445 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 446 NullValue = "nil"; 447 else if (getLangOpts().CPlusPlus11) 448 NullValue = "nullptr"; 449 else if (PP.isMacroDefined("NULL")) 450 NullValue = "NULL"; 451 else 452 NullValue = "(void*) 0"; 453 454 if (MissingNilLoc.isInvalid()) 455 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 456 else 457 Diag(MissingNilLoc, diag::warn_missing_sentinel) 458 << int(calleeType) 459 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 460 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 461 } 462 463 SourceRange Sema::getExprRange(Expr *E) const { 464 return E ? E->getSourceRange() : SourceRange(); 465 } 466 467 //===----------------------------------------------------------------------===// 468 // Standard Promotions and Conversions 469 //===----------------------------------------------------------------------===// 470 471 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 472 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 473 // Handle any placeholder expressions which made it here. 474 if (E->getType()->isPlaceholderType()) { 475 ExprResult result = CheckPlaceholderExpr(E); 476 if (result.isInvalid()) return ExprError(); 477 E = result.get(); 478 } 479 480 QualType Ty = E->getType(); 481 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 482 483 if (Ty->isFunctionType()) { 484 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 485 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 486 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 487 return ExprError(); 488 489 E = ImpCastExprToType(E, Context.getPointerType(Ty), 490 CK_FunctionToPointerDecay).get(); 491 } else if (Ty->isArrayType()) { 492 // In C90 mode, arrays only promote to pointers if the array expression is 493 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 494 // type 'array of type' is converted to an expression that has type 'pointer 495 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 496 // that has type 'array of type' ...". The relevant change is "an lvalue" 497 // (C90) to "an expression" (C99). 498 // 499 // C++ 4.2p1: 500 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 501 // T" can be converted to an rvalue of type "pointer to T". 502 // 503 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 504 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 505 CK_ArrayToPointerDecay).get(); 506 } 507 return E; 508 } 509 510 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 511 // Check to see if we are dereferencing a null pointer. If so, 512 // and if not volatile-qualified, this is undefined behavior that the 513 // optimizer will delete, so warn about it. People sometimes try to use this 514 // to get a deterministic trap and are surprised by clang's behavior. This 515 // only handles the pattern "*null", which is a very syntactic check. 516 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 517 if (UO && UO->getOpcode() == UO_Deref && 518 UO->getSubExpr()->getType()->isPointerType()) { 519 const LangAS AS = 520 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 521 if ((!isTargetAddressSpace(AS) || 522 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 523 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 524 S.Context, Expr::NPC_ValueDependentIsNotNull) && 525 !UO->getType().isVolatileQualified()) { 526 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 527 S.PDiag(diag::warn_indirection_through_null) 528 << UO->getSubExpr()->getSourceRange()); 529 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 530 S.PDiag(diag::note_indirection_through_null)); 531 } 532 } 533 } 534 535 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 536 SourceLocation AssignLoc, 537 const Expr* RHS) { 538 const ObjCIvarDecl *IV = OIRE->getDecl(); 539 if (!IV) 540 return; 541 542 DeclarationName MemberName = IV->getDeclName(); 543 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 544 if (!Member || !Member->isStr("isa")) 545 return; 546 547 const Expr *Base = OIRE->getBase(); 548 QualType BaseType = Base->getType(); 549 if (OIRE->isArrow()) 550 BaseType = BaseType->getPointeeType(); 551 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 552 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 553 ObjCInterfaceDecl *ClassDeclared = nullptr; 554 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 555 if (!ClassDeclared->getSuperClass() 556 && (*ClassDeclared->ivar_begin()) == IV) { 557 if (RHS) { 558 NamedDecl *ObjectSetClass = 559 S.LookupSingleName(S.TUScope, 560 &S.Context.Idents.get("object_setClass"), 561 SourceLocation(), S.LookupOrdinaryName); 562 if (ObjectSetClass) { 563 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 564 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 565 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 566 "object_setClass(") 567 << FixItHint::CreateReplacement( 568 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 569 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 570 } 571 else 572 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 573 } else { 574 NamedDecl *ObjectGetClass = 575 S.LookupSingleName(S.TUScope, 576 &S.Context.Idents.get("object_getClass"), 577 SourceLocation(), S.LookupOrdinaryName); 578 if (ObjectGetClass) 579 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 580 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 581 "object_getClass(") 582 << FixItHint::CreateReplacement( 583 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 584 else 585 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 586 } 587 S.Diag(IV->getLocation(), diag::note_ivar_decl); 588 } 589 } 590 } 591 592 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 593 // Handle any placeholder expressions which made it here. 594 if (E->getType()->isPlaceholderType()) { 595 ExprResult result = CheckPlaceholderExpr(E); 596 if (result.isInvalid()) return ExprError(); 597 E = result.get(); 598 } 599 600 // C++ [conv.lval]p1: 601 // A glvalue of a non-function, non-array type T can be 602 // converted to a prvalue. 603 if (!E->isGLValue()) return E; 604 605 QualType T = E->getType(); 606 assert(!T.isNull() && "r-value conversion on typeless expression?"); 607 608 // We don't want to throw lvalue-to-rvalue casts on top of 609 // expressions of certain types in C++. 610 if (getLangOpts().CPlusPlus && 611 (E->getType() == Context.OverloadTy || 612 T->isDependentType() || 613 T->isRecordType())) 614 return E; 615 616 // The C standard is actually really unclear on this point, and 617 // DR106 tells us what the result should be but not why. It's 618 // generally best to say that void types just doesn't undergo 619 // lvalue-to-rvalue at all. Note that expressions of unqualified 620 // 'void' type are never l-values, but qualified void can be. 621 if (T->isVoidType()) 622 return E; 623 624 // OpenCL usually rejects direct accesses to values of 'half' type. 625 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 626 T->isHalfType()) { 627 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 628 << 0 << T; 629 return ExprError(); 630 } 631 632 CheckForNullPointerDereference(*this, E); 633 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 634 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 635 &Context.Idents.get("object_getClass"), 636 SourceLocation(), LookupOrdinaryName); 637 if (ObjectGetClass) 638 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 639 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 640 << FixItHint::CreateReplacement( 641 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 642 else 643 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 644 } 645 else if (const ObjCIvarRefExpr *OIRE = 646 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 647 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 648 649 // C++ [conv.lval]p1: 650 // [...] If T is a non-class type, the type of the prvalue is the 651 // cv-unqualified version of T. Otherwise, the type of the 652 // rvalue is T. 653 // 654 // C99 6.3.2.1p2: 655 // If the lvalue has qualified type, the value has the unqualified 656 // version of the type of the lvalue; otherwise, the value has the 657 // type of the lvalue. 658 if (T.hasQualifiers()) 659 T = T.getUnqualifiedType(); 660 661 // Under the MS ABI, lock down the inheritance model now. 662 if (T->isMemberPointerType() && 663 Context.getTargetInfo().getCXXABI().isMicrosoft()) 664 (void)isCompleteType(E->getExprLoc(), T); 665 666 ExprResult Res = CheckLValueToRValueConversionOperand(E); 667 if (Res.isInvalid()) 668 return Res; 669 E = Res.get(); 670 671 // Loading a __weak object implicitly retains the value, so we need a cleanup to 672 // balance that. 673 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 674 Cleanup.setExprNeedsCleanups(true); 675 676 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 677 Cleanup.setExprNeedsCleanups(true); 678 679 // C++ [conv.lval]p3: 680 // If T is cv std::nullptr_t, the result is a null pointer constant. 681 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 682 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue); 683 684 // C11 6.3.2.1p2: 685 // ... if the lvalue has atomic type, the value has the non-atomic version 686 // of the type of the lvalue ... 687 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 688 T = Atomic->getValueType().getUnqualifiedType(); 689 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 690 nullptr, VK_RValue); 691 } 692 693 return Res; 694 } 695 696 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 697 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 698 if (Res.isInvalid()) 699 return ExprError(); 700 Res = DefaultLvalueConversion(Res.get()); 701 if (Res.isInvalid()) 702 return ExprError(); 703 return Res; 704 } 705 706 /// CallExprUnaryConversions - a special case of an unary conversion 707 /// performed on a function designator of a call expression. 708 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 709 QualType Ty = E->getType(); 710 ExprResult Res = E; 711 // Only do implicit cast for a function type, but not for a pointer 712 // to function type. 713 if (Ty->isFunctionType()) { 714 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 715 CK_FunctionToPointerDecay).get(); 716 if (Res.isInvalid()) 717 return ExprError(); 718 } 719 Res = DefaultLvalueConversion(Res.get()); 720 if (Res.isInvalid()) 721 return ExprError(); 722 return Res.get(); 723 } 724 725 /// UsualUnaryConversions - Performs various conversions that are common to most 726 /// operators (C99 6.3). The conversions of array and function types are 727 /// sometimes suppressed. For example, the array->pointer conversion doesn't 728 /// apply if the array is an argument to the sizeof or address (&) operators. 729 /// In these instances, this routine should *not* be called. 730 ExprResult Sema::UsualUnaryConversions(Expr *E) { 731 // First, convert to an r-value. 732 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 733 if (Res.isInvalid()) 734 return ExprError(); 735 E = Res.get(); 736 737 QualType Ty = E->getType(); 738 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 739 740 // Half FP have to be promoted to float unless it is natively supported 741 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 742 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 743 744 // Try to perform integral promotions if the object has a theoretically 745 // promotable type. 746 if (Ty->isIntegralOrUnscopedEnumerationType()) { 747 // C99 6.3.1.1p2: 748 // 749 // The following may be used in an expression wherever an int or 750 // unsigned int may be used: 751 // - an object or expression with an integer type whose integer 752 // conversion rank is less than or equal to the rank of int 753 // and unsigned int. 754 // - A bit-field of type _Bool, int, signed int, or unsigned int. 755 // 756 // If an int can represent all values of the original type, the 757 // value is converted to an int; otherwise, it is converted to an 758 // unsigned int. These are called the integer promotions. All 759 // other types are unchanged by the integer promotions. 760 761 QualType PTy = Context.isPromotableBitField(E); 762 if (!PTy.isNull()) { 763 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 764 return E; 765 } 766 if (Ty->isPromotableIntegerType()) { 767 QualType PT = Context.getPromotedIntegerType(Ty); 768 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 769 return E; 770 } 771 } 772 return E; 773 } 774 775 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 776 /// do not have a prototype. Arguments that have type float or __fp16 777 /// are promoted to double. All other argument types are converted by 778 /// UsualUnaryConversions(). 779 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 780 QualType Ty = E->getType(); 781 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 782 783 ExprResult Res = UsualUnaryConversions(E); 784 if (Res.isInvalid()) 785 return ExprError(); 786 E = Res.get(); 787 788 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 789 // promote to double. 790 // Note that default argument promotion applies only to float (and 791 // half/fp16); it does not apply to _Float16. 792 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 793 if (BTy && (BTy->getKind() == BuiltinType::Half || 794 BTy->getKind() == BuiltinType::Float)) { 795 if (getLangOpts().OpenCL && 796 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 797 if (BTy->getKind() == BuiltinType::Half) { 798 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 799 } 800 } else { 801 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 802 } 803 } 804 805 // C++ performs lvalue-to-rvalue conversion as a default argument 806 // promotion, even on class types, but note: 807 // C++11 [conv.lval]p2: 808 // When an lvalue-to-rvalue conversion occurs in an unevaluated 809 // operand or a subexpression thereof the value contained in the 810 // referenced object is not accessed. Otherwise, if the glvalue 811 // has a class type, the conversion copy-initializes a temporary 812 // of type T from the glvalue and the result of the conversion 813 // is a prvalue for the temporary. 814 // FIXME: add some way to gate this entire thing for correctness in 815 // potentially potentially evaluated contexts. 816 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 817 ExprResult Temp = PerformCopyInitialization( 818 InitializedEntity::InitializeTemporary(E->getType()), 819 E->getExprLoc(), E); 820 if (Temp.isInvalid()) 821 return ExprError(); 822 E = Temp.get(); 823 } 824 825 return E; 826 } 827 828 /// Determine the degree of POD-ness for an expression. 829 /// Incomplete types are considered POD, since this check can be performed 830 /// when we're in an unevaluated context. 831 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 832 if (Ty->isIncompleteType()) { 833 // C++11 [expr.call]p7: 834 // After these conversions, if the argument does not have arithmetic, 835 // enumeration, pointer, pointer to member, or class type, the program 836 // is ill-formed. 837 // 838 // Since we've already performed array-to-pointer and function-to-pointer 839 // decay, the only such type in C++ is cv void. This also handles 840 // initializer lists as variadic arguments. 841 if (Ty->isVoidType()) 842 return VAK_Invalid; 843 844 if (Ty->isObjCObjectType()) 845 return VAK_Invalid; 846 return VAK_Valid; 847 } 848 849 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 850 return VAK_Invalid; 851 852 if (Ty.isCXX98PODType(Context)) 853 return VAK_Valid; 854 855 // C++11 [expr.call]p7: 856 // Passing a potentially-evaluated argument of class type (Clause 9) 857 // having a non-trivial copy constructor, a non-trivial move constructor, 858 // or a non-trivial destructor, with no corresponding parameter, 859 // is conditionally-supported with implementation-defined semantics. 860 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 861 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 862 if (!Record->hasNonTrivialCopyConstructor() && 863 !Record->hasNonTrivialMoveConstructor() && 864 !Record->hasNonTrivialDestructor()) 865 return VAK_ValidInCXX11; 866 867 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 868 return VAK_Valid; 869 870 if (Ty->isObjCObjectType()) 871 return VAK_Invalid; 872 873 if (getLangOpts().MSVCCompat) 874 return VAK_MSVCUndefined; 875 876 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 877 // permitted to reject them. We should consider doing so. 878 return VAK_Undefined; 879 } 880 881 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 882 // Don't allow one to pass an Objective-C interface to a vararg. 883 const QualType &Ty = E->getType(); 884 VarArgKind VAK = isValidVarArgType(Ty); 885 886 // Complain about passing non-POD types through varargs. 887 switch (VAK) { 888 case VAK_ValidInCXX11: 889 DiagRuntimeBehavior( 890 E->getBeginLoc(), nullptr, 891 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 892 LLVM_FALLTHROUGH; 893 case VAK_Valid: 894 if (Ty->isRecordType()) { 895 // This is unlikely to be what the user intended. If the class has a 896 // 'c_str' member function, the user probably meant to call that. 897 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 898 PDiag(diag::warn_pass_class_arg_to_vararg) 899 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 900 } 901 break; 902 903 case VAK_Undefined: 904 case VAK_MSVCUndefined: 905 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 906 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 907 << getLangOpts().CPlusPlus11 << Ty << CT); 908 break; 909 910 case VAK_Invalid: 911 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 912 Diag(E->getBeginLoc(), 913 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 914 << Ty << CT; 915 else if (Ty->isObjCObjectType()) 916 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 917 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 918 << Ty << CT); 919 else 920 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 921 << isa<InitListExpr>(E) << Ty << CT; 922 break; 923 } 924 } 925 926 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 927 /// will create a trap if the resulting type is not a POD type. 928 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 929 FunctionDecl *FDecl) { 930 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 931 // Strip the unbridged-cast placeholder expression off, if applicable. 932 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 933 (CT == VariadicMethod || 934 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 935 E = stripARCUnbridgedCast(E); 936 937 // Otherwise, do normal placeholder checking. 938 } else { 939 ExprResult ExprRes = CheckPlaceholderExpr(E); 940 if (ExprRes.isInvalid()) 941 return ExprError(); 942 E = ExprRes.get(); 943 } 944 } 945 946 ExprResult ExprRes = DefaultArgumentPromotion(E); 947 if (ExprRes.isInvalid()) 948 return ExprError(); 949 E = ExprRes.get(); 950 951 // Diagnostics regarding non-POD argument types are 952 // emitted along with format string checking in Sema::CheckFunctionCall(). 953 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 954 // Turn this into a trap. 955 CXXScopeSpec SS; 956 SourceLocation TemplateKWLoc; 957 UnqualifiedId Name; 958 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 959 E->getBeginLoc()); 960 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 961 /*HasTrailingLParen=*/true, 962 /*IsAddressOfOperand=*/false); 963 if (TrapFn.isInvalid()) 964 return ExprError(); 965 966 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 967 None, E->getEndLoc()); 968 if (Call.isInvalid()) 969 return ExprError(); 970 971 ExprResult Comma = 972 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 973 if (Comma.isInvalid()) 974 return ExprError(); 975 return Comma.get(); 976 } 977 978 if (!getLangOpts().CPlusPlus && 979 RequireCompleteType(E->getExprLoc(), E->getType(), 980 diag::err_call_incomplete_argument)) 981 return ExprError(); 982 983 return E; 984 } 985 986 /// Converts an integer to complex float type. Helper function of 987 /// UsualArithmeticConversions() 988 /// 989 /// \return false if the integer expression is an integer type and is 990 /// successfully converted to the complex type. 991 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 992 ExprResult &ComplexExpr, 993 QualType IntTy, 994 QualType ComplexTy, 995 bool SkipCast) { 996 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 997 if (SkipCast) return false; 998 if (IntTy->isIntegerType()) { 999 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1000 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1002 CK_FloatingRealToComplex); 1003 } else { 1004 assert(IntTy->isComplexIntegerType()); 1005 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1006 CK_IntegralComplexToFloatingComplex); 1007 } 1008 return false; 1009 } 1010 1011 /// Handle arithmetic conversion with complex types. Helper function of 1012 /// UsualArithmeticConversions() 1013 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1014 ExprResult &RHS, QualType LHSType, 1015 QualType RHSType, 1016 bool IsCompAssign) { 1017 // if we have an integer operand, the result is the complex type. 1018 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1019 /*skipCast*/false)) 1020 return LHSType; 1021 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1022 /*skipCast*/IsCompAssign)) 1023 return RHSType; 1024 1025 // This handles complex/complex, complex/float, or float/complex. 1026 // When both operands are complex, the shorter operand is converted to the 1027 // type of the longer, and that is the type of the result. This corresponds 1028 // to what is done when combining two real floating-point operands. 1029 // The fun begins when size promotion occur across type domains. 1030 // From H&S 6.3.4: When one operand is complex and the other is a real 1031 // floating-point type, the less precise type is converted, within it's 1032 // real or complex domain, to the precision of the other type. For example, 1033 // when combining a "long double" with a "double _Complex", the 1034 // "double _Complex" is promoted to "long double _Complex". 1035 1036 // Compute the rank of the two types, regardless of whether they are complex. 1037 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1038 1039 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1040 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1041 QualType LHSElementType = 1042 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1043 QualType RHSElementType = 1044 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1045 1046 QualType ResultType = S.Context.getComplexType(LHSElementType); 1047 if (Order < 0) { 1048 // Promote the precision of the LHS if not an assignment. 1049 ResultType = S.Context.getComplexType(RHSElementType); 1050 if (!IsCompAssign) { 1051 if (LHSComplexType) 1052 LHS = 1053 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1054 else 1055 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1056 } 1057 } else if (Order > 0) { 1058 // Promote the precision of the RHS. 1059 if (RHSComplexType) 1060 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1061 else 1062 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1063 } 1064 return ResultType; 1065 } 1066 1067 /// Handle arithmetic conversion from integer to float. Helper function 1068 /// of UsualArithmeticConversions() 1069 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1070 ExprResult &IntExpr, 1071 QualType FloatTy, QualType IntTy, 1072 bool ConvertFloat, bool ConvertInt) { 1073 if (IntTy->isIntegerType()) { 1074 if (ConvertInt) 1075 // Convert intExpr to the lhs floating point type. 1076 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1077 CK_IntegralToFloating); 1078 return FloatTy; 1079 } 1080 1081 // Convert both sides to the appropriate complex float. 1082 assert(IntTy->isComplexIntegerType()); 1083 QualType result = S.Context.getComplexType(FloatTy); 1084 1085 // _Complex int -> _Complex float 1086 if (ConvertInt) 1087 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1088 CK_IntegralComplexToFloatingComplex); 1089 1090 // float -> _Complex float 1091 if (ConvertFloat) 1092 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1093 CK_FloatingRealToComplex); 1094 1095 return result; 1096 } 1097 1098 /// Handle arithmethic conversion with floating point types. Helper 1099 /// function of UsualArithmeticConversions() 1100 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1101 ExprResult &RHS, QualType LHSType, 1102 QualType RHSType, bool IsCompAssign) { 1103 bool LHSFloat = LHSType->isRealFloatingType(); 1104 bool RHSFloat = RHSType->isRealFloatingType(); 1105 1106 // If we have two real floating types, convert the smaller operand 1107 // to the bigger result. 1108 if (LHSFloat && RHSFloat) { 1109 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1110 if (order > 0) { 1111 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1112 return LHSType; 1113 } 1114 1115 assert(order < 0 && "illegal float comparison"); 1116 if (!IsCompAssign) 1117 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1118 return RHSType; 1119 } 1120 1121 if (LHSFloat) { 1122 // Half FP has to be promoted to float unless it is natively supported 1123 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1124 LHSType = S.Context.FloatTy; 1125 1126 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1127 /*ConvertFloat=*/!IsCompAssign, 1128 /*ConvertInt=*/ true); 1129 } 1130 assert(RHSFloat); 1131 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1132 /*convertInt=*/ true, 1133 /*convertFloat=*/!IsCompAssign); 1134 } 1135 1136 /// Diagnose attempts to convert between __float128 and long double if 1137 /// there is no support for such conversion. Helper function of 1138 /// UsualArithmeticConversions(). 1139 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1140 QualType RHSType) { 1141 /* No issue converting if at least one of the types is not a floating point 1142 type or the two types have the same rank. 1143 */ 1144 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1145 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1146 return false; 1147 1148 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1149 "The remaining types must be floating point types."); 1150 1151 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1152 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1153 1154 QualType LHSElemType = LHSComplex ? 1155 LHSComplex->getElementType() : LHSType; 1156 QualType RHSElemType = RHSComplex ? 1157 RHSComplex->getElementType() : RHSType; 1158 1159 // No issue if the two types have the same representation 1160 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1161 &S.Context.getFloatTypeSemantics(RHSElemType)) 1162 return false; 1163 1164 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1165 RHSElemType == S.Context.LongDoubleTy); 1166 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1167 RHSElemType == S.Context.Float128Ty); 1168 1169 // We've handled the situation where __float128 and long double have the same 1170 // representation. We allow all conversions for all possible long double types 1171 // except PPC's double double. 1172 return Float128AndLongDouble && 1173 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1174 &llvm::APFloat::PPCDoubleDouble()); 1175 } 1176 1177 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1178 1179 namespace { 1180 /// These helper callbacks are placed in an anonymous namespace to 1181 /// permit their use as function template parameters. 1182 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1183 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1184 } 1185 1186 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1187 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1188 CK_IntegralComplexCast); 1189 } 1190 } 1191 1192 /// Handle integer arithmetic conversions. Helper function of 1193 /// UsualArithmeticConversions() 1194 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1195 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1196 ExprResult &RHS, QualType LHSType, 1197 QualType RHSType, bool IsCompAssign) { 1198 // The rules for this case are in C99 6.3.1.8 1199 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1200 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1201 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1202 if (LHSSigned == RHSSigned) { 1203 // Same signedness; use the higher-ranked type 1204 if (order >= 0) { 1205 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1206 return LHSType; 1207 } else if (!IsCompAssign) 1208 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1209 return RHSType; 1210 } else if (order != (LHSSigned ? 1 : -1)) { 1211 // The unsigned type has greater than or equal rank to the 1212 // signed type, so use the unsigned type 1213 if (RHSSigned) { 1214 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1215 return LHSType; 1216 } else if (!IsCompAssign) 1217 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1218 return RHSType; 1219 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1220 // The two types are different widths; if we are here, that 1221 // means the signed type is larger than the unsigned type, so 1222 // use the signed type. 1223 if (LHSSigned) { 1224 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1225 return LHSType; 1226 } else if (!IsCompAssign) 1227 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1228 return RHSType; 1229 } else { 1230 // The signed type is higher-ranked than the unsigned type, 1231 // but isn't actually any bigger (like unsigned int and long 1232 // on most 32-bit systems). Use the unsigned type corresponding 1233 // to the signed type. 1234 QualType result = 1235 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1236 RHS = (*doRHSCast)(S, RHS.get(), result); 1237 if (!IsCompAssign) 1238 LHS = (*doLHSCast)(S, LHS.get(), result); 1239 return result; 1240 } 1241 } 1242 1243 /// Handle conversions with GCC complex int extension. Helper function 1244 /// of UsualArithmeticConversions() 1245 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1246 ExprResult &RHS, QualType LHSType, 1247 QualType RHSType, 1248 bool IsCompAssign) { 1249 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1250 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1251 1252 if (LHSComplexInt && RHSComplexInt) { 1253 QualType LHSEltType = LHSComplexInt->getElementType(); 1254 QualType RHSEltType = RHSComplexInt->getElementType(); 1255 QualType ScalarType = 1256 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1257 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1258 1259 return S.Context.getComplexType(ScalarType); 1260 } 1261 1262 if (LHSComplexInt) { 1263 QualType LHSEltType = LHSComplexInt->getElementType(); 1264 QualType ScalarType = 1265 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1266 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1267 QualType ComplexType = S.Context.getComplexType(ScalarType); 1268 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1269 CK_IntegralRealToComplex); 1270 1271 return ComplexType; 1272 } 1273 1274 assert(RHSComplexInt); 1275 1276 QualType RHSEltType = RHSComplexInt->getElementType(); 1277 QualType ScalarType = 1278 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1279 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1280 QualType ComplexType = S.Context.getComplexType(ScalarType); 1281 1282 if (!IsCompAssign) 1283 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1284 CK_IntegralRealToComplex); 1285 return ComplexType; 1286 } 1287 1288 /// Return the rank of a given fixed point or integer type. The value itself 1289 /// doesn't matter, but the values must be increasing with proper increasing 1290 /// rank as described in N1169 4.1.1. 1291 static unsigned GetFixedPointRank(QualType Ty) { 1292 const auto *BTy = Ty->getAs<BuiltinType>(); 1293 assert(BTy && "Expected a builtin type."); 1294 1295 switch (BTy->getKind()) { 1296 case BuiltinType::ShortFract: 1297 case BuiltinType::UShortFract: 1298 case BuiltinType::SatShortFract: 1299 case BuiltinType::SatUShortFract: 1300 return 1; 1301 case BuiltinType::Fract: 1302 case BuiltinType::UFract: 1303 case BuiltinType::SatFract: 1304 case BuiltinType::SatUFract: 1305 return 2; 1306 case BuiltinType::LongFract: 1307 case BuiltinType::ULongFract: 1308 case BuiltinType::SatLongFract: 1309 case BuiltinType::SatULongFract: 1310 return 3; 1311 case BuiltinType::ShortAccum: 1312 case BuiltinType::UShortAccum: 1313 case BuiltinType::SatShortAccum: 1314 case BuiltinType::SatUShortAccum: 1315 return 4; 1316 case BuiltinType::Accum: 1317 case BuiltinType::UAccum: 1318 case BuiltinType::SatAccum: 1319 case BuiltinType::SatUAccum: 1320 return 5; 1321 case BuiltinType::LongAccum: 1322 case BuiltinType::ULongAccum: 1323 case BuiltinType::SatLongAccum: 1324 case BuiltinType::SatULongAccum: 1325 return 6; 1326 default: 1327 if (BTy->isInteger()) 1328 return 0; 1329 llvm_unreachable("Unexpected fixed point or integer type"); 1330 } 1331 } 1332 1333 /// handleFixedPointConversion - Fixed point operations between fixed 1334 /// point types and integers or other fixed point types do not fall under 1335 /// usual arithmetic conversion since these conversions could result in loss 1336 /// of precsision (N1169 4.1.4). These operations should be calculated with 1337 /// the full precision of their result type (N1169 4.1.6.2.1). 1338 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1339 QualType RHSTy) { 1340 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1341 "Expected at least one of the operands to be a fixed point type"); 1342 assert((LHSTy->isFixedPointOrIntegerType() || 1343 RHSTy->isFixedPointOrIntegerType()) && 1344 "Special fixed point arithmetic operation conversions are only " 1345 "applied to ints or other fixed point types"); 1346 1347 // If one operand has signed fixed-point type and the other operand has 1348 // unsigned fixed-point type, then the unsigned fixed-point operand is 1349 // converted to its corresponding signed fixed-point type and the resulting 1350 // type is the type of the converted operand. 1351 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1352 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1353 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1354 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1355 1356 // The result type is the type with the highest rank, whereby a fixed-point 1357 // conversion rank is always greater than an integer conversion rank; if the 1358 // type of either of the operands is a saturating fixedpoint type, the result 1359 // type shall be the saturating fixed-point type corresponding to the type 1360 // with the highest rank; the resulting value is converted (taking into 1361 // account rounding and overflow) to the precision of the resulting type. 1362 // Same ranks between signed and unsigned types are resolved earlier, so both 1363 // types are either signed or both unsigned at this point. 1364 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1365 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1366 1367 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1368 1369 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1370 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1371 1372 return ResultTy; 1373 } 1374 1375 /// Check that the usual arithmetic conversions can be performed on this pair of 1376 /// expressions that might be of enumeration type. 1377 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1378 SourceLocation Loc, 1379 Sema::ArithConvKind ACK) { 1380 // C++2a [expr.arith.conv]p1: 1381 // If one operand is of enumeration type and the other operand is of a 1382 // different enumeration type or a floating-point type, this behavior is 1383 // deprecated ([depr.arith.conv.enum]). 1384 // 1385 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1386 // Eventually we will presumably reject these cases (in C++23 onwards?). 1387 QualType L = LHS->getType(), R = RHS->getType(); 1388 bool LEnum = L->isUnscopedEnumerationType(), 1389 REnum = R->isUnscopedEnumerationType(); 1390 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1391 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1392 (REnum && L->isFloatingType())) { 1393 S.Diag(Loc, S.getLangOpts().CPlusPlus2a 1394 ? diag::warn_arith_conv_enum_float_cxx2a 1395 : diag::warn_arith_conv_enum_float) 1396 << LHS->getSourceRange() << RHS->getSourceRange() 1397 << (int)ACK << LEnum << L << R; 1398 } else if (!IsCompAssign && LEnum && REnum && 1399 !S.Context.hasSameUnqualifiedType(L, R)) { 1400 unsigned DiagID; 1401 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1402 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1403 // If either enumeration type is unnamed, it's less likely that the 1404 // user cares about this, but this situation is still deprecated in 1405 // C++2a. Use a different warning group. 1406 DiagID = S.getLangOpts().CPlusPlus2a 1407 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a 1408 : diag::warn_arith_conv_mixed_anon_enum_types; 1409 } else if (ACK == Sema::ACK_Conditional) { 1410 // Conditional expressions are separated out because they have 1411 // historically had a different warning flag. 1412 DiagID = S.getLangOpts().CPlusPlus2a 1413 ? diag::warn_conditional_mixed_enum_types_cxx2a 1414 : diag::warn_conditional_mixed_enum_types; 1415 } else if (ACK == Sema::ACK_Comparison) { 1416 // Comparison expressions are separated out because they have 1417 // historically had a different warning flag. 1418 DiagID = S.getLangOpts().CPlusPlus2a 1419 ? diag::warn_comparison_mixed_enum_types_cxx2a 1420 : diag::warn_comparison_mixed_enum_types; 1421 } else { 1422 DiagID = S.getLangOpts().CPlusPlus2a 1423 ? diag::warn_arith_conv_mixed_enum_types_cxx2a 1424 : diag::warn_arith_conv_mixed_enum_types; 1425 } 1426 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1427 << (int)ACK << L << R; 1428 } 1429 } 1430 1431 /// UsualArithmeticConversions - Performs various conversions that are common to 1432 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1433 /// routine returns the first non-arithmetic type found. The client is 1434 /// responsible for emitting appropriate error diagnostics. 1435 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1436 SourceLocation Loc, 1437 ArithConvKind ACK) { 1438 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1439 1440 if (ACK != ACK_CompAssign) { 1441 LHS = UsualUnaryConversions(LHS.get()); 1442 if (LHS.isInvalid()) 1443 return QualType(); 1444 } 1445 1446 RHS = UsualUnaryConversions(RHS.get()); 1447 if (RHS.isInvalid()) 1448 return QualType(); 1449 1450 // For conversion purposes, we ignore any qualifiers. 1451 // For example, "const float" and "float" are equivalent. 1452 QualType LHSType = 1453 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1454 QualType RHSType = 1455 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1456 1457 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1458 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1459 LHSType = AtomicLHS->getValueType(); 1460 1461 // If both types are identical, no conversion is needed. 1462 if (LHSType == RHSType) 1463 return LHSType; 1464 1465 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1466 // The caller can deal with this (e.g. pointer + int). 1467 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1468 return QualType(); 1469 1470 // Apply unary and bitfield promotions to the LHS's type. 1471 QualType LHSUnpromotedType = LHSType; 1472 if (LHSType->isPromotableIntegerType()) 1473 LHSType = Context.getPromotedIntegerType(LHSType); 1474 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1475 if (!LHSBitfieldPromoteTy.isNull()) 1476 LHSType = LHSBitfieldPromoteTy; 1477 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1478 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1479 1480 // If both types are identical, no conversion is needed. 1481 if (LHSType == RHSType) 1482 return LHSType; 1483 1484 // At this point, we have two different arithmetic types. 1485 1486 // Diagnose attempts to convert between __float128 and long double where 1487 // such conversions currently can't be handled. 1488 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1489 return QualType(); 1490 1491 // Handle complex types first (C99 6.3.1.8p1). 1492 if (LHSType->isComplexType() || RHSType->isComplexType()) 1493 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1494 ACK == ACK_CompAssign); 1495 1496 // Now handle "real" floating types (i.e. float, double, long double). 1497 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1498 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1499 ACK == ACK_CompAssign); 1500 1501 // Handle GCC complex int extension. 1502 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1503 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1504 ACK == ACK_CompAssign); 1505 1506 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1507 return handleFixedPointConversion(*this, LHSType, RHSType); 1508 1509 // Finally, we have two differing integer types. 1510 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1511 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1512 } 1513 1514 //===----------------------------------------------------------------------===// 1515 // Semantic Analysis for various Expression Types 1516 //===----------------------------------------------------------------------===// 1517 1518 1519 ExprResult 1520 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1521 SourceLocation DefaultLoc, 1522 SourceLocation RParenLoc, 1523 Expr *ControllingExpr, 1524 ArrayRef<ParsedType> ArgTypes, 1525 ArrayRef<Expr *> ArgExprs) { 1526 unsigned NumAssocs = ArgTypes.size(); 1527 assert(NumAssocs == ArgExprs.size()); 1528 1529 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1530 for (unsigned i = 0; i < NumAssocs; ++i) { 1531 if (ArgTypes[i]) 1532 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1533 else 1534 Types[i] = nullptr; 1535 } 1536 1537 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1538 ControllingExpr, 1539 llvm::makeArrayRef(Types, NumAssocs), 1540 ArgExprs); 1541 delete [] Types; 1542 return ER; 1543 } 1544 1545 ExprResult 1546 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1547 SourceLocation DefaultLoc, 1548 SourceLocation RParenLoc, 1549 Expr *ControllingExpr, 1550 ArrayRef<TypeSourceInfo *> Types, 1551 ArrayRef<Expr *> Exprs) { 1552 unsigned NumAssocs = Types.size(); 1553 assert(NumAssocs == Exprs.size()); 1554 1555 // Decay and strip qualifiers for the controlling expression type, and handle 1556 // placeholder type replacement. See committee discussion from WG14 DR423. 1557 { 1558 EnterExpressionEvaluationContext Unevaluated( 1559 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1560 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1561 if (R.isInvalid()) 1562 return ExprError(); 1563 ControllingExpr = R.get(); 1564 } 1565 1566 // The controlling expression is an unevaluated operand, so side effects are 1567 // likely unintended. 1568 if (!inTemplateInstantiation() && 1569 ControllingExpr->HasSideEffects(Context, false)) 1570 Diag(ControllingExpr->getExprLoc(), 1571 diag::warn_side_effects_unevaluated_context); 1572 1573 bool TypeErrorFound = false, 1574 IsResultDependent = ControllingExpr->isTypeDependent(), 1575 ContainsUnexpandedParameterPack 1576 = ControllingExpr->containsUnexpandedParameterPack(); 1577 1578 for (unsigned i = 0; i < NumAssocs; ++i) { 1579 if (Exprs[i]->containsUnexpandedParameterPack()) 1580 ContainsUnexpandedParameterPack = true; 1581 1582 if (Types[i]) { 1583 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1584 ContainsUnexpandedParameterPack = true; 1585 1586 if (Types[i]->getType()->isDependentType()) { 1587 IsResultDependent = true; 1588 } else { 1589 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1590 // complete object type other than a variably modified type." 1591 unsigned D = 0; 1592 if (Types[i]->getType()->isIncompleteType()) 1593 D = diag::err_assoc_type_incomplete; 1594 else if (!Types[i]->getType()->isObjectType()) 1595 D = diag::err_assoc_type_nonobject; 1596 else if (Types[i]->getType()->isVariablyModifiedType()) 1597 D = diag::err_assoc_type_variably_modified; 1598 1599 if (D != 0) { 1600 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1601 << Types[i]->getTypeLoc().getSourceRange() 1602 << Types[i]->getType(); 1603 TypeErrorFound = true; 1604 } 1605 1606 // C11 6.5.1.1p2 "No two generic associations in the same generic 1607 // selection shall specify compatible types." 1608 for (unsigned j = i+1; j < NumAssocs; ++j) 1609 if (Types[j] && !Types[j]->getType()->isDependentType() && 1610 Context.typesAreCompatible(Types[i]->getType(), 1611 Types[j]->getType())) { 1612 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1613 diag::err_assoc_compatible_types) 1614 << Types[j]->getTypeLoc().getSourceRange() 1615 << Types[j]->getType() 1616 << Types[i]->getType(); 1617 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1618 diag::note_compat_assoc) 1619 << Types[i]->getTypeLoc().getSourceRange() 1620 << Types[i]->getType(); 1621 TypeErrorFound = true; 1622 } 1623 } 1624 } 1625 } 1626 if (TypeErrorFound) 1627 return ExprError(); 1628 1629 // If we determined that the generic selection is result-dependent, don't 1630 // try to compute the result expression. 1631 if (IsResultDependent) 1632 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1633 Exprs, DefaultLoc, RParenLoc, 1634 ContainsUnexpandedParameterPack); 1635 1636 SmallVector<unsigned, 1> CompatIndices; 1637 unsigned DefaultIndex = -1U; 1638 for (unsigned i = 0; i < NumAssocs; ++i) { 1639 if (!Types[i]) 1640 DefaultIndex = i; 1641 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1642 Types[i]->getType())) 1643 CompatIndices.push_back(i); 1644 } 1645 1646 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1647 // type compatible with at most one of the types named in its generic 1648 // association list." 1649 if (CompatIndices.size() > 1) { 1650 // We strip parens here because the controlling expression is typically 1651 // parenthesized in macro definitions. 1652 ControllingExpr = ControllingExpr->IgnoreParens(); 1653 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1654 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1655 << (unsigned)CompatIndices.size(); 1656 for (unsigned I : CompatIndices) { 1657 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1658 diag::note_compat_assoc) 1659 << Types[I]->getTypeLoc().getSourceRange() 1660 << Types[I]->getType(); 1661 } 1662 return ExprError(); 1663 } 1664 1665 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1666 // its controlling expression shall have type compatible with exactly one of 1667 // the types named in its generic association list." 1668 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1669 // We strip parens here because the controlling expression is typically 1670 // parenthesized in macro definitions. 1671 ControllingExpr = ControllingExpr->IgnoreParens(); 1672 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1673 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1674 return ExprError(); 1675 } 1676 1677 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1678 // type name that is compatible with the type of the controlling expression, 1679 // then the result expression of the generic selection is the expression 1680 // in that generic association. Otherwise, the result expression of the 1681 // generic selection is the expression in the default generic association." 1682 unsigned ResultIndex = 1683 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1684 1685 return GenericSelectionExpr::Create( 1686 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1687 ContainsUnexpandedParameterPack, ResultIndex); 1688 } 1689 1690 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1691 /// location of the token and the offset of the ud-suffix within it. 1692 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1693 unsigned Offset) { 1694 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1695 S.getLangOpts()); 1696 } 1697 1698 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1699 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1700 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1701 IdentifierInfo *UDSuffix, 1702 SourceLocation UDSuffixLoc, 1703 ArrayRef<Expr*> Args, 1704 SourceLocation LitEndLoc) { 1705 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1706 1707 QualType ArgTy[2]; 1708 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1709 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1710 if (ArgTy[ArgIdx]->isArrayType()) 1711 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1712 } 1713 1714 DeclarationName OpName = 1715 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1716 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1717 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1718 1719 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1720 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1721 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1722 /*AllowStringTemplate*/ false, 1723 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1724 return ExprError(); 1725 1726 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1727 } 1728 1729 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1730 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1731 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1732 /// multiple tokens. However, the common case is that StringToks points to one 1733 /// string. 1734 /// 1735 ExprResult 1736 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1737 assert(!StringToks.empty() && "Must have at least one string!"); 1738 1739 StringLiteralParser Literal(StringToks, PP); 1740 if (Literal.hadError) 1741 return ExprError(); 1742 1743 SmallVector<SourceLocation, 4> StringTokLocs; 1744 for (const Token &Tok : StringToks) 1745 StringTokLocs.push_back(Tok.getLocation()); 1746 1747 QualType CharTy = Context.CharTy; 1748 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1749 if (Literal.isWide()) { 1750 CharTy = Context.getWideCharType(); 1751 Kind = StringLiteral::Wide; 1752 } else if (Literal.isUTF8()) { 1753 if (getLangOpts().Char8) 1754 CharTy = Context.Char8Ty; 1755 Kind = StringLiteral::UTF8; 1756 } else if (Literal.isUTF16()) { 1757 CharTy = Context.Char16Ty; 1758 Kind = StringLiteral::UTF16; 1759 } else if (Literal.isUTF32()) { 1760 CharTy = Context.Char32Ty; 1761 Kind = StringLiteral::UTF32; 1762 } else if (Literal.isPascal()) { 1763 CharTy = Context.UnsignedCharTy; 1764 } 1765 1766 // Warn on initializing an array of char from a u8 string literal; this 1767 // becomes ill-formed in C++2a. 1768 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1769 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1770 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1771 1772 // Create removals for all 'u8' prefixes in the string literal(s). This 1773 // ensures C++2a compatibility (but may change the program behavior when 1774 // built by non-Clang compilers for which the execution character set is 1775 // not always UTF-8). 1776 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1777 SourceLocation RemovalDiagLoc; 1778 for (const Token &Tok : StringToks) { 1779 if (Tok.getKind() == tok::utf8_string_literal) { 1780 if (RemovalDiagLoc.isInvalid()) 1781 RemovalDiagLoc = Tok.getLocation(); 1782 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1783 Tok.getLocation(), 1784 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1785 getSourceManager(), getLangOpts()))); 1786 } 1787 } 1788 Diag(RemovalDiagLoc, RemovalDiag); 1789 } 1790 1791 QualType StrTy = 1792 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1793 1794 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1795 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1796 Kind, Literal.Pascal, StrTy, 1797 &StringTokLocs[0], 1798 StringTokLocs.size()); 1799 if (Literal.getUDSuffix().empty()) 1800 return Lit; 1801 1802 // We're building a user-defined literal. 1803 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1804 SourceLocation UDSuffixLoc = 1805 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1806 Literal.getUDSuffixOffset()); 1807 1808 // Make sure we're allowed user-defined literals here. 1809 if (!UDLScope) 1810 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1811 1812 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1813 // operator "" X (str, len) 1814 QualType SizeType = Context.getSizeType(); 1815 1816 DeclarationName OpName = 1817 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1818 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1819 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1820 1821 QualType ArgTy[] = { 1822 Context.getArrayDecayedType(StrTy), SizeType 1823 }; 1824 1825 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1826 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1827 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1828 /*AllowStringTemplate*/ true, 1829 /*DiagnoseMissing*/ true)) { 1830 1831 case LOLR_Cooked: { 1832 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1833 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1834 StringTokLocs[0]); 1835 Expr *Args[] = { Lit, LenArg }; 1836 1837 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1838 } 1839 1840 case LOLR_StringTemplate: { 1841 TemplateArgumentListInfo ExplicitArgs; 1842 1843 unsigned CharBits = Context.getIntWidth(CharTy); 1844 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1845 llvm::APSInt Value(CharBits, CharIsUnsigned); 1846 1847 TemplateArgument TypeArg(CharTy); 1848 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1849 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1850 1851 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1852 Value = Lit->getCodeUnit(I); 1853 TemplateArgument Arg(Context, Value, CharTy); 1854 TemplateArgumentLocInfo ArgInfo; 1855 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1856 } 1857 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1858 &ExplicitArgs); 1859 } 1860 case LOLR_Raw: 1861 case LOLR_Template: 1862 case LOLR_ErrorNoDiagnostic: 1863 llvm_unreachable("unexpected literal operator lookup result"); 1864 case LOLR_Error: 1865 return ExprError(); 1866 } 1867 llvm_unreachable("unexpected literal operator lookup result"); 1868 } 1869 1870 DeclRefExpr * 1871 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1872 SourceLocation Loc, 1873 const CXXScopeSpec *SS) { 1874 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1875 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1876 } 1877 1878 DeclRefExpr * 1879 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1880 const DeclarationNameInfo &NameInfo, 1881 const CXXScopeSpec *SS, NamedDecl *FoundD, 1882 SourceLocation TemplateKWLoc, 1883 const TemplateArgumentListInfo *TemplateArgs) { 1884 NestedNameSpecifierLoc NNS = 1885 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1886 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1887 TemplateArgs); 1888 } 1889 1890 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1891 // A declaration named in an unevaluated operand never constitutes an odr-use. 1892 if (isUnevaluatedContext()) 1893 return NOUR_Unevaluated; 1894 1895 // C++2a [basic.def.odr]p4: 1896 // A variable x whose name appears as a potentially-evaluated expression e 1897 // is odr-used by e unless [...] x is a reference that is usable in 1898 // constant expressions. 1899 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1900 if (VD->getType()->isReferenceType() && 1901 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1902 VD->isUsableInConstantExpressions(Context)) 1903 return NOUR_Constant; 1904 } 1905 1906 // All remaining non-variable cases constitute an odr-use. For variables, we 1907 // need to wait and see how the expression is used. 1908 return NOUR_None; 1909 } 1910 1911 /// BuildDeclRefExpr - Build an expression that references a 1912 /// declaration that does not require a closure capture. 1913 DeclRefExpr * 1914 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1915 const DeclarationNameInfo &NameInfo, 1916 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 1917 SourceLocation TemplateKWLoc, 1918 const TemplateArgumentListInfo *TemplateArgs) { 1919 bool RefersToCapturedVariable = 1920 isa<VarDecl>(D) && 1921 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1922 1923 DeclRefExpr *E = DeclRefExpr::Create( 1924 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 1925 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 1926 MarkDeclRefReferenced(E); 1927 1928 // C++ [except.spec]p17: 1929 // An exception-specification is considered to be needed when: 1930 // - in an expression, the function is the unique lookup result or 1931 // the selected member of a set of overloaded functions. 1932 // 1933 // We delay doing this until after we've built the function reference and 1934 // marked it as used so that: 1935 // a) if the function is defaulted, we get errors from defining it before / 1936 // instead of errors from computing its exception specification, and 1937 // b) if the function is a defaulted comparison, we can use the body we 1938 // build when defining it as input to the exception specification 1939 // computation rather than computing a new body. 1940 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 1941 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 1942 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 1943 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 1944 } 1945 } 1946 1947 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1948 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1949 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1950 getCurFunction()->recordUseOfWeak(E); 1951 1952 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1953 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1954 FD = IFD->getAnonField(); 1955 if (FD) { 1956 UnusedPrivateFields.remove(FD); 1957 // Just in case we're building an illegal pointer-to-member. 1958 if (FD->isBitField()) 1959 E->setObjectKind(OK_BitField); 1960 } 1961 1962 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1963 // designates a bit-field. 1964 if (auto *BD = dyn_cast<BindingDecl>(D)) 1965 if (auto *BE = BD->getBinding()) 1966 E->setObjectKind(BE->getObjectKind()); 1967 1968 return E; 1969 } 1970 1971 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1972 /// possibly a list of template arguments. 1973 /// 1974 /// If this produces template arguments, it is permitted to call 1975 /// DecomposeTemplateName. 1976 /// 1977 /// This actually loses a lot of source location information for 1978 /// non-standard name kinds; we should consider preserving that in 1979 /// some way. 1980 void 1981 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1982 TemplateArgumentListInfo &Buffer, 1983 DeclarationNameInfo &NameInfo, 1984 const TemplateArgumentListInfo *&TemplateArgs) { 1985 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1986 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1987 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1988 1989 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1990 Id.TemplateId->NumArgs); 1991 translateTemplateArguments(TemplateArgsPtr, Buffer); 1992 1993 TemplateName TName = Id.TemplateId->Template.get(); 1994 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1995 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1996 TemplateArgs = &Buffer; 1997 } else { 1998 NameInfo = GetNameFromUnqualifiedId(Id); 1999 TemplateArgs = nullptr; 2000 } 2001 } 2002 2003 static void emitEmptyLookupTypoDiagnostic( 2004 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2005 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2006 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2007 DeclContext *Ctx = 2008 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2009 if (!TC) { 2010 // Emit a special diagnostic for failed member lookups. 2011 // FIXME: computing the declaration context might fail here (?) 2012 if (Ctx) 2013 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2014 << SS.getRange(); 2015 else 2016 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2017 return; 2018 } 2019 2020 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2021 bool DroppedSpecifier = 2022 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2023 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2024 ? diag::note_implicit_param_decl 2025 : diag::note_previous_decl; 2026 if (!Ctx) 2027 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2028 SemaRef.PDiag(NoteID)); 2029 else 2030 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2031 << Typo << Ctx << DroppedSpecifier 2032 << SS.getRange(), 2033 SemaRef.PDiag(NoteID)); 2034 } 2035 2036 /// Diagnose an empty lookup. 2037 /// 2038 /// \return false if new lookup candidates were found 2039 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2040 CorrectionCandidateCallback &CCC, 2041 TemplateArgumentListInfo *ExplicitTemplateArgs, 2042 ArrayRef<Expr *> Args, TypoExpr **Out) { 2043 DeclarationName Name = R.getLookupName(); 2044 2045 unsigned diagnostic = diag::err_undeclared_var_use; 2046 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2047 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2048 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2049 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2050 diagnostic = diag::err_undeclared_use; 2051 diagnostic_suggest = diag::err_undeclared_use_suggest; 2052 } 2053 2054 // If the original lookup was an unqualified lookup, fake an 2055 // unqualified lookup. This is useful when (for example) the 2056 // original lookup would not have found something because it was a 2057 // dependent name. 2058 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2059 while (DC) { 2060 if (isa<CXXRecordDecl>(DC)) { 2061 LookupQualifiedName(R, DC); 2062 2063 if (!R.empty()) { 2064 // Don't give errors about ambiguities in this lookup. 2065 R.suppressDiagnostics(); 2066 2067 // During a default argument instantiation the CurContext points 2068 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2069 // function parameter list, hence add an explicit check. 2070 bool isDefaultArgument = 2071 !CodeSynthesisContexts.empty() && 2072 CodeSynthesisContexts.back().Kind == 2073 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2074 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2075 bool isInstance = CurMethod && 2076 CurMethod->isInstance() && 2077 DC == CurMethod->getParent() && !isDefaultArgument; 2078 2079 // Give a code modification hint to insert 'this->'. 2080 // TODO: fixit for inserting 'Base<T>::' in the other cases. 2081 // Actually quite difficult! 2082 if (getLangOpts().MSVCCompat) 2083 diagnostic = diag::ext_found_via_dependent_bases_lookup; 2084 if (isInstance) { 2085 Diag(R.getNameLoc(), diagnostic) << Name 2086 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2087 CheckCXXThisCapture(R.getNameLoc()); 2088 } else { 2089 Diag(R.getNameLoc(), diagnostic) << Name; 2090 } 2091 2092 // Do we really want to note all of these? 2093 for (NamedDecl *D : R) 2094 Diag(D->getLocation(), diag::note_dependent_var_use); 2095 2096 // Return true if we are inside a default argument instantiation 2097 // and the found name refers to an instance member function, otherwise 2098 // the function calling DiagnoseEmptyLookup will try to create an 2099 // implicit member call and this is wrong for default argument. 2100 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2101 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2102 return true; 2103 } 2104 2105 // Tell the callee to try to recover. 2106 return false; 2107 } 2108 2109 R.clear(); 2110 } 2111 2112 DC = DC->getLookupParent(); 2113 } 2114 2115 // We didn't find anything, so try to correct for a typo. 2116 TypoCorrection Corrected; 2117 if (S && Out) { 2118 SourceLocation TypoLoc = R.getNameLoc(); 2119 assert(!ExplicitTemplateArgs && 2120 "Diagnosing an empty lookup with explicit template args!"); 2121 *Out = CorrectTypoDelayed( 2122 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2123 [=](const TypoCorrection &TC) { 2124 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2125 diagnostic, diagnostic_suggest); 2126 }, 2127 nullptr, CTK_ErrorRecovery); 2128 if (*Out) 2129 return true; 2130 } else if (S && 2131 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2132 S, &SS, CCC, CTK_ErrorRecovery))) { 2133 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2134 bool DroppedSpecifier = 2135 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2136 R.setLookupName(Corrected.getCorrection()); 2137 2138 bool AcceptableWithRecovery = false; 2139 bool AcceptableWithoutRecovery = false; 2140 NamedDecl *ND = Corrected.getFoundDecl(); 2141 if (ND) { 2142 if (Corrected.isOverloaded()) { 2143 OverloadCandidateSet OCS(R.getNameLoc(), 2144 OverloadCandidateSet::CSK_Normal); 2145 OverloadCandidateSet::iterator Best; 2146 for (NamedDecl *CD : Corrected) { 2147 if (FunctionTemplateDecl *FTD = 2148 dyn_cast<FunctionTemplateDecl>(CD)) 2149 AddTemplateOverloadCandidate( 2150 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2151 Args, OCS); 2152 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2153 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2154 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2155 Args, OCS); 2156 } 2157 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2158 case OR_Success: 2159 ND = Best->FoundDecl; 2160 Corrected.setCorrectionDecl(ND); 2161 break; 2162 default: 2163 // FIXME: Arbitrarily pick the first declaration for the note. 2164 Corrected.setCorrectionDecl(ND); 2165 break; 2166 } 2167 } 2168 R.addDecl(ND); 2169 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2170 CXXRecordDecl *Record = nullptr; 2171 if (Corrected.getCorrectionSpecifier()) { 2172 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2173 Record = Ty->getAsCXXRecordDecl(); 2174 } 2175 if (!Record) 2176 Record = cast<CXXRecordDecl>( 2177 ND->getDeclContext()->getRedeclContext()); 2178 R.setNamingClass(Record); 2179 } 2180 2181 auto *UnderlyingND = ND->getUnderlyingDecl(); 2182 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2183 isa<FunctionTemplateDecl>(UnderlyingND); 2184 // FIXME: If we ended up with a typo for a type name or 2185 // Objective-C class name, we're in trouble because the parser 2186 // is in the wrong place to recover. Suggest the typo 2187 // correction, but don't make it a fix-it since we're not going 2188 // to recover well anyway. 2189 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2190 getAsTypeTemplateDecl(UnderlyingND) || 2191 isa<ObjCInterfaceDecl>(UnderlyingND); 2192 } else { 2193 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2194 // because we aren't able to recover. 2195 AcceptableWithoutRecovery = true; 2196 } 2197 2198 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2199 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2200 ? diag::note_implicit_param_decl 2201 : diag::note_previous_decl; 2202 if (SS.isEmpty()) 2203 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2204 PDiag(NoteID), AcceptableWithRecovery); 2205 else 2206 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2207 << Name << computeDeclContext(SS, false) 2208 << DroppedSpecifier << SS.getRange(), 2209 PDiag(NoteID), AcceptableWithRecovery); 2210 2211 // Tell the callee whether to try to recover. 2212 return !AcceptableWithRecovery; 2213 } 2214 } 2215 R.clear(); 2216 2217 // Emit a special diagnostic for failed member lookups. 2218 // FIXME: computing the declaration context might fail here (?) 2219 if (!SS.isEmpty()) { 2220 Diag(R.getNameLoc(), diag::err_no_member) 2221 << Name << computeDeclContext(SS, false) 2222 << SS.getRange(); 2223 return true; 2224 } 2225 2226 // Give up, we can't recover. 2227 Diag(R.getNameLoc(), diagnostic) << Name; 2228 return true; 2229 } 2230 2231 /// In Microsoft mode, if we are inside a template class whose parent class has 2232 /// dependent base classes, and we can't resolve an unqualified identifier, then 2233 /// assume the identifier is a member of a dependent base class. We can only 2234 /// recover successfully in static methods, instance methods, and other contexts 2235 /// where 'this' is available. This doesn't precisely match MSVC's 2236 /// instantiation model, but it's close enough. 2237 static Expr * 2238 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2239 DeclarationNameInfo &NameInfo, 2240 SourceLocation TemplateKWLoc, 2241 const TemplateArgumentListInfo *TemplateArgs) { 2242 // Only try to recover from lookup into dependent bases in static methods or 2243 // contexts where 'this' is available. 2244 QualType ThisType = S.getCurrentThisType(); 2245 const CXXRecordDecl *RD = nullptr; 2246 if (!ThisType.isNull()) 2247 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2248 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2249 RD = MD->getParent(); 2250 if (!RD || !RD->hasAnyDependentBases()) 2251 return nullptr; 2252 2253 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2254 // is available, suggest inserting 'this->' as a fixit. 2255 SourceLocation Loc = NameInfo.getLoc(); 2256 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2257 DB << NameInfo.getName() << RD; 2258 2259 if (!ThisType.isNull()) { 2260 DB << FixItHint::CreateInsertion(Loc, "this->"); 2261 return CXXDependentScopeMemberExpr::Create( 2262 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2263 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2264 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2265 } 2266 2267 // Synthesize a fake NNS that points to the derived class. This will 2268 // perform name lookup during template instantiation. 2269 CXXScopeSpec SS; 2270 auto *NNS = 2271 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2272 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2273 return DependentScopeDeclRefExpr::Create( 2274 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2275 TemplateArgs); 2276 } 2277 2278 ExprResult 2279 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2280 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2281 bool HasTrailingLParen, bool IsAddressOfOperand, 2282 CorrectionCandidateCallback *CCC, 2283 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2284 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2285 "cannot be direct & operand and have a trailing lparen"); 2286 if (SS.isInvalid()) 2287 return ExprError(); 2288 2289 TemplateArgumentListInfo TemplateArgsBuffer; 2290 2291 // Decompose the UnqualifiedId into the following data. 2292 DeclarationNameInfo NameInfo; 2293 const TemplateArgumentListInfo *TemplateArgs; 2294 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2295 2296 DeclarationName Name = NameInfo.getName(); 2297 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2298 SourceLocation NameLoc = NameInfo.getLoc(); 2299 2300 if (II && II->isEditorPlaceholder()) { 2301 // FIXME: When typed placeholders are supported we can create a typed 2302 // placeholder expression node. 2303 return ExprError(); 2304 } 2305 2306 // C++ [temp.dep.expr]p3: 2307 // An id-expression is type-dependent if it contains: 2308 // -- an identifier that was declared with a dependent type, 2309 // (note: handled after lookup) 2310 // -- a template-id that is dependent, 2311 // (note: handled in BuildTemplateIdExpr) 2312 // -- a conversion-function-id that specifies a dependent type, 2313 // -- a nested-name-specifier that contains a class-name that 2314 // names a dependent type. 2315 // Determine whether this is a member of an unknown specialization; 2316 // we need to handle these differently. 2317 bool DependentID = false; 2318 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2319 Name.getCXXNameType()->isDependentType()) { 2320 DependentID = true; 2321 } else if (SS.isSet()) { 2322 if (DeclContext *DC = computeDeclContext(SS, false)) { 2323 if (RequireCompleteDeclContext(SS, DC)) 2324 return ExprError(); 2325 } else { 2326 DependentID = true; 2327 } 2328 } 2329 2330 if (DependentID) 2331 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2332 IsAddressOfOperand, TemplateArgs); 2333 2334 // Perform the required lookup. 2335 LookupResult R(*this, NameInfo, 2336 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2337 ? LookupObjCImplicitSelfParam 2338 : LookupOrdinaryName); 2339 if (TemplateKWLoc.isValid() || TemplateArgs) { 2340 // Lookup the template name again to correctly establish the context in 2341 // which it was found. This is really unfortunate as we already did the 2342 // lookup to determine that it was a template name in the first place. If 2343 // this becomes a performance hit, we can work harder to preserve those 2344 // results until we get here but it's likely not worth it. 2345 bool MemberOfUnknownSpecialization; 2346 AssumedTemplateKind AssumedTemplate; 2347 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2348 MemberOfUnknownSpecialization, TemplateKWLoc, 2349 &AssumedTemplate)) 2350 return ExprError(); 2351 2352 if (MemberOfUnknownSpecialization || 2353 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2354 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2355 IsAddressOfOperand, TemplateArgs); 2356 } else { 2357 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2358 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2359 2360 // If the result might be in a dependent base class, this is a dependent 2361 // id-expression. 2362 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2363 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2364 IsAddressOfOperand, TemplateArgs); 2365 2366 // If this reference is in an Objective-C method, then we need to do 2367 // some special Objective-C lookup, too. 2368 if (IvarLookupFollowUp) { 2369 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2370 if (E.isInvalid()) 2371 return ExprError(); 2372 2373 if (Expr *Ex = E.getAs<Expr>()) 2374 return Ex; 2375 } 2376 } 2377 2378 if (R.isAmbiguous()) 2379 return ExprError(); 2380 2381 // This could be an implicitly declared function reference (legal in C90, 2382 // extension in C99, forbidden in C++). 2383 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2384 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2385 if (D) R.addDecl(D); 2386 } 2387 2388 // Determine whether this name might be a candidate for 2389 // argument-dependent lookup. 2390 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2391 2392 if (R.empty() && !ADL) { 2393 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2394 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2395 TemplateKWLoc, TemplateArgs)) 2396 return E; 2397 } 2398 2399 // Don't diagnose an empty lookup for inline assembly. 2400 if (IsInlineAsmIdentifier) 2401 return ExprError(); 2402 2403 // If this name wasn't predeclared and if this is not a function 2404 // call, diagnose the problem. 2405 TypoExpr *TE = nullptr; 2406 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2407 : nullptr); 2408 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2409 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2410 "Typo correction callback misconfigured"); 2411 if (CCC) { 2412 // Make sure the callback knows what the typo being diagnosed is. 2413 CCC->setTypoName(II); 2414 if (SS.isValid()) 2415 CCC->setTypoNNS(SS.getScopeRep()); 2416 } 2417 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2418 // a template name, but we happen to have always already looked up the name 2419 // before we get here if it must be a template name. 2420 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2421 None, &TE)) { 2422 if (TE && KeywordReplacement) { 2423 auto &State = getTypoExprState(TE); 2424 auto BestTC = State.Consumer->getNextCorrection(); 2425 if (BestTC.isKeyword()) { 2426 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2427 if (State.DiagHandler) 2428 State.DiagHandler(BestTC); 2429 KeywordReplacement->startToken(); 2430 KeywordReplacement->setKind(II->getTokenID()); 2431 KeywordReplacement->setIdentifierInfo(II); 2432 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2433 // Clean up the state associated with the TypoExpr, since it has 2434 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2435 clearDelayedTypo(TE); 2436 // Signal that a correction to a keyword was performed by returning a 2437 // valid-but-null ExprResult. 2438 return (Expr*)nullptr; 2439 } 2440 State.Consumer->resetCorrectionStream(); 2441 } 2442 return TE ? TE : ExprError(); 2443 } 2444 2445 assert(!R.empty() && 2446 "DiagnoseEmptyLookup returned false but added no results"); 2447 2448 // If we found an Objective-C instance variable, let 2449 // LookupInObjCMethod build the appropriate expression to 2450 // reference the ivar. 2451 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2452 R.clear(); 2453 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2454 // In a hopelessly buggy code, Objective-C instance variable 2455 // lookup fails and no expression will be built to reference it. 2456 if (!E.isInvalid() && !E.get()) 2457 return ExprError(); 2458 return E; 2459 } 2460 } 2461 2462 // This is guaranteed from this point on. 2463 assert(!R.empty() || ADL); 2464 2465 // Check whether this might be a C++ implicit instance member access. 2466 // C++ [class.mfct.non-static]p3: 2467 // When an id-expression that is not part of a class member access 2468 // syntax and not used to form a pointer to member is used in the 2469 // body of a non-static member function of class X, if name lookup 2470 // resolves the name in the id-expression to a non-static non-type 2471 // member of some class C, the id-expression is transformed into a 2472 // class member access expression using (*this) as the 2473 // postfix-expression to the left of the . operator. 2474 // 2475 // But we don't actually need to do this for '&' operands if R 2476 // resolved to a function or overloaded function set, because the 2477 // expression is ill-formed if it actually works out to be a 2478 // non-static member function: 2479 // 2480 // C++ [expr.ref]p4: 2481 // Otherwise, if E1.E2 refers to a non-static member function. . . 2482 // [t]he expression can be used only as the left-hand operand of a 2483 // member function call. 2484 // 2485 // There are other safeguards against such uses, but it's important 2486 // to get this right here so that we don't end up making a 2487 // spuriously dependent expression if we're inside a dependent 2488 // instance method. 2489 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2490 bool MightBeImplicitMember; 2491 if (!IsAddressOfOperand) 2492 MightBeImplicitMember = true; 2493 else if (!SS.isEmpty()) 2494 MightBeImplicitMember = false; 2495 else if (R.isOverloadedResult()) 2496 MightBeImplicitMember = false; 2497 else if (R.isUnresolvableResult()) 2498 MightBeImplicitMember = true; 2499 else 2500 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2501 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2502 isa<MSPropertyDecl>(R.getFoundDecl()); 2503 2504 if (MightBeImplicitMember) 2505 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2506 R, TemplateArgs, S); 2507 } 2508 2509 if (TemplateArgs || TemplateKWLoc.isValid()) { 2510 2511 // In C++1y, if this is a variable template id, then check it 2512 // in BuildTemplateIdExpr(). 2513 // The single lookup result must be a variable template declaration. 2514 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2515 Id.TemplateId->Kind == TNK_Var_template) { 2516 assert(R.getAsSingle<VarTemplateDecl>() && 2517 "There should only be one declaration found."); 2518 } 2519 2520 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2521 } 2522 2523 return BuildDeclarationNameExpr(SS, R, ADL); 2524 } 2525 2526 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2527 /// declaration name, generally during template instantiation. 2528 /// There's a large number of things which don't need to be done along 2529 /// this path. 2530 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2531 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2532 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2533 DeclContext *DC = computeDeclContext(SS, false); 2534 if (!DC) 2535 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2536 NameInfo, /*TemplateArgs=*/nullptr); 2537 2538 if (RequireCompleteDeclContext(SS, DC)) 2539 return ExprError(); 2540 2541 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2542 LookupQualifiedName(R, DC); 2543 2544 if (R.isAmbiguous()) 2545 return ExprError(); 2546 2547 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2548 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2549 NameInfo, /*TemplateArgs=*/nullptr); 2550 2551 if (R.empty()) { 2552 Diag(NameInfo.getLoc(), diag::err_no_member) 2553 << NameInfo.getName() << DC << SS.getRange(); 2554 return ExprError(); 2555 } 2556 2557 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2558 // Diagnose a missing typename if this resolved unambiguously to a type in 2559 // a dependent context. If we can recover with a type, downgrade this to 2560 // a warning in Microsoft compatibility mode. 2561 unsigned DiagID = diag::err_typename_missing; 2562 if (RecoveryTSI && getLangOpts().MSVCCompat) 2563 DiagID = diag::ext_typename_missing; 2564 SourceLocation Loc = SS.getBeginLoc(); 2565 auto D = Diag(Loc, DiagID); 2566 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2567 << SourceRange(Loc, NameInfo.getEndLoc()); 2568 2569 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2570 // context. 2571 if (!RecoveryTSI) 2572 return ExprError(); 2573 2574 // Only issue the fixit if we're prepared to recover. 2575 D << FixItHint::CreateInsertion(Loc, "typename "); 2576 2577 // Recover by pretending this was an elaborated type. 2578 QualType Ty = Context.getTypeDeclType(TD); 2579 TypeLocBuilder TLB; 2580 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2581 2582 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2583 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2584 QTL.setElaboratedKeywordLoc(SourceLocation()); 2585 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2586 2587 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2588 2589 return ExprEmpty(); 2590 } 2591 2592 // Defend against this resolving to an implicit member access. We usually 2593 // won't get here if this might be a legitimate a class member (we end up in 2594 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2595 // a pointer-to-member or in an unevaluated context in C++11. 2596 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2597 return BuildPossibleImplicitMemberExpr(SS, 2598 /*TemplateKWLoc=*/SourceLocation(), 2599 R, /*TemplateArgs=*/nullptr, S); 2600 2601 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2602 } 2603 2604 /// The parser has read a name in, and Sema has detected that we're currently 2605 /// inside an ObjC method. Perform some additional checks and determine if we 2606 /// should form a reference to an ivar. 2607 /// 2608 /// Ideally, most of this would be done by lookup, but there's 2609 /// actually quite a lot of extra work involved. 2610 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2611 IdentifierInfo *II) { 2612 SourceLocation Loc = Lookup.getNameLoc(); 2613 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2614 2615 // Check for error condition which is already reported. 2616 if (!CurMethod) 2617 return DeclResult(true); 2618 2619 // There are two cases to handle here. 1) scoped lookup could have failed, 2620 // in which case we should look for an ivar. 2) scoped lookup could have 2621 // found a decl, but that decl is outside the current instance method (i.e. 2622 // a global variable). In these two cases, we do a lookup for an ivar with 2623 // this name, if the lookup sucedes, we replace it our current decl. 2624 2625 // If we're in a class method, we don't normally want to look for 2626 // ivars. But if we don't find anything else, and there's an 2627 // ivar, that's an error. 2628 bool IsClassMethod = CurMethod->isClassMethod(); 2629 2630 bool LookForIvars; 2631 if (Lookup.empty()) 2632 LookForIvars = true; 2633 else if (IsClassMethod) 2634 LookForIvars = false; 2635 else 2636 LookForIvars = (Lookup.isSingleResult() && 2637 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2638 ObjCInterfaceDecl *IFace = nullptr; 2639 if (LookForIvars) { 2640 IFace = CurMethod->getClassInterface(); 2641 ObjCInterfaceDecl *ClassDeclared; 2642 ObjCIvarDecl *IV = nullptr; 2643 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2644 // Diagnose using an ivar in a class method. 2645 if (IsClassMethod) { 2646 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2647 return DeclResult(true); 2648 } 2649 2650 // Diagnose the use of an ivar outside of the declaring class. 2651 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2652 !declaresSameEntity(ClassDeclared, IFace) && 2653 !getLangOpts().DebuggerSupport) 2654 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2655 2656 // Success. 2657 return IV; 2658 } 2659 } else if (CurMethod->isInstanceMethod()) { 2660 // We should warn if a local variable hides an ivar. 2661 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2662 ObjCInterfaceDecl *ClassDeclared; 2663 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2664 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2665 declaresSameEntity(IFace, ClassDeclared)) 2666 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2667 } 2668 } 2669 } else if (Lookup.isSingleResult() && 2670 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2671 // If accessing a stand-alone ivar in a class method, this is an error. 2672 if (const ObjCIvarDecl *IV = 2673 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2674 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2675 return DeclResult(true); 2676 } 2677 } 2678 2679 // Didn't encounter an error, didn't find an ivar. 2680 return DeclResult(false); 2681 } 2682 2683 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2684 ObjCIvarDecl *IV) { 2685 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2686 assert(CurMethod && CurMethod->isInstanceMethod() && 2687 "should not reference ivar from this context"); 2688 2689 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2690 assert(IFace && "should not reference ivar from this context"); 2691 2692 // If we're referencing an invalid decl, just return this as a silent 2693 // error node. The error diagnostic was already emitted on the decl. 2694 if (IV->isInvalidDecl()) 2695 return ExprError(); 2696 2697 // Check if referencing a field with __attribute__((deprecated)). 2698 if (DiagnoseUseOfDecl(IV, Loc)) 2699 return ExprError(); 2700 2701 // FIXME: This should use a new expr for a direct reference, don't 2702 // turn this into Self->ivar, just return a BareIVarExpr or something. 2703 IdentifierInfo &II = Context.Idents.get("self"); 2704 UnqualifiedId SelfName; 2705 SelfName.setIdentifier(&II, SourceLocation()); 2706 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2707 CXXScopeSpec SelfScopeSpec; 2708 SourceLocation TemplateKWLoc; 2709 ExprResult SelfExpr = 2710 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2711 /*HasTrailingLParen=*/false, 2712 /*IsAddressOfOperand=*/false); 2713 if (SelfExpr.isInvalid()) 2714 return ExprError(); 2715 2716 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2717 if (SelfExpr.isInvalid()) 2718 return ExprError(); 2719 2720 MarkAnyDeclReferenced(Loc, IV, true); 2721 2722 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2723 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2724 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2725 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2726 2727 ObjCIvarRefExpr *Result = new (Context) 2728 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2729 IV->getLocation(), SelfExpr.get(), true, true); 2730 2731 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2732 if (!isUnevaluatedContext() && 2733 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2734 getCurFunction()->recordUseOfWeak(Result); 2735 } 2736 if (getLangOpts().ObjCAutoRefCount) 2737 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2738 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2739 2740 return Result; 2741 } 2742 2743 /// The parser has read a name in, and Sema has detected that we're currently 2744 /// inside an ObjC method. Perform some additional checks and determine if we 2745 /// should form a reference to an ivar. If so, build an expression referencing 2746 /// that ivar. 2747 ExprResult 2748 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2749 IdentifierInfo *II, bool AllowBuiltinCreation) { 2750 // FIXME: Integrate this lookup step into LookupParsedName. 2751 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2752 if (Ivar.isInvalid()) 2753 return ExprError(); 2754 if (Ivar.isUsable()) 2755 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2756 cast<ObjCIvarDecl>(Ivar.get())); 2757 2758 if (Lookup.empty() && II && AllowBuiltinCreation) 2759 LookupBuiltin(Lookup); 2760 2761 // Sentinel value saying that we didn't do anything special. 2762 return ExprResult(false); 2763 } 2764 2765 /// Cast a base object to a member's actual type. 2766 /// 2767 /// Logically this happens in three phases: 2768 /// 2769 /// * First we cast from the base type to the naming class. 2770 /// The naming class is the class into which we were looking 2771 /// when we found the member; it's the qualifier type if a 2772 /// qualifier was provided, and otherwise it's the base type. 2773 /// 2774 /// * Next we cast from the naming class to the declaring class. 2775 /// If the member we found was brought into a class's scope by 2776 /// a using declaration, this is that class; otherwise it's 2777 /// the class declaring the member. 2778 /// 2779 /// * Finally we cast from the declaring class to the "true" 2780 /// declaring class of the member. This conversion does not 2781 /// obey access control. 2782 ExprResult 2783 Sema::PerformObjectMemberConversion(Expr *From, 2784 NestedNameSpecifier *Qualifier, 2785 NamedDecl *FoundDecl, 2786 NamedDecl *Member) { 2787 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2788 if (!RD) 2789 return From; 2790 2791 QualType DestRecordType; 2792 QualType DestType; 2793 QualType FromRecordType; 2794 QualType FromType = From->getType(); 2795 bool PointerConversions = false; 2796 if (isa<FieldDecl>(Member)) { 2797 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2798 auto FromPtrType = FromType->getAs<PointerType>(); 2799 DestRecordType = Context.getAddrSpaceQualType( 2800 DestRecordType, FromPtrType 2801 ? FromType->getPointeeType().getAddressSpace() 2802 : FromType.getAddressSpace()); 2803 2804 if (FromPtrType) { 2805 DestType = Context.getPointerType(DestRecordType); 2806 FromRecordType = FromPtrType->getPointeeType(); 2807 PointerConversions = true; 2808 } else { 2809 DestType = DestRecordType; 2810 FromRecordType = FromType; 2811 } 2812 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2813 if (Method->isStatic()) 2814 return From; 2815 2816 DestType = Method->getThisType(); 2817 DestRecordType = DestType->getPointeeType(); 2818 2819 if (FromType->getAs<PointerType>()) { 2820 FromRecordType = FromType->getPointeeType(); 2821 PointerConversions = true; 2822 } else { 2823 FromRecordType = FromType; 2824 DestType = DestRecordType; 2825 } 2826 2827 LangAS FromAS = FromRecordType.getAddressSpace(); 2828 LangAS DestAS = DestRecordType.getAddressSpace(); 2829 if (FromAS != DestAS) { 2830 QualType FromRecordTypeWithoutAS = 2831 Context.removeAddrSpaceQualType(FromRecordType); 2832 QualType FromTypeWithDestAS = 2833 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2834 if (PointerConversions) 2835 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2836 From = ImpCastExprToType(From, FromTypeWithDestAS, 2837 CK_AddressSpaceConversion, From->getValueKind()) 2838 .get(); 2839 } 2840 } else { 2841 // No conversion necessary. 2842 return From; 2843 } 2844 2845 if (DestType->isDependentType() || FromType->isDependentType()) 2846 return From; 2847 2848 // If the unqualified types are the same, no conversion is necessary. 2849 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2850 return From; 2851 2852 SourceRange FromRange = From->getSourceRange(); 2853 SourceLocation FromLoc = FromRange.getBegin(); 2854 2855 ExprValueKind VK = From->getValueKind(); 2856 2857 // C++ [class.member.lookup]p8: 2858 // [...] Ambiguities can often be resolved by qualifying a name with its 2859 // class name. 2860 // 2861 // If the member was a qualified name and the qualified referred to a 2862 // specific base subobject type, we'll cast to that intermediate type 2863 // first and then to the object in which the member is declared. That allows 2864 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2865 // 2866 // class Base { public: int x; }; 2867 // class Derived1 : public Base { }; 2868 // class Derived2 : public Base { }; 2869 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2870 // 2871 // void VeryDerived::f() { 2872 // x = 17; // error: ambiguous base subobjects 2873 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2874 // } 2875 if (Qualifier && Qualifier->getAsType()) { 2876 QualType QType = QualType(Qualifier->getAsType(), 0); 2877 assert(QType->isRecordType() && "lookup done with non-record type"); 2878 2879 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2880 2881 // In C++98, the qualifier type doesn't actually have to be a base 2882 // type of the object type, in which case we just ignore it. 2883 // Otherwise build the appropriate casts. 2884 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2885 CXXCastPath BasePath; 2886 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2887 FromLoc, FromRange, &BasePath)) 2888 return ExprError(); 2889 2890 if (PointerConversions) 2891 QType = Context.getPointerType(QType); 2892 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2893 VK, &BasePath).get(); 2894 2895 FromType = QType; 2896 FromRecordType = QRecordType; 2897 2898 // If the qualifier type was the same as the destination type, 2899 // we're done. 2900 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2901 return From; 2902 } 2903 } 2904 2905 bool IgnoreAccess = false; 2906 2907 // If we actually found the member through a using declaration, cast 2908 // down to the using declaration's type. 2909 // 2910 // Pointer equality is fine here because only one declaration of a 2911 // class ever has member declarations. 2912 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2913 assert(isa<UsingShadowDecl>(FoundDecl)); 2914 QualType URecordType = Context.getTypeDeclType( 2915 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2916 2917 // We only need to do this if the naming-class to declaring-class 2918 // conversion is non-trivial. 2919 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2920 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2921 CXXCastPath BasePath; 2922 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2923 FromLoc, FromRange, &BasePath)) 2924 return ExprError(); 2925 2926 QualType UType = URecordType; 2927 if (PointerConversions) 2928 UType = Context.getPointerType(UType); 2929 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2930 VK, &BasePath).get(); 2931 FromType = UType; 2932 FromRecordType = URecordType; 2933 } 2934 2935 // We don't do access control for the conversion from the 2936 // declaring class to the true declaring class. 2937 IgnoreAccess = true; 2938 } 2939 2940 CXXCastPath BasePath; 2941 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2942 FromLoc, FromRange, &BasePath, 2943 IgnoreAccess)) 2944 return ExprError(); 2945 2946 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2947 VK, &BasePath); 2948 } 2949 2950 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2951 const LookupResult &R, 2952 bool HasTrailingLParen) { 2953 // Only when used directly as the postfix-expression of a call. 2954 if (!HasTrailingLParen) 2955 return false; 2956 2957 // Never if a scope specifier was provided. 2958 if (SS.isSet()) 2959 return false; 2960 2961 // Only in C++ or ObjC++. 2962 if (!getLangOpts().CPlusPlus) 2963 return false; 2964 2965 // Turn off ADL when we find certain kinds of declarations during 2966 // normal lookup: 2967 for (NamedDecl *D : R) { 2968 // C++0x [basic.lookup.argdep]p3: 2969 // -- a declaration of a class member 2970 // Since using decls preserve this property, we check this on the 2971 // original decl. 2972 if (D->isCXXClassMember()) 2973 return false; 2974 2975 // C++0x [basic.lookup.argdep]p3: 2976 // -- a block-scope function declaration that is not a 2977 // using-declaration 2978 // NOTE: we also trigger this for function templates (in fact, we 2979 // don't check the decl type at all, since all other decl types 2980 // turn off ADL anyway). 2981 if (isa<UsingShadowDecl>(D)) 2982 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2983 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2984 return false; 2985 2986 // C++0x [basic.lookup.argdep]p3: 2987 // -- a declaration that is neither a function or a function 2988 // template 2989 // And also for builtin functions. 2990 if (isa<FunctionDecl>(D)) { 2991 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2992 2993 // But also builtin functions. 2994 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2995 return false; 2996 } else if (!isa<FunctionTemplateDecl>(D)) 2997 return false; 2998 } 2999 3000 return true; 3001 } 3002 3003 3004 /// Diagnoses obvious problems with the use of the given declaration 3005 /// as an expression. This is only actually called for lookups that 3006 /// were not overloaded, and it doesn't promise that the declaration 3007 /// will in fact be used. 3008 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3009 if (D->isInvalidDecl()) 3010 return true; 3011 3012 if (isa<TypedefNameDecl>(D)) { 3013 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3014 return true; 3015 } 3016 3017 if (isa<ObjCInterfaceDecl>(D)) { 3018 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3019 return true; 3020 } 3021 3022 if (isa<NamespaceDecl>(D)) { 3023 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3024 return true; 3025 } 3026 3027 return false; 3028 } 3029 3030 // Certain multiversion types should be treated as overloaded even when there is 3031 // only one result. 3032 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3033 assert(R.isSingleResult() && "Expected only a single result"); 3034 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3035 return FD && 3036 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3037 } 3038 3039 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3040 LookupResult &R, bool NeedsADL, 3041 bool AcceptInvalidDecl) { 3042 // If this is a single, fully-resolved result and we don't need ADL, 3043 // just build an ordinary singleton decl ref. 3044 if (!NeedsADL && R.isSingleResult() && 3045 !R.getAsSingle<FunctionTemplateDecl>() && 3046 !ShouldLookupResultBeMultiVersionOverload(R)) 3047 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3048 R.getRepresentativeDecl(), nullptr, 3049 AcceptInvalidDecl); 3050 3051 // We only need to check the declaration if there's exactly one 3052 // result, because in the overloaded case the results can only be 3053 // functions and function templates. 3054 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3055 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3056 return ExprError(); 3057 3058 // Otherwise, just build an unresolved lookup expression. Suppress 3059 // any lookup-related diagnostics; we'll hash these out later, when 3060 // we've picked a target. 3061 R.suppressDiagnostics(); 3062 3063 UnresolvedLookupExpr *ULE 3064 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3065 SS.getWithLocInContext(Context), 3066 R.getLookupNameInfo(), 3067 NeedsADL, R.isOverloadedResult(), 3068 R.begin(), R.end()); 3069 3070 return ULE; 3071 } 3072 3073 static void 3074 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3075 ValueDecl *var, DeclContext *DC); 3076 3077 /// Complete semantic analysis for a reference to the given declaration. 3078 ExprResult Sema::BuildDeclarationNameExpr( 3079 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3080 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3081 bool AcceptInvalidDecl) { 3082 assert(D && "Cannot refer to a NULL declaration"); 3083 assert(!isa<FunctionTemplateDecl>(D) && 3084 "Cannot refer unambiguously to a function template"); 3085 3086 SourceLocation Loc = NameInfo.getLoc(); 3087 if (CheckDeclInExpr(*this, Loc, D)) 3088 return ExprError(); 3089 3090 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3091 // Specifically diagnose references to class templates that are missing 3092 // a template argument list. 3093 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3094 return ExprError(); 3095 } 3096 3097 // Make sure that we're referring to a value. 3098 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3099 if (!VD) { 3100 Diag(Loc, diag::err_ref_non_value) 3101 << D << SS.getRange(); 3102 Diag(D->getLocation(), diag::note_declared_at); 3103 return ExprError(); 3104 } 3105 3106 // Check whether this declaration can be used. Note that we suppress 3107 // this check when we're going to perform argument-dependent lookup 3108 // on this function name, because this might not be the function 3109 // that overload resolution actually selects. 3110 if (DiagnoseUseOfDecl(VD, Loc)) 3111 return ExprError(); 3112 3113 // Only create DeclRefExpr's for valid Decl's. 3114 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3115 return ExprError(); 3116 3117 // Handle members of anonymous structs and unions. If we got here, 3118 // and the reference is to a class member indirect field, then this 3119 // must be the subject of a pointer-to-member expression. 3120 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3121 if (!indirectField->isCXXClassMember()) 3122 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3123 indirectField); 3124 3125 { 3126 QualType type = VD->getType(); 3127 if (type.isNull()) 3128 return ExprError(); 3129 ExprValueKind valueKind = VK_RValue; 3130 3131 switch (D->getKind()) { 3132 // Ignore all the non-ValueDecl kinds. 3133 #define ABSTRACT_DECL(kind) 3134 #define VALUE(type, base) 3135 #define DECL(type, base) \ 3136 case Decl::type: 3137 #include "clang/AST/DeclNodes.inc" 3138 llvm_unreachable("invalid value decl kind"); 3139 3140 // These shouldn't make it here. 3141 case Decl::ObjCAtDefsField: 3142 llvm_unreachable("forming non-member reference to ivar?"); 3143 3144 // Enum constants are always r-values and never references. 3145 // Unresolved using declarations are dependent. 3146 case Decl::EnumConstant: 3147 case Decl::UnresolvedUsingValue: 3148 case Decl::OMPDeclareReduction: 3149 case Decl::OMPDeclareMapper: 3150 valueKind = VK_RValue; 3151 break; 3152 3153 // Fields and indirect fields that got here must be for 3154 // pointer-to-member expressions; we just call them l-values for 3155 // internal consistency, because this subexpression doesn't really 3156 // exist in the high-level semantics. 3157 case Decl::Field: 3158 case Decl::IndirectField: 3159 case Decl::ObjCIvar: 3160 assert(getLangOpts().CPlusPlus && 3161 "building reference to field in C?"); 3162 3163 // These can't have reference type in well-formed programs, but 3164 // for internal consistency we do this anyway. 3165 type = type.getNonReferenceType(); 3166 valueKind = VK_LValue; 3167 break; 3168 3169 // Non-type template parameters are either l-values or r-values 3170 // depending on the type. 3171 case Decl::NonTypeTemplateParm: { 3172 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3173 type = reftype->getPointeeType(); 3174 valueKind = VK_LValue; // even if the parameter is an r-value reference 3175 break; 3176 } 3177 3178 // For non-references, we need to strip qualifiers just in case 3179 // the template parameter was declared as 'const int' or whatever. 3180 valueKind = VK_RValue; 3181 type = type.getUnqualifiedType(); 3182 break; 3183 } 3184 3185 case Decl::Var: 3186 case Decl::VarTemplateSpecialization: 3187 case Decl::VarTemplatePartialSpecialization: 3188 case Decl::Decomposition: 3189 case Decl::OMPCapturedExpr: 3190 // In C, "extern void blah;" is valid and is an r-value. 3191 if (!getLangOpts().CPlusPlus && 3192 !type.hasQualifiers() && 3193 type->isVoidType()) { 3194 valueKind = VK_RValue; 3195 break; 3196 } 3197 LLVM_FALLTHROUGH; 3198 3199 case Decl::ImplicitParam: 3200 case Decl::ParmVar: { 3201 // These are always l-values. 3202 valueKind = VK_LValue; 3203 type = type.getNonReferenceType(); 3204 3205 // FIXME: Does the addition of const really only apply in 3206 // potentially-evaluated contexts? Since the variable isn't actually 3207 // captured in an unevaluated context, it seems that the answer is no. 3208 if (!isUnevaluatedContext()) { 3209 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3210 if (!CapturedType.isNull()) 3211 type = CapturedType; 3212 } 3213 3214 break; 3215 } 3216 3217 case Decl::Binding: { 3218 // These are always lvalues. 3219 valueKind = VK_LValue; 3220 type = type.getNonReferenceType(); 3221 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3222 // decides how that's supposed to work. 3223 auto *BD = cast<BindingDecl>(VD); 3224 if (BD->getDeclContext() != CurContext) { 3225 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3226 if (DD && DD->hasLocalStorage()) 3227 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3228 } 3229 break; 3230 } 3231 3232 case Decl::Function: { 3233 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3234 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3235 type = Context.BuiltinFnTy; 3236 valueKind = VK_RValue; 3237 break; 3238 } 3239 } 3240 3241 const FunctionType *fty = type->castAs<FunctionType>(); 3242 3243 // If we're referring to a function with an __unknown_anytype 3244 // result type, make the entire expression __unknown_anytype. 3245 if (fty->getReturnType() == Context.UnknownAnyTy) { 3246 type = Context.UnknownAnyTy; 3247 valueKind = VK_RValue; 3248 break; 3249 } 3250 3251 // Functions are l-values in C++. 3252 if (getLangOpts().CPlusPlus) { 3253 valueKind = VK_LValue; 3254 break; 3255 } 3256 3257 // C99 DR 316 says that, if a function type comes from a 3258 // function definition (without a prototype), that type is only 3259 // used for checking compatibility. Therefore, when referencing 3260 // the function, we pretend that we don't have the full function 3261 // type. 3262 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3263 isa<FunctionProtoType>(fty)) 3264 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3265 fty->getExtInfo()); 3266 3267 // Functions are r-values in C. 3268 valueKind = VK_RValue; 3269 break; 3270 } 3271 3272 case Decl::CXXDeductionGuide: 3273 llvm_unreachable("building reference to deduction guide"); 3274 3275 case Decl::MSProperty: 3276 valueKind = VK_LValue; 3277 break; 3278 3279 case Decl::CXXMethod: 3280 // If we're referring to a method with an __unknown_anytype 3281 // result type, make the entire expression __unknown_anytype. 3282 // This should only be possible with a type written directly. 3283 if (const FunctionProtoType *proto 3284 = dyn_cast<FunctionProtoType>(VD->getType())) 3285 if (proto->getReturnType() == Context.UnknownAnyTy) { 3286 type = Context.UnknownAnyTy; 3287 valueKind = VK_RValue; 3288 break; 3289 } 3290 3291 // C++ methods are l-values if static, r-values if non-static. 3292 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3293 valueKind = VK_LValue; 3294 break; 3295 } 3296 LLVM_FALLTHROUGH; 3297 3298 case Decl::CXXConversion: 3299 case Decl::CXXDestructor: 3300 case Decl::CXXConstructor: 3301 valueKind = VK_RValue; 3302 break; 3303 } 3304 3305 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3306 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3307 TemplateArgs); 3308 } 3309 } 3310 3311 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3312 SmallString<32> &Target) { 3313 Target.resize(CharByteWidth * (Source.size() + 1)); 3314 char *ResultPtr = &Target[0]; 3315 const llvm::UTF8 *ErrorPtr; 3316 bool success = 3317 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3318 (void)success; 3319 assert(success); 3320 Target.resize(ResultPtr - &Target[0]); 3321 } 3322 3323 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3324 PredefinedExpr::IdentKind IK) { 3325 // Pick the current block, lambda, captured statement or function. 3326 Decl *currentDecl = nullptr; 3327 if (const BlockScopeInfo *BSI = getCurBlock()) 3328 currentDecl = BSI->TheDecl; 3329 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3330 currentDecl = LSI->CallOperator; 3331 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3332 currentDecl = CSI->TheCapturedDecl; 3333 else 3334 currentDecl = getCurFunctionOrMethodDecl(); 3335 3336 if (!currentDecl) { 3337 Diag(Loc, diag::ext_predef_outside_function); 3338 currentDecl = Context.getTranslationUnitDecl(); 3339 } 3340 3341 QualType ResTy; 3342 StringLiteral *SL = nullptr; 3343 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3344 ResTy = Context.DependentTy; 3345 else { 3346 // Pre-defined identifiers are of type char[x], where x is the length of 3347 // the string. 3348 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3349 unsigned Length = Str.length(); 3350 3351 llvm::APInt LengthI(32, Length + 1); 3352 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3353 ResTy = 3354 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3355 SmallString<32> RawChars; 3356 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3357 Str, RawChars); 3358 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3359 ArrayType::Normal, 3360 /*IndexTypeQuals*/ 0); 3361 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3362 /*Pascal*/ false, ResTy, Loc); 3363 } else { 3364 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3365 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3366 ArrayType::Normal, 3367 /*IndexTypeQuals*/ 0); 3368 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3369 /*Pascal*/ false, ResTy, Loc); 3370 } 3371 } 3372 3373 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3374 } 3375 3376 static std::pair<QualType, StringLiteral *> 3377 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType, 3378 SourceLocation OpLoc, PredefinedExpr::IdentKind K) { 3379 std::pair<QualType, StringLiteral*> Result{{}, nullptr}; 3380 3381 if (OpType->isDependentType()) { 3382 Result.first = Context.DependentTy; 3383 return Result; 3384 } 3385 3386 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType); 3387 llvm::APInt Length(32, Str.length() + 1); 3388 Result.first = 3389 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3390 Result.first = Context.getConstantArrayType( 3391 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0); 3392 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3393 /*Pascal*/ false, Result.first, OpLoc); 3394 return Result; 3395 } 3396 3397 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3398 TypeSourceInfo *Operand) { 3399 QualType ResultTy; 3400 StringLiteral *SL; 3401 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3402 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType); 3403 3404 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3405 PredefinedExpr::UniqueStableNameType, SL, 3406 Operand); 3407 } 3408 3409 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc, 3410 Expr *E) { 3411 QualType ResultTy; 3412 StringLiteral *SL; 3413 std::tie(ResultTy, SL) = GetUniqueStableNameInfo( 3414 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr); 3415 3416 return PredefinedExpr::Create(Context, OpLoc, ResultTy, 3417 PredefinedExpr::UniqueStableNameExpr, SL, E); 3418 } 3419 3420 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3421 SourceLocation L, SourceLocation R, 3422 ParsedType Ty) { 3423 TypeSourceInfo *TInfo = nullptr; 3424 QualType T = GetTypeFromParser(Ty, &TInfo); 3425 3426 if (T.isNull()) 3427 return ExprError(); 3428 if (!TInfo) 3429 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 3430 3431 return BuildUniqueStableName(OpLoc, TInfo); 3432 } 3433 3434 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc, 3435 SourceLocation L, SourceLocation R, 3436 Expr *E) { 3437 return BuildUniqueStableName(OpLoc, E); 3438 } 3439 3440 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3441 PredefinedExpr::IdentKind IK; 3442 3443 switch (Kind) { 3444 default: llvm_unreachable("Unknown simple primary expr!"); 3445 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3446 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3447 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3448 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3449 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3450 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3451 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3452 } 3453 3454 return BuildPredefinedExpr(Loc, IK); 3455 } 3456 3457 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3458 SmallString<16> CharBuffer; 3459 bool Invalid = false; 3460 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3461 if (Invalid) 3462 return ExprError(); 3463 3464 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3465 PP, Tok.getKind()); 3466 if (Literal.hadError()) 3467 return ExprError(); 3468 3469 QualType Ty; 3470 if (Literal.isWide()) 3471 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3472 else if (Literal.isUTF8() && getLangOpts().Char8) 3473 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3474 else if (Literal.isUTF16()) 3475 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3476 else if (Literal.isUTF32()) 3477 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3478 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3479 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3480 else 3481 Ty = Context.CharTy; // 'x' -> char in C++ 3482 3483 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3484 if (Literal.isWide()) 3485 Kind = CharacterLiteral::Wide; 3486 else if (Literal.isUTF16()) 3487 Kind = CharacterLiteral::UTF16; 3488 else if (Literal.isUTF32()) 3489 Kind = CharacterLiteral::UTF32; 3490 else if (Literal.isUTF8()) 3491 Kind = CharacterLiteral::UTF8; 3492 3493 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3494 Tok.getLocation()); 3495 3496 if (Literal.getUDSuffix().empty()) 3497 return Lit; 3498 3499 // We're building a user-defined literal. 3500 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3501 SourceLocation UDSuffixLoc = 3502 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3503 3504 // Make sure we're allowed user-defined literals here. 3505 if (!UDLScope) 3506 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3507 3508 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3509 // operator "" X (ch) 3510 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3511 Lit, Tok.getLocation()); 3512 } 3513 3514 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3515 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3516 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3517 Context.IntTy, Loc); 3518 } 3519 3520 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3521 QualType Ty, SourceLocation Loc) { 3522 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3523 3524 using llvm::APFloat; 3525 APFloat Val(Format); 3526 3527 APFloat::opStatus result = Literal.GetFloatValue(Val); 3528 3529 // Overflow is always an error, but underflow is only an error if 3530 // we underflowed to zero (APFloat reports denormals as underflow). 3531 if ((result & APFloat::opOverflow) || 3532 ((result & APFloat::opUnderflow) && Val.isZero())) { 3533 unsigned diagnostic; 3534 SmallString<20> buffer; 3535 if (result & APFloat::opOverflow) { 3536 diagnostic = diag::warn_float_overflow; 3537 APFloat::getLargest(Format).toString(buffer); 3538 } else { 3539 diagnostic = diag::warn_float_underflow; 3540 APFloat::getSmallest(Format).toString(buffer); 3541 } 3542 3543 S.Diag(Loc, diagnostic) 3544 << Ty 3545 << StringRef(buffer.data(), buffer.size()); 3546 } 3547 3548 bool isExact = (result == APFloat::opOK); 3549 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3550 } 3551 3552 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3553 assert(E && "Invalid expression"); 3554 3555 if (E->isValueDependent()) 3556 return false; 3557 3558 QualType QT = E->getType(); 3559 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3560 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3561 return true; 3562 } 3563 3564 llvm::APSInt ValueAPS; 3565 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3566 3567 if (R.isInvalid()) 3568 return true; 3569 3570 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3571 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3572 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3573 << ValueAPS.toString(10) << ValueIsPositive; 3574 return true; 3575 } 3576 3577 return false; 3578 } 3579 3580 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3581 // Fast path for a single digit (which is quite common). A single digit 3582 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3583 if (Tok.getLength() == 1) { 3584 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3585 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3586 } 3587 3588 SmallString<128> SpellingBuffer; 3589 // NumericLiteralParser wants to overread by one character. Add padding to 3590 // the buffer in case the token is copied to the buffer. If getSpelling() 3591 // returns a StringRef to the memory buffer, it should have a null char at 3592 // the EOF, so it is also safe. 3593 SpellingBuffer.resize(Tok.getLength() + 1); 3594 3595 // Get the spelling of the token, which eliminates trigraphs, etc. 3596 bool Invalid = false; 3597 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3598 if (Invalid) 3599 return ExprError(); 3600 3601 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3602 if (Literal.hadError) 3603 return ExprError(); 3604 3605 if (Literal.hasUDSuffix()) { 3606 // We're building a user-defined literal. 3607 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3608 SourceLocation UDSuffixLoc = 3609 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3610 3611 // Make sure we're allowed user-defined literals here. 3612 if (!UDLScope) 3613 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3614 3615 QualType CookedTy; 3616 if (Literal.isFloatingLiteral()) { 3617 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3618 // long double, the literal is treated as a call of the form 3619 // operator "" X (f L) 3620 CookedTy = Context.LongDoubleTy; 3621 } else { 3622 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3623 // unsigned long long, the literal is treated as a call of the form 3624 // operator "" X (n ULL) 3625 CookedTy = Context.UnsignedLongLongTy; 3626 } 3627 3628 DeclarationName OpName = 3629 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3630 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3631 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3632 3633 SourceLocation TokLoc = Tok.getLocation(); 3634 3635 // Perform literal operator lookup to determine if we're building a raw 3636 // literal or a cooked one. 3637 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3638 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3639 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3640 /*AllowStringTemplate*/ false, 3641 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3642 case LOLR_ErrorNoDiagnostic: 3643 // Lookup failure for imaginary constants isn't fatal, there's still the 3644 // GNU extension producing _Complex types. 3645 break; 3646 case LOLR_Error: 3647 return ExprError(); 3648 case LOLR_Cooked: { 3649 Expr *Lit; 3650 if (Literal.isFloatingLiteral()) { 3651 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3652 } else { 3653 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3654 if (Literal.GetIntegerValue(ResultVal)) 3655 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3656 << /* Unsigned */ 1; 3657 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3658 Tok.getLocation()); 3659 } 3660 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3661 } 3662 3663 case LOLR_Raw: { 3664 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3665 // literal is treated as a call of the form 3666 // operator "" X ("n") 3667 unsigned Length = Literal.getUDSuffixOffset(); 3668 QualType StrTy = Context.getConstantArrayType( 3669 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3670 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3671 Expr *Lit = StringLiteral::Create( 3672 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3673 /*Pascal*/false, StrTy, &TokLoc, 1); 3674 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3675 } 3676 3677 case LOLR_Template: { 3678 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3679 // template), L is treated as a call fo the form 3680 // operator "" X <'c1', 'c2', ... 'ck'>() 3681 // where n is the source character sequence c1 c2 ... ck. 3682 TemplateArgumentListInfo ExplicitArgs; 3683 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3684 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3685 llvm::APSInt Value(CharBits, CharIsUnsigned); 3686 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3687 Value = TokSpelling[I]; 3688 TemplateArgument Arg(Context, Value, Context.CharTy); 3689 TemplateArgumentLocInfo ArgInfo; 3690 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3691 } 3692 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3693 &ExplicitArgs); 3694 } 3695 case LOLR_StringTemplate: 3696 llvm_unreachable("unexpected literal operator lookup result"); 3697 } 3698 } 3699 3700 Expr *Res; 3701 3702 if (Literal.isFixedPointLiteral()) { 3703 QualType Ty; 3704 3705 if (Literal.isAccum) { 3706 if (Literal.isHalf) { 3707 Ty = Context.ShortAccumTy; 3708 } else if (Literal.isLong) { 3709 Ty = Context.LongAccumTy; 3710 } else { 3711 Ty = Context.AccumTy; 3712 } 3713 } else if (Literal.isFract) { 3714 if (Literal.isHalf) { 3715 Ty = Context.ShortFractTy; 3716 } else if (Literal.isLong) { 3717 Ty = Context.LongFractTy; 3718 } else { 3719 Ty = Context.FractTy; 3720 } 3721 } 3722 3723 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3724 3725 bool isSigned = !Literal.isUnsigned; 3726 unsigned scale = Context.getFixedPointScale(Ty); 3727 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3728 3729 llvm::APInt Val(bit_width, 0, isSigned); 3730 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3731 bool ValIsZero = Val.isNullValue() && !Overflowed; 3732 3733 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3734 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3735 // Clause 6.4.4 - The value of a constant shall be in the range of 3736 // representable values for its type, with exception for constants of a 3737 // fract type with a value of exactly 1; such a constant shall denote 3738 // the maximal value for the type. 3739 --Val; 3740 else if (Val.ugt(MaxVal) || Overflowed) 3741 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3742 3743 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3744 Tok.getLocation(), scale); 3745 } else if (Literal.isFloatingLiteral()) { 3746 QualType Ty; 3747 if (Literal.isHalf){ 3748 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3749 Ty = Context.HalfTy; 3750 else { 3751 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3752 return ExprError(); 3753 } 3754 } else if (Literal.isFloat) 3755 Ty = Context.FloatTy; 3756 else if (Literal.isLong) 3757 Ty = Context.LongDoubleTy; 3758 else if (Literal.isFloat16) 3759 Ty = Context.Float16Ty; 3760 else if (Literal.isFloat128) 3761 Ty = Context.Float128Ty; 3762 else 3763 Ty = Context.DoubleTy; 3764 3765 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3766 3767 if (Ty == Context.DoubleTy) { 3768 if (getLangOpts().SinglePrecisionConstants) { 3769 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3770 if (BTy->getKind() != BuiltinType::Float) { 3771 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3772 } 3773 } else if (getLangOpts().OpenCL && 3774 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3775 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3776 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3777 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3778 } 3779 } 3780 } else if (!Literal.isIntegerLiteral()) { 3781 return ExprError(); 3782 } else { 3783 QualType Ty; 3784 3785 // 'long long' is a C99 or C++11 feature. 3786 if (!getLangOpts().C99 && Literal.isLongLong) { 3787 if (getLangOpts().CPlusPlus) 3788 Diag(Tok.getLocation(), 3789 getLangOpts().CPlusPlus11 ? 3790 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3791 else 3792 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3793 } 3794 3795 // Get the value in the widest-possible width. 3796 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3797 llvm::APInt ResultVal(MaxWidth, 0); 3798 3799 if (Literal.GetIntegerValue(ResultVal)) { 3800 // If this value didn't fit into uintmax_t, error and force to ull. 3801 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3802 << /* Unsigned */ 1; 3803 Ty = Context.UnsignedLongLongTy; 3804 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3805 "long long is not intmax_t?"); 3806 } else { 3807 // If this value fits into a ULL, try to figure out what else it fits into 3808 // according to the rules of C99 6.4.4.1p5. 3809 3810 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3811 // be an unsigned int. 3812 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3813 3814 // Check from smallest to largest, picking the smallest type we can. 3815 unsigned Width = 0; 3816 3817 // Microsoft specific integer suffixes are explicitly sized. 3818 if (Literal.MicrosoftInteger) { 3819 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3820 Width = 8; 3821 Ty = Context.CharTy; 3822 } else { 3823 Width = Literal.MicrosoftInteger; 3824 Ty = Context.getIntTypeForBitwidth(Width, 3825 /*Signed=*/!Literal.isUnsigned); 3826 } 3827 } 3828 3829 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3830 // Are int/unsigned possibilities? 3831 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3832 3833 // Does it fit in a unsigned int? 3834 if (ResultVal.isIntN(IntSize)) { 3835 // Does it fit in a signed int? 3836 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3837 Ty = Context.IntTy; 3838 else if (AllowUnsigned) 3839 Ty = Context.UnsignedIntTy; 3840 Width = IntSize; 3841 } 3842 } 3843 3844 // Are long/unsigned long possibilities? 3845 if (Ty.isNull() && !Literal.isLongLong) { 3846 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3847 3848 // Does it fit in a unsigned long? 3849 if (ResultVal.isIntN(LongSize)) { 3850 // Does it fit in a signed long? 3851 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3852 Ty = Context.LongTy; 3853 else if (AllowUnsigned) 3854 Ty = Context.UnsignedLongTy; 3855 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3856 // is compatible. 3857 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3858 const unsigned LongLongSize = 3859 Context.getTargetInfo().getLongLongWidth(); 3860 Diag(Tok.getLocation(), 3861 getLangOpts().CPlusPlus 3862 ? Literal.isLong 3863 ? diag::warn_old_implicitly_unsigned_long_cxx 3864 : /*C++98 UB*/ diag:: 3865 ext_old_implicitly_unsigned_long_cxx 3866 : diag::warn_old_implicitly_unsigned_long) 3867 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3868 : /*will be ill-formed*/ 1); 3869 Ty = Context.UnsignedLongTy; 3870 } 3871 Width = LongSize; 3872 } 3873 } 3874 3875 // Check long long if needed. 3876 if (Ty.isNull()) { 3877 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3878 3879 // Does it fit in a unsigned long long? 3880 if (ResultVal.isIntN(LongLongSize)) { 3881 // Does it fit in a signed long long? 3882 // To be compatible with MSVC, hex integer literals ending with the 3883 // LL or i64 suffix are always signed in Microsoft mode. 3884 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3885 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3886 Ty = Context.LongLongTy; 3887 else if (AllowUnsigned) 3888 Ty = Context.UnsignedLongLongTy; 3889 Width = LongLongSize; 3890 } 3891 } 3892 3893 // If we still couldn't decide a type, we probably have something that 3894 // does not fit in a signed long long, but has no U suffix. 3895 if (Ty.isNull()) { 3896 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3897 Ty = Context.UnsignedLongLongTy; 3898 Width = Context.getTargetInfo().getLongLongWidth(); 3899 } 3900 3901 if (ResultVal.getBitWidth() != Width) 3902 ResultVal = ResultVal.trunc(Width); 3903 } 3904 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3905 } 3906 3907 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3908 if (Literal.isImaginary) { 3909 Res = new (Context) ImaginaryLiteral(Res, 3910 Context.getComplexType(Res->getType())); 3911 3912 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3913 } 3914 return Res; 3915 } 3916 3917 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3918 assert(E && "ActOnParenExpr() missing expr"); 3919 return new (Context) ParenExpr(L, R, E); 3920 } 3921 3922 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3923 SourceLocation Loc, 3924 SourceRange ArgRange) { 3925 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3926 // scalar or vector data type argument..." 3927 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3928 // type (C99 6.2.5p18) or void. 3929 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3930 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3931 << T << ArgRange; 3932 return true; 3933 } 3934 3935 assert((T->isVoidType() || !T->isIncompleteType()) && 3936 "Scalar types should always be complete"); 3937 return false; 3938 } 3939 3940 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3941 SourceLocation Loc, 3942 SourceRange ArgRange, 3943 UnaryExprOrTypeTrait TraitKind) { 3944 // Invalid types must be hard errors for SFINAE in C++. 3945 if (S.LangOpts.CPlusPlus) 3946 return true; 3947 3948 // C99 6.5.3.4p1: 3949 if (T->isFunctionType() && 3950 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3951 TraitKind == UETT_PreferredAlignOf)) { 3952 // sizeof(function)/alignof(function) is allowed as an extension. 3953 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3954 << TraitKind << ArgRange; 3955 return false; 3956 } 3957 3958 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3959 // this is an error (OpenCL v1.1 s6.3.k) 3960 if (T->isVoidType()) { 3961 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3962 : diag::ext_sizeof_alignof_void_type; 3963 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3964 return false; 3965 } 3966 3967 return true; 3968 } 3969 3970 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3971 SourceLocation Loc, 3972 SourceRange ArgRange, 3973 UnaryExprOrTypeTrait TraitKind) { 3974 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3975 // runtime doesn't allow it. 3976 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3977 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3978 << T << (TraitKind == UETT_SizeOf) 3979 << ArgRange; 3980 return true; 3981 } 3982 3983 return false; 3984 } 3985 3986 /// Check whether E is a pointer from a decayed array type (the decayed 3987 /// pointer type is equal to T) and emit a warning if it is. 3988 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3989 Expr *E) { 3990 // Don't warn if the operation changed the type. 3991 if (T != E->getType()) 3992 return; 3993 3994 // Now look for array decays. 3995 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3996 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3997 return; 3998 3999 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4000 << ICE->getType() 4001 << ICE->getSubExpr()->getType(); 4002 } 4003 4004 /// Check the constraints on expression operands to unary type expression 4005 /// and type traits. 4006 /// 4007 /// Completes any types necessary and validates the constraints on the operand 4008 /// expression. The logic mostly mirrors the type-based overload, but may modify 4009 /// the expression as it completes the type for that expression through template 4010 /// instantiation, etc. 4011 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4012 UnaryExprOrTypeTrait ExprKind) { 4013 QualType ExprTy = E->getType(); 4014 assert(!ExprTy->isReferenceType()); 4015 4016 bool IsUnevaluatedOperand = 4017 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4018 ExprKind == UETT_PreferredAlignOf); 4019 if (IsUnevaluatedOperand) { 4020 ExprResult Result = CheckUnevaluatedOperand(E); 4021 if (Result.isInvalid()) 4022 return true; 4023 E = Result.get(); 4024 } 4025 4026 if (ExprKind == UETT_VecStep) 4027 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4028 E->getSourceRange()); 4029 4030 // Whitelist some types as extensions 4031 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4032 E->getSourceRange(), ExprKind)) 4033 return false; 4034 4035 // 'alignof' applied to an expression only requires the base element type of 4036 // the expression to be complete. 'sizeof' requires the expression's type to 4037 // be complete (and will attempt to complete it if it's an array of unknown 4038 // bound). 4039 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4040 if (RequireCompleteSizedType( 4041 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4042 diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4043 E->getSourceRange())) 4044 return true; 4045 } else { 4046 if (RequireCompleteSizedExprType( 4047 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, ExprKind, 4048 E->getSourceRange())) 4049 return true; 4050 } 4051 4052 // Completing the expression's type may have changed it. 4053 ExprTy = E->getType(); 4054 assert(!ExprTy->isReferenceType()); 4055 4056 if (ExprTy->isFunctionType()) { 4057 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4058 << ExprKind << E->getSourceRange(); 4059 return true; 4060 } 4061 4062 // The operand for sizeof and alignof is in an unevaluated expression context, 4063 // so side effects could result in unintended consequences. 4064 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4065 E->HasSideEffects(Context, false)) 4066 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4067 4068 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4069 E->getSourceRange(), ExprKind)) 4070 return true; 4071 4072 if (ExprKind == UETT_SizeOf) { 4073 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4074 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4075 QualType OType = PVD->getOriginalType(); 4076 QualType Type = PVD->getType(); 4077 if (Type->isPointerType() && OType->isArrayType()) { 4078 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4079 << Type << OType; 4080 Diag(PVD->getLocation(), diag::note_declared_at); 4081 } 4082 } 4083 } 4084 4085 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4086 // decays into a pointer and returns an unintended result. This is most 4087 // likely a typo for "sizeof(array) op x". 4088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4089 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4090 BO->getLHS()); 4091 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4092 BO->getRHS()); 4093 } 4094 } 4095 4096 return false; 4097 } 4098 4099 /// Check the constraints on operands to unary expression and type 4100 /// traits. 4101 /// 4102 /// This will complete any types necessary, and validate the various constraints 4103 /// on those operands. 4104 /// 4105 /// The UsualUnaryConversions() function is *not* called by this routine. 4106 /// C99 6.3.2.1p[2-4] all state: 4107 /// Except when it is the operand of the sizeof operator ... 4108 /// 4109 /// C++ [expr.sizeof]p4 4110 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4111 /// standard conversions are not applied to the operand of sizeof. 4112 /// 4113 /// This policy is followed for all of the unary trait expressions. 4114 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4115 SourceLocation OpLoc, 4116 SourceRange ExprRange, 4117 UnaryExprOrTypeTrait ExprKind) { 4118 if (ExprType->isDependentType()) 4119 return false; 4120 4121 // C++ [expr.sizeof]p2: 4122 // When applied to a reference or a reference type, the result 4123 // is the size of the referenced type. 4124 // C++11 [expr.alignof]p3: 4125 // When alignof is applied to a reference type, the result 4126 // shall be the alignment of the referenced type. 4127 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4128 ExprType = Ref->getPointeeType(); 4129 4130 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4131 // When alignof or _Alignof is applied to an array type, the result 4132 // is the alignment of the element type. 4133 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4134 ExprKind == UETT_OpenMPRequiredSimdAlign) 4135 ExprType = Context.getBaseElementType(ExprType); 4136 4137 if (ExprKind == UETT_VecStep) 4138 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4139 4140 // Whitelist some types as extensions 4141 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4142 ExprKind)) 4143 return false; 4144 4145 if (RequireCompleteSizedType( 4146 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4147 ExprKind, ExprRange)) 4148 return true; 4149 4150 if (ExprType->isFunctionType()) { 4151 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4152 << ExprKind << ExprRange; 4153 return true; 4154 } 4155 4156 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4157 ExprKind)) 4158 return true; 4159 4160 return false; 4161 } 4162 4163 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4164 // Cannot know anything else if the expression is dependent. 4165 if (E->isTypeDependent()) 4166 return false; 4167 4168 if (E->getObjectKind() == OK_BitField) { 4169 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4170 << 1 << E->getSourceRange(); 4171 return true; 4172 } 4173 4174 ValueDecl *D = nullptr; 4175 Expr *Inner = E->IgnoreParens(); 4176 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4177 D = DRE->getDecl(); 4178 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4179 D = ME->getMemberDecl(); 4180 } 4181 4182 // If it's a field, require the containing struct to have a 4183 // complete definition so that we can compute the layout. 4184 // 4185 // This can happen in C++11 onwards, either by naming the member 4186 // in a way that is not transformed into a member access expression 4187 // (in an unevaluated operand, for instance), or by naming the member 4188 // in a trailing-return-type. 4189 // 4190 // For the record, since __alignof__ on expressions is a GCC 4191 // extension, GCC seems to permit this but always gives the 4192 // nonsensical answer 0. 4193 // 4194 // We don't really need the layout here --- we could instead just 4195 // directly check for all the appropriate alignment-lowing 4196 // attributes --- but that would require duplicating a lot of 4197 // logic that just isn't worth duplicating for such a marginal 4198 // use-case. 4199 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4200 // Fast path this check, since we at least know the record has a 4201 // definition if we can find a member of it. 4202 if (!FD->getParent()->isCompleteDefinition()) { 4203 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4204 << E->getSourceRange(); 4205 return true; 4206 } 4207 4208 // Otherwise, if it's a field, and the field doesn't have 4209 // reference type, then it must have a complete type (or be a 4210 // flexible array member, which we explicitly want to 4211 // white-list anyway), which makes the following checks trivial. 4212 if (!FD->getType()->isReferenceType()) 4213 return false; 4214 } 4215 4216 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4217 } 4218 4219 bool Sema::CheckVecStepExpr(Expr *E) { 4220 E = E->IgnoreParens(); 4221 4222 // Cannot know anything else if the expression is dependent. 4223 if (E->isTypeDependent()) 4224 return false; 4225 4226 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4227 } 4228 4229 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4230 CapturingScopeInfo *CSI) { 4231 assert(T->isVariablyModifiedType()); 4232 assert(CSI != nullptr); 4233 4234 // We're going to walk down into the type and look for VLA expressions. 4235 do { 4236 const Type *Ty = T.getTypePtr(); 4237 switch (Ty->getTypeClass()) { 4238 #define TYPE(Class, Base) 4239 #define ABSTRACT_TYPE(Class, Base) 4240 #define NON_CANONICAL_TYPE(Class, Base) 4241 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4242 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4243 #include "clang/AST/TypeNodes.inc" 4244 T = QualType(); 4245 break; 4246 // These types are never variably-modified. 4247 case Type::Builtin: 4248 case Type::Complex: 4249 case Type::Vector: 4250 case Type::ExtVector: 4251 case Type::Record: 4252 case Type::Enum: 4253 case Type::Elaborated: 4254 case Type::TemplateSpecialization: 4255 case Type::ObjCObject: 4256 case Type::ObjCInterface: 4257 case Type::ObjCObjectPointer: 4258 case Type::ObjCTypeParam: 4259 case Type::Pipe: 4260 llvm_unreachable("type class is never variably-modified!"); 4261 case Type::Adjusted: 4262 T = cast<AdjustedType>(Ty)->getOriginalType(); 4263 break; 4264 case Type::Decayed: 4265 T = cast<DecayedType>(Ty)->getPointeeType(); 4266 break; 4267 case Type::Pointer: 4268 T = cast<PointerType>(Ty)->getPointeeType(); 4269 break; 4270 case Type::BlockPointer: 4271 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4272 break; 4273 case Type::LValueReference: 4274 case Type::RValueReference: 4275 T = cast<ReferenceType>(Ty)->getPointeeType(); 4276 break; 4277 case Type::MemberPointer: 4278 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4279 break; 4280 case Type::ConstantArray: 4281 case Type::IncompleteArray: 4282 // Losing element qualification here is fine. 4283 T = cast<ArrayType>(Ty)->getElementType(); 4284 break; 4285 case Type::VariableArray: { 4286 // Losing element qualification here is fine. 4287 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4288 4289 // Unknown size indication requires no size computation. 4290 // Otherwise, evaluate and record it. 4291 auto Size = VAT->getSizeExpr(); 4292 if (Size && !CSI->isVLATypeCaptured(VAT) && 4293 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4294 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4295 4296 T = VAT->getElementType(); 4297 break; 4298 } 4299 case Type::FunctionProto: 4300 case Type::FunctionNoProto: 4301 T = cast<FunctionType>(Ty)->getReturnType(); 4302 break; 4303 case Type::Paren: 4304 case Type::TypeOf: 4305 case Type::UnaryTransform: 4306 case Type::Attributed: 4307 case Type::SubstTemplateTypeParm: 4308 case Type::PackExpansion: 4309 case Type::MacroQualified: 4310 // Keep walking after single level desugaring. 4311 T = T.getSingleStepDesugaredType(Context); 4312 break; 4313 case Type::Typedef: 4314 T = cast<TypedefType>(Ty)->desugar(); 4315 break; 4316 case Type::Decltype: 4317 T = cast<DecltypeType>(Ty)->desugar(); 4318 break; 4319 case Type::Auto: 4320 case Type::DeducedTemplateSpecialization: 4321 T = cast<DeducedType>(Ty)->getDeducedType(); 4322 break; 4323 case Type::TypeOfExpr: 4324 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4325 break; 4326 case Type::Atomic: 4327 T = cast<AtomicType>(Ty)->getValueType(); 4328 break; 4329 } 4330 } while (!T.isNull() && T->isVariablyModifiedType()); 4331 } 4332 4333 /// Build a sizeof or alignof expression given a type operand. 4334 ExprResult 4335 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4336 SourceLocation OpLoc, 4337 UnaryExprOrTypeTrait ExprKind, 4338 SourceRange R) { 4339 if (!TInfo) 4340 return ExprError(); 4341 4342 QualType T = TInfo->getType(); 4343 4344 if (!T->isDependentType() && 4345 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4346 return ExprError(); 4347 4348 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4349 if (auto *TT = T->getAs<TypedefType>()) { 4350 for (auto I = FunctionScopes.rbegin(), 4351 E = std::prev(FunctionScopes.rend()); 4352 I != E; ++I) { 4353 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4354 if (CSI == nullptr) 4355 break; 4356 DeclContext *DC = nullptr; 4357 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4358 DC = LSI->CallOperator; 4359 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4360 DC = CRSI->TheCapturedDecl; 4361 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4362 DC = BSI->TheDecl; 4363 if (DC) { 4364 if (DC->containsDecl(TT->getDecl())) 4365 break; 4366 captureVariablyModifiedType(Context, T, CSI); 4367 } 4368 } 4369 } 4370 } 4371 4372 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4373 return new (Context) UnaryExprOrTypeTraitExpr( 4374 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4375 } 4376 4377 /// Build a sizeof or alignof expression given an expression 4378 /// operand. 4379 ExprResult 4380 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4381 UnaryExprOrTypeTrait ExprKind) { 4382 ExprResult PE = CheckPlaceholderExpr(E); 4383 if (PE.isInvalid()) 4384 return ExprError(); 4385 4386 E = PE.get(); 4387 4388 // Verify that the operand is valid. 4389 bool isInvalid = false; 4390 if (E->isTypeDependent()) { 4391 // Delay type-checking for type-dependent expressions. 4392 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4393 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4394 } else if (ExprKind == UETT_VecStep) { 4395 isInvalid = CheckVecStepExpr(E); 4396 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4397 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4398 isInvalid = true; 4399 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4400 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4401 isInvalid = true; 4402 } else { 4403 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4404 } 4405 4406 if (isInvalid) 4407 return ExprError(); 4408 4409 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4410 PE = TransformToPotentiallyEvaluated(E); 4411 if (PE.isInvalid()) return ExprError(); 4412 E = PE.get(); 4413 } 4414 4415 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4416 return new (Context) UnaryExprOrTypeTraitExpr( 4417 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4418 } 4419 4420 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4421 /// expr and the same for @c alignof and @c __alignof 4422 /// Note that the ArgRange is invalid if isType is false. 4423 ExprResult 4424 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4425 UnaryExprOrTypeTrait ExprKind, bool IsType, 4426 void *TyOrEx, SourceRange ArgRange) { 4427 // If error parsing type, ignore. 4428 if (!TyOrEx) return ExprError(); 4429 4430 if (IsType) { 4431 TypeSourceInfo *TInfo; 4432 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4433 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4434 } 4435 4436 Expr *ArgEx = (Expr *)TyOrEx; 4437 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4438 return Result; 4439 } 4440 4441 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4442 bool IsReal) { 4443 if (V.get()->isTypeDependent()) 4444 return S.Context.DependentTy; 4445 4446 // _Real and _Imag are only l-values for normal l-values. 4447 if (V.get()->getObjectKind() != OK_Ordinary) { 4448 V = S.DefaultLvalueConversion(V.get()); 4449 if (V.isInvalid()) 4450 return QualType(); 4451 } 4452 4453 // These operators return the element type of a complex type. 4454 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4455 return CT->getElementType(); 4456 4457 // Otherwise they pass through real integer and floating point types here. 4458 if (V.get()->getType()->isArithmeticType()) 4459 return V.get()->getType(); 4460 4461 // Test for placeholders. 4462 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4463 if (PR.isInvalid()) return QualType(); 4464 if (PR.get() != V.get()) { 4465 V = PR; 4466 return CheckRealImagOperand(S, V, Loc, IsReal); 4467 } 4468 4469 // Reject anything else. 4470 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4471 << (IsReal ? "__real" : "__imag"); 4472 return QualType(); 4473 } 4474 4475 4476 4477 ExprResult 4478 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4479 tok::TokenKind Kind, Expr *Input) { 4480 UnaryOperatorKind Opc; 4481 switch (Kind) { 4482 default: llvm_unreachable("Unknown unary op!"); 4483 case tok::plusplus: Opc = UO_PostInc; break; 4484 case tok::minusminus: Opc = UO_PostDec; break; 4485 } 4486 4487 // Since this might is a postfix expression, get rid of ParenListExprs. 4488 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4489 if (Result.isInvalid()) return ExprError(); 4490 Input = Result.get(); 4491 4492 return BuildUnaryOp(S, OpLoc, Opc, Input); 4493 } 4494 4495 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4496 /// 4497 /// \return true on error 4498 static bool checkArithmeticOnObjCPointer(Sema &S, 4499 SourceLocation opLoc, 4500 Expr *op) { 4501 assert(op->getType()->isObjCObjectPointerType()); 4502 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4503 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4504 return false; 4505 4506 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4507 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4508 << op->getSourceRange(); 4509 return true; 4510 } 4511 4512 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4513 auto *BaseNoParens = Base->IgnoreParens(); 4514 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4515 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4516 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4517 } 4518 4519 ExprResult 4520 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4521 Expr *idx, SourceLocation rbLoc) { 4522 if (base && !base->getType().isNull() && 4523 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4524 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4525 /*Length=*/nullptr, rbLoc); 4526 4527 // Since this might be a postfix expression, get rid of ParenListExprs. 4528 if (isa<ParenListExpr>(base)) { 4529 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4530 if (result.isInvalid()) return ExprError(); 4531 base = result.get(); 4532 } 4533 4534 // A comma-expression as the index is deprecated in C++2a onwards. 4535 if (getLangOpts().CPlusPlus2a && 4536 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4537 (isa<CXXOperatorCallExpr>(idx) && 4538 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4539 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4540 << SourceRange(base->getBeginLoc(), rbLoc); 4541 } 4542 4543 // Handle any non-overload placeholder types in the base and index 4544 // expressions. We can't handle overloads here because the other 4545 // operand might be an overloadable type, in which case the overload 4546 // resolution for the operator overload should get the first crack 4547 // at the overload. 4548 bool IsMSPropertySubscript = false; 4549 if (base->getType()->isNonOverloadPlaceholderType()) { 4550 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4551 if (!IsMSPropertySubscript) { 4552 ExprResult result = CheckPlaceholderExpr(base); 4553 if (result.isInvalid()) 4554 return ExprError(); 4555 base = result.get(); 4556 } 4557 } 4558 if (idx->getType()->isNonOverloadPlaceholderType()) { 4559 ExprResult result = CheckPlaceholderExpr(idx); 4560 if (result.isInvalid()) return ExprError(); 4561 idx = result.get(); 4562 } 4563 4564 // Build an unanalyzed expression if either operand is type-dependent. 4565 if (getLangOpts().CPlusPlus && 4566 (base->isTypeDependent() || idx->isTypeDependent())) { 4567 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4568 VK_LValue, OK_Ordinary, rbLoc); 4569 } 4570 4571 // MSDN, property (C++) 4572 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4573 // This attribute can also be used in the declaration of an empty array in a 4574 // class or structure definition. For example: 4575 // __declspec(property(get=GetX, put=PutX)) int x[]; 4576 // The above statement indicates that x[] can be used with one or more array 4577 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4578 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4579 if (IsMSPropertySubscript) { 4580 // Build MS property subscript expression if base is MS property reference 4581 // or MS property subscript. 4582 return new (Context) MSPropertySubscriptExpr( 4583 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4584 } 4585 4586 // Use C++ overloaded-operator rules if either operand has record 4587 // type. The spec says to do this if either type is *overloadable*, 4588 // but enum types can't declare subscript operators or conversion 4589 // operators, so there's nothing interesting for overload resolution 4590 // to do if there aren't any record types involved. 4591 // 4592 // ObjC pointers have their own subscripting logic that is not tied 4593 // to overload resolution and so should not take this path. 4594 if (getLangOpts().CPlusPlus && 4595 (base->getType()->isRecordType() || 4596 (!base->getType()->isObjCObjectPointerType() && 4597 idx->getType()->isRecordType()))) { 4598 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4599 } 4600 4601 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4602 4603 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4604 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4605 4606 return Res; 4607 } 4608 4609 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4610 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4611 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4612 4613 // For expressions like `&(*s).b`, the base is recorded and what should be 4614 // checked. 4615 const MemberExpr *Member = nullptr; 4616 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4617 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4618 4619 LastRecord.PossibleDerefs.erase(StrippedExpr); 4620 } 4621 4622 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4623 QualType ResultTy = E->getType(); 4624 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4625 4626 // Bail if the element is an array since it is not memory access. 4627 if (isa<ArrayType>(ResultTy)) 4628 return; 4629 4630 if (ResultTy->hasAttr(attr::NoDeref)) { 4631 LastRecord.PossibleDerefs.insert(E); 4632 return; 4633 } 4634 4635 // Check if the base type is a pointer to a member access of a struct 4636 // marked with noderef. 4637 const Expr *Base = E->getBase(); 4638 QualType BaseTy = Base->getType(); 4639 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4640 // Not a pointer access 4641 return; 4642 4643 const MemberExpr *Member = nullptr; 4644 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4645 Member->isArrow()) 4646 Base = Member->getBase(); 4647 4648 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4649 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4650 LastRecord.PossibleDerefs.insert(E); 4651 } 4652 } 4653 4654 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4655 Expr *LowerBound, 4656 SourceLocation ColonLoc, Expr *Length, 4657 SourceLocation RBLoc) { 4658 if (Base->getType()->isPlaceholderType() && 4659 !Base->getType()->isSpecificPlaceholderType( 4660 BuiltinType::OMPArraySection)) { 4661 ExprResult Result = CheckPlaceholderExpr(Base); 4662 if (Result.isInvalid()) 4663 return ExprError(); 4664 Base = Result.get(); 4665 } 4666 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4667 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4668 if (Result.isInvalid()) 4669 return ExprError(); 4670 Result = DefaultLvalueConversion(Result.get()); 4671 if (Result.isInvalid()) 4672 return ExprError(); 4673 LowerBound = Result.get(); 4674 } 4675 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4676 ExprResult Result = CheckPlaceholderExpr(Length); 4677 if (Result.isInvalid()) 4678 return ExprError(); 4679 Result = DefaultLvalueConversion(Result.get()); 4680 if (Result.isInvalid()) 4681 return ExprError(); 4682 Length = Result.get(); 4683 } 4684 4685 // Build an unanalyzed expression if either operand is type-dependent. 4686 if (Base->isTypeDependent() || 4687 (LowerBound && 4688 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4689 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4690 return new (Context) 4691 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4692 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4693 } 4694 4695 // Perform default conversions. 4696 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4697 QualType ResultTy; 4698 if (OriginalTy->isAnyPointerType()) { 4699 ResultTy = OriginalTy->getPointeeType(); 4700 } else if (OriginalTy->isArrayType()) { 4701 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4702 } else { 4703 return ExprError( 4704 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4705 << Base->getSourceRange()); 4706 } 4707 // C99 6.5.2.1p1 4708 if (LowerBound) { 4709 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4710 LowerBound); 4711 if (Res.isInvalid()) 4712 return ExprError(Diag(LowerBound->getExprLoc(), 4713 diag::err_omp_typecheck_section_not_integer) 4714 << 0 << LowerBound->getSourceRange()); 4715 LowerBound = Res.get(); 4716 4717 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4718 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4719 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4720 << 0 << LowerBound->getSourceRange(); 4721 } 4722 if (Length) { 4723 auto Res = 4724 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4725 if (Res.isInvalid()) 4726 return ExprError(Diag(Length->getExprLoc(), 4727 diag::err_omp_typecheck_section_not_integer) 4728 << 1 << Length->getSourceRange()); 4729 Length = Res.get(); 4730 4731 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4732 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4733 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4734 << 1 << Length->getSourceRange(); 4735 } 4736 4737 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4738 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4739 // type. Note that functions are not objects, and that (in C99 parlance) 4740 // incomplete types are not object types. 4741 if (ResultTy->isFunctionType()) { 4742 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4743 << ResultTy << Base->getSourceRange(); 4744 return ExprError(); 4745 } 4746 4747 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4748 diag::err_omp_section_incomplete_type, Base)) 4749 return ExprError(); 4750 4751 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4752 Expr::EvalResult Result; 4753 if (LowerBound->EvaluateAsInt(Result, Context)) { 4754 // OpenMP 4.5, [2.4 Array Sections] 4755 // The array section must be a subset of the original array. 4756 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4757 if (LowerBoundValue.isNegative()) { 4758 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4759 << LowerBound->getSourceRange(); 4760 return ExprError(); 4761 } 4762 } 4763 } 4764 4765 if (Length) { 4766 Expr::EvalResult Result; 4767 if (Length->EvaluateAsInt(Result, Context)) { 4768 // OpenMP 4.5, [2.4 Array Sections] 4769 // The length must evaluate to non-negative integers. 4770 llvm::APSInt LengthValue = Result.Val.getInt(); 4771 if (LengthValue.isNegative()) { 4772 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4773 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4774 << Length->getSourceRange(); 4775 return ExprError(); 4776 } 4777 } 4778 } else if (ColonLoc.isValid() && 4779 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4780 !OriginalTy->isVariableArrayType()))) { 4781 // OpenMP 4.5, [2.4 Array Sections] 4782 // When the size of the array dimension is not known, the length must be 4783 // specified explicitly. 4784 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4785 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4786 return ExprError(); 4787 } 4788 4789 if (!Base->getType()->isSpecificPlaceholderType( 4790 BuiltinType::OMPArraySection)) { 4791 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4792 if (Result.isInvalid()) 4793 return ExprError(); 4794 Base = Result.get(); 4795 } 4796 return new (Context) 4797 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4798 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4799 } 4800 4801 ExprResult 4802 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4803 Expr *Idx, SourceLocation RLoc) { 4804 Expr *LHSExp = Base; 4805 Expr *RHSExp = Idx; 4806 4807 ExprValueKind VK = VK_LValue; 4808 ExprObjectKind OK = OK_Ordinary; 4809 4810 // Per C++ core issue 1213, the result is an xvalue if either operand is 4811 // a non-lvalue array, and an lvalue otherwise. 4812 if (getLangOpts().CPlusPlus11) { 4813 for (auto *Op : {LHSExp, RHSExp}) { 4814 Op = Op->IgnoreImplicit(); 4815 if (Op->getType()->isArrayType() && !Op->isLValue()) 4816 VK = VK_XValue; 4817 } 4818 } 4819 4820 // Perform default conversions. 4821 if (!LHSExp->getType()->getAs<VectorType>()) { 4822 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4823 if (Result.isInvalid()) 4824 return ExprError(); 4825 LHSExp = Result.get(); 4826 } 4827 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4828 if (Result.isInvalid()) 4829 return ExprError(); 4830 RHSExp = Result.get(); 4831 4832 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4833 4834 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4835 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4836 // in the subscript position. As a result, we need to derive the array base 4837 // and index from the expression types. 4838 Expr *BaseExpr, *IndexExpr; 4839 QualType ResultType; 4840 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4841 BaseExpr = LHSExp; 4842 IndexExpr = RHSExp; 4843 ResultType = Context.DependentTy; 4844 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4845 BaseExpr = LHSExp; 4846 IndexExpr = RHSExp; 4847 ResultType = PTy->getPointeeType(); 4848 } else if (const ObjCObjectPointerType *PTy = 4849 LHSTy->getAs<ObjCObjectPointerType>()) { 4850 BaseExpr = LHSExp; 4851 IndexExpr = RHSExp; 4852 4853 // Use custom logic if this should be the pseudo-object subscript 4854 // expression. 4855 if (!LangOpts.isSubscriptPointerArithmetic()) 4856 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4857 nullptr); 4858 4859 ResultType = PTy->getPointeeType(); 4860 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4861 // Handle the uncommon case of "123[Ptr]". 4862 BaseExpr = RHSExp; 4863 IndexExpr = LHSExp; 4864 ResultType = PTy->getPointeeType(); 4865 } else if (const ObjCObjectPointerType *PTy = 4866 RHSTy->getAs<ObjCObjectPointerType>()) { 4867 // Handle the uncommon case of "123[Ptr]". 4868 BaseExpr = RHSExp; 4869 IndexExpr = LHSExp; 4870 ResultType = PTy->getPointeeType(); 4871 if (!LangOpts.isSubscriptPointerArithmetic()) { 4872 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4873 << ResultType << BaseExpr->getSourceRange(); 4874 return ExprError(); 4875 } 4876 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4877 BaseExpr = LHSExp; // vectors: V[123] 4878 IndexExpr = RHSExp; 4879 // We apply C++ DR1213 to vector subscripting too. 4880 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4881 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4882 if (Materialized.isInvalid()) 4883 return ExprError(); 4884 LHSExp = Materialized.get(); 4885 } 4886 VK = LHSExp->getValueKind(); 4887 if (VK != VK_RValue) 4888 OK = OK_VectorComponent; 4889 4890 ResultType = VTy->getElementType(); 4891 QualType BaseType = BaseExpr->getType(); 4892 Qualifiers BaseQuals = BaseType.getQualifiers(); 4893 Qualifiers MemberQuals = ResultType.getQualifiers(); 4894 Qualifiers Combined = BaseQuals + MemberQuals; 4895 if (Combined != MemberQuals) 4896 ResultType = Context.getQualifiedType(ResultType, Combined); 4897 } else if (LHSTy->isArrayType()) { 4898 // If we see an array that wasn't promoted by 4899 // DefaultFunctionArrayLvalueConversion, it must be an array that 4900 // wasn't promoted because of the C90 rule that doesn't 4901 // allow promoting non-lvalue arrays. Warn, then 4902 // force the promotion here. 4903 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4904 << LHSExp->getSourceRange(); 4905 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4906 CK_ArrayToPointerDecay).get(); 4907 LHSTy = LHSExp->getType(); 4908 4909 BaseExpr = LHSExp; 4910 IndexExpr = RHSExp; 4911 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4912 } else if (RHSTy->isArrayType()) { 4913 // Same as previous, except for 123[f().a] case 4914 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4915 << RHSExp->getSourceRange(); 4916 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4917 CK_ArrayToPointerDecay).get(); 4918 RHSTy = RHSExp->getType(); 4919 4920 BaseExpr = RHSExp; 4921 IndexExpr = LHSExp; 4922 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4923 } else { 4924 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4925 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4926 } 4927 // C99 6.5.2.1p1 4928 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4929 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4930 << IndexExpr->getSourceRange()); 4931 4932 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4933 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4934 && !IndexExpr->isTypeDependent()) 4935 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4936 4937 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4938 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4939 // type. Note that Functions are not objects, and that (in C99 parlance) 4940 // incomplete types are not object types. 4941 if (ResultType->isFunctionType()) { 4942 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4943 << ResultType << BaseExpr->getSourceRange(); 4944 return ExprError(); 4945 } 4946 4947 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4948 // GNU extension: subscripting on pointer to void 4949 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4950 << BaseExpr->getSourceRange(); 4951 4952 // C forbids expressions of unqualified void type from being l-values. 4953 // See IsCForbiddenLValueType. 4954 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4955 } else if (!ResultType->isDependentType() && 4956 RequireCompleteSizedType( 4957 LLoc, ResultType, 4958 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 4959 return ExprError(); 4960 4961 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4962 !ResultType.isCForbiddenLValueType()); 4963 4964 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 4965 FunctionScopes.size() > 1) { 4966 if (auto *TT = 4967 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 4968 for (auto I = FunctionScopes.rbegin(), 4969 E = std::prev(FunctionScopes.rend()); 4970 I != E; ++I) { 4971 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4972 if (CSI == nullptr) 4973 break; 4974 DeclContext *DC = nullptr; 4975 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4976 DC = LSI->CallOperator; 4977 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4978 DC = CRSI->TheCapturedDecl; 4979 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4980 DC = BSI->TheDecl; 4981 if (DC) { 4982 if (DC->containsDecl(TT->getDecl())) 4983 break; 4984 captureVariablyModifiedType( 4985 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 4986 } 4987 } 4988 } 4989 } 4990 4991 return new (Context) 4992 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4993 } 4994 4995 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4996 ParmVarDecl *Param) { 4997 if (Param->hasUnparsedDefaultArg()) { 4998 Diag(CallLoc, 4999 diag::err_use_of_default_argument_to_function_declared_later) << 5000 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 5001 Diag(UnparsedDefaultArgLocs[Param], 5002 diag::note_default_argument_declared_here); 5003 return true; 5004 } 5005 5006 if (Param->hasUninstantiatedDefaultArg()) { 5007 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 5008 5009 EnterExpressionEvaluationContext EvalContext( 5010 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5011 5012 // Instantiate the expression. 5013 // 5014 // FIXME: Pass in a correct Pattern argument, otherwise 5015 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 5016 // 5017 // template<typename T> 5018 // struct A { 5019 // static int FooImpl(); 5020 // 5021 // template<typename Tp> 5022 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 5023 // // template argument list [[T], [Tp]], should be [[Tp]]. 5024 // friend A<Tp> Foo(int a); 5025 // }; 5026 // 5027 // template<typename T> 5028 // A<T> Foo(int a = A<T>::FooImpl()); 5029 MultiLevelTemplateArgumentList MutiLevelArgList 5030 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 5031 5032 InstantiatingTemplate Inst(*this, CallLoc, Param, 5033 MutiLevelArgList.getInnermost()); 5034 if (Inst.isInvalid()) 5035 return true; 5036 if (Inst.isAlreadyInstantiating()) { 5037 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5038 Param->setInvalidDecl(); 5039 return true; 5040 } 5041 5042 ExprResult Result; 5043 { 5044 // C++ [dcl.fct.default]p5: 5045 // The names in the [default argument] expression are bound, and 5046 // the semantic constraints are checked, at the point where the 5047 // default argument expression appears. 5048 ContextRAII SavedContext(*this, FD); 5049 LocalInstantiationScope Local(*this); 5050 runWithSufficientStackSpace(CallLoc, [&] { 5051 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 5052 /*DirectInit*/false); 5053 }); 5054 } 5055 if (Result.isInvalid()) 5056 return true; 5057 5058 // Check the expression as an initializer for the parameter. 5059 InitializedEntity Entity 5060 = InitializedEntity::InitializeParameter(Context, Param); 5061 InitializationKind Kind = InitializationKind::CreateCopy( 5062 Param->getLocation(), 5063 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 5064 Expr *ResultE = Result.getAs<Expr>(); 5065 5066 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 5067 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 5068 if (Result.isInvalid()) 5069 return true; 5070 5071 Result = 5072 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 5073 /*DiscardedValue*/ false); 5074 if (Result.isInvalid()) 5075 return true; 5076 5077 // Remember the instantiated default argument. 5078 Param->setDefaultArg(Result.getAs<Expr>()); 5079 if (ASTMutationListener *L = getASTMutationListener()) { 5080 L->DefaultArgumentInstantiated(Param); 5081 } 5082 } 5083 5084 // If the default argument expression is not set yet, we are building it now. 5085 if (!Param->hasInit()) { 5086 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5087 Param->setInvalidDecl(); 5088 return true; 5089 } 5090 5091 // If the default expression creates temporaries, we need to 5092 // push them to the current stack of expression temporaries so they'll 5093 // be properly destroyed. 5094 // FIXME: We should really be rebuilding the default argument with new 5095 // bound temporaries; see the comment in PR5810. 5096 // We don't need to do that with block decls, though, because 5097 // blocks in default argument expression can never capture anything. 5098 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5099 // Set the "needs cleanups" bit regardless of whether there are 5100 // any explicit objects. 5101 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5102 5103 // Append all the objects to the cleanup list. Right now, this 5104 // should always be a no-op, because blocks in default argument 5105 // expressions should never be able to capture anything. 5106 assert(!Init->getNumObjects() && 5107 "default argument expression has capturing blocks?"); 5108 } 5109 5110 // We already type-checked the argument, so we know it works. 5111 // Just mark all of the declarations in this potentially-evaluated expression 5112 // as being "referenced". 5113 EnterExpressionEvaluationContext EvalContext( 5114 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5115 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5116 /*SkipLocalVariables=*/true); 5117 return false; 5118 } 5119 5120 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5121 FunctionDecl *FD, ParmVarDecl *Param) { 5122 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5123 return ExprError(); 5124 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5125 } 5126 5127 Sema::VariadicCallType 5128 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5129 Expr *Fn) { 5130 if (Proto && Proto->isVariadic()) { 5131 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5132 return VariadicConstructor; 5133 else if (Fn && Fn->getType()->isBlockPointerType()) 5134 return VariadicBlock; 5135 else if (FDecl) { 5136 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5137 if (Method->isInstance()) 5138 return VariadicMethod; 5139 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5140 return VariadicMethod; 5141 return VariadicFunction; 5142 } 5143 return VariadicDoesNotApply; 5144 } 5145 5146 namespace { 5147 class FunctionCallCCC final : public FunctionCallFilterCCC { 5148 public: 5149 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5150 unsigned NumArgs, MemberExpr *ME) 5151 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5152 FunctionName(FuncName) {} 5153 5154 bool ValidateCandidate(const TypoCorrection &candidate) override { 5155 if (!candidate.getCorrectionSpecifier() || 5156 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5157 return false; 5158 } 5159 5160 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5161 } 5162 5163 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5164 return std::make_unique<FunctionCallCCC>(*this); 5165 } 5166 5167 private: 5168 const IdentifierInfo *const FunctionName; 5169 }; 5170 } 5171 5172 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5173 FunctionDecl *FDecl, 5174 ArrayRef<Expr *> Args) { 5175 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5176 DeclarationName FuncName = FDecl->getDeclName(); 5177 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5178 5179 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5180 if (TypoCorrection Corrected = S.CorrectTypo( 5181 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5182 S.getScopeForContext(S.CurContext), nullptr, CCC, 5183 Sema::CTK_ErrorRecovery)) { 5184 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5185 if (Corrected.isOverloaded()) { 5186 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5187 OverloadCandidateSet::iterator Best; 5188 for (NamedDecl *CD : Corrected) { 5189 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5190 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5191 OCS); 5192 } 5193 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5194 case OR_Success: 5195 ND = Best->FoundDecl; 5196 Corrected.setCorrectionDecl(ND); 5197 break; 5198 default: 5199 break; 5200 } 5201 } 5202 ND = ND->getUnderlyingDecl(); 5203 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5204 return Corrected; 5205 } 5206 } 5207 return TypoCorrection(); 5208 } 5209 5210 /// ConvertArgumentsForCall - Converts the arguments specified in 5211 /// Args/NumArgs to the parameter types of the function FDecl with 5212 /// function prototype Proto. Call is the call expression itself, and 5213 /// Fn is the function expression. For a C++ member function, this 5214 /// routine does not attempt to convert the object argument. Returns 5215 /// true if the call is ill-formed. 5216 bool 5217 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5218 FunctionDecl *FDecl, 5219 const FunctionProtoType *Proto, 5220 ArrayRef<Expr *> Args, 5221 SourceLocation RParenLoc, 5222 bool IsExecConfig) { 5223 // Bail out early if calling a builtin with custom typechecking. 5224 if (FDecl) 5225 if (unsigned ID = FDecl->getBuiltinID()) 5226 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5227 return false; 5228 5229 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5230 // assignment, to the types of the corresponding parameter, ... 5231 unsigned NumParams = Proto->getNumParams(); 5232 bool Invalid = false; 5233 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5234 unsigned FnKind = Fn->getType()->isBlockPointerType() 5235 ? 1 /* block */ 5236 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5237 : 0 /* function */); 5238 5239 // If too few arguments are available (and we don't have default 5240 // arguments for the remaining parameters), don't make the call. 5241 if (Args.size() < NumParams) { 5242 if (Args.size() < MinArgs) { 5243 TypoCorrection TC; 5244 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5245 unsigned diag_id = 5246 MinArgs == NumParams && !Proto->isVariadic() 5247 ? diag::err_typecheck_call_too_few_args_suggest 5248 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5249 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5250 << static_cast<unsigned>(Args.size()) 5251 << TC.getCorrectionRange()); 5252 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5253 Diag(RParenLoc, 5254 MinArgs == NumParams && !Proto->isVariadic() 5255 ? diag::err_typecheck_call_too_few_args_one 5256 : diag::err_typecheck_call_too_few_args_at_least_one) 5257 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5258 else 5259 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5260 ? diag::err_typecheck_call_too_few_args 5261 : diag::err_typecheck_call_too_few_args_at_least) 5262 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5263 << Fn->getSourceRange(); 5264 5265 // Emit the location of the prototype. 5266 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5267 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5268 5269 return true; 5270 } 5271 // We reserve space for the default arguments when we create 5272 // the call expression, before calling ConvertArgumentsForCall. 5273 assert((Call->getNumArgs() == NumParams) && 5274 "We should have reserved space for the default arguments before!"); 5275 } 5276 5277 // If too many are passed and not variadic, error on the extras and drop 5278 // them. 5279 if (Args.size() > NumParams) { 5280 if (!Proto->isVariadic()) { 5281 TypoCorrection TC; 5282 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5283 unsigned diag_id = 5284 MinArgs == NumParams && !Proto->isVariadic() 5285 ? diag::err_typecheck_call_too_many_args_suggest 5286 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5287 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5288 << static_cast<unsigned>(Args.size()) 5289 << TC.getCorrectionRange()); 5290 } else if (NumParams == 1 && FDecl && 5291 FDecl->getParamDecl(0)->getDeclName()) 5292 Diag(Args[NumParams]->getBeginLoc(), 5293 MinArgs == NumParams 5294 ? diag::err_typecheck_call_too_many_args_one 5295 : diag::err_typecheck_call_too_many_args_at_most_one) 5296 << FnKind << FDecl->getParamDecl(0) 5297 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5298 << SourceRange(Args[NumParams]->getBeginLoc(), 5299 Args.back()->getEndLoc()); 5300 else 5301 Diag(Args[NumParams]->getBeginLoc(), 5302 MinArgs == NumParams 5303 ? diag::err_typecheck_call_too_many_args 5304 : diag::err_typecheck_call_too_many_args_at_most) 5305 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5306 << Fn->getSourceRange() 5307 << SourceRange(Args[NumParams]->getBeginLoc(), 5308 Args.back()->getEndLoc()); 5309 5310 // Emit the location of the prototype. 5311 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5312 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5313 5314 // This deletes the extra arguments. 5315 Call->shrinkNumArgs(NumParams); 5316 return true; 5317 } 5318 } 5319 SmallVector<Expr *, 8> AllArgs; 5320 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5321 5322 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5323 AllArgs, CallType); 5324 if (Invalid) 5325 return true; 5326 unsigned TotalNumArgs = AllArgs.size(); 5327 for (unsigned i = 0; i < TotalNumArgs; ++i) 5328 Call->setArg(i, AllArgs[i]); 5329 5330 return false; 5331 } 5332 5333 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5334 const FunctionProtoType *Proto, 5335 unsigned FirstParam, ArrayRef<Expr *> Args, 5336 SmallVectorImpl<Expr *> &AllArgs, 5337 VariadicCallType CallType, bool AllowExplicit, 5338 bool IsListInitialization) { 5339 unsigned NumParams = Proto->getNumParams(); 5340 bool Invalid = false; 5341 size_t ArgIx = 0; 5342 // Continue to check argument types (even if we have too few/many args). 5343 for (unsigned i = FirstParam; i < NumParams; i++) { 5344 QualType ProtoArgType = Proto->getParamType(i); 5345 5346 Expr *Arg; 5347 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5348 if (ArgIx < Args.size()) { 5349 Arg = Args[ArgIx++]; 5350 5351 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5352 diag::err_call_incomplete_argument, Arg)) 5353 return true; 5354 5355 // Strip the unbridged-cast placeholder expression off, if applicable. 5356 bool CFAudited = false; 5357 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5358 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5359 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5360 Arg = stripARCUnbridgedCast(Arg); 5361 else if (getLangOpts().ObjCAutoRefCount && 5362 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5363 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5364 CFAudited = true; 5365 5366 if (Proto->getExtParameterInfo(i).isNoEscape()) 5367 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5368 BE->getBlockDecl()->setDoesNotEscape(); 5369 5370 InitializedEntity Entity = 5371 Param ? InitializedEntity::InitializeParameter(Context, Param, 5372 ProtoArgType) 5373 : InitializedEntity::InitializeParameter( 5374 Context, ProtoArgType, Proto->isParamConsumed(i)); 5375 5376 // Remember that parameter belongs to a CF audited API. 5377 if (CFAudited) 5378 Entity.setParameterCFAudited(); 5379 5380 ExprResult ArgE = PerformCopyInitialization( 5381 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5382 if (ArgE.isInvalid()) 5383 return true; 5384 5385 Arg = ArgE.getAs<Expr>(); 5386 } else { 5387 assert(Param && "can't use default arguments without a known callee"); 5388 5389 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5390 if (ArgExpr.isInvalid()) 5391 return true; 5392 5393 Arg = ArgExpr.getAs<Expr>(); 5394 } 5395 5396 // Check for array bounds violations for each argument to the call. This 5397 // check only triggers warnings when the argument isn't a more complex Expr 5398 // with its own checking, such as a BinaryOperator. 5399 CheckArrayAccess(Arg); 5400 5401 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5402 CheckStaticArrayArgument(CallLoc, Param, Arg); 5403 5404 AllArgs.push_back(Arg); 5405 } 5406 5407 // If this is a variadic call, handle args passed through "...". 5408 if (CallType != VariadicDoesNotApply) { 5409 // Assume that extern "C" functions with variadic arguments that 5410 // return __unknown_anytype aren't *really* variadic. 5411 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5412 FDecl->isExternC()) { 5413 for (Expr *A : Args.slice(ArgIx)) { 5414 QualType paramType; // ignored 5415 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5416 Invalid |= arg.isInvalid(); 5417 AllArgs.push_back(arg.get()); 5418 } 5419 5420 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5421 } else { 5422 for (Expr *A : Args.slice(ArgIx)) { 5423 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5424 Invalid |= Arg.isInvalid(); 5425 // Copy blocks to the heap. 5426 if (A->getType()->isBlockPointerType()) 5427 maybeExtendBlockObject(Arg); 5428 AllArgs.push_back(Arg.get()); 5429 } 5430 } 5431 5432 // Check for array bounds violations. 5433 for (Expr *A : Args.slice(ArgIx)) 5434 CheckArrayAccess(A); 5435 } 5436 return Invalid; 5437 } 5438 5439 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5440 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5441 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5442 TL = DTL.getOriginalLoc(); 5443 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5444 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5445 << ATL.getLocalSourceRange(); 5446 } 5447 5448 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5449 /// array parameter, check that it is non-null, and that if it is formed by 5450 /// array-to-pointer decay, the underlying array is sufficiently large. 5451 /// 5452 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5453 /// array type derivation, then for each call to the function, the value of the 5454 /// corresponding actual argument shall provide access to the first element of 5455 /// an array with at least as many elements as specified by the size expression. 5456 void 5457 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5458 ParmVarDecl *Param, 5459 const Expr *ArgExpr) { 5460 // Static array parameters are not supported in C++. 5461 if (!Param || getLangOpts().CPlusPlus) 5462 return; 5463 5464 QualType OrigTy = Param->getOriginalType(); 5465 5466 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5467 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5468 return; 5469 5470 if (ArgExpr->isNullPointerConstant(Context, 5471 Expr::NPC_NeverValueDependent)) { 5472 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5473 DiagnoseCalleeStaticArrayParam(*this, Param); 5474 return; 5475 } 5476 5477 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5478 if (!CAT) 5479 return; 5480 5481 const ConstantArrayType *ArgCAT = 5482 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 5483 if (!ArgCAT) 5484 return; 5485 5486 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 5487 ArgCAT->getElementType())) { 5488 if (ArgCAT->getSize().ult(CAT->getSize())) { 5489 Diag(CallLoc, diag::warn_static_array_too_small) 5490 << ArgExpr->getSourceRange() 5491 << (unsigned)ArgCAT->getSize().getZExtValue() 5492 << (unsigned)CAT->getSize().getZExtValue() << 0; 5493 DiagnoseCalleeStaticArrayParam(*this, Param); 5494 } 5495 return; 5496 } 5497 5498 Optional<CharUnits> ArgSize = 5499 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 5500 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 5501 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 5502 Diag(CallLoc, diag::warn_static_array_too_small) 5503 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 5504 << (unsigned)ParmSize->getQuantity() << 1; 5505 DiagnoseCalleeStaticArrayParam(*this, Param); 5506 } 5507 } 5508 5509 /// Given a function expression of unknown-any type, try to rebuild it 5510 /// to have a function type. 5511 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5512 5513 /// Is the given type a placeholder that we need to lower out 5514 /// immediately during argument processing? 5515 static bool isPlaceholderToRemoveAsArg(QualType type) { 5516 // Placeholders are never sugared. 5517 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5518 if (!placeholder) return false; 5519 5520 switch (placeholder->getKind()) { 5521 // Ignore all the non-placeholder types. 5522 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5523 case BuiltinType::Id: 5524 #include "clang/Basic/OpenCLImageTypes.def" 5525 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5526 case BuiltinType::Id: 5527 #include "clang/Basic/OpenCLExtensionTypes.def" 5528 // In practice we'll never use this, since all SVE types are sugared 5529 // via TypedefTypes rather than exposed directly as BuiltinTypes. 5530 #define SVE_TYPE(Name, Id, SingletonId) \ 5531 case BuiltinType::Id: 5532 #include "clang/Basic/AArch64SVEACLETypes.def" 5533 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5534 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5535 #include "clang/AST/BuiltinTypes.def" 5536 return false; 5537 5538 // We cannot lower out overload sets; they might validly be resolved 5539 // by the call machinery. 5540 case BuiltinType::Overload: 5541 return false; 5542 5543 // Unbridged casts in ARC can be handled in some call positions and 5544 // should be left in place. 5545 case BuiltinType::ARCUnbridgedCast: 5546 return false; 5547 5548 // Pseudo-objects should be converted as soon as possible. 5549 case BuiltinType::PseudoObject: 5550 return true; 5551 5552 // The debugger mode could theoretically but currently does not try 5553 // to resolve unknown-typed arguments based on known parameter types. 5554 case BuiltinType::UnknownAny: 5555 return true; 5556 5557 // These are always invalid as call arguments and should be reported. 5558 case BuiltinType::BoundMember: 5559 case BuiltinType::BuiltinFn: 5560 case BuiltinType::OMPArraySection: 5561 return true; 5562 5563 } 5564 llvm_unreachable("bad builtin type kind"); 5565 } 5566 5567 /// Check an argument list for placeholders that we won't try to 5568 /// handle later. 5569 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5570 // Apply this processing to all the arguments at once instead of 5571 // dying at the first failure. 5572 bool hasInvalid = false; 5573 for (size_t i = 0, e = args.size(); i != e; i++) { 5574 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5575 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5576 if (result.isInvalid()) hasInvalid = true; 5577 else args[i] = result.get(); 5578 } else if (hasInvalid) { 5579 (void)S.CorrectDelayedTyposInExpr(args[i]); 5580 } 5581 } 5582 return hasInvalid; 5583 } 5584 5585 /// If a builtin function has a pointer argument with no explicit address 5586 /// space, then it should be able to accept a pointer to any address 5587 /// space as input. In order to do this, we need to replace the 5588 /// standard builtin declaration with one that uses the same address space 5589 /// as the call. 5590 /// 5591 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5592 /// it does not contain any pointer arguments without 5593 /// an address space qualifer. Otherwise the rewritten 5594 /// FunctionDecl is returned. 5595 /// TODO: Handle pointer return types. 5596 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5597 FunctionDecl *FDecl, 5598 MultiExprArg ArgExprs) { 5599 5600 QualType DeclType = FDecl->getType(); 5601 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5602 5603 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 5604 ArgExprs.size() < FT->getNumParams()) 5605 return nullptr; 5606 5607 bool NeedsNewDecl = false; 5608 unsigned i = 0; 5609 SmallVector<QualType, 8> OverloadParams; 5610 5611 for (QualType ParamType : FT->param_types()) { 5612 5613 // Convert array arguments to pointer to simplify type lookup. 5614 ExprResult ArgRes = 5615 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5616 if (ArgRes.isInvalid()) 5617 return nullptr; 5618 Expr *Arg = ArgRes.get(); 5619 QualType ArgType = Arg->getType(); 5620 if (!ParamType->isPointerType() || 5621 ParamType.hasAddressSpace() || 5622 !ArgType->isPointerType() || 5623 !ArgType->getPointeeType().hasAddressSpace()) { 5624 OverloadParams.push_back(ParamType); 5625 continue; 5626 } 5627 5628 QualType PointeeType = ParamType->getPointeeType(); 5629 if (PointeeType.hasAddressSpace()) 5630 continue; 5631 5632 NeedsNewDecl = true; 5633 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5634 5635 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5636 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5637 } 5638 5639 if (!NeedsNewDecl) 5640 return nullptr; 5641 5642 FunctionProtoType::ExtProtoInfo EPI; 5643 EPI.Variadic = FT->isVariadic(); 5644 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5645 OverloadParams, EPI); 5646 DeclContext *Parent = FDecl->getParent(); 5647 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5648 FDecl->getLocation(), 5649 FDecl->getLocation(), 5650 FDecl->getIdentifier(), 5651 OverloadTy, 5652 /*TInfo=*/nullptr, 5653 SC_Extern, false, 5654 /*hasPrototype=*/true); 5655 SmallVector<ParmVarDecl*, 16> Params; 5656 FT = cast<FunctionProtoType>(OverloadTy); 5657 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5658 QualType ParamType = FT->getParamType(i); 5659 ParmVarDecl *Parm = 5660 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5661 SourceLocation(), nullptr, ParamType, 5662 /*TInfo=*/nullptr, SC_None, nullptr); 5663 Parm->setScopeInfo(0, i); 5664 Params.push_back(Parm); 5665 } 5666 OverloadDecl->setParams(Params); 5667 return OverloadDecl; 5668 } 5669 5670 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5671 FunctionDecl *Callee, 5672 MultiExprArg ArgExprs) { 5673 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5674 // similar attributes) really don't like it when functions are called with an 5675 // invalid number of args. 5676 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5677 /*PartialOverloading=*/false) && 5678 !Callee->isVariadic()) 5679 return; 5680 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5681 return; 5682 5683 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5684 S.Diag(Fn->getBeginLoc(), 5685 isa<CXXMethodDecl>(Callee) 5686 ? diag::err_ovl_no_viable_member_function_in_call 5687 : diag::err_ovl_no_viable_function_in_call) 5688 << Callee << Callee->getSourceRange(); 5689 S.Diag(Callee->getLocation(), 5690 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5691 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5692 return; 5693 } 5694 } 5695 5696 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5697 const UnresolvedMemberExpr *const UME, Sema &S) { 5698 5699 const auto GetFunctionLevelDCIfCXXClass = 5700 [](Sema &S) -> const CXXRecordDecl * { 5701 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5702 if (!DC || !DC->getParent()) 5703 return nullptr; 5704 5705 // If the call to some member function was made from within a member 5706 // function body 'M' return return 'M's parent. 5707 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5708 return MD->getParent()->getCanonicalDecl(); 5709 // else the call was made from within a default member initializer of a 5710 // class, so return the class. 5711 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5712 return RD->getCanonicalDecl(); 5713 return nullptr; 5714 }; 5715 // If our DeclContext is neither a member function nor a class (in the 5716 // case of a lambda in a default member initializer), we can't have an 5717 // enclosing 'this'. 5718 5719 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5720 if (!CurParentClass) 5721 return false; 5722 5723 // The naming class for implicit member functions call is the class in which 5724 // name lookup starts. 5725 const CXXRecordDecl *const NamingClass = 5726 UME->getNamingClass()->getCanonicalDecl(); 5727 assert(NamingClass && "Must have naming class even for implicit access"); 5728 5729 // If the unresolved member functions were found in a 'naming class' that is 5730 // related (either the same or derived from) to the class that contains the 5731 // member function that itself contained the implicit member access. 5732 5733 return CurParentClass == NamingClass || 5734 CurParentClass->isDerivedFrom(NamingClass); 5735 } 5736 5737 static void 5738 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5739 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5740 5741 if (!UME) 5742 return; 5743 5744 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5745 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5746 // already been captured, or if this is an implicit member function call (if 5747 // it isn't, an attempt to capture 'this' should already have been made). 5748 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5749 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5750 return; 5751 5752 // Check if the naming class in which the unresolved members were found is 5753 // related (same as or is a base of) to the enclosing class. 5754 5755 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5756 return; 5757 5758 5759 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5760 // If the enclosing function is not dependent, then this lambda is 5761 // capture ready, so if we can capture this, do so. 5762 if (!EnclosingFunctionCtx->isDependentContext()) { 5763 // If the current lambda and all enclosing lambdas can capture 'this' - 5764 // then go ahead and capture 'this' (since our unresolved overload set 5765 // contains at least one non-static member function). 5766 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5767 S.CheckCXXThisCapture(CallLoc); 5768 } else if (S.CurContext->isDependentContext()) { 5769 // ... since this is an implicit member reference, that might potentially 5770 // involve a 'this' capture, mark 'this' for potential capture in 5771 // enclosing lambdas. 5772 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5773 CurLSI->addPotentialThisCapture(CallLoc); 5774 } 5775 } 5776 5777 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5778 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5779 Expr *ExecConfig) { 5780 ExprResult Call = 5781 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig); 5782 if (Call.isInvalid()) 5783 return Call; 5784 5785 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 5786 // language modes. 5787 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 5788 if (ULE->hasExplicitTemplateArgs() && 5789 ULE->decls_begin() == ULE->decls_end()) { 5790 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a 5791 ? diag::warn_cxx17_compat_adl_only_template_id 5792 : diag::ext_adl_only_template_id) 5793 << ULE->getName(); 5794 } 5795 } 5796 5797 if (LangOpts.OpenMP) 5798 Call = ActOnOpenMPCall(*this, Call, Scope, LParenLoc, ArgExprs, RParenLoc, 5799 ExecConfig); 5800 5801 return Call; 5802 } 5803 5804 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 5805 /// This provides the location of the left/right parens and a list of comma 5806 /// locations. 5807 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5808 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5809 Expr *ExecConfig, bool IsExecConfig) { 5810 // Since this might be a postfix expression, get rid of ParenListExprs. 5811 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5812 if (Result.isInvalid()) return ExprError(); 5813 Fn = Result.get(); 5814 5815 if (checkArgsForPlaceholders(*this, ArgExprs)) 5816 return ExprError(); 5817 5818 if (getLangOpts().CPlusPlus) { 5819 // If this is a pseudo-destructor expression, build the call immediately. 5820 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5821 if (!ArgExprs.empty()) { 5822 // Pseudo-destructor calls should not have any arguments. 5823 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5824 << FixItHint::CreateRemoval( 5825 SourceRange(ArgExprs.front()->getBeginLoc(), 5826 ArgExprs.back()->getEndLoc())); 5827 } 5828 5829 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 5830 VK_RValue, RParenLoc); 5831 } 5832 if (Fn->getType() == Context.PseudoObjectTy) { 5833 ExprResult result = CheckPlaceholderExpr(Fn); 5834 if (result.isInvalid()) return ExprError(); 5835 Fn = result.get(); 5836 } 5837 5838 // Determine whether this is a dependent call inside a C++ template, 5839 // in which case we won't do any semantic analysis now. 5840 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5841 if (ExecConfig) { 5842 return CUDAKernelCallExpr::Create( 5843 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5844 Context.DependentTy, VK_RValue, RParenLoc); 5845 } else { 5846 5847 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5848 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5849 Fn->getBeginLoc()); 5850 5851 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5852 VK_RValue, RParenLoc); 5853 } 5854 } 5855 5856 // Determine whether this is a call to an object (C++ [over.call.object]). 5857 if (Fn->getType()->isRecordType()) 5858 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5859 RParenLoc); 5860 5861 if (Fn->getType() == Context.UnknownAnyTy) { 5862 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5863 if (result.isInvalid()) return ExprError(); 5864 Fn = result.get(); 5865 } 5866 5867 if (Fn->getType() == Context.BoundMemberTy) { 5868 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5869 RParenLoc); 5870 } 5871 } 5872 5873 // Check for overloaded calls. This can happen even in C due to extensions. 5874 if (Fn->getType() == Context.OverloadTy) { 5875 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5876 5877 // We aren't supposed to apply this logic if there's an '&' involved. 5878 if (!find.HasFormOfMemberPointer) { 5879 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5880 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 5881 VK_RValue, RParenLoc); 5882 OverloadExpr *ovl = find.Expression; 5883 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5884 return BuildOverloadedCallExpr( 5885 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5886 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5887 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5888 RParenLoc); 5889 } 5890 } 5891 5892 // If we're directly calling a function, get the appropriate declaration. 5893 if (Fn->getType() == Context.UnknownAnyTy) { 5894 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5895 if (result.isInvalid()) return ExprError(); 5896 Fn = result.get(); 5897 } 5898 5899 Expr *NakedFn = Fn->IgnoreParens(); 5900 5901 bool CallingNDeclIndirectly = false; 5902 NamedDecl *NDecl = nullptr; 5903 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5904 if (UnOp->getOpcode() == UO_AddrOf) { 5905 CallingNDeclIndirectly = true; 5906 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5907 } 5908 } 5909 5910 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 5911 NDecl = DRE->getDecl(); 5912 5913 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5914 if (FDecl && FDecl->getBuiltinID()) { 5915 // Rewrite the function decl for this builtin by replacing parameters 5916 // with no explicit address space with the address space of the arguments 5917 // in ArgExprs. 5918 if ((FDecl = 5919 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5920 NDecl = FDecl; 5921 Fn = DeclRefExpr::Create( 5922 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5923 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 5924 nullptr, DRE->isNonOdrUse()); 5925 } 5926 } 5927 } else if (isa<MemberExpr>(NakedFn)) 5928 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5929 5930 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5931 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5932 FD, /*Complain=*/true, Fn->getBeginLoc())) 5933 return ExprError(); 5934 5935 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5936 return ExprError(); 5937 5938 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5939 } 5940 5941 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5942 ExecConfig, IsExecConfig); 5943 } 5944 5945 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5946 /// 5947 /// __builtin_astype( value, dst type ) 5948 /// 5949 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5950 SourceLocation BuiltinLoc, 5951 SourceLocation RParenLoc) { 5952 ExprValueKind VK = VK_RValue; 5953 ExprObjectKind OK = OK_Ordinary; 5954 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5955 QualType SrcTy = E->getType(); 5956 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5957 return ExprError(Diag(BuiltinLoc, 5958 diag::err_invalid_astype_of_different_size) 5959 << DstTy 5960 << SrcTy 5961 << E->getSourceRange()); 5962 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5963 } 5964 5965 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5966 /// provided arguments. 5967 /// 5968 /// __builtin_convertvector( value, dst type ) 5969 /// 5970 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5971 SourceLocation BuiltinLoc, 5972 SourceLocation RParenLoc) { 5973 TypeSourceInfo *TInfo; 5974 GetTypeFromParser(ParsedDestTy, &TInfo); 5975 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5976 } 5977 5978 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5979 /// i.e. an expression not of \p OverloadTy. The expression should 5980 /// unary-convert to an expression of function-pointer or 5981 /// block-pointer type. 5982 /// 5983 /// \param NDecl the declaration being called, if available 5984 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5985 SourceLocation LParenLoc, 5986 ArrayRef<Expr *> Args, 5987 SourceLocation RParenLoc, Expr *Config, 5988 bool IsExecConfig, ADLCallKind UsesADL) { 5989 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5990 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5991 5992 // Functions with 'interrupt' attribute cannot be called directly. 5993 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5994 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5995 return ExprError(); 5996 } 5997 5998 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5999 // so there's some risk when calling out to non-interrupt handler functions 6000 // that the callee might not preserve them. This is easy to diagnose here, 6001 // but can be very challenging to debug. 6002 if (auto *Caller = getCurFunctionDecl()) 6003 if (Caller->hasAttr<ARMInterruptAttr>()) { 6004 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6005 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 6006 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6007 } 6008 6009 // Promote the function operand. 6010 // We special-case function promotion here because we only allow promoting 6011 // builtin functions to function pointers in the callee of a call. 6012 ExprResult Result; 6013 QualType ResultTy; 6014 if (BuiltinID && 6015 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6016 // Extract the return type from the (builtin) function pointer type. 6017 // FIXME Several builtins still have setType in 6018 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6019 // Builtins.def to ensure they are correct before removing setType calls. 6020 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6021 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6022 ResultTy = FDecl->getCallResultType(); 6023 } else { 6024 Result = CallExprUnaryConversions(Fn); 6025 ResultTy = Context.BoolTy; 6026 } 6027 if (Result.isInvalid()) 6028 return ExprError(); 6029 Fn = Result.get(); 6030 6031 // Check for a valid function type, but only if it is not a builtin which 6032 // requires custom type checking. These will be handled by 6033 // CheckBuiltinFunctionCall below just after creation of the call expression. 6034 const FunctionType *FuncT = nullptr; 6035 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6036 retry: 6037 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6038 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6039 // have type pointer to function". 6040 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6041 if (!FuncT) 6042 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6043 << Fn->getType() << Fn->getSourceRange()); 6044 } else if (const BlockPointerType *BPT = 6045 Fn->getType()->getAs<BlockPointerType>()) { 6046 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6047 } else { 6048 // Handle calls to expressions of unknown-any type. 6049 if (Fn->getType() == Context.UnknownAnyTy) { 6050 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6051 if (rewrite.isInvalid()) 6052 return ExprError(); 6053 Fn = rewrite.get(); 6054 goto retry; 6055 } 6056 6057 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6058 << Fn->getType() << Fn->getSourceRange()); 6059 } 6060 } 6061 6062 // Get the number of parameters in the function prototype, if any. 6063 // We will allocate space for max(Args.size(), NumParams) arguments 6064 // in the call expression. 6065 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6066 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6067 6068 CallExpr *TheCall; 6069 if (Config) { 6070 assert(UsesADL == ADLCallKind::NotADL && 6071 "CUDAKernelCallExpr should not use ADL"); 6072 TheCall = 6073 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args, 6074 ResultTy, VK_RValue, RParenLoc, NumParams); 6075 } else { 6076 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6077 RParenLoc, NumParams, UsesADL); 6078 } 6079 6080 if (!getLangOpts().CPlusPlus) { 6081 // Forget about the nulled arguments since typo correction 6082 // do not handle them well. 6083 TheCall->shrinkNumArgs(Args.size()); 6084 // C cannot always handle TypoExpr nodes in builtin calls and direct 6085 // function calls as their argument checking don't necessarily handle 6086 // dependent types properly, so make sure any TypoExprs have been 6087 // dealt with. 6088 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6089 if (!Result.isUsable()) return ExprError(); 6090 CallExpr *TheOldCall = TheCall; 6091 TheCall = dyn_cast<CallExpr>(Result.get()); 6092 bool CorrectedTypos = TheCall != TheOldCall; 6093 if (!TheCall) return Result; 6094 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6095 6096 // A new call expression node was created if some typos were corrected. 6097 // However it may not have been constructed with enough storage. In this 6098 // case, rebuild the node with enough storage. The waste of space is 6099 // immaterial since this only happens when some typos were corrected. 6100 if (CorrectedTypos && Args.size() < NumParams) { 6101 if (Config) 6102 TheCall = CUDAKernelCallExpr::Create( 6103 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6104 RParenLoc, NumParams); 6105 else 6106 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, 6107 RParenLoc, NumParams, UsesADL); 6108 } 6109 // We can now handle the nulled arguments for the default arguments. 6110 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6111 } 6112 6113 // Bail out early if calling a builtin with custom type checking. 6114 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6115 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6116 6117 if (getLangOpts().CUDA) { 6118 if (Config) { 6119 // CUDA: Kernel calls must be to global functions 6120 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6121 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6122 << FDecl << Fn->getSourceRange()); 6123 6124 // CUDA: Kernel function must have 'void' return type 6125 if (!FuncT->getReturnType()->isVoidType() && 6126 !FuncT->getReturnType()->getAs<AutoType>() && 6127 !FuncT->getReturnType()->isInstantiationDependentType()) 6128 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6129 << Fn->getType() << Fn->getSourceRange()); 6130 } else { 6131 // CUDA: Calls to global functions must be configured 6132 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6133 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6134 << FDecl << Fn->getSourceRange()); 6135 } 6136 } 6137 6138 // Check for a valid return type 6139 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6140 FDecl)) 6141 return ExprError(); 6142 6143 // We know the result type of the call, set it. 6144 TheCall->setType(FuncT->getCallResultType(Context)); 6145 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6146 6147 if (Proto) { 6148 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6149 IsExecConfig)) 6150 return ExprError(); 6151 } else { 6152 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6153 6154 if (FDecl) { 6155 // Check if we have too few/too many template arguments, based 6156 // on our knowledge of the function definition. 6157 const FunctionDecl *Def = nullptr; 6158 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6159 Proto = Def->getType()->getAs<FunctionProtoType>(); 6160 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6161 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6162 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6163 } 6164 6165 // If the function we're calling isn't a function prototype, but we have 6166 // a function prototype from a prior declaratiom, use that prototype. 6167 if (!FDecl->hasPrototype()) 6168 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6169 } 6170 6171 // Promote the arguments (C99 6.5.2.2p6). 6172 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6173 Expr *Arg = Args[i]; 6174 6175 if (Proto && i < Proto->getNumParams()) { 6176 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6177 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6178 ExprResult ArgE = 6179 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6180 if (ArgE.isInvalid()) 6181 return true; 6182 6183 Arg = ArgE.getAs<Expr>(); 6184 6185 } else { 6186 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6187 6188 if (ArgE.isInvalid()) 6189 return true; 6190 6191 Arg = ArgE.getAs<Expr>(); 6192 } 6193 6194 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6195 diag::err_call_incomplete_argument, Arg)) 6196 return ExprError(); 6197 6198 TheCall->setArg(i, Arg); 6199 } 6200 } 6201 6202 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6203 if (!Method->isStatic()) 6204 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6205 << Fn->getSourceRange()); 6206 6207 // Check for sentinels 6208 if (NDecl) 6209 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6210 6211 // Do special checking on direct calls to functions. 6212 if (FDecl) { 6213 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6214 return ExprError(); 6215 6216 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6217 6218 if (BuiltinID) 6219 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6220 } else if (NDecl) { 6221 if (CheckPointerCall(NDecl, TheCall, Proto)) 6222 return ExprError(); 6223 } else { 6224 if (CheckOtherCall(TheCall, Proto)) 6225 return ExprError(); 6226 } 6227 6228 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6229 } 6230 6231 ExprResult 6232 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6233 SourceLocation RParenLoc, Expr *InitExpr) { 6234 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6235 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6236 6237 TypeSourceInfo *TInfo; 6238 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6239 if (!TInfo) 6240 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6241 6242 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6243 } 6244 6245 ExprResult 6246 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6247 SourceLocation RParenLoc, Expr *LiteralExpr) { 6248 QualType literalType = TInfo->getType(); 6249 6250 if (literalType->isArrayType()) { 6251 if (RequireCompleteSizedType( 6252 LParenLoc, Context.getBaseElementType(literalType), 6253 diag::err_array_incomplete_or_sizeless_type, 6254 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6255 return ExprError(); 6256 if (literalType->isVariableArrayType()) 6257 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 6258 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 6259 } else if (!literalType->isDependentType() && 6260 RequireCompleteType(LParenLoc, literalType, 6261 diag::err_typecheck_decl_incomplete_type, 6262 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6263 return ExprError(); 6264 6265 InitializedEntity Entity 6266 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6267 InitializationKind Kind 6268 = InitializationKind::CreateCStyleCast(LParenLoc, 6269 SourceRange(LParenLoc, RParenLoc), 6270 /*InitList=*/true); 6271 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6272 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6273 &literalType); 6274 if (Result.isInvalid()) 6275 return ExprError(); 6276 LiteralExpr = Result.get(); 6277 6278 bool isFileScope = !CurContext->isFunctionOrMethod(); 6279 6280 // In C, compound literals are l-values for some reason. 6281 // For GCC compatibility, in C++, file-scope array compound literals with 6282 // constant initializers are also l-values, and compound literals are 6283 // otherwise prvalues. 6284 // 6285 // (GCC also treats C++ list-initialized file-scope array prvalues with 6286 // constant initializers as l-values, but that's non-conforming, so we don't 6287 // follow it there.) 6288 // 6289 // FIXME: It would be better to handle the lvalue cases as materializing and 6290 // lifetime-extending a temporary object, but our materialized temporaries 6291 // representation only supports lifetime extension from a variable, not "out 6292 // of thin air". 6293 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6294 // is bound to the result of applying array-to-pointer decay to the compound 6295 // literal. 6296 // FIXME: GCC supports compound literals of reference type, which should 6297 // obviously have a value kind derived from the kind of reference involved. 6298 ExprValueKind VK = 6299 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6300 ? VK_RValue 6301 : VK_LValue; 6302 6303 if (isFileScope) 6304 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6305 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6306 Expr *Init = ILE->getInit(i); 6307 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6308 } 6309 6310 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6311 VK, LiteralExpr, isFileScope); 6312 if (isFileScope) { 6313 if (!LiteralExpr->isTypeDependent() && 6314 !LiteralExpr->isValueDependent() && 6315 !literalType->isDependentType()) // C99 6.5.2.5p3 6316 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6317 return ExprError(); 6318 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6319 literalType.getAddressSpace() != LangAS::Default) { 6320 // Embedded-C extensions to C99 6.5.2.5: 6321 // "If the compound literal occurs inside the body of a function, the 6322 // type name shall not be qualified by an address-space qualifier." 6323 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6324 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6325 return ExprError(); 6326 } 6327 6328 if (!isFileScope && !getLangOpts().CPlusPlus) { 6329 // Compound literals that have automatic storage duration are destroyed at 6330 // the end of the scope in C; in C++, they're just temporaries. 6331 6332 // Emit diagnostics if it is or contains a C union type that is non-trivial 6333 // to destruct. 6334 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6335 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6336 NTCUC_CompoundLiteral, NTCUK_Destruct); 6337 6338 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6339 if (literalType.isDestructedType()) { 6340 Cleanup.setExprNeedsCleanups(true); 6341 ExprCleanupObjects.push_back(E); 6342 getCurFunction()->setHasBranchProtectedScope(); 6343 } 6344 } 6345 6346 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6347 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6348 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6349 E->getInitializer()->getExprLoc()); 6350 6351 return MaybeBindToTemporary(E); 6352 } 6353 6354 ExprResult 6355 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6356 SourceLocation RBraceLoc) { 6357 // Only produce each kind of designated initialization diagnostic once. 6358 SourceLocation FirstDesignator; 6359 bool DiagnosedArrayDesignator = false; 6360 bool DiagnosedNestedDesignator = false; 6361 bool DiagnosedMixedDesignator = false; 6362 6363 // Check that any designated initializers are syntactically valid in the 6364 // current language mode. 6365 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6366 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6367 if (FirstDesignator.isInvalid()) 6368 FirstDesignator = DIE->getBeginLoc(); 6369 6370 if (!getLangOpts().CPlusPlus) 6371 break; 6372 6373 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6374 DiagnosedNestedDesignator = true; 6375 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6376 << DIE->getDesignatorsSourceRange(); 6377 } 6378 6379 for (auto &Desig : DIE->designators()) { 6380 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6381 DiagnosedArrayDesignator = true; 6382 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6383 << Desig.getSourceRange(); 6384 } 6385 } 6386 6387 if (!DiagnosedMixedDesignator && 6388 !isa<DesignatedInitExpr>(InitArgList[0])) { 6389 DiagnosedMixedDesignator = true; 6390 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6391 << DIE->getSourceRange(); 6392 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6393 << InitArgList[0]->getSourceRange(); 6394 } 6395 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 6396 isa<DesignatedInitExpr>(InitArgList[0])) { 6397 DiagnosedMixedDesignator = true; 6398 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 6399 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6400 << DIE->getSourceRange(); 6401 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 6402 << InitArgList[I]->getSourceRange(); 6403 } 6404 } 6405 6406 if (FirstDesignator.isValid()) { 6407 // Only diagnose designated initiaization as a C++20 extension if we didn't 6408 // already diagnose use of (non-C++20) C99 designator syntax. 6409 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 6410 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 6411 Diag(FirstDesignator, getLangOpts().CPlusPlus2a 6412 ? diag::warn_cxx17_compat_designated_init 6413 : diag::ext_cxx_designated_init); 6414 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 6415 Diag(FirstDesignator, diag::ext_designated_init); 6416 } 6417 } 6418 6419 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 6420 } 6421 6422 ExprResult 6423 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6424 SourceLocation RBraceLoc) { 6425 // Semantic analysis for initializers is done by ActOnDeclarator() and 6426 // CheckInitializer() - it requires knowledge of the object being initialized. 6427 6428 // Immediately handle non-overload placeholders. Overloads can be 6429 // resolved contextually, but everything else here can't. 6430 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6431 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 6432 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 6433 6434 // Ignore failures; dropping the entire initializer list because 6435 // of one failure would be terrible for indexing/etc. 6436 if (result.isInvalid()) continue; 6437 6438 InitArgList[I] = result.get(); 6439 } 6440 } 6441 6442 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 6443 RBraceLoc); 6444 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 6445 return E; 6446 } 6447 6448 /// Do an explicit extend of the given block pointer if we're in ARC. 6449 void Sema::maybeExtendBlockObject(ExprResult &E) { 6450 assert(E.get()->getType()->isBlockPointerType()); 6451 assert(E.get()->isRValue()); 6452 6453 // Only do this in an r-value context. 6454 if (!getLangOpts().ObjCAutoRefCount) return; 6455 6456 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 6457 CK_ARCExtendBlockObject, E.get(), 6458 /*base path*/ nullptr, VK_RValue); 6459 Cleanup.setExprNeedsCleanups(true); 6460 } 6461 6462 /// Prepare a conversion of the given expression to an ObjC object 6463 /// pointer type. 6464 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 6465 QualType type = E.get()->getType(); 6466 if (type->isObjCObjectPointerType()) { 6467 return CK_BitCast; 6468 } else if (type->isBlockPointerType()) { 6469 maybeExtendBlockObject(E); 6470 return CK_BlockPointerToObjCPointerCast; 6471 } else { 6472 assert(type->isPointerType()); 6473 return CK_CPointerToObjCPointerCast; 6474 } 6475 } 6476 6477 /// Prepares for a scalar cast, performing all the necessary stages 6478 /// except the final cast and returning the kind required. 6479 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 6480 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 6481 // Also, callers should have filtered out the invalid cases with 6482 // pointers. Everything else should be possible. 6483 6484 QualType SrcTy = Src.get()->getType(); 6485 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 6486 return CK_NoOp; 6487 6488 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 6489 case Type::STK_MemberPointer: 6490 llvm_unreachable("member pointer type in C"); 6491 6492 case Type::STK_CPointer: 6493 case Type::STK_BlockPointer: 6494 case Type::STK_ObjCObjectPointer: 6495 switch (DestTy->getScalarTypeKind()) { 6496 case Type::STK_CPointer: { 6497 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 6498 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 6499 if (SrcAS != DestAS) 6500 return CK_AddressSpaceConversion; 6501 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 6502 return CK_NoOp; 6503 return CK_BitCast; 6504 } 6505 case Type::STK_BlockPointer: 6506 return (SrcKind == Type::STK_BlockPointer 6507 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 6508 case Type::STK_ObjCObjectPointer: 6509 if (SrcKind == Type::STK_ObjCObjectPointer) 6510 return CK_BitCast; 6511 if (SrcKind == Type::STK_CPointer) 6512 return CK_CPointerToObjCPointerCast; 6513 maybeExtendBlockObject(Src); 6514 return CK_BlockPointerToObjCPointerCast; 6515 case Type::STK_Bool: 6516 return CK_PointerToBoolean; 6517 case Type::STK_Integral: 6518 return CK_PointerToIntegral; 6519 case Type::STK_Floating: 6520 case Type::STK_FloatingComplex: 6521 case Type::STK_IntegralComplex: 6522 case Type::STK_MemberPointer: 6523 case Type::STK_FixedPoint: 6524 llvm_unreachable("illegal cast from pointer"); 6525 } 6526 llvm_unreachable("Should have returned before this"); 6527 6528 case Type::STK_FixedPoint: 6529 switch (DestTy->getScalarTypeKind()) { 6530 case Type::STK_FixedPoint: 6531 return CK_FixedPointCast; 6532 case Type::STK_Bool: 6533 return CK_FixedPointToBoolean; 6534 case Type::STK_Integral: 6535 return CK_FixedPointToIntegral; 6536 case Type::STK_Floating: 6537 case Type::STK_IntegralComplex: 6538 case Type::STK_FloatingComplex: 6539 Diag(Src.get()->getExprLoc(), 6540 diag::err_unimplemented_conversion_with_fixed_point_type) 6541 << DestTy; 6542 return CK_IntegralCast; 6543 case Type::STK_CPointer: 6544 case Type::STK_ObjCObjectPointer: 6545 case Type::STK_BlockPointer: 6546 case Type::STK_MemberPointer: 6547 llvm_unreachable("illegal cast to pointer type"); 6548 } 6549 llvm_unreachable("Should have returned before this"); 6550 6551 case Type::STK_Bool: // casting from bool is like casting from an integer 6552 case Type::STK_Integral: 6553 switch (DestTy->getScalarTypeKind()) { 6554 case Type::STK_CPointer: 6555 case Type::STK_ObjCObjectPointer: 6556 case Type::STK_BlockPointer: 6557 if (Src.get()->isNullPointerConstant(Context, 6558 Expr::NPC_ValueDependentIsNull)) 6559 return CK_NullToPointer; 6560 return CK_IntegralToPointer; 6561 case Type::STK_Bool: 6562 return CK_IntegralToBoolean; 6563 case Type::STK_Integral: 6564 return CK_IntegralCast; 6565 case Type::STK_Floating: 6566 return CK_IntegralToFloating; 6567 case Type::STK_IntegralComplex: 6568 Src = ImpCastExprToType(Src.get(), 6569 DestTy->castAs<ComplexType>()->getElementType(), 6570 CK_IntegralCast); 6571 return CK_IntegralRealToComplex; 6572 case Type::STK_FloatingComplex: 6573 Src = ImpCastExprToType(Src.get(), 6574 DestTy->castAs<ComplexType>()->getElementType(), 6575 CK_IntegralToFloating); 6576 return CK_FloatingRealToComplex; 6577 case Type::STK_MemberPointer: 6578 llvm_unreachable("member pointer type in C"); 6579 case Type::STK_FixedPoint: 6580 return CK_IntegralToFixedPoint; 6581 } 6582 llvm_unreachable("Should have returned before this"); 6583 6584 case Type::STK_Floating: 6585 switch (DestTy->getScalarTypeKind()) { 6586 case Type::STK_Floating: 6587 return CK_FloatingCast; 6588 case Type::STK_Bool: 6589 return CK_FloatingToBoolean; 6590 case Type::STK_Integral: 6591 return CK_FloatingToIntegral; 6592 case Type::STK_FloatingComplex: 6593 Src = ImpCastExprToType(Src.get(), 6594 DestTy->castAs<ComplexType>()->getElementType(), 6595 CK_FloatingCast); 6596 return CK_FloatingRealToComplex; 6597 case Type::STK_IntegralComplex: 6598 Src = ImpCastExprToType(Src.get(), 6599 DestTy->castAs<ComplexType>()->getElementType(), 6600 CK_FloatingToIntegral); 6601 return CK_IntegralRealToComplex; 6602 case Type::STK_CPointer: 6603 case Type::STK_ObjCObjectPointer: 6604 case Type::STK_BlockPointer: 6605 llvm_unreachable("valid float->pointer cast?"); 6606 case Type::STK_MemberPointer: 6607 llvm_unreachable("member pointer type in C"); 6608 case Type::STK_FixedPoint: 6609 Diag(Src.get()->getExprLoc(), 6610 diag::err_unimplemented_conversion_with_fixed_point_type) 6611 << SrcTy; 6612 return CK_IntegralCast; 6613 } 6614 llvm_unreachable("Should have returned before this"); 6615 6616 case Type::STK_FloatingComplex: 6617 switch (DestTy->getScalarTypeKind()) { 6618 case Type::STK_FloatingComplex: 6619 return CK_FloatingComplexCast; 6620 case Type::STK_IntegralComplex: 6621 return CK_FloatingComplexToIntegralComplex; 6622 case Type::STK_Floating: { 6623 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6624 if (Context.hasSameType(ET, DestTy)) 6625 return CK_FloatingComplexToReal; 6626 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6627 return CK_FloatingCast; 6628 } 6629 case Type::STK_Bool: 6630 return CK_FloatingComplexToBoolean; 6631 case Type::STK_Integral: 6632 Src = ImpCastExprToType(Src.get(), 6633 SrcTy->castAs<ComplexType>()->getElementType(), 6634 CK_FloatingComplexToReal); 6635 return CK_FloatingToIntegral; 6636 case Type::STK_CPointer: 6637 case Type::STK_ObjCObjectPointer: 6638 case Type::STK_BlockPointer: 6639 llvm_unreachable("valid complex float->pointer cast?"); 6640 case Type::STK_MemberPointer: 6641 llvm_unreachable("member pointer type in C"); 6642 case Type::STK_FixedPoint: 6643 Diag(Src.get()->getExprLoc(), 6644 diag::err_unimplemented_conversion_with_fixed_point_type) 6645 << SrcTy; 6646 return CK_IntegralCast; 6647 } 6648 llvm_unreachable("Should have returned before this"); 6649 6650 case Type::STK_IntegralComplex: 6651 switch (DestTy->getScalarTypeKind()) { 6652 case Type::STK_FloatingComplex: 6653 return CK_IntegralComplexToFloatingComplex; 6654 case Type::STK_IntegralComplex: 6655 return CK_IntegralComplexCast; 6656 case Type::STK_Integral: { 6657 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6658 if (Context.hasSameType(ET, DestTy)) 6659 return CK_IntegralComplexToReal; 6660 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6661 return CK_IntegralCast; 6662 } 6663 case Type::STK_Bool: 6664 return CK_IntegralComplexToBoolean; 6665 case Type::STK_Floating: 6666 Src = ImpCastExprToType(Src.get(), 6667 SrcTy->castAs<ComplexType>()->getElementType(), 6668 CK_IntegralComplexToReal); 6669 return CK_IntegralToFloating; 6670 case Type::STK_CPointer: 6671 case Type::STK_ObjCObjectPointer: 6672 case Type::STK_BlockPointer: 6673 llvm_unreachable("valid complex int->pointer cast?"); 6674 case Type::STK_MemberPointer: 6675 llvm_unreachable("member pointer type in C"); 6676 case Type::STK_FixedPoint: 6677 Diag(Src.get()->getExprLoc(), 6678 diag::err_unimplemented_conversion_with_fixed_point_type) 6679 << SrcTy; 6680 return CK_IntegralCast; 6681 } 6682 llvm_unreachable("Should have returned before this"); 6683 } 6684 6685 llvm_unreachable("Unhandled scalar cast"); 6686 } 6687 6688 static bool breakDownVectorType(QualType type, uint64_t &len, 6689 QualType &eltType) { 6690 // Vectors are simple. 6691 if (const VectorType *vecType = type->getAs<VectorType>()) { 6692 len = vecType->getNumElements(); 6693 eltType = vecType->getElementType(); 6694 assert(eltType->isScalarType()); 6695 return true; 6696 } 6697 6698 // We allow lax conversion to and from non-vector types, but only if 6699 // they're real types (i.e. non-complex, non-pointer scalar types). 6700 if (!type->isRealType()) return false; 6701 6702 len = 1; 6703 eltType = type; 6704 return true; 6705 } 6706 6707 /// Are the two types lax-compatible vector types? That is, given 6708 /// that one of them is a vector, do they have equal storage sizes, 6709 /// where the storage size is the number of elements times the element 6710 /// size? 6711 /// 6712 /// This will also return false if either of the types is neither a 6713 /// vector nor a real type. 6714 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6715 assert(destTy->isVectorType() || srcTy->isVectorType()); 6716 6717 // Disallow lax conversions between scalars and ExtVectors (these 6718 // conversions are allowed for other vector types because common headers 6719 // depend on them). Most scalar OP ExtVector cases are handled by the 6720 // splat path anyway, which does what we want (convert, not bitcast). 6721 // What this rules out for ExtVectors is crazy things like char4*float. 6722 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6723 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6724 6725 uint64_t srcLen, destLen; 6726 QualType srcEltTy, destEltTy; 6727 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6728 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6729 6730 // ASTContext::getTypeSize will return the size rounded up to a 6731 // power of 2, so instead of using that, we need to use the raw 6732 // element size multiplied by the element count. 6733 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6734 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6735 6736 return (srcLen * srcEltSize == destLen * destEltSize); 6737 } 6738 6739 /// Is this a legal conversion between two types, one of which is 6740 /// known to be a vector type? 6741 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6742 assert(destTy->isVectorType() || srcTy->isVectorType()); 6743 6744 switch (Context.getLangOpts().getLaxVectorConversions()) { 6745 case LangOptions::LaxVectorConversionKind::None: 6746 return false; 6747 6748 case LangOptions::LaxVectorConversionKind::Integer: 6749 if (!srcTy->isIntegralOrEnumerationType()) { 6750 auto *Vec = srcTy->getAs<VectorType>(); 6751 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6752 return false; 6753 } 6754 if (!destTy->isIntegralOrEnumerationType()) { 6755 auto *Vec = destTy->getAs<VectorType>(); 6756 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 6757 return false; 6758 } 6759 // OK, integer (vector) -> integer (vector) bitcast. 6760 break; 6761 6762 case LangOptions::LaxVectorConversionKind::All: 6763 break; 6764 } 6765 6766 return areLaxCompatibleVectorTypes(srcTy, destTy); 6767 } 6768 6769 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6770 CastKind &Kind) { 6771 assert(VectorTy->isVectorType() && "Not a vector type!"); 6772 6773 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6774 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6775 return Diag(R.getBegin(), 6776 Ty->isVectorType() ? 6777 diag::err_invalid_conversion_between_vectors : 6778 diag::err_invalid_conversion_between_vector_and_integer) 6779 << VectorTy << Ty << R; 6780 } else 6781 return Diag(R.getBegin(), 6782 diag::err_invalid_conversion_between_vector_and_scalar) 6783 << VectorTy << Ty << R; 6784 6785 Kind = CK_BitCast; 6786 return false; 6787 } 6788 6789 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6790 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6791 6792 if (DestElemTy == SplattedExpr->getType()) 6793 return SplattedExpr; 6794 6795 assert(DestElemTy->isFloatingType() || 6796 DestElemTy->isIntegralOrEnumerationType()); 6797 6798 CastKind CK; 6799 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6800 // OpenCL requires that we convert `true` boolean expressions to -1, but 6801 // only when splatting vectors. 6802 if (DestElemTy->isFloatingType()) { 6803 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6804 // in two steps: boolean to signed integral, then to floating. 6805 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6806 CK_BooleanToSignedIntegral); 6807 SplattedExpr = CastExprRes.get(); 6808 CK = CK_IntegralToFloating; 6809 } else { 6810 CK = CK_BooleanToSignedIntegral; 6811 } 6812 } else { 6813 ExprResult CastExprRes = SplattedExpr; 6814 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6815 if (CastExprRes.isInvalid()) 6816 return ExprError(); 6817 SplattedExpr = CastExprRes.get(); 6818 } 6819 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6820 } 6821 6822 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6823 Expr *CastExpr, CastKind &Kind) { 6824 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6825 6826 QualType SrcTy = CastExpr->getType(); 6827 6828 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6829 // an ExtVectorType. 6830 // In OpenCL, casts between vectors of different types are not allowed. 6831 // (See OpenCL 6.2). 6832 if (SrcTy->isVectorType()) { 6833 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6834 (getLangOpts().OpenCL && 6835 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6836 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6837 << DestTy << SrcTy << R; 6838 return ExprError(); 6839 } 6840 Kind = CK_BitCast; 6841 return CastExpr; 6842 } 6843 6844 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6845 // conversion will take place first from scalar to elt type, and then 6846 // splat from elt type to vector. 6847 if (SrcTy->isPointerType()) 6848 return Diag(R.getBegin(), 6849 diag::err_invalid_conversion_between_vector_and_scalar) 6850 << DestTy << SrcTy << R; 6851 6852 Kind = CK_VectorSplat; 6853 return prepareVectorSplat(DestTy, CastExpr); 6854 } 6855 6856 ExprResult 6857 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6858 Declarator &D, ParsedType &Ty, 6859 SourceLocation RParenLoc, Expr *CastExpr) { 6860 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6861 "ActOnCastExpr(): missing type or expr"); 6862 6863 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6864 if (D.isInvalidType()) 6865 return ExprError(); 6866 6867 if (getLangOpts().CPlusPlus) { 6868 // Check that there are no default arguments (C++ only). 6869 CheckExtraCXXDefaultArguments(D); 6870 } else { 6871 // Make sure any TypoExprs have been dealt with. 6872 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6873 if (!Res.isUsable()) 6874 return ExprError(); 6875 CastExpr = Res.get(); 6876 } 6877 6878 checkUnusedDeclAttributes(D); 6879 6880 QualType castType = castTInfo->getType(); 6881 Ty = CreateParsedType(castType, castTInfo); 6882 6883 bool isVectorLiteral = false; 6884 6885 // Check for an altivec or OpenCL literal, 6886 // i.e. all the elements are integer constants. 6887 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6888 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6889 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6890 && castType->isVectorType() && (PE || PLE)) { 6891 if (PLE && PLE->getNumExprs() == 0) { 6892 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6893 return ExprError(); 6894 } 6895 if (PE || PLE->getNumExprs() == 1) { 6896 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6897 if (!E->getType()->isVectorType()) 6898 isVectorLiteral = true; 6899 } 6900 else 6901 isVectorLiteral = true; 6902 } 6903 6904 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6905 // then handle it as such. 6906 if (isVectorLiteral) 6907 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6908 6909 // If the Expr being casted is a ParenListExpr, handle it specially. 6910 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6911 // sequence of BinOp comma operators. 6912 if (isa<ParenListExpr>(CastExpr)) { 6913 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6914 if (Result.isInvalid()) return ExprError(); 6915 CastExpr = Result.get(); 6916 } 6917 6918 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6919 !getSourceManager().isInSystemMacro(LParenLoc)) 6920 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6921 6922 CheckTollFreeBridgeCast(castType, CastExpr); 6923 6924 CheckObjCBridgeRelatedCast(castType, CastExpr); 6925 6926 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6927 6928 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6929 } 6930 6931 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6932 SourceLocation RParenLoc, Expr *E, 6933 TypeSourceInfo *TInfo) { 6934 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6935 "Expected paren or paren list expression"); 6936 6937 Expr **exprs; 6938 unsigned numExprs; 6939 Expr *subExpr; 6940 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6941 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6942 LiteralLParenLoc = PE->getLParenLoc(); 6943 LiteralRParenLoc = PE->getRParenLoc(); 6944 exprs = PE->getExprs(); 6945 numExprs = PE->getNumExprs(); 6946 } else { // isa<ParenExpr> by assertion at function entrance 6947 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6948 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6949 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6950 exprs = &subExpr; 6951 numExprs = 1; 6952 } 6953 6954 QualType Ty = TInfo->getType(); 6955 assert(Ty->isVectorType() && "Expected vector type"); 6956 6957 SmallVector<Expr *, 8> initExprs; 6958 const VectorType *VTy = Ty->castAs<VectorType>(); 6959 unsigned numElems = VTy->getNumElements(); 6960 6961 // '(...)' form of vector initialization in AltiVec: the number of 6962 // initializers must be one or must match the size of the vector. 6963 // If a single value is specified in the initializer then it will be 6964 // replicated to all the components of the vector 6965 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6966 // The number of initializers must be one or must match the size of the 6967 // vector. If a single value is specified in the initializer then it will 6968 // be replicated to all the components of the vector 6969 if (numExprs == 1) { 6970 QualType ElemTy = VTy->getElementType(); 6971 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6972 if (Literal.isInvalid()) 6973 return ExprError(); 6974 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6975 PrepareScalarCast(Literal, ElemTy)); 6976 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6977 } 6978 else if (numExprs < numElems) { 6979 Diag(E->getExprLoc(), 6980 diag::err_incorrect_number_of_vector_initializers); 6981 return ExprError(); 6982 } 6983 else 6984 initExprs.append(exprs, exprs + numExprs); 6985 } 6986 else { 6987 // For OpenCL, when the number of initializers is a single value, 6988 // it will be replicated to all components of the vector. 6989 if (getLangOpts().OpenCL && 6990 VTy->getVectorKind() == VectorType::GenericVector && 6991 numExprs == 1) { 6992 QualType ElemTy = VTy->getElementType(); 6993 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6994 if (Literal.isInvalid()) 6995 return ExprError(); 6996 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6997 PrepareScalarCast(Literal, ElemTy)); 6998 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6999 } 7000 7001 initExprs.append(exprs, exprs + numExprs); 7002 } 7003 // FIXME: This means that pretty-printing the final AST will produce curly 7004 // braces instead of the original commas. 7005 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7006 initExprs, LiteralRParenLoc); 7007 initE->setType(Ty); 7008 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7009 } 7010 7011 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7012 /// the ParenListExpr into a sequence of comma binary operators. 7013 ExprResult 7014 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7015 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7016 if (!E) 7017 return OrigExpr; 7018 7019 ExprResult Result(E->getExpr(0)); 7020 7021 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7022 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7023 E->getExpr(i)); 7024 7025 if (Result.isInvalid()) return ExprError(); 7026 7027 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7028 } 7029 7030 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7031 SourceLocation R, 7032 MultiExprArg Val) { 7033 return ParenListExpr::Create(Context, L, Val, R); 7034 } 7035 7036 /// Emit a specialized diagnostic when one expression is a null pointer 7037 /// constant and the other is not a pointer. Returns true if a diagnostic is 7038 /// emitted. 7039 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7040 SourceLocation QuestionLoc) { 7041 Expr *NullExpr = LHSExpr; 7042 Expr *NonPointerExpr = RHSExpr; 7043 Expr::NullPointerConstantKind NullKind = 7044 NullExpr->isNullPointerConstant(Context, 7045 Expr::NPC_ValueDependentIsNotNull); 7046 7047 if (NullKind == Expr::NPCK_NotNull) { 7048 NullExpr = RHSExpr; 7049 NonPointerExpr = LHSExpr; 7050 NullKind = 7051 NullExpr->isNullPointerConstant(Context, 7052 Expr::NPC_ValueDependentIsNotNull); 7053 } 7054 7055 if (NullKind == Expr::NPCK_NotNull) 7056 return false; 7057 7058 if (NullKind == Expr::NPCK_ZeroExpression) 7059 return false; 7060 7061 if (NullKind == Expr::NPCK_ZeroLiteral) { 7062 // In this case, check to make sure that we got here from a "NULL" 7063 // string in the source code. 7064 NullExpr = NullExpr->IgnoreParenImpCasts(); 7065 SourceLocation loc = NullExpr->getExprLoc(); 7066 if (!findMacroSpelling(loc, "NULL")) 7067 return false; 7068 } 7069 7070 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7071 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7072 << NonPointerExpr->getType() << DiagType 7073 << NonPointerExpr->getSourceRange(); 7074 return true; 7075 } 7076 7077 /// Return false if the condition expression is valid, true otherwise. 7078 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7079 QualType CondTy = Cond->getType(); 7080 7081 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7082 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7083 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7084 << CondTy << Cond->getSourceRange(); 7085 return true; 7086 } 7087 7088 // C99 6.5.15p2 7089 if (CondTy->isScalarType()) return false; 7090 7091 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7092 << CondTy << Cond->getSourceRange(); 7093 return true; 7094 } 7095 7096 /// Handle when one or both operands are void type. 7097 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7098 ExprResult &RHS) { 7099 Expr *LHSExpr = LHS.get(); 7100 Expr *RHSExpr = RHS.get(); 7101 7102 if (!LHSExpr->getType()->isVoidType()) 7103 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7104 << RHSExpr->getSourceRange(); 7105 if (!RHSExpr->getType()->isVoidType()) 7106 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7107 << LHSExpr->getSourceRange(); 7108 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7109 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7110 return S.Context.VoidTy; 7111 } 7112 7113 /// Return false if the NullExpr can be promoted to PointerTy, 7114 /// true otherwise. 7115 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7116 QualType PointerTy) { 7117 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7118 !NullExpr.get()->isNullPointerConstant(S.Context, 7119 Expr::NPC_ValueDependentIsNull)) 7120 return true; 7121 7122 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7123 return false; 7124 } 7125 7126 /// Checks compatibility between two pointers and return the resulting 7127 /// type. 7128 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7129 ExprResult &RHS, 7130 SourceLocation Loc) { 7131 QualType LHSTy = LHS.get()->getType(); 7132 QualType RHSTy = RHS.get()->getType(); 7133 7134 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7135 // Two identical pointers types are always compatible. 7136 return LHSTy; 7137 } 7138 7139 QualType lhptee, rhptee; 7140 7141 // Get the pointee types. 7142 bool IsBlockPointer = false; 7143 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7144 lhptee = LHSBTy->getPointeeType(); 7145 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7146 IsBlockPointer = true; 7147 } else { 7148 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7149 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7150 } 7151 7152 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7153 // differently qualified versions of compatible types, the result type is 7154 // a pointer to an appropriately qualified version of the composite 7155 // type. 7156 7157 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7158 // clause doesn't make sense for our extensions. E.g. address space 2 should 7159 // be incompatible with address space 3: they may live on different devices or 7160 // anything. 7161 Qualifiers lhQual = lhptee.getQualifiers(); 7162 Qualifiers rhQual = rhptee.getQualifiers(); 7163 7164 LangAS ResultAddrSpace = LangAS::Default; 7165 LangAS LAddrSpace = lhQual.getAddressSpace(); 7166 LangAS RAddrSpace = rhQual.getAddressSpace(); 7167 7168 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7169 // spaces is disallowed. 7170 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7171 ResultAddrSpace = LAddrSpace; 7172 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7173 ResultAddrSpace = RAddrSpace; 7174 else { 7175 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7176 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7177 << RHS.get()->getSourceRange(); 7178 return QualType(); 7179 } 7180 7181 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7182 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7183 lhQual.removeCVRQualifiers(); 7184 rhQual.removeCVRQualifiers(); 7185 7186 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7187 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7188 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7189 // qual types are compatible iff 7190 // * corresponded types are compatible 7191 // * CVR qualifiers are equal 7192 // * address spaces are equal 7193 // Thus for conditional operator we merge CVR and address space unqualified 7194 // pointees and if there is a composite type we return a pointer to it with 7195 // merged qualifiers. 7196 LHSCastKind = 7197 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7198 RHSCastKind = 7199 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7200 lhQual.removeAddressSpace(); 7201 rhQual.removeAddressSpace(); 7202 7203 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7204 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7205 7206 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7207 7208 if (CompositeTy.isNull()) { 7209 // In this situation, we assume void* type. No especially good 7210 // reason, but this is what gcc does, and we do have to pick 7211 // to get a consistent AST. 7212 QualType incompatTy; 7213 incompatTy = S.Context.getPointerType( 7214 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7215 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7216 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7217 7218 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7219 // for casts between types with incompatible address space qualifiers. 7220 // For the following code the compiler produces casts between global and 7221 // local address spaces of the corresponded innermost pointees: 7222 // local int *global *a; 7223 // global int *global *b; 7224 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7225 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7226 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7227 << RHS.get()->getSourceRange(); 7228 7229 return incompatTy; 7230 } 7231 7232 // The pointer types are compatible. 7233 // In case of OpenCL ResultTy should have the address space qualifier 7234 // which is a superset of address spaces of both the 2nd and the 3rd 7235 // operands of the conditional operator. 7236 QualType ResultTy = [&, ResultAddrSpace]() { 7237 if (S.getLangOpts().OpenCL) { 7238 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7239 CompositeQuals.setAddressSpace(ResultAddrSpace); 7240 return S.Context 7241 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7242 .withCVRQualifiers(MergedCVRQual); 7243 } 7244 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7245 }(); 7246 if (IsBlockPointer) 7247 ResultTy = S.Context.getBlockPointerType(ResultTy); 7248 else 7249 ResultTy = S.Context.getPointerType(ResultTy); 7250 7251 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7252 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7253 return ResultTy; 7254 } 7255 7256 /// Return the resulting type when the operands are both block pointers. 7257 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7258 ExprResult &LHS, 7259 ExprResult &RHS, 7260 SourceLocation Loc) { 7261 QualType LHSTy = LHS.get()->getType(); 7262 QualType RHSTy = RHS.get()->getType(); 7263 7264 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7265 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7266 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7267 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7268 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7269 return destType; 7270 } 7271 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7272 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7273 << RHS.get()->getSourceRange(); 7274 return QualType(); 7275 } 7276 7277 // We have 2 block pointer types. 7278 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7279 } 7280 7281 /// Return the resulting type when the operands are both pointers. 7282 static QualType 7283 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7284 ExprResult &RHS, 7285 SourceLocation Loc) { 7286 // get the pointer types 7287 QualType LHSTy = LHS.get()->getType(); 7288 QualType RHSTy = RHS.get()->getType(); 7289 7290 // get the "pointed to" types 7291 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7292 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7293 7294 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7295 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7296 // Figure out necessary qualifiers (C99 6.5.15p6) 7297 QualType destPointee 7298 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7299 QualType destType = S.Context.getPointerType(destPointee); 7300 // Add qualifiers if necessary. 7301 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7302 // Promote to void*. 7303 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7304 return destType; 7305 } 7306 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7307 QualType destPointee 7308 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7309 QualType destType = S.Context.getPointerType(destPointee); 7310 // Add qualifiers if necessary. 7311 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7312 // Promote to void*. 7313 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7314 return destType; 7315 } 7316 7317 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7318 } 7319 7320 /// Return false if the first expression is not an integer and the second 7321 /// expression is not a pointer, true otherwise. 7322 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7323 Expr* PointerExpr, SourceLocation Loc, 7324 bool IsIntFirstExpr) { 7325 if (!PointerExpr->getType()->isPointerType() || 7326 !Int.get()->getType()->isIntegerType()) 7327 return false; 7328 7329 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7330 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7331 7332 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7333 << Expr1->getType() << Expr2->getType() 7334 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7335 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7336 CK_IntegralToPointer); 7337 return true; 7338 } 7339 7340 /// Simple conversion between integer and floating point types. 7341 /// 7342 /// Used when handling the OpenCL conditional operator where the 7343 /// condition is a vector while the other operands are scalar. 7344 /// 7345 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 7346 /// types are either integer or floating type. Between the two 7347 /// operands, the type with the higher rank is defined as the "result 7348 /// type". The other operand needs to be promoted to the same type. No 7349 /// other type promotion is allowed. We cannot use 7350 /// UsualArithmeticConversions() for this purpose, since it always 7351 /// promotes promotable types. 7352 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 7353 ExprResult &RHS, 7354 SourceLocation QuestionLoc) { 7355 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 7356 if (LHS.isInvalid()) 7357 return QualType(); 7358 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 7359 if (RHS.isInvalid()) 7360 return QualType(); 7361 7362 // For conversion purposes, we ignore any qualifiers. 7363 // For example, "const float" and "float" are equivalent. 7364 QualType LHSType = 7365 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 7366 QualType RHSType = 7367 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 7368 7369 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 7370 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7371 << LHSType << LHS.get()->getSourceRange(); 7372 return QualType(); 7373 } 7374 7375 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 7376 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 7377 << RHSType << RHS.get()->getSourceRange(); 7378 return QualType(); 7379 } 7380 7381 // If both types are identical, no conversion is needed. 7382 if (LHSType == RHSType) 7383 return LHSType; 7384 7385 // Now handle "real" floating types (i.e. float, double, long double). 7386 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 7387 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 7388 /*IsCompAssign = */ false); 7389 7390 // Finally, we have two differing integer types. 7391 return handleIntegerConversion<doIntegralCast, doIntegralCast> 7392 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 7393 } 7394 7395 /// Convert scalar operands to a vector that matches the 7396 /// condition in length. 7397 /// 7398 /// Used when handling the OpenCL conditional operator where the 7399 /// condition is a vector while the other operands are scalar. 7400 /// 7401 /// We first compute the "result type" for the scalar operands 7402 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 7403 /// into a vector of that type where the length matches the condition 7404 /// vector type. s6.11.6 requires that the element types of the result 7405 /// and the condition must have the same number of bits. 7406 static QualType 7407 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 7408 QualType CondTy, SourceLocation QuestionLoc) { 7409 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 7410 if (ResTy.isNull()) return QualType(); 7411 7412 const VectorType *CV = CondTy->getAs<VectorType>(); 7413 assert(CV); 7414 7415 // Determine the vector result type 7416 unsigned NumElements = CV->getNumElements(); 7417 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 7418 7419 // Ensure that all types have the same number of bits 7420 if (S.Context.getTypeSize(CV->getElementType()) 7421 != S.Context.getTypeSize(ResTy)) { 7422 // Since VectorTy is created internally, it does not pretty print 7423 // with an OpenCL name. Instead, we just print a description. 7424 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 7425 SmallString<64> Str; 7426 llvm::raw_svector_ostream OS(Str); 7427 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 7428 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7429 << CondTy << OS.str(); 7430 return QualType(); 7431 } 7432 7433 // Convert operands to the vector result type 7434 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 7435 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 7436 7437 return VectorTy; 7438 } 7439 7440 /// Return false if this is a valid OpenCL condition vector 7441 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 7442 SourceLocation QuestionLoc) { 7443 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 7444 // integral type. 7445 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 7446 assert(CondTy); 7447 QualType EleTy = CondTy->getElementType(); 7448 if (EleTy->isIntegerType()) return false; 7449 7450 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7451 << Cond->getType() << Cond->getSourceRange(); 7452 return true; 7453 } 7454 7455 /// Return false if the vector condition type and the vector 7456 /// result type are compatible. 7457 /// 7458 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 7459 /// number of elements, and their element types have the same number 7460 /// of bits. 7461 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 7462 SourceLocation QuestionLoc) { 7463 const VectorType *CV = CondTy->getAs<VectorType>(); 7464 const VectorType *RV = VecResTy->getAs<VectorType>(); 7465 assert(CV && RV); 7466 7467 if (CV->getNumElements() != RV->getNumElements()) { 7468 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 7469 << CondTy << VecResTy; 7470 return true; 7471 } 7472 7473 QualType CVE = CV->getElementType(); 7474 QualType RVE = RV->getElementType(); 7475 7476 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 7477 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 7478 << CondTy << VecResTy; 7479 return true; 7480 } 7481 7482 return false; 7483 } 7484 7485 /// Return the resulting type for the conditional operator in 7486 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 7487 /// s6.3.i) when the condition is a vector type. 7488 static QualType 7489 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 7490 ExprResult &LHS, ExprResult &RHS, 7491 SourceLocation QuestionLoc) { 7492 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 7493 if (Cond.isInvalid()) 7494 return QualType(); 7495 QualType CondTy = Cond.get()->getType(); 7496 7497 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 7498 return QualType(); 7499 7500 // If either operand is a vector then find the vector type of the 7501 // result as specified in OpenCL v1.1 s6.3.i. 7502 if (LHS.get()->getType()->isVectorType() || 7503 RHS.get()->getType()->isVectorType()) { 7504 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 7505 /*isCompAssign*/false, 7506 /*AllowBothBool*/true, 7507 /*AllowBoolConversions*/false); 7508 if (VecResTy.isNull()) return QualType(); 7509 // The result type must match the condition type as specified in 7510 // OpenCL v1.1 s6.11.6. 7511 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 7512 return QualType(); 7513 return VecResTy; 7514 } 7515 7516 // Both operands are scalar. 7517 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 7518 } 7519 7520 /// Return true if the Expr is block type 7521 static bool checkBlockType(Sema &S, const Expr *E) { 7522 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 7523 QualType Ty = CE->getCallee()->getType(); 7524 if (Ty->isBlockPointerType()) { 7525 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 7526 return true; 7527 } 7528 } 7529 return false; 7530 } 7531 7532 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 7533 /// In that case, LHS = cond. 7534 /// C99 6.5.15 7535 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 7536 ExprResult &RHS, ExprValueKind &VK, 7537 ExprObjectKind &OK, 7538 SourceLocation QuestionLoc) { 7539 7540 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 7541 if (!LHSResult.isUsable()) return QualType(); 7542 LHS = LHSResult; 7543 7544 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 7545 if (!RHSResult.isUsable()) return QualType(); 7546 RHS = RHSResult; 7547 7548 // C++ is sufficiently different to merit its own checker. 7549 if (getLangOpts().CPlusPlus) 7550 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 7551 7552 VK = VK_RValue; 7553 OK = OK_Ordinary; 7554 7555 // The OpenCL operator with a vector condition is sufficiently 7556 // different to merit its own checker. 7557 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 7558 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 7559 7560 // First, check the condition. 7561 Cond = UsualUnaryConversions(Cond.get()); 7562 if (Cond.isInvalid()) 7563 return QualType(); 7564 if (checkCondition(*this, Cond.get(), QuestionLoc)) 7565 return QualType(); 7566 7567 // Now check the two expressions. 7568 if (LHS.get()->getType()->isVectorType() || 7569 RHS.get()->getType()->isVectorType()) 7570 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 7571 /*AllowBothBool*/true, 7572 /*AllowBoolConversions*/false); 7573 7574 QualType ResTy = 7575 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7576 if (LHS.isInvalid() || RHS.isInvalid()) 7577 return QualType(); 7578 7579 QualType LHSTy = LHS.get()->getType(); 7580 QualType RHSTy = RHS.get()->getType(); 7581 7582 // Diagnose attempts to convert between __float128 and long double where 7583 // such conversions currently can't be handled. 7584 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7585 Diag(QuestionLoc, 7586 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7587 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7588 return QualType(); 7589 } 7590 7591 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7592 // selection operator (?:). 7593 if (getLangOpts().OpenCL && 7594 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7595 return QualType(); 7596 } 7597 7598 // If both operands have arithmetic type, do the usual arithmetic conversions 7599 // to find a common type: C99 6.5.15p3,5. 7600 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7601 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7602 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7603 7604 return ResTy; 7605 } 7606 7607 // If both operands are the same structure or union type, the result is that 7608 // type. 7609 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7610 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7611 if (LHSRT->getDecl() == RHSRT->getDecl()) 7612 // "If both the operands have structure or union type, the result has 7613 // that type." This implies that CV qualifiers are dropped. 7614 return LHSTy.getUnqualifiedType(); 7615 // FIXME: Type of conditional expression must be complete in C mode. 7616 } 7617 7618 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7619 // The following || allows only one side to be void (a GCC-ism). 7620 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7621 return checkConditionalVoidType(*this, LHS, RHS); 7622 } 7623 7624 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7625 // the type of the other operand." 7626 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7627 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7628 7629 // All objective-c pointer type analysis is done here. 7630 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7631 QuestionLoc); 7632 if (LHS.isInvalid() || RHS.isInvalid()) 7633 return QualType(); 7634 if (!compositeType.isNull()) 7635 return compositeType; 7636 7637 7638 // Handle block pointer types. 7639 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7640 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7641 QuestionLoc); 7642 7643 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7644 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7645 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7646 QuestionLoc); 7647 7648 // GCC compatibility: soften pointer/integer mismatch. Note that 7649 // null pointers have been filtered out by this point. 7650 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7651 /*IsIntFirstExpr=*/true)) 7652 return RHSTy; 7653 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7654 /*IsIntFirstExpr=*/false)) 7655 return LHSTy; 7656 7657 // Allow ?: operations in which both operands have the same 7658 // built-in sizeless type. 7659 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 7660 return LHSTy; 7661 7662 // Emit a better diagnostic if one of the expressions is a null pointer 7663 // constant and the other is not a pointer type. In this case, the user most 7664 // likely forgot to take the address of the other expression. 7665 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7666 return QualType(); 7667 7668 // Otherwise, the operands are not compatible. 7669 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7670 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7671 << RHS.get()->getSourceRange(); 7672 return QualType(); 7673 } 7674 7675 /// FindCompositeObjCPointerType - Helper method to find composite type of 7676 /// two objective-c pointer types of the two input expressions. 7677 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7678 SourceLocation QuestionLoc) { 7679 QualType LHSTy = LHS.get()->getType(); 7680 QualType RHSTy = RHS.get()->getType(); 7681 7682 // Handle things like Class and struct objc_class*. Here we case the result 7683 // to the pseudo-builtin, because that will be implicitly cast back to the 7684 // redefinition type if an attempt is made to access its fields. 7685 if (LHSTy->isObjCClassType() && 7686 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7687 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7688 return LHSTy; 7689 } 7690 if (RHSTy->isObjCClassType() && 7691 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7692 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7693 return RHSTy; 7694 } 7695 // And the same for struct objc_object* / id 7696 if (LHSTy->isObjCIdType() && 7697 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7698 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7699 return LHSTy; 7700 } 7701 if (RHSTy->isObjCIdType() && 7702 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7703 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7704 return RHSTy; 7705 } 7706 // And the same for struct objc_selector* / SEL 7707 if (Context.isObjCSelType(LHSTy) && 7708 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7709 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7710 return LHSTy; 7711 } 7712 if (Context.isObjCSelType(RHSTy) && 7713 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7714 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7715 return RHSTy; 7716 } 7717 // Check constraints for Objective-C object pointers types. 7718 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7719 7720 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7721 // Two identical object pointer types are always compatible. 7722 return LHSTy; 7723 } 7724 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7725 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7726 QualType compositeType = LHSTy; 7727 7728 // If both operands are interfaces and either operand can be 7729 // assigned to the other, use that type as the composite 7730 // type. This allows 7731 // xxx ? (A*) a : (B*) b 7732 // where B is a subclass of A. 7733 // 7734 // Additionally, as for assignment, if either type is 'id' 7735 // allow silent coercion. Finally, if the types are 7736 // incompatible then make sure to use 'id' as the composite 7737 // type so the result is acceptable for sending messages to. 7738 7739 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7740 // It could return the composite type. 7741 if (!(compositeType = 7742 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7743 // Nothing more to do. 7744 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7745 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7746 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7747 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7748 } else if ((LHSOPT->isObjCQualifiedIdType() || 7749 RHSOPT->isObjCQualifiedIdType()) && 7750 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 7751 true)) { 7752 // Need to handle "id<xx>" explicitly. 7753 // GCC allows qualified id and any Objective-C type to devolve to 7754 // id. Currently localizing to here until clear this should be 7755 // part of ObjCQualifiedIdTypesAreCompatible. 7756 compositeType = Context.getObjCIdType(); 7757 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7758 compositeType = Context.getObjCIdType(); 7759 } else { 7760 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7761 << LHSTy << RHSTy 7762 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7763 QualType incompatTy = Context.getObjCIdType(); 7764 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7765 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7766 return incompatTy; 7767 } 7768 // The object pointer types are compatible. 7769 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7770 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7771 return compositeType; 7772 } 7773 // Check Objective-C object pointer types and 'void *' 7774 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7775 if (getLangOpts().ObjCAutoRefCount) { 7776 // ARC forbids the implicit conversion of object pointers to 'void *', 7777 // so these types are not compatible. 7778 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7779 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7780 LHS = RHS = true; 7781 return QualType(); 7782 } 7783 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7784 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7785 QualType destPointee 7786 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7787 QualType destType = Context.getPointerType(destPointee); 7788 // Add qualifiers if necessary. 7789 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7790 // Promote to void*. 7791 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7792 return destType; 7793 } 7794 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7795 if (getLangOpts().ObjCAutoRefCount) { 7796 // ARC forbids the implicit conversion of object pointers to 'void *', 7797 // so these types are not compatible. 7798 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7799 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7800 LHS = RHS = true; 7801 return QualType(); 7802 } 7803 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 7804 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7805 QualType destPointee 7806 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7807 QualType destType = Context.getPointerType(destPointee); 7808 // Add qualifiers if necessary. 7809 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7810 // Promote to void*. 7811 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7812 return destType; 7813 } 7814 return QualType(); 7815 } 7816 7817 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7818 /// ParenRange in parentheses. 7819 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7820 const PartialDiagnostic &Note, 7821 SourceRange ParenRange) { 7822 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7823 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7824 EndLoc.isValid()) { 7825 Self.Diag(Loc, Note) 7826 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7827 << FixItHint::CreateInsertion(EndLoc, ")"); 7828 } else { 7829 // We can't display the parentheses, so just show the bare note. 7830 Self.Diag(Loc, Note) << ParenRange; 7831 } 7832 } 7833 7834 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7835 return BinaryOperator::isAdditiveOp(Opc) || 7836 BinaryOperator::isMultiplicativeOp(Opc) || 7837 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 7838 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 7839 // not any of the logical operators. Bitwise-xor is commonly used as a 7840 // logical-xor because there is no logical-xor operator. The logical 7841 // operators, including uses of xor, have a high false positive rate for 7842 // precedence warnings. 7843 } 7844 7845 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7846 /// expression, either using a built-in or overloaded operator, 7847 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7848 /// expression. 7849 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7850 Expr **RHSExprs) { 7851 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7852 E = E->IgnoreImpCasts(); 7853 E = E->IgnoreConversionOperator(); 7854 E = E->IgnoreImpCasts(); 7855 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7856 E = MTE->getSubExpr(); 7857 E = E->IgnoreImpCasts(); 7858 } 7859 7860 // Built-in binary operator. 7861 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7862 if (IsArithmeticOp(OP->getOpcode())) { 7863 *Opcode = OP->getOpcode(); 7864 *RHSExprs = OP->getRHS(); 7865 return true; 7866 } 7867 } 7868 7869 // Overloaded operator. 7870 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7871 if (Call->getNumArgs() != 2) 7872 return false; 7873 7874 // Make sure this is really a binary operator that is safe to pass into 7875 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7876 OverloadedOperatorKind OO = Call->getOperator(); 7877 if (OO < OO_Plus || OO > OO_Arrow || 7878 OO == OO_PlusPlus || OO == OO_MinusMinus) 7879 return false; 7880 7881 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7882 if (IsArithmeticOp(OpKind)) { 7883 *Opcode = OpKind; 7884 *RHSExprs = Call->getArg(1); 7885 return true; 7886 } 7887 } 7888 7889 return false; 7890 } 7891 7892 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7893 /// or is a logical expression such as (x==y) which has int type, but is 7894 /// commonly interpreted as boolean. 7895 static bool ExprLooksBoolean(Expr *E) { 7896 E = E->IgnoreParenImpCasts(); 7897 7898 if (E->getType()->isBooleanType()) 7899 return true; 7900 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7901 return OP->isComparisonOp() || OP->isLogicalOp(); 7902 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7903 return OP->getOpcode() == UO_LNot; 7904 if (E->getType()->isPointerType()) 7905 return true; 7906 // FIXME: What about overloaded operator calls returning "unspecified boolean 7907 // type"s (commonly pointer-to-members)? 7908 7909 return false; 7910 } 7911 7912 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7913 /// and binary operator are mixed in a way that suggests the programmer assumed 7914 /// the conditional operator has higher precedence, for example: 7915 /// "int x = a + someBinaryCondition ? 1 : 2". 7916 static void DiagnoseConditionalPrecedence(Sema &Self, 7917 SourceLocation OpLoc, 7918 Expr *Condition, 7919 Expr *LHSExpr, 7920 Expr *RHSExpr) { 7921 BinaryOperatorKind CondOpcode; 7922 Expr *CondRHS; 7923 7924 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7925 return; 7926 if (!ExprLooksBoolean(CondRHS)) 7927 return; 7928 7929 // The condition is an arithmetic binary expression, with a right- 7930 // hand side that looks boolean, so warn. 7931 7932 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 7933 ? diag::warn_precedence_bitwise_conditional 7934 : diag::warn_precedence_conditional; 7935 7936 Self.Diag(OpLoc, DiagID) 7937 << Condition->getSourceRange() 7938 << BinaryOperator::getOpcodeStr(CondOpcode); 7939 7940 SuggestParentheses( 7941 Self, OpLoc, 7942 Self.PDiag(diag::note_precedence_silence) 7943 << BinaryOperator::getOpcodeStr(CondOpcode), 7944 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7945 7946 SuggestParentheses(Self, OpLoc, 7947 Self.PDiag(diag::note_precedence_conditional_first), 7948 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7949 } 7950 7951 /// Compute the nullability of a conditional expression. 7952 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7953 QualType LHSTy, QualType RHSTy, 7954 ASTContext &Ctx) { 7955 if (!ResTy->isAnyPointerType()) 7956 return ResTy; 7957 7958 auto GetNullability = [&Ctx](QualType Ty) { 7959 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7960 if (Kind) 7961 return *Kind; 7962 return NullabilityKind::Unspecified; 7963 }; 7964 7965 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7966 NullabilityKind MergedKind; 7967 7968 // Compute nullability of a binary conditional expression. 7969 if (IsBin) { 7970 if (LHSKind == NullabilityKind::NonNull) 7971 MergedKind = NullabilityKind::NonNull; 7972 else 7973 MergedKind = RHSKind; 7974 // Compute nullability of a normal conditional expression. 7975 } else { 7976 if (LHSKind == NullabilityKind::Nullable || 7977 RHSKind == NullabilityKind::Nullable) 7978 MergedKind = NullabilityKind::Nullable; 7979 else if (LHSKind == NullabilityKind::NonNull) 7980 MergedKind = RHSKind; 7981 else if (RHSKind == NullabilityKind::NonNull) 7982 MergedKind = LHSKind; 7983 else 7984 MergedKind = NullabilityKind::Unspecified; 7985 } 7986 7987 // Return if ResTy already has the correct nullability. 7988 if (GetNullability(ResTy) == MergedKind) 7989 return ResTy; 7990 7991 // Strip all nullability from ResTy. 7992 while (ResTy->getNullability(Ctx)) 7993 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7994 7995 // Create a new AttributedType with the new nullability kind. 7996 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7997 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7998 } 7999 8000 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8001 /// in the case of a the GNU conditional expr extension. 8002 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8003 SourceLocation ColonLoc, 8004 Expr *CondExpr, Expr *LHSExpr, 8005 Expr *RHSExpr) { 8006 if (!getLangOpts().CPlusPlus) { 8007 // C cannot handle TypoExpr nodes in the condition because it 8008 // doesn't handle dependent types properly, so make sure any TypoExprs have 8009 // been dealt with before checking the operands. 8010 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8011 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8012 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8013 8014 if (!CondResult.isUsable()) 8015 return ExprError(); 8016 8017 if (LHSExpr) { 8018 if (!LHSResult.isUsable()) 8019 return ExprError(); 8020 } 8021 8022 if (!RHSResult.isUsable()) 8023 return ExprError(); 8024 8025 CondExpr = CondResult.get(); 8026 LHSExpr = LHSResult.get(); 8027 RHSExpr = RHSResult.get(); 8028 } 8029 8030 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8031 // was the condition. 8032 OpaqueValueExpr *opaqueValue = nullptr; 8033 Expr *commonExpr = nullptr; 8034 if (!LHSExpr) { 8035 commonExpr = CondExpr; 8036 // Lower out placeholder types first. This is important so that we don't 8037 // try to capture a placeholder. This happens in few cases in C++; such 8038 // as Objective-C++'s dictionary subscripting syntax. 8039 if (commonExpr->hasPlaceholderType()) { 8040 ExprResult result = CheckPlaceholderExpr(commonExpr); 8041 if (!result.isUsable()) return ExprError(); 8042 commonExpr = result.get(); 8043 } 8044 // We usually want to apply unary conversions *before* saving, except 8045 // in the special case of a C++ l-value conditional. 8046 if (!(getLangOpts().CPlusPlus 8047 && !commonExpr->isTypeDependent() 8048 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8049 && commonExpr->isGLValue() 8050 && commonExpr->isOrdinaryOrBitFieldObject() 8051 && RHSExpr->isOrdinaryOrBitFieldObject() 8052 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8053 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8054 if (commonRes.isInvalid()) 8055 return ExprError(); 8056 commonExpr = commonRes.get(); 8057 } 8058 8059 // If the common expression is a class or array prvalue, materialize it 8060 // so that we can safely refer to it multiple times. 8061 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8062 commonExpr->getType()->isArrayType())) { 8063 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8064 if (MatExpr.isInvalid()) 8065 return ExprError(); 8066 commonExpr = MatExpr.get(); 8067 } 8068 8069 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8070 commonExpr->getType(), 8071 commonExpr->getValueKind(), 8072 commonExpr->getObjectKind(), 8073 commonExpr); 8074 LHSExpr = CondExpr = opaqueValue; 8075 } 8076 8077 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8078 ExprValueKind VK = VK_RValue; 8079 ExprObjectKind OK = OK_Ordinary; 8080 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8081 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8082 VK, OK, QuestionLoc); 8083 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8084 RHS.isInvalid()) 8085 return ExprError(); 8086 8087 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8088 RHS.get()); 8089 8090 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8091 8092 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8093 Context); 8094 8095 if (!commonExpr) 8096 return new (Context) 8097 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8098 RHS.get(), result, VK, OK); 8099 8100 return new (Context) BinaryConditionalOperator( 8101 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8102 ColonLoc, result, VK, OK); 8103 } 8104 8105 // Check if we have a conversion between incompatible cmse function pointer 8106 // types, that is, a conversion between a function pointer with the 8107 // cmse_nonsecure_call attribute and one without. 8108 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8109 QualType ToType) { 8110 if (const auto *ToFn = 8111 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8112 if (const auto *FromFn = 8113 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8114 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8115 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8116 8117 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8118 } 8119 } 8120 return false; 8121 } 8122 8123 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8124 // being closely modeled after the C99 spec:-). The odd characteristic of this 8125 // routine is it effectively iqnores the qualifiers on the top level pointee. 8126 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8127 // FIXME: add a couple examples in this comment. 8128 static Sema::AssignConvertType 8129 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8130 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8131 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8132 8133 // get the "pointed to" type (ignoring qualifiers at the top level) 8134 const Type *lhptee, *rhptee; 8135 Qualifiers lhq, rhq; 8136 std::tie(lhptee, lhq) = 8137 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8138 std::tie(rhptee, rhq) = 8139 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8140 8141 Sema::AssignConvertType ConvTy = Sema::Compatible; 8142 8143 // C99 6.5.16.1p1: This following citation is common to constraints 8144 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8145 // qualifiers of the type *pointed to* by the right; 8146 8147 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8148 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8149 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8150 // Ignore lifetime for further calculation. 8151 lhq.removeObjCLifetime(); 8152 rhq.removeObjCLifetime(); 8153 } 8154 8155 if (!lhq.compatiblyIncludes(rhq)) { 8156 // Treat address-space mismatches as fatal. 8157 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8158 return Sema::IncompatiblePointerDiscardsQualifiers; 8159 8160 // It's okay to add or remove GC or lifetime qualifiers when converting to 8161 // and from void*. 8162 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8163 .compatiblyIncludes( 8164 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8165 && (lhptee->isVoidType() || rhptee->isVoidType())) 8166 ; // keep old 8167 8168 // Treat lifetime mismatches as fatal. 8169 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8170 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8171 8172 // For GCC/MS compatibility, other qualifier mismatches are treated 8173 // as still compatible in C. 8174 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8175 } 8176 8177 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8178 // incomplete type and the other is a pointer to a qualified or unqualified 8179 // version of void... 8180 if (lhptee->isVoidType()) { 8181 if (rhptee->isIncompleteOrObjectType()) 8182 return ConvTy; 8183 8184 // As an extension, we allow cast to/from void* to function pointer. 8185 assert(rhptee->isFunctionType()); 8186 return Sema::FunctionVoidPointer; 8187 } 8188 8189 if (rhptee->isVoidType()) { 8190 if (lhptee->isIncompleteOrObjectType()) 8191 return ConvTy; 8192 8193 // As an extension, we allow cast to/from void* to function pointer. 8194 assert(lhptee->isFunctionType()); 8195 return Sema::FunctionVoidPointer; 8196 } 8197 8198 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8199 // unqualified versions of compatible types, ... 8200 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8201 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8202 // Check if the pointee types are compatible ignoring the sign. 8203 // We explicitly check for char so that we catch "char" vs 8204 // "unsigned char" on systems where "char" is unsigned. 8205 if (lhptee->isCharType()) 8206 ltrans = S.Context.UnsignedCharTy; 8207 else if (lhptee->hasSignedIntegerRepresentation()) 8208 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8209 8210 if (rhptee->isCharType()) 8211 rtrans = S.Context.UnsignedCharTy; 8212 else if (rhptee->hasSignedIntegerRepresentation()) 8213 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8214 8215 if (ltrans == rtrans) { 8216 // Types are compatible ignoring the sign. Qualifier incompatibility 8217 // takes priority over sign incompatibility because the sign 8218 // warning can be disabled. 8219 if (ConvTy != Sema::Compatible) 8220 return ConvTy; 8221 8222 return Sema::IncompatiblePointerSign; 8223 } 8224 8225 // If we are a multi-level pointer, it's possible that our issue is simply 8226 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8227 // the eventual target type is the same and the pointers have the same 8228 // level of indirection, this must be the issue. 8229 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8230 do { 8231 std::tie(lhptee, lhq) = 8232 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8233 std::tie(rhptee, rhq) = 8234 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8235 8236 // Inconsistent address spaces at this point is invalid, even if the 8237 // address spaces would be compatible. 8238 // FIXME: This doesn't catch address space mismatches for pointers of 8239 // different nesting levels, like: 8240 // __local int *** a; 8241 // int ** b = a; 8242 // It's not clear how to actually determine when such pointers are 8243 // invalidly incompatible. 8244 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8245 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8246 8247 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8248 8249 if (lhptee == rhptee) 8250 return Sema::IncompatibleNestedPointerQualifiers; 8251 } 8252 8253 // General pointer incompatibility takes priority over qualifiers. 8254 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8255 return Sema::IncompatibleFunctionPointer; 8256 return Sema::IncompatiblePointer; 8257 } 8258 if (!S.getLangOpts().CPlusPlus && 8259 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8260 return Sema::IncompatibleFunctionPointer; 8261 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8262 return Sema::IncompatibleFunctionPointer; 8263 return ConvTy; 8264 } 8265 8266 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8267 /// block pointer types are compatible or whether a block and normal pointer 8268 /// are compatible. It is more restrict than comparing two function pointer 8269 // types. 8270 static Sema::AssignConvertType 8271 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8272 QualType RHSType) { 8273 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8274 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8275 8276 QualType lhptee, rhptee; 8277 8278 // get the "pointed to" type (ignoring qualifiers at the top level) 8279 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8280 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8281 8282 // In C++, the types have to match exactly. 8283 if (S.getLangOpts().CPlusPlus) 8284 return Sema::IncompatibleBlockPointer; 8285 8286 Sema::AssignConvertType ConvTy = Sema::Compatible; 8287 8288 // For blocks we enforce that qualifiers are identical. 8289 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8290 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8291 if (S.getLangOpts().OpenCL) { 8292 LQuals.removeAddressSpace(); 8293 RQuals.removeAddressSpace(); 8294 } 8295 if (LQuals != RQuals) 8296 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8297 8298 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8299 // assignment. 8300 // The current behavior is similar to C++ lambdas. A block might be 8301 // assigned to a variable iff its return type and parameters are compatible 8302 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8303 // an assignment. Presumably it should behave in way that a function pointer 8304 // assignment does in C, so for each parameter and return type: 8305 // * CVR and address space of LHS should be a superset of CVR and address 8306 // space of RHS. 8307 // * unqualified types should be compatible. 8308 if (S.getLangOpts().OpenCL) { 8309 if (!S.Context.typesAreBlockPointerCompatible( 8310 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 8311 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 8312 return Sema::IncompatibleBlockPointer; 8313 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 8314 return Sema::IncompatibleBlockPointer; 8315 8316 return ConvTy; 8317 } 8318 8319 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 8320 /// for assignment compatibility. 8321 static Sema::AssignConvertType 8322 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 8323 QualType RHSType) { 8324 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 8325 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 8326 8327 if (LHSType->isObjCBuiltinType()) { 8328 // Class is not compatible with ObjC object pointers. 8329 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 8330 !RHSType->isObjCQualifiedClassType()) 8331 return Sema::IncompatiblePointer; 8332 return Sema::Compatible; 8333 } 8334 if (RHSType->isObjCBuiltinType()) { 8335 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 8336 !LHSType->isObjCQualifiedClassType()) 8337 return Sema::IncompatiblePointer; 8338 return Sema::Compatible; 8339 } 8340 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8341 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 8342 8343 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 8344 // make an exception for id<P> 8345 !LHSType->isObjCQualifiedIdType()) 8346 return Sema::CompatiblePointerDiscardsQualifiers; 8347 8348 if (S.Context.typesAreCompatible(LHSType, RHSType)) 8349 return Sema::Compatible; 8350 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 8351 return Sema::IncompatibleObjCQualifiedId; 8352 return Sema::IncompatiblePointer; 8353 } 8354 8355 Sema::AssignConvertType 8356 Sema::CheckAssignmentConstraints(SourceLocation Loc, 8357 QualType LHSType, QualType RHSType) { 8358 // Fake up an opaque expression. We don't actually care about what 8359 // cast operations are required, so if CheckAssignmentConstraints 8360 // adds casts to this they'll be wasted, but fortunately that doesn't 8361 // usually happen on valid code. 8362 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 8363 ExprResult RHSPtr = &RHSExpr; 8364 CastKind K; 8365 8366 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 8367 } 8368 8369 /// This helper function returns true if QT is a vector type that has element 8370 /// type ElementType. 8371 static bool isVector(QualType QT, QualType ElementType) { 8372 if (const VectorType *VT = QT->getAs<VectorType>()) 8373 return VT->getElementType().getCanonicalType() == ElementType; 8374 return false; 8375 } 8376 8377 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 8378 /// has code to accommodate several GCC extensions when type checking 8379 /// pointers. Here are some objectionable examples that GCC considers warnings: 8380 /// 8381 /// int a, *pint; 8382 /// short *pshort; 8383 /// struct foo *pfoo; 8384 /// 8385 /// pint = pshort; // warning: assignment from incompatible pointer type 8386 /// a = pint; // warning: assignment makes integer from pointer without a cast 8387 /// pint = a; // warning: assignment makes pointer from integer without a cast 8388 /// pint = pfoo; // warning: assignment from incompatible pointer type 8389 /// 8390 /// As a result, the code for dealing with pointers is more complex than the 8391 /// C99 spec dictates. 8392 /// 8393 /// Sets 'Kind' for any result kind except Incompatible. 8394 Sema::AssignConvertType 8395 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 8396 CastKind &Kind, bool ConvertRHS) { 8397 QualType RHSType = RHS.get()->getType(); 8398 QualType OrigLHSType = LHSType; 8399 8400 // Get canonical types. We're not formatting these types, just comparing 8401 // them. 8402 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 8403 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 8404 8405 // Common case: no conversion required. 8406 if (LHSType == RHSType) { 8407 Kind = CK_NoOp; 8408 return Compatible; 8409 } 8410 8411 // If we have an atomic type, try a non-atomic assignment, then just add an 8412 // atomic qualification step. 8413 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 8414 Sema::AssignConvertType result = 8415 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 8416 if (result != Compatible) 8417 return result; 8418 if (Kind != CK_NoOp && ConvertRHS) 8419 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 8420 Kind = CK_NonAtomicToAtomic; 8421 return Compatible; 8422 } 8423 8424 // If the left-hand side is a reference type, then we are in a 8425 // (rare!) case where we've allowed the use of references in C, 8426 // e.g., as a parameter type in a built-in function. In this case, 8427 // just make sure that the type referenced is compatible with the 8428 // right-hand side type. The caller is responsible for adjusting 8429 // LHSType so that the resulting expression does not have reference 8430 // type. 8431 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 8432 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 8433 Kind = CK_LValueBitCast; 8434 return Compatible; 8435 } 8436 return Incompatible; 8437 } 8438 8439 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 8440 // to the same ExtVector type. 8441 if (LHSType->isExtVectorType()) { 8442 if (RHSType->isExtVectorType()) 8443 return Incompatible; 8444 if (RHSType->isArithmeticType()) { 8445 // CK_VectorSplat does T -> vector T, so first cast to the element type. 8446 if (ConvertRHS) 8447 RHS = prepareVectorSplat(LHSType, RHS.get()); 8448 Kind = CK_VectorSplat; 8449 return Compatible; 8450 } 8451 } 8452 8453 // Conversions to or from vector type. 8454 if (LHSType->isVectorType() || RHSType->isVectorType()) { 8455 if (LHSType->isVectorType() && RHSType->isVectorType()) { 8456 // Allow assignments of an AltiVec vector type to an equivalent GCC 8457 // vector type and vice versa 8458 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8459 Kind = CK_BitCast; 8460 return Compatible; 8461 } 8462 8463 // If we are allowing lax vector conversions, and LHS and RHS are both 8464 // vectors, the total size only needs to be the same. This is a bitcast; 8465 // no bits are changed but the result type is different. 8466 if (isLaxVectorConversion(RHSType, LHSType)) { 8467 Kind = CK_BitCast; 8468 return IncompatibleVectors; 8469 } 8470 } 8471 8472 // When the RHS comes from another lax conversion (e.g. binops between 8473 // scalars and vectors) the result is canonicalized as a vector. When the 8474 // LHS is also a vector, the lax is allowed by the condition above. Handle 8475 // the case where LHS is a scalar. 8476 if (LHSType->isScalarType()) { 8477 const VectorType *VecType = RHSType->getAs<VectorType>(); 8478 if (VecType && VecType->getNumElements() == 1 && 8479 isLaxVectorConversion(RHSType, LHSType)) { 8480 ExprResult *VecExpr = &RHS; 8481 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 8482 Kind = CK_BitCast; 8483 return Compatible; 8484 } 8485 } 8486 8487 return Incompatible; 8488 } 8489 8490 // Diagnose attempts to convert between __float128 and long double where 8491 // such conversions currently can't be handled. 8492 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 8493 return Incompatible; 8494 8495 // Disallow assigning a _Complex to a real type in C++ mode since it simply 8496 // discards the imaginary part. 8497 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 8498 !LHSType->getAs<ComplexType>()) 8499 return Incompatible; 8500 8501 // Arithmetic conversions. 8502 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 8503 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 8504 if (ConvertRHS) 8505 Kind = PrepareScalarCast(RHS, LHSType); 8506 return Compatible; 8507 } 8508 8509 // Conversions to normal pointers. 8510 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 8511 // U* -> T* 8512 if (isa<PointerType>(RHSType)) { 8513 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8514 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 8515 if (AddrSpaceL != AddrSpaceR) 8516 Kind = CK_AddressSpaceConversion; 8517 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 8518 Kind = CK_NoOp; 8519 else 8520 Kind = CK_BitCast; 8521 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 8522 } 8523 8524 // int -> T* 8525 if (RHSType->isIntegerType()) { 8526 Kind = CK_IntegralToPointer; // FIXME: null? 8527 return IntToPointer; 8528 } 8529 8530 // C pointers are not compatible with ObjC object pointers, 8531 // with two exceptions: 8532 if (isa<ObjCObjectPointerType>(RHSType)) { 8533 // - conversions to void* 8534 if (LHSPointer->getPointeeType()->isVoidType()) { 8535 Kind = CK_BitCast; 8536 return Compatible; 8537 } 8538 8539 // - conversions from 'Class' to the redefinition type 8540 if (RHSType->isObjCClassType() && 8541 Context.hasSameType(LHSType, 8542 Context.getObjCClassRedefinitionType())) { 8543 Kind = CK_BitCast; 8544 return Compatible; 8545 } 8546 8547 Kind = CK_BitCast; 8548 return IncompatiblePointer; 8549 } 8550 8551 // U^ -> void* 8552 if (RHSType->getAs<BlockPointerType>()) { 8553 if (LHSPointer->getPointeeType()->isVoidType()) { 8554 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 8555 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8556 ->getPointeeType() 8557 .getAddressSpace(); 8558 Kind = 8559 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8560 return Compatible; 8561 } 8562 } 8563 8564 return Incompatible; 8565 } 8566 8567 // Conversions to block pointers. 8568 if (isa<BlockPointerType>(LHSType)) { 8569 // U^ -> T^ 8570 if (RHSType->isBlockPointerType()) { 8571 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 8572 ->getPointeeType() 8573 .getAddressSpace(); 8574 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 8575 ->getPointeeType() 8576 .getAddressSpace(); 8577 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 8578 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 8579 } 8580 8581 // int or null -> T^ 8582 if (RHSType->isIntegerType()) { 8583 Kind = CK_IntegralToPointer; // FIXME: null 8584 return IntToBlockPointer; 8585 } 8586 8587 // id -> T^ 8588 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 8589 Kind = CK_AnyPointerToBlockPointerCast; 8590 return Compatible; 8591 } 8592 8593 // void* -> T^ 8594 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 8595 if (RHSPT->getPointeeType()->isVoidType()) { 8596 Kind = CK_AnyPointerToBlockPointerCast; 8597 return Compatible; 8598 } 8599 8600 return Incompatible; 8601 } 8602 8603 // Conversions to Objective-C pointers. 8604 if (isa<ObjCObjectPointerType>(LHSType)) { 8605 // A* -> B* 8606 if (RHSType->isObjCObjectPointerType()) { 8607 Kind = CK_BitCast; 8608 Sema::AssignConvertType result = 8609 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 8610 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8611 result == Compatible && 8612 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 8613 result = IncompatibleObjCWeakRef; 8614 return result; 8615 } 8616 8617 // int or null -> A* 8618 if (RHSType->isIntegerType()) { 8619 Kind = CK_IntegralToPointer; // FIXME: null 8620 return IntToPointer; 8621 } 8622 8623 // In general, C pointers are not compatible with ObjC object pointers, 8624 // with two exceptions: 8625 if (isa<PointerType>(RHSType)) { 8626 Kind = CK_CPointerToObjCPointerCast; 8627 8628 // - conversions from 'void*' 8629 if (RHSType->isVoidPointerType()) { 8630 return Compatible; 8631 } 8632 8633 // - conversions to 'Class' from its redefinition type 8634 if (LHSType->isObjCClassType() && 8635 Context.hasSameType(RHSType, 8636 Context.getObjCClassRedefinitionType())) { 8637 return Compatible; 8638 } 8639 8640 return IncompatiblePointer; 8641 } 8642 8643 // Only under strict condition T^ is compatible with an Objective-C pointer. 8644 if (RHSType->isBlockPointerType() && 8645 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8646 if (ConvertRHS) 8647 maybeExtendBlockObject(RHS); 8648 Kind = CK_BlockPointerToObjCPointerCast; 8649 return Compatible; 8650 } 8651 8652 return Incompatible; 8653 } 8654 8655 // Conversions from pointers that are not covered by the above. 8656 if (isa<PointerType>(RHSType)) { 8657 // T* -> _Bool 8658 if (LHSType == Context.BoolTy) { 8659 Kind = CK_PointerToBoolean; 8660 return Compatible; 8661 } 8662 8663 // T* -> int 8664 if (LHSType->isIntegerType()) { 8665 Kind = CK_PointerToIntegral; 8666 return PointerToInt; 8667 } 8668 8669 return Incompatible; 8670 } 8671 8672 // Conversions from Objective-C pointers that are not covered by the above. 8673 if (isa<ObjCObjectPointerType>(RHSType)) { 8674 // T* -> _Bool 8675 if (LHSType == Context.BoolTy) { 8676 Kind = CK_PointerToBoolean; 8677 return Compatible; 8678 } 8679 8680 // T* -> int 8681 if (LHSType->isIntegerType()) { 8682 Kind = CK_PointerToIntegral; 8683 return PointerToInt; 8684 } 8685 8686 return Incompatible; 8687 } 8688 8689 // struct A -> struct B 8690 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8691 if (Context.typesAreCompatible(LHSType, RHSType)) { 8692 Kind = CK_NoOp; 8693 return Compatible; 8694 } 8695 } 8696 8697 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8698 Kind = CK_IntToOCLSampler; 8699 return Compatible; 8700 } 8701 8702 return Incompatible; 8703 } 8704 8705 /// Constructs a transparent union from an expression that is 8706 /// used to initialize the transparent union. 8707 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8708 ExprResult &EResult, QualType UnionType, 8709 FieldDecl *Field) { 8710 // Build an initializer list that designates the appropriate member 8711 // of the transparent union. 8712 Expr *E = EResult.get(); 8713 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8714 E, SourceLocation()); 8715 Initializer->setType(UnionType); 8716 Initializer->setInitializedFieldInUnion(Field); 8717 8718 // Build a compound literal constructing a value of the transparent 8719 // union type from this initializer list. 8720 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8721 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8722 VK_RValue, Initializer, false); 8723 } 8724 8725 Sema::AssignConvertType 8726 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8727 ExprResult &RHS) { 8728 QualType RHSType = RHS.get()->getType(); 8729 8730 // If the ArgType is a Union type, we want to handle a potential 8731 // transparent_union GCC extension. 8732 const RecordType *UT = ArgType->getAsUnionType(); 8733 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8734 return Incompatible; 8735 8736 // The field to initialize within the transparent union. 8737 RecordDecl *UD = UT->getDecl(); 8738 FieldDecl *InitField = nullptr; 8739 // It's compatible if the expression matches any of the fields. 8740 for (auto *it : UD->fields()) { 8741 if (it->getType()->isPointerType()) { 8742 // If the transparent union contains a pointer type, we allow: 8743 // 1) void pointer 8744 // 2) null pointer constant 8745 if (RHSType->isPointerType()) 8746 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8747 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8748 InitField = it; 8749 break; 8750 } 8751 8752 if (RHS.get()->isNullPointerConstant(Context, 8753 Expr::NPC_ValueDependentIsNull)) { 8754 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8755 CK_NullToPointer); 8756 InitField = it; 8757 break; 8758 } 8759 } 8760 8761 CastKind Kind; 8762 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8763 == Compatible) { 8764 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8765 InitField = it; 8766 break; 8767 } 8768 } 8769 8770 if (!InitField) 8771 return Incompatible; 8772 8773 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8774 return Compatible; 8775 } 8776 8777 Sema::AssignConvertType 8778 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8779 bool Diagnose, 8780 bool DiagnoseCFAudited, 8781 bool ConvertRHS) { 8782 // We need to be able to tell the caller whether we diagnosed a problem, if 8783 // they ask us to issue diagnostics. 8784 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8785 8786 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8787 // we can't avoid *all* modifications at the moment, so we need some somewhere 8788 // to put the updated value. 8789 ExprResult LocalRHS = CallerRHS; 8790 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8791 8792 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 8793 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 8794 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 8795 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 8796 Diag(RHS.get()->getExprLoc(), 8797 diag::warn_noderef_to_dereferenceable_pointer) 8798 << RHS.get()->getSourceRange(); 8799 } 8800 } 8801 } 8802 8803 if (getLangOpts().CPlusPlus) { 8804 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8805 // C++ 5.17p3: If the left operand is not of class type, the 8806 // expression is implicitly converted (C++ 4) to the 8807 // cv-unqualified type of the left operand. 8808 QualType RHSType = RHS.get()->getType(); 8809 if (Diagnose) { 8810 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8811 AA_Assigning); 8812 } else { 8813 ImplicitConversionSequence ICS = 8814 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8815 /*SuppressUserConversions=*/false, 8816 AllowedExplicit::None, 8817 /*InOverloadResolution=*/false, 8818 /*CStyle=*/false, 8819 /*AllowObjCWritebackConversion=*/false); 8820 if (ICS.isFailure()) 8821 return Incompatible; 8822 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8823 ICS, AA_Assigning); 8824 } 8825 if (RHS.isInvalid()) 8826 return Incompatible; 8827 Sema::AssignConvertType result = Compatible; 8828 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8829 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8830 result = IncompatibleObjCWeakRef; 8831 return result; 8832 } 8833 8834 // FIXME: Currently, we fall through and treat C++ classes like C 8835 // structures. 8836 // FIXME: We also fall through for atomics; not sure what should 8837 // happen there, though. 8838 } else if (RHS.get()->getType() == Context.OverloadTy) { 8839 // As a set of extensions to C, we support overloading on functions. These 8840 // functions need to be resolved here. 8841 DeclAccessPair DAP; 8842 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8843 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8844 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8845 else 8846 return Incompatible; 8847 } 8848 8849 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8850 // a null pointer constant. 8851 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8852 LHSType->isBlockPointerType()) && 8853 RHS.get()->isNullPointerConstant(Context, 8854 Expr::NPC_ValueDependentIsNull)) { 8855 if (Diagnose || ConvertRHS) { 8856 CastKind Kind; 8857 CXXCastPath Path; 8858 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8859 /*IgnoreBaseAccess=*/false, Diagnose); 8860 if (ConvertRHS) 8861 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8862 } 8863 return Compatible; 8864 } 8865 8866 // OpenCL queue_t type assignment. 8867 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8868 Context, Expr::NPC_ValueDependentIsNull)) { 8869 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8870 return Compatible; 8871 } 8872 8873 // This check seems unnatural, however it is necessary to ensure the proper 8874 // conversion of functions/arrays. If the conversion were done for all 8875 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8876 // expressions that suppress this implicit conversion (&, sizeof). 8877 // 8878 // Suppress this for references: C++ 8.5.3p5. 8879 if (!LHSType->isReferenceType()) { 8880 // FIXME: We potentially allocate here even if ConvertRHS is false. 8881 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8882 if (RHS.isInvalid()) 8883 return Incompatible; 8884 } 8885 CastKind Kind; 8886 Sema::AssignConvertType result = 8887 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8888 8889 // C99 6.5.16.1p2: The value of the right operand is converted to the 8890 // type of the assignment expression. 8891 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8892 // so that we can use references in built-in functions even in C. 8893 // The getNonReferenceType() call makes sure that the resulting expression 8894 // does not have reference type. 8895 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8896 QualType Ty = LHSType.getNonLValueExprType(Context); 8897 Expr *E = RHS.get(); 8898 8899 // Check for various Objective-C errors. If we are not reporting 8900 // diagnostics and just checking for errors, e.g., during overload 8901 // resolution, return Incompatible to indicate the failure. 8902 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8903 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8904 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8905 if (!Diagnose) 8906 return Incompatible; 8907 } 8908 if (getLangOpts().ObjC && 8909 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8910 E->getType(), E, Diagnose) || 8911 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8912 if (!Diagnose) 8913 return Incompatible; 8914 // Replace the expression with a corrected version and continue so we 8915 // can find further errors. 8916 RHS = E; 8917 return Compatible; 8918 } 8919 8920 if (ConvertRHS) 8921 RHS = ImpCastExprToType(E, Ty, Kind); 8922 } 8923 8924 return result; 8925 } 8926 8927 namespace { 8928 /// The original operand to an operator, prior to the application of the usual 8929 /// arithmetic conversions and converting the arguments of a builtin operator 8930 /// candidate. 8931 struct OriginalOperand { 8932 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8933 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8934 Op = MTE->getSubExpr(); 8935 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8936 Op = BTE->getSubExpr(); 8937 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8938 Orig = ICE->getSubExprAsWritten(); 8939 Conversion = ICE->getConversionFunction(); 8940 } 8941 } 8942 8943 QualType getType() const { return Orig->getType(); } 8944 8945 Expr *Orig; 8946 NamedDecl *Conversion; 8947 }; 8948 } 8949 8950 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8951 ExprResult &RHS) { 8952 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8953 8954 Diag(Loc, diag::err_typecheck_invalid_operands) 8955 << OrigLHS.getType() << OrigRHS.getType() 8956 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8957 8958 // If a user-defined conversion was applied to either of the operands prior 8959 // to applying the built-in operator rules, tell the user about it. 8960 if (OrigLHS.Conversion) { 8961 Diag(OrigLHS.Conversion->getLocation(), 8962 diag::note_typecheck_invalid_operands_converted) 8963 << 0 << LHS.get()->getType(); 8964 } 8965 if (OrigRHS.Conversion) { 8966 Diag(OrigRHS.Conversion->getLocation(), 8967 diag::note_typecheck_invalid_operands_converted) 8968 << 1 << RHS.get()->getType(); 8969 } 8970 8971 return QualType(); 8972 } 8973 8974 // Diagnose cases where a scalar was implicitly converted to a vector and 8975 // diagnose the underlying types. Otherwise, diagnose the error 8976 // as invalid vector logical operands for non-C++ cases. 8977 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8978 ExprResult &RHS) { 8979 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8980 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8981 8982 bool LHSNatVec = LHSType->isVectorType(); 8983 bool RHSNatVec = RHSType->isVectorType(); 8984 8985 if (!(LHSNatVec && RHSNatVec)) { 8986 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8987 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8988 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8989 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8990 << Vector->getSourceRange(); 8991 return QualType(); 8992 } 8993 8994 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8995 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8996 << RHS.get()->getSourceRange(); 8997 8998 return QualType(); 8999 } 9000 9001 /// Try to convert a value of non-vector type to a vector type by converting 9002 /// the type to the element type of the vector and then performing a splat. 9003 /// If the language is OpenCL, we only use conversions that promote scalar 9004 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9005 /// for float->int. 9006 /// 9007 /// OpenCL V2.0 6.2.6.p2: 9008 /// An error shall occur if any scalar operand type has greater rank 9009 /// than the type of the vector element. 9010 /// 9011 /// \param scalar - if non-null, actually perform the conversions 9012 /// \return true if the operation fails (but without diagnosing the failure) 9013 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9014 QualType scalarTy, 9015 QualType vectorEltTy, 9016 QualType vectorTy, 9017 unsigned &DiagID) { 9018 // The conversion to apply to the scalar before splatting it, 9019 // if necessary. 9020 CastKind scalarCast = CK_NoOp; 9021 9022 if (vectorEltTy->isIntegralType(S.Context)) { 9023 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9024 (scalarTy->isIntegerType() && 9025 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9026 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9027 return true; 9028 } 9029 if (!scalarTy->isIntegralType(S.Context)) 9030 return true; 9031 scalarCast = CK_IntegralCast; 9032 } else if (vectorEltTy->isRealFloatingType()) { 9033 if (scalarTy->isRealFloatingType()) { 9034 if (S.getLangOpts().OpenCL && 9035 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9036 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9037 return true; 9038 } 9039 scalarCast = CK_FloatingCast; 9040 } 9041 else if (scalarTy->isIntegralType(S.Context)) 9042 scalarCast = CK_IntegralToFloating; 9043 else 9044 return true; 9045 } else { 9046 return true; 9047 } 9048 9049 // Adjust scalar if desired. 9050 if (scalar) { 9051 if (scalarCast != CK_NoOp) 9052 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9053 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9054 } 9055 return false; 9056 } 9057 9058 /// Convert vector E to a vector with the same number of elements but different 9059 /// element type. 9060 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9061 const auto *VecTy = E->getType()->getAs<VectorType>(); 9062 assert(VecTy && "Expression E must be a vector"); 9063 QualType NewVecTy = S.Context.getVectorType(ElementType, 9064 VecTy->getNumElements(), 9065 VecTy->getVectorKind()); 9066 9067 // Look through the implicit cast. Return the subexpression if its type is 9068 // NewVecTy. 9069 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9070 if (ICE->getSubExpr()->getType() == NewVecTy) 9071 return ICE->getSubExpr(); 9072 9073 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9074 return S.ImpCastExprToType(E, NewVecTy, Cast); 9075 } 9076 9077 /// Test if a (constant) integer Int can be casted to another integer type 9078 /// IntTy without losing precision. 9079 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9080 QualType OtherIntTy) { 9081 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9082 9083 // Reject cases where the value of the Int is unknown as that would 9084 // possibly cause truncation, but accept cases where the scalar can be 9085 // demoted without loss of precision. 9086 Expr::EvalResult EVResult; 9087 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9088 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9089 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9090 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9091 9092 if (CstInt) { 9093 // If the scalar is constant and is of a higher order and has more active 9094 // bits that the vector element type, reject it. 9095 llvm::APSInt Result = EVResult.Val.getInt(); 9096 unsigned NumBits = IntSigned 9097 ? (Result.isNegative() ? Result.getMinSignedBits() 9098 : Result.getActiveBits()) 9099 : Result.getActiveBits(); 9100 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9101 return true; 9102 9103 // If the signedness of the scalar type and the vector element type 9104 // differs and the number of bits is greater than that of the vector 9105 // element reject it. 9106 return (IntSigned != OtherIntSigned && 9107 NumBits > S.Context.getIntWidth(OtherIntTy)); 9108 } 9109 9110 // Reject cases where the value of the scalar is not constant and it's 9111 // order is greater than that of the vector element type. 9112 return (Order < 0); 9113 } 9114 9115 /// Test if a (constant) integer Int can be casted to floating point type 9116 /// FloatTy without losing precision. 9117 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9118 QualType FloatTy) { 9119 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9120 9121 // Determine if the integer constant can be expressed as a floating point 9122 // number of the appropriate type. 9123 Expr::EvalResult EVResult; 9124 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9125 9126 uint64_t Bits = 0; 9127 if (CstInt) { 9128 // Reject constants that would be truncated if they were converted to 9129 // the floating point type. Test by simple to/from conversion. 9130 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9131 // could be avoided if there was a convertFromAPInt method 9132 // which could signal back if implicit truncation occurred. 9133 llvm::APSInt Result = EVResult.Val.getInt(); 9134 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9135 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9136 llvm::APFloat::rmTowardZero); 9137 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9138 !IntTy->hasSignedIntegerRepresentation()); 9139 bool Ignored = false; 9140 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9141 &Ignored); 9142 if (Result != ConvertBack) 9143 return true; 9144 } else { 9145 // Reject types that cannot be fully encoded into the mantissa of 9146 // the float. 9147 Bits = S.Context.getTypeSize(IntTy); 9148 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9149 S.Context.getFloatTypeSemantics(FloatTy)); 9150 if (Bits > FloatPrec) 9151 return true; 9152 } 9153 9154 return false; 9155 } 9156 9157 /// Attempt to convert and splat Scalar into a vector whose types matches 9158 /// Vector following GCC conversion rules. The rule is that implicit 9159 /// conversion can occur when Scalar can be casted to match Vector's element 9160 /// type without causing truncation of Scalar. 9161 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9162 ExprResult *Vector) { 9163 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9164 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9165 const VectorType *VT = VectorTy->getAs<VectorType>(); 9166 9167 assert(!isa<ExtVectorType>(VT) && 9168 "ExtVectorTypes should not be handled here!"); 9169 9170 QualType VectorEltTy = VT->getElementType(); 9171 9172 // Reject cases where the vector element type or the scalar element type are 9173 // not integral or floating point types. 9174 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9175 return true; 9176 9177 // The conversion to apply to the scalar before splatting it, 9178 // if necessary. 9179 CastKind ScalarCast = CK_NoOp; 9180 9181 // Accept cases where the vector elements are integers and the scalar is 9182 // an integer. 9183 // FIXME: Notionally if the scalar was a floating point value with a precise 9184 // integral representation, we could cast it to an appropriate integer 9185 // type and then perform the rest of the checks here. GCC will perform 9186 // this conversion in some cases as determined by the input language. 9187 // We should accept it on a language independent basis. 9188 if (VectorEltTy->isIntegralType(S.Context) && 9189 ScalarTy->isIntegralType(S.Context) && 9190 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9191 9192 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9193 return true; 9194 9195 ScalarCast = CK_IntegralCast; 9196 } else if (VectorEltTy->isIntegralType(S.Context) && 9197 ScalarTy->isRealFloatingType()) { 9198 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9199 ScalarCast = CK_FloatingToIntegral; 9200 else 9201 return true; 9202 } else if (VectorEltTy->isRealFloatingType()) { 9203 if (ScalarTy->isRealFloatingType()) { 9204 9205 // Reject cases where the scalar type is not a constant and has a higher 9206 // Order than the vector element type. 9207 llvm::APFloat Result(0.0); 9208 9209 // Determine whether this is a constant scalar. In the event that the 9210 // value is dependent (and thus cannot be evaluated by the constant 9211 // evaluator), skip the evaluation. This will then diagnose once the 9212 // expression is instantiated. 9213 bool CstScalar = Scalar->get()->isValueDependent() || 9214 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9215 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9216 if (!CstScalar && Order < 0) 9217 return true; 9218 9219 // If the scalar cannot be safely casted to the vector element type, 9220 // reject it. 9221 if (CstScalar) { 9222 bool Truncated = false; 9223 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9224 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9225 if (Truncated) 9226 return true; 9227 } 9228 9229 ScalarCast = CK_FloatingCast; 9230 } else if (ScalarTy->isIntegralType(S.Context)) { 9231 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9232 return true; 9233 9234 ScalarCast = CK_IntegralToFloating; 9235 } else 9236 return true; 9237 } 9238 9239 // Adjust scalar if desired. 9240 if (Scalar) { 9241 if (ScalarCast != CK_NoOp) 9242 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9243 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9244 } 9245 return false; 9246 } 9247 9248 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9249 SourceLocation Loc, bool IsCompAssign, 9250 bool AllowBothBool, 9251 bool AllowBoolConversions) { 9252 if (!IsCompAssign) { 9253 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9254 if (LHS.isInvalid()) 9255 return QualType(); 9256 } 9257 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9258 if (RHS.isInvalid()) 9259 return QualType(); 9260 9261 // For conversion purposes, we ignore any qualifiers. 9262 // For example, "const float" and "float" are equivalent. 9263 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9264 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9265 9266 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9267 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9268 assert(LHSVecType || RHSVecType); 9269 9270 // AltiVec-style "vector bool op vector bool" combinations are allowed 9271 // for some operators but not others. 9272 if (!AllowBothBool && 9273 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9274 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9275 return InvalidOperands(Loc, LHS, RHS); 9276 9277 // If the vector types are identical, return. 9278 if (Context.hasSameType(LHSType, RHSType)) 9279 return LHSType; 9280 9281 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9282 if (LHSVecType && RHSVecType && 9283 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9284 if (isa<ExtVectorType>(LHSVecType)) { 9285 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9286 return LHSType; 9287 } 9288 9289 if (!IsCompAssign) 9290 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9291 return RHSType; 9292 } 9293 9294 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9295 // can be mixed, with the result being the non-bool type. The non-bool 9296 // operand must have integer element type. 9297 if (AllowBoolConversions && LHSVecType && RHSVecType && 9298 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 9299 (Context.getTypeSize(LHSVecType->getElementType()) == 9300 Context.getTypeSize(RHSVecType->getElementType()))) { 9301 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 9302 LHSVecType->getElementType()->isIntegerType() && 9303 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 9304 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9305 return LHSType; 9306 } 9307 if (!IsCompAssign && 9308 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9309 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 9310 RHSVecType->getElementType()->isIntegerType()) { 9311 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9312 return RHSType; 9313 } 9314 } 9315 9316 // If there's a vector type and a scalar, try to convert the scalar to 9317 // the vector element type and splat. 9318 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 9319 if (!RHSVecType) { 9320 if (isa<ExtVectorType>(LHSVecType)) { 9321 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 9322 LHSVecType->getElementType(), LHSType, 9323 DiagID)) 9324 return LHSType; 9325 } else { 9326 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 9327 return LHSType; 9328 } 9329 } 9330 if (!LHSVecType) { 9331 if (isa<ExtVectorType>(RHSVecType)) { 9332 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 9333 LHSType, RHSVecType->getElementType(), 9334 RHSType, DiagID)) 9335 return RHSType; 9336 } else { 9337 if (LHS.get()->getValueKind() == VK_LValue || 9338 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 9339 return RHSType; 9340 } 9341 } 9342 9343 // FIXME: The code below also handles conversion between vectors and 9344 // non-scalars, we should break this down into fine grained specific checks 9345 // and emit proper diagnostics. 9346 QualType VecType = LHSVecType ? LHSType : RHSType; 9347 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 9348 QualType OtherType = LHSVecType ? RHSType : LHSType; 9349 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 9350 if (isLaxVectorConversion(OtherType, VecType)) { 9351 // If we're allowing lax vector conversions, only the total (data) size 9352 // needs to be the same. For non compound assignment, if one of the types is 9353 // scalar, the result is always the vector type. 9354 if (!IsCompAssign) { 9355 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 9356 return VecType; 9357 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 9358 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 9359 // type. Note that this is already done by non-compound assignments in 9360 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 9361 // <1 x T> -> T. The result is also a vector type. 9362 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 9363 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 9364 ExprResult *RHSExpr = &RHS; 9365 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 9366 return VecType; 9367 } 9368 } 9369 9370 // Okay, the expression is invalid. 9371 9372 // If there's a non-vector, non-real operand, diagnose that. 9373 if ((!RHSVecType && !RHSType->isRealType()) || 9374 (!LHSVecType && !LHSType->isRealType())) { 9375 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 9376 << LHSType << RHSType 9377 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9378 return QualType(); 9379 } 9380 9381 // OpenCL V1.1 6.2.6.p1: 9382 // If the operands are of more than one vector type, then an error shall 9383 // occur. Implicit conversions between vector types are not permitted, per 9384 // section 6.2.1. 9385 if (getLangOpts().OpenCL && 9386 RHSVecType && isa<ExtVectorType>(RHSVecType) && 9387 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 9388 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 9389 << RHSType; 9390 return QualType(); 9391 } 9392 9393 9394 // If there is a vector type that is not a ExtVector and a scalar, we reach 9395 // this point if scalar could not be converted to the vector's element type 9396 // without truncation. 9397 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 9398 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 9399 QualType Scalar = LHSVecType ? RHSType : LHSType; 9400 QualType Vector = LHSVecType ? LHSType : RHSType; 9401 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 9402 Diag(Loc, 9403 diag::err_typecheck_vector_not_convertable_implict_truncation) 9404 << ScalarOrVector << Scalar << Vector; 9405 9406 return QualType(); 9407 } 9408 9409 // Otherwise, use the generic diagnostic. 9410 Diag(Loc, DiagID) 9411 << LHSType << RHSType 9412 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9413 return QualType(); 9414 } 9415 9416 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 9417 // expression. These are mainly cases where the null pointer is used as an 9418 // integer instead of a pointer. 9419 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 9420 SourceLocation Loc, bool IsCompare) { 9421 // The canonical way to check for a GNU null is with isNullPointerConstant, 9422 // but we use a bit of a hack here for speed; this is a relatively 9423 // hot path, and isNullPointerConstant is slow. 9424 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 9425 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 9426 9427 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 9428 9429 // Avoid analyzing cases where the result will either be invalid (and 9430 // diagnosed as such) or entirely valid and not something to warn about. 9431 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 9432 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 9433 return; 9434 9435 // Comparison operations would not make sense with a null pointer no matter 9436 // what the other expression is. 9437 if (!IsCompare) { 9438 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 9439 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 9440 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 9441 return; 9442 } 9443 9444 // The rest of the operations only make sense with a null pointer 9445 // if the other expression is a pointer. 9446 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 9447 NonNullType->canDecayToPointerType()) 9448 return; 9449 9450 S.Diag(Loc, diag::warn_null_in_comparison_operation) 9451 << LHSNull /* LHS is NULL */ << NonNullType 9452 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9453 } 9454 9455 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 9456 SourceLocation Loc) { 9457 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 9458 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 9459 if (!LUE || !RUE) 9460 return; 9461 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 9462 RUE->getKind() != UETT_SizeOf) 9463 return; 9464 9465 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 9466 QualType LHSTy = LHSArg->getType(); 9467 QualType RHSTy; 9468 9469 if (RUE->isArgumentType()) 9470 RHSTy = RUE->getArgumentType(); 9471 else 9472 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 9473 9474 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 9475 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 9476 return; 9477 9478 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 9479 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9480 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9481 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 9482 << LHSArgDecl; 9483 } 9484 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 9485 QualType ArrayElemTy = ArrayTy->getElementType(); 9486 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 9487 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 9488 ArrayElemTy->isCharType() || 9489 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 9490 return; 9491 S.Diag(Loc, diag::warn_division_sizeof_array) 9492 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 9493 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 9494 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 9495 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 9496 << LHSArgDecl; 9497 } 9498 9499 S.Diag(Loc, diag::note_precedence_silence) << RHS; 9500 } 9501 } 9502 9503 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 9504 ExprResult &RHS, 9505 SourceLocation Loc, bool IsDiv) { 9506 // Check for division/remainder by zero. 9507 Expr::EvalResult RHSValue; 9508 if (!RHS.get()->isValueDependent() && 9509 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 9510 RHSValue.Val.getInt() == 0) 9511 S.DiagRuntimeBehavior(Loc, RHS.get(), 9512 S.PDiag(diag::warn_remainder_division_by_zero) 9513 << IsDiv << RHS.get()->getSourceRange()); 9514 } 9515 9516 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 9517 SourceLocation Loc, 9518 bool IsCompAssign, bool IsDiv) { 9519 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9520 9521 if (LHS.get()->getType()->isVectorType() || 9522 RHS.get()->getType()->isVectorType()) 9523 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9524 /*AllowBothBool*/getLangOpts().AltiVec, 9525 /*AllowBoolConversions*/false); 9526 9527 QualType compType = UsualArithmeticConversions( 9528 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9529 if (LHS.isInvalid() || RHS.isInvalid()) 9530 return QualType(); 9531 9532 9533 if (compType.isNull() || !compType->isArithmeticType()) 9534 return InvalidOperands(Loc, LHS, RHS); 9535 if (IsDiv) { 9536 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 9537 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 9538 } 9539 return compType; 9540 } 9541 9542 QualType Sema::CheckRemainderOperands( 9543 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9544 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9545 9546 if (LHS.get()->getType()->isVectorType() || 9547 RHS.get()->getType()->isVectorType()) { 9548 if (LHS.get()->getType()->hasIntegerRepresentation() && 9549 RHS.get()->getType()->hasIntegerRepresentation()) 9550 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9551 /*AllowBothBool*/getLangOpts().AltiVec, 9552 /*AllowBoolConversions*/false); 9553 return InvalidOperands(Loc, LHS, RHS); 9554 } 9555 9556 QualType compType = UsualArithmeticConversions( 9557 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 9558 if (LHS.isInvalid() || RHS.isInvalid()) 9559 return QualType(); 9560 9561 if (compType.isNull() || !compType->isIntegerType()) 9562 return InvalidOperands(Loc, LHS, RHS); 9563 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 9564 return compType; 9565 } 9566 9567 /// Diagnose invalid arithmetic on two void pointers. 9568 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 9569 Expr *LHSExpr, Expr *RHSExpr) { 9570 S.Diag(Loc, S.getLangOpts().CPlusPlus 9571 ? diag::err_typecheck_pointer_arith_void_type 9572 : diag::ext_gnu_void_ptr) 9573 << 1 /* two pointers */ << LHSExpr->getSourceRange() 9574 << RHSExpr->getSourceRange(); 9575 } 9576 9577 /// Diagnose invalid arithmetic on a void pointer. 9578 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 9579 Expr *Pointer) { 9580 S.Diag(Loc, S.getLangOpts().CPlusPlus 9581 ? diag::err_typecheck_pointer_arith_void_type 9582 : diag::ext_gnu_void_ptr) 9583 << 0 /* one pointer */ << Pointer->getSourceRange(); 9584 } 9585 9586 /// Diagnose invalid arithmetic on a null pointer. 9587 /// 9588 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 9589 /// idiom, which we recognize as a GNU extension. 9590 /// 9591 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 9592 Expr *Pointer, bool IsGNUIdiom) { 9593 if (IsGNUIdiom) 9594 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 9595 << Pointer->getSourceRange(); 9596 else 9597 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 9598 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 9599 } 9600 9601 /// Diagnose invalid arithmetic on two function pointers. 9602 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 9603 Expr *LHS, Expr *RHS) { 9604 assert(LHS->getType()->isAnyPointerType()); 9605 assert(RHS->getType()->isAnyPointerType()); 9606 S.Diag(Loc, S.getLangOpts().CPlusPlus 9607 ? diag::err_typecheck_pointer_arith_function_type 9608 : diag::ext_gnu_ptr_func_arith) 9609 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 9610 // We only show the second type if it differs from the first. 9611 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 9612 RHS->getType()) 9613 << RHS->getType()->getPointeeType() 9614 << LHS->getSourceRange() << RHS->getSourceRange(); 9615 } 9616 9617 /// Diagnose invalid arithmetic on a function pointer. 9618 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 9619 Expr *Pointer) { 9620 assert(Pointer->getType()->isAnyPointerType()); 9621 S.Diag(Loc, S.getLangOpts().CPlusPlus 9622 ? diag::err_typecheck_pointer_arith_function_type 9623 : diag::ext_gnu_ptr_func_arith) 9624 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 9625 << 0 /* one pointer, so only one type */ 9626 << Pointer->getSourceRange(); 9627 } 9628 9629 /// Emit error if Operand is incomplete pointer type 9630 /// 9631 /// \returns True if pointer has incomplete type 9632 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 9633 Expr *Operand) { 9634 QualType ResType = Operand->getType(); 9635 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9636 ResType = ResAtomicType->getValueType(); 9637 9638 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 9639 QualType PointeeTy = ResType->getPointeeType(); 9640 return S.RequireCompleteSizedType( 9641 Loc, PointeeTy, 9642 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 9643 Operand->getSourceRange()); 9644 } 9645 9646 /// Check the validity of an arithmetic pointer operand. 9647 /// 9648 /// If the operand has pointer type, this code will check for pointer types 9649 /// which are invalid in arithmetic operations. These will be diagnosed 9650 /// appropriately, including whether or not the use is supported as an 9651 /// extension. 9652 /// 9653 /// \returns True when the operand is valid to use (even if as an extension). 9654 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 9655 Expr *Operand) { 9656 QualType ResType = Operand->getType(); 9657 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9658 ResType = ResAtomicType->getValueType(); 9659 9660 if (!ResType->isAnyPointerType()) return true; 9661 9662 QualType PointeeTy = ResType->getPointeeType(); 9663 if (PointeeTy->isVoidType()) { 9664 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 9665 return !S.getLangOpts().CPlusPlus; 9666 } 9667 if (PointeeTy->isFunctionType()) { 9668 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 9669 return !S.getLangOpts().CPlusPlus; 9670 } 9671 9672 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 9673 9674 return true; 9675 } 9676 9677 /// Check the validity of a binary arithmetic operation w.r.t. pointer 9678 /// operands. 9679 /// 9680 /// This routine will diagnose any invalid arithmetic on pointer operands much 9681 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9682 /// for emitting a single diagnostic even for operations where both LHS and RHS 9683 /// are (potentially problematic) pointers. 9684 /// 9685 /// \returns True when the operand is valid to use (even if as an extension). 9686 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9687 Expr *LHSExpr, Expr *RHSExpr) { 9688 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9689 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9690 if (!isLHSPointer && !isRHSPointer) return true; 9691 9692 QualType LHSPointeeTy, RHSPointeeTy; 9693 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9694 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9695 9696 // if both are pointers check if operation is valid wrt address spaces 9697 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9698 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>(); 9699 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>(); 9700 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9701 S.Diag(Loc, 9702 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9703 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9704 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9705 return false; 9706 } 9707 } 9708 9709 // Check for arithmetic on pointers to incomplete types. 9710 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9711 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9712 if (isLHSVoidPtr || isRHSVoidPtr) { 9713 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9714 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9715 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9716 9717 return !S.getLangOpts().CPlusPlus; 9718 } 9719 9720 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9721 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9722 if (isLHSFuncPtr || isRHSFuncPtr) { 9723 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9724 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9725 RHSExpr); 9726 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9727 9728 return !S.getLangOpts().CPlusPlus; 9729 } 9730 9731 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9732 return false; 9733 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9734 return false; 9735 9736 return true; 9737 } 9738 9739 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9740 /// literal. 9741 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9742 Expr *LHSExpr, Expr *RHSExpr) { 9743 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9744 Expr* IndexExpr = RHSExpr; 9745 if (!StrExpr) { 9746 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9747 IndexExpr = LHSExpr; 9748 } 9749 9750 bool IsStringPlusInt = StrExpr && 9751 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9752 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9753 return; 9754 9755 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9756 Self.Diag(OpLoc, diag::warn_string_plus_int) 9757 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9758 9759 // Only print a fixit for "str" + int, not for int + "str". 9760 if (IndexExpr == RHSExpr) { 9761 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9762 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9763 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9764 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9765 << FixItHint::CreateInsertion(EndLoc, "]"); 9766 } else 9767 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9768 } 9769 9770 /// Emit a warning when adding a char literal to a string. 9771 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9772 Expr *LHSExpr, Expr *RHSExpr) { 9773 const Expr *StringRefExpr = LHSExpr; 9774 const CharacterLiteral *CharExpr = 9775 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9776 9777 if (!CharExpr) { 9778 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9779 StringRefExpr = RHSExpr; 9780 } 9781 9782 if (!CharExpr || !StringRefExpr) 9783 return; 9784 9785 const QualType StringType = StringRefExpr->getType(); 9786 9787 // Return if not a PointerType. 9788 if (!StringType->isAnyPointerType()) 9789 return; 9790 9791 // Return if not a CharacterType. 9792 if (!StringType->getPointeeType()->isAnyCharacterType()) 9793 return; 9794 9795 ASTContext &Ctx = Self.getASTContext(); 9796 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9797 9798 const QualType CharType = CharExpr->getType(); 9799 if (!CharType->isAnyCharacterType() && 9800 CharType->isIntegerType() && 9801 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9802 Self.Diag(OpLoc, diag::warn_string_plus_char) 9803 << DiagRange << Ctx.CharTy; 9804 } else { 9805 Self.Diag(OpLoc, diag::warn_string_plus_char) 9806 << DiagRange << CharExpr->getType(); 9807 } 9808 9809 // Only print a fixit for str + char, not for char + str. 9810 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9811 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9812 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9813 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9814 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9815 << FixItHint::CreateInsertion(EndLoc, "]"); 9816 } else { 9817 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9818 } 9819 } 9820 9821 /// Emit error when two pointers are incompatible. 9822 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9823 Expr *LHSExpr, Expr *RHSExpr) { 9824 assert(LHSExpr->getType()->isAnyPointerType()); 9825 assert(RHSExpr->getType()->isAnyPointerType()); 9826 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9827 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9828 << RHSExpr->getSourceRange(); 9829 } 9830 9831 // C99 6.5.6 9832 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9833 SourceLocation Loc, BinaryOperatorKind Opc, 9834 QualType* CompLHSTy) { 9835 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9836 9837 if (LHS.get()->getType()->isVectorType() || 9838 RHS.get()->getType()->isVectorType()) { 9839 QualType compType = CheckVectorOperands( 9840 LHS, RHS, Loc, CompLHSTy, 9841 /*AllowBothBool*/getLangOpts().AltiVec, 9842 /*AllowBoolConversions*/getLangOpts().ZVector); 9843 if (CompLHSTy) *CompLHSTy = compType; 9844 return compType; 9845 } 9846 9847 QualType compType = UsualArithmeticConversions( 9848 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9849 if (LHS.isInvalid() || RHS.isInvalid()) 9850 return QualType(); 9851 9852 // Diagnose "string literal" '+' int and string '+' "char literal". 9853 if (Opc == BO_Add) { 9854 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9855 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9856 } 9857 9858 // handle the common case first (both operands are arithmetic). 9859 if (!compType.isNull() && compType->isArithmeticType()) { 9860 if (CompLHSTy) *CompLHSTy = compType; 9861 return compType; 9862 } 9863 9864 // Type-checking. Ultimately the pointer's going to be in PExp; 9865 // note that we bias towards the LHS being the pointer. 9866 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9867 9868 bool isObjCPointer; 9869 if (PExp->getType()->isPointerType()) { 9870 isObjCPointer = false; 9871 } else if (PExp->getType()->isObjCObjectPointerType()) { 9872 isObjCPointer = true; 9873 } else { 9874 std::swap(PExp, IExp); 9875 if (PExp->getType()->isPointerType()) { 9876 isObjCPointer = false; 9877 } else if (PExp->getType()->isObjCObjectPointerType()) { 9878 isObjCPointer = true; 9879 } else { 9880 return InvalidOperands(Loc, LHS, RHS); 9881 } 9882 } 9883 assert(PExp->getType()->isAnyPointerType()); 9884 9885 if (!IExp->getType()->isIntegerType()) 9886 return InvalidOperands(Loc, LHS, RHS); 9887 9888 // Adding to a null pointer results in undefined behavior. 9889 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9890 Context, Expr::NPC_ValueDependentIsNotNull)) { 9891 // In C++ adding zero to a null pointer is defined. 9892 Expr::EvalResult KnownVal; 9893 if (!getLangOpts().CPlusPlus || 9894 (!IExp->isValueDependent() && 9895 (!IExp->EvaluateAsInt(KnownVal, Context) || 9896 KnownVal.Val.getInt() != 0))) { 9897 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9898 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9899 Context, BO_Add, PExp, IExp); 9900 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9901 } 9902 } 9903 9904 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9905 return QualType(); 9906 9907 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9908 return QualType(); 9909 9910 // Check array bounds for pointer arithemtic 9911 CheckArrayAccess(PExp, IExp); 9912 9913 if (CompLHSTy) { 9914 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9915 if (LHSTy.isNull()) { 9916 LHSTy = LHS.get()->getType(); 9917 if (LHSTy->isPromotableIntegerType()) 9918 LHSTy = Context.getPromotedIntegerType(LHSTy); 9919 } 9920 *CompLHSTy = LHSTy; 9921 } 9922 9923 return PExp->getType(); 9924 } 9925 9926 // C99 6.5.6 9927 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9928 SourceLocation Loc, 9929 QualType* CompLHSTy) { 9930 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 9931 9932 if (LHS.get()->getType()->isVectorType() || 9933 RHS.get()->getType()->isVectorType()) { 9934 QualType compType = CheckVectorOperands( 9935 LHS, RHS, Loc, CompLHSTy, 9936 /*AllowBothBool*/getLangOpts().AltiVec, 9937 /*AllowBoolConversions*/getLangOpts().ZVector); 9938 if (CompLHSTy) *CompLHSTy = compType; 9939 return compType; 9940 } 9941 9942 QualType compType = UsualArithmeticConversions( 9943 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 9944 if (LHS.isInvalid() || RHS.isInvalid()) 9945 return QualType(); 9946 9947 // Enforce type constraints: C99 6.5.6p3. 9948 9949 // Handle the common case first (both operands are arithmetic). 9950 if (!compType.isNull() && compType->isArithmeticType()) { 9951 if (CompLHSTy) *CompLHSTy = compType; 9952 return compType; 9953 } 9954 9955 // Either ptr - int or ptr - ptr. 9956 if (LHS.get()->getType()->isAnyPointerType()) { 9957 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9958 9959 // Diagnose bad cases where we step over interface counts. 9960 if (LHS.get()->getType()->isObjCObjectPointerType() && 9961 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9962 return QualType(); 9963 9964 // The result type of a pointer-int computation is the pointer type. 9965 if (RHS.get()->getType()->isIntegerType()) { 9966 // Subtracting from a null pointer should produce a warning. 9967 // The last argument to the diagnose call says this doesn't match the 9968 // GNU int-to-pointer idiom. 9969 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9970 Expr::NPC_ValueDependentIsNotNull)) { 9971 // In C++ adding zero to a null pointer is defined. 9972 Expr::EvalResult KnownVal; 9973 if (!getLangOpts().CPlusPlus || 9974 (!RHS.get()->isValueDependent() && 9975 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9976 KnownVal.Val.getInt() != 0))) { 9977 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9978 } 9979 } 9980 9981 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9982 return QualType(); 9983 9984 // Check array bounds for pointer arithemtic 9985 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9986 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9987 9988 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9989 return LHS.get()->getType(); 9990 } 9991 9992 // Handle pointer-pointer subtractions. 9993 if (const PointerType *RHSPTy 9994 = RHS.get()->getType()->getAs<PointerType>()) { 9995 QualType rpointee = RHSPTy->getPointeeType(); 9996 9997 if (getLangOpts().CPlusPlus) { 9998 // Pointee types must be the same: C++ [expr.add] 9999 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10000 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10001 } 10002 } else { 10003 // Pointee types must be compatible C99 6.5.6p3 10004 if (!Context.typesAreCompatible( 10005 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10006 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10007 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10008 return QualType(); 10009 } 10010 } 10011 10012 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10013 LHS.get(), RHS.get())) 10014 return QualType(); 10015 10016 // FIXME: Add warnings for nullptr - ptr. 10017 10018 // The pointee type may have zero size. As an extension, a structure or 10019 // union may have zero size or an array may have zero length. In this 10020 // case subtraction does not make sense. 10021 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10022 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10023 if (ElementSize.isZero()) { 10024 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10025 << rpointee.getUnqualifiedType() 10026 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10027 } 10028 } 10029 10030 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10031 return Context.getPointerDiffType(); 10032 } 10033 } 10034 10035 return InvalidOperands(Loc, LHS, RHS); 10036 } 10037 10038 static bool isScopedEnumerationType(QualType T) { 10039 if (const EnumType *ET = T->getAs<EnumType>()) 10040 return ET->getDecl()->isScoped(); 10041 return false; 10042 } 10043 10044 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10045 SourceLocation Loc, BinaryOperatorKind Opc, 10046 QualType LHSType) { 10047 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10048 // so skip remaining warnings as we don't want to modify values within Sema. 10049 if (S.getLangOpts().OpenCL) 10050 return; 10051 10052 // Check right/shifter operand 10053 Expr::EvalResult RHSResult; 10054 if (RHS.get()->isValueDependent() || 10055 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10056 return; 10057 llvm::APSInt Right = RHSResult.Val.getInt(); 10058 10059 if (Right.isNegative()) { 10060 S.DiagRuntimeBehavior(Loc, RHS.get(), 10061 S.PDiag(diag::warn_shift_negative) 10062 << RHS.get()->getSourceRange()); 10063 return; 10064 } 10065 llvm::APInt LeftBits(Right.getBitWidth(), 10066 S.Context.getTypeSize(LHS.get()->getType())); 10067 if (Right.uge(LeftBits)) { 10068 S.DiagRuntimeBehavior(Loc, RHS.get(), 10069 S.PDiag(diag::warn_shift_gt_typewidth) 10070 << RHS.get()->getSourceRange()); 10071 return; 10072 } 10073 if (Opc != BO_Shl) 10074 return; 10075 10076 // When left shifting an ICE which is signed, we can check for overflow which 10077 // according to C++ standards prior to C++2a has undefined behavior 10078 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10079 // more than the maximum value representable in the result type, so never 10080 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10081 // expression is still probably a bug.) 10082 Expr::EvalResult LHSResult; 10083 if (LHS.get()->isValueDependent() || 10084 LHSType->hasUnsignedIntegerRepresentation() || 10085 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10086 return; 10087 llvm::APSInt Left = LHSResult.Val.getInt(); 10088 10089 // If LHS does not have a signed type and non-negative value 10090 // then, the behavior is undefined before C++2a. Warn about it. 10091 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10092 !S.getLangOpts().CPlusPlus2a) { 10093 S.DiagRuntimeBehavior(Loc, LHS.get(), 10094 S.PDiag(diag::warn_shift_lhs_negative) 10095 << LHS.get()->getSourceRange()); 10096 return; 10097 } 10098 10099 llvm::APInt ResultBits = 10100 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10101 if (LeftBits.uge(ResultBits)) 10102 return; 10103 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10104 Result = Result.shl(Right); 10105 10106 // Print the bit representation of the signed integer as an unsigned 10107 // hexadecimal number. 10108 SmallString<40> HexResult; 10109 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10110 10111 // If we are only missing a sign bit, this is less likely to result in actual 10112 // bugs -- if the result is cast back to an unsigned type, it will have the 10113 // expected value. Thus we place this behind a different warning that can be 10114 // turned off separately if needed. 10115 if (LeftBits == ResultBits - 1) { 10116 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10117 << HexResult << LHSType 10118 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10119 return; 10120 } 10121 10122 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10123 << HexResult.str() << Result.getMinSignedBits() << LHSType 10124 << Left.getBitWidth() << LHS.get()->getSourceRange() 10125 << RHS.get()->getSourceRange(); 10126 } 10127 10128 /// Return the resulting type when a vector is shifted 10129 /// by a scalar or vector shift amount. 10130 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10131 SourceLocation Loc, bool IsCompAssign) { 10132 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10133 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10134 !LHS.get()->getType()->isVectorType()) { 10135 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10136 << RHS.get()->getType() << LHS.get()->getType() 10137 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10138 return QualType(); 10139 } 10140 10141 if (!IsCompAssign) { 10142 LHS = S.UsualUnaryConversions(LHS.get()); 10143 if (LHS.isInvalid()) return QualType(); 10144 } 10145 10146 RHS = S.UsualUnaryConversions(RHS.get()); 10147 if (RHS.isInvalid()) return QualType(); 10148 10149 QualType LHSType = LHS.get()->getType(); 10150 // Note that LHS might be a scalar because the routine calls not only in 10151 // OpenCL case. 10152 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10153 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10154 10155 // Note that RHS might not be a vector. 10156 QualType RHSType = RHS.get()->getType(); 10157 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10158 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10159 10160 // The operands need to be integers. 10161 if (!LHSEleType->isIntegerType()) { 10162 S.Diag(Loc, diag::err_typecheck_expect_int) 10163 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10164 return QualType(); 10165 } 10166 10167 if (!RHSEleType->isIntegerType()) { 10168 S.Diag(Loc, diag::err_typecheck_expect_int) 10169 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10170 return QualType(); 10171 } 10172 10173 if (!LHSVecTy) { 10174 assert(RHSVecTy); 10175 if (IsCompAssign) 10176 return RHSType; 10177 if (LHSEleType != RHSEleType) { 10178 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10179 LHSEleType = RHSEleType; 10180 } 10181 QualType VecTy = 10182 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10183 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10184 LHSType = VecTy; 10185 } else if (RHSVecTy) { 10186 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10187 // are applied component-wise. So if RHS is a vector, then ensure 10188 // that the number of elements is the same as LHS... 10189 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10190 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10191 << LHS.get()->getType() << RHS.get()->getType() 10192 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10193 return QualType(); 10194 } 10195 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10196 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10197 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10198 if (LHSBT != RHSBT && 10199 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10200 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10201 << LHS.get()->getType() << RHS.get()->getType() 10202 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10203 } 10204 } 10205 } else { 10206 // ...else expand RHS to match the number of elements in LHS. 10207 QualType VecTy = 10208 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10209 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10210 } 10211 10212 return LHSType; 10213 } 10214 10215 // C99 6.5.7 10216 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10217 SourceLocation Loc, BinaryOperatorKind Opc, 10218 bool IsCompAssign) { 10219 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10220 10221 // Vector shifts promote their scalar inputs to vector type. 10222 if (LHS.get()->getType()->isVectorType() || 10223 RHS.get()->getType()->isVectorType()) { 10224 if (LangOpts.ZVector) { 10225 // The shift operators for the z vector extensions work basically 10226 // like general shifts, except that neither the LHS nor the RHS is 10227 // allowed to be a "vector bool". 10228 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 10229 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 10230 return InvalidOperands(Loc, LHS, RHS); 10231 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 10232 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10233 return InvalidOperands(Loc, LHS, RHS); 10234 } 10235 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 10236 } 10237 10238 // Shifts don't perform usual arithmetic conversions, they just do integer 10239 // promotions on each operand. C99 6.5.7p3 10240 10241 // For the LHS, do usual unary conversions, but then reset them away 10242 // if this is a compound assignment. 10243 ExprResult OldLHS = LHS; 10244 LHS = UsualUnaryConversions(LHS.get()); 10245 if (LHS.isInvalid()) 10246 return QualType(); 10247 QualType LHSType = LHS.get()->getType(); 10248 if (IsCompAssign) LHS = OldLHS; 10249 10250 // The RHS is simpler. 10251 RHS = UsualUnaryConversions(RHS.get()); 10252 if (RHS.isInvalid()) 10253 return QualType(); 10254 QualType RHSType = RHS.get()->getType(); 10255 10256 // C99 6.5.7p2: Each of the operands shall have integer type. 10257 if (!LHSType->hasIntegerRepresentation() || 10258 !RHSType->hasIntegerRepresentation()) 10259 return InvalidOperands(Loc, LHS, RHS); 10260 10261 // C++0x: Don't allow scoped enums. FIXME: Use something better than 10262 // hasIntegerRepresentation() above instead of this. 10263 if (isScopedEnumerationType(LHSType) || 10264 isScopedEnumerationType(RHSType)) { 10265 return InvalidOperands(Loc, LHS, RHS); 10266 } 10267 // Sanity-check shift operands 10268 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 10269 10270 // "The type of the result is that of the promoted left operand." 10271 return LHSType; 10272 } 10273 10274 /// Diagnose bad pointer comparisons. 10275 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 10276 ExprResult &LHS, ExprResult &RHS, 10277 bool IsError) { 10278 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 10279 : diag::ext_typecheck_comparison_of_distinct_pointers) 10280 << LHS.get()->getType() << RHS.get()->getType() 10281 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10282 } 10283 10284 /// Returns false if the pointers are converted to a composite type, 10285 /// true otherwise. 10286 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 10287 ExprResult &LHS, ExprResult &RHS) { 10288 // C++ [expr.rel]p2: 10289 // [...] Pointer conversions (4.10) and qualification 10290 // conversions (4.4) are performed on pointer operands (or on 10291 // a pointer operand and a null pointer constant) to bring 10292 // them to their composite pointer type. [...] 10293 // 10294 // C++ [expr.eq]p1 uses the same notion for (in)equality 10295 // comparisons of pointers. 10296 10297 QualType LHSType = LHS.get()->getType(); 10298 QualType RHSType = RHS.get()->getType(); 10299 assert(LHSType->isPointerType() || RHSType->isPointerType() || 10300 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 10301 10302 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 10303 if (T.isNull()) { 10304 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 10305 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 10306 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 10307 else 10308 S.InvalidOperands(Loc, LHS, RHS); 10309 return true; 10310 } 10311 10312 return false; 10313 } 10314 10315 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 10316 ExprResult &LHS, 10317 ExprResult &RHS, 10318 bool IsError) { 10319 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 10320 : diag::ext_typecheck_comparison_of_fptr_to_void) 10321 << LHS.get()->getType() << RHS.get()->getType() 10322 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10323 } 10324 10325 static bool isObjCObjectLiteral(ExprResult &E) { 10326 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 10327 case Stmt::ObjCArrayLiteralClass: 10328 case Stmt::ObjCDictionaryLiteralClass: 10329 case Stmt::ObjCStringLiteralClass: 10330 case Stmt::ObjCBoxedExprClass: 10331 return true; 10332 default: 10333 // Note that ObjCBoolLiteral is NOT an object literal! 10334 return false; 10335 } 10336 } 10337 10338 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 10339 const ObjCObjectPointerType *Type = 10340 LHS->getType()->getAs<ObjCObjectPointerType>(); 10341 10342 // If this is not actually an Objective-C object, bail out. 10343 if (!Type) 10344 return false; 10345 10346 // Get the LHS object's interface type. 10347 QualType InterfaceType = Type->getPointeeType(); 10348 10349 // If the RHS isn't an Objective-C object, bail out. 10350 if (!RHS->getType()->isObjCObjectPointerType()) 10351 return false; 10352 10353 // Try to find the -isEqual: method. 10354 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 10355 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 10356 InterfaceType, 10357 /*IsInstance=*/true); 10358 if (!Method) { 10359 if (Type->isObjCIdType()) { 10360 // For 'id', just check the global pool. 10361 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 10362 /*receiverId=*/true); 10363 } else { 10364 // Check protocols. 10365 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 10366 /*IsInstance=*/true); 10367 } 10368 } 10369 10370 if (!Method) 10371 return false; 10372 10373 QualType T = Method->parameters()[0]->getType(); 10374 if (!T->isObjCObjectPointerType()) 10375 return false; 10376 10377 QualType R = Method->getReturnType(); 10378 if (!R->isScalarType()) 10379 return false; 10380 10381 return true; 10382 } 10383 10384 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 10385 FromE = FromE->IgnoreParenImpCasts(); 10386 switch (FromE->getStmtClass()) { 10387 default: 10388 break; 10389 case Stmt::ObjCStringLiteralClass: 10390 // "string literal" 10391 return LK_String; 10392 case Stmt::ObjCArrayLiteralClass: 10393 // "array literal" 10394 return LK_Array; 10395 case Stmt::ObjCDictionaryLiteralClass: 10396 // "dictionary literal" 10397 return LK_Dictionary; 10398 case Stmt::BlockExprClass: 10399 return LK_Block; 10400 case Stmt::ObjCBoxedExprClass: { 10401 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 10402 switch (Inner->getStmtClass()) { 10403 case Stmt::IntegerLiteralClass: 10404 case Stmt::FloatingLiteralClass: 10405 case Stmt::CharacterLiteralClass: 10406 case Stmt::ObjCBoolLiteralExprClass: 10407 case Stmt::CXXBoolLiteralExprClass: 10408 // "numeric literal" 10409 return LK_Numeric; 10410 case Stmt::ImplicitCastExprClass: { 10411 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 10412 // Boolean literals can be represented by implicit casts. 10413 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 10414 return LK_Numeric; 10415 break; 10416 } 10417 default: 10418 break; 10419 } 10420 return LK_Boxed; 10421 } 10422 } 10423 return LK_None; 10424 } 10425 10426 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 10427 ExprResult &LHS, ExprResult &RHS, 10428 BinaryOperator::Opcode Opc){ 10429 Expr *Literal; 10430 Expr *Other; 10431 if (isObjCObjectLiteral(LHS)) { 10432 Literal = LHS.get(); 10433 Other = RHS.get(); 10434 } else { 10435 Literal = RHS.get(); 10436 Other = LHS.get(); 10437 } 10438 10439 // Don't warn on comparisons against nil. 10440 Other = Other->IgnoreParenCasts(); 10441 if (Other->isNullPointerConstant(S.getASTContext(), 10442 Expr::NPC_ValueDependentIsNotNull)) 10443 return; 10444 10445 // This should be kept in sync with warn_objc_literal_comparison. 10446 // LK_String should always be after the other literals, since it has its own 10447 // warning flag. 10448 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 10449 assert(LiteralKind != Sema::LK_Block); 10450 if (LiteralKind == Sema::LK_None) { 10451 llvm_unreachable("Unknown Objective-C object literal kind"); 10452 } 10453 10454 if (LiteralKind == Sema::LK_String) 10455 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 10456 << Literal->getSourceRange(); 10457 else 10458 S.Diag(Loc, diag::warn_objc_literal_comparison) 10459 << LiteralKind << Literal->getSourceRange(); 10460 10461 if (BinaryOperator::isEqualityOp(Opc) && 10462 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 10463 SourceLocation Start = LHS.get()->getBeginLoc(); 10464 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 10465 CharSourceRange OpRange = 10466 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 10467 10468 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 10469 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 10470 << FixItHint::CreateReplacement(OpRange, " isEqual:") 10471 << FixItHint::CreateInsertion(End, "]"); 10472 } 10473 } 10474 10475 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 10476 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 10477 ExprResult &RHS, SourceLocation Loc, 10478 BinaryOperatorKind Opc) { 10479 // Check that left hand side is !something. 10480 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 10481 if (!UO || UO->getOpcode() != UO_LNot) return; 10482 10483 // Only check if the right hand side is non-bool arithmetic type. 10484 if (RHS.get()->isKnownToHaveBooleanValue()) return; 10485 10486 // Make sure that the something in !something is not bool. 10487 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 10488 if (SubExpr->isKnownToHaveBooleanValue()) return; 10489 10490 // Emit warning. 10491 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 10492 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 10493 << Loc << IsBitwiseOp; 10494 10495 // First note suggest !(x < y) 10496 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 10497 SourceLocation FirstClose = RHS.get()->getEndLoc(); 10498 FirstClose = S.getLocForEndOfToken(FirstClose); 10499 if (FirstClose.isInvalid()) 10500 FirstOpen = SourceLocation(); 10501 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 10502 << IsBitwiseOp 10503 << FixItHint::CreateInsertion(FirstOpen, "(") 10504 << FixItHint::CreateInsertion(FirstClose, ")"); 10505 10506 // Second note suggests (!x) < y 10507 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 10508 SourceLocation SecondClose = LHS.get()->getEndLoc(); 10509 SecondClose = S.getLocForEndOfToken(SecondClose); 10510 if (SecondClose.isInvalid()) 10511 SecondOpen = SourceLocation(); 10512 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 10513 << FixItHint::CreateInsertion(SecondOpen, "(") 10514 << FixItHint::CreateInsertion(SecondClose, ")"); 10515 } 10516 10517 // Returns true if E refers to a non-weak array. 10518 static bool checkForArray(const Expr *E) { 10519 const ValueDecl *D = nullptr; 10520 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 10521 D = DR->getDecl(); 10522 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 10523 if (Mem->isImplicitAccess()) 10524 D = Mem->getMemberDecl(); 10525 } 10526 if (!D) 10527 return false; 10528 return D->getType()->isArrayType() && !D->isWeak(); 10529 } 10530 10531 /// Diagnose some forms of syntactically-obvious tautological comparison. 10532 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 10533 Expr *LHS, Expr *RHS, 10534 BinaryOperatorKind Opc) { 10535 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 10536 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 10537 10538 QualType LHSType = LHS->getType(); 10539 QualType RHSType = RHS->getType(); 10540 if (LHSType->hasFloatingRepresentation() || 10541 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 10542 S.inTemplateInstantiation()) 10543 return; 10544 10545 // Comparisons between two array types are ill-formed for operator<=>, so 10546 // we shouldn't emit any additional warnings about it. 10547 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 10548 return; 10549 10550 // For non-floating point types, check for self-comparisons of the form 10551 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10552 // often indicate logic errors in the program. 10553 // 10554 // NOTE: Don't warn about comparison expressions resulting from macro 10555 // expansion. Also don't warn about comparisons which are only self 10556 // comparisons within a template instantiation. The warnings should catch 10557 // obvious cases in the definition of the template anyways. The idea is to 10558 // warn when the typed comparison operator will always evaluate to the same 10559 // result. 10560 10561 // Used for indexing into %select in warn_comparison_always 10562 enum { 10563 AlwaysConstant, 10564 AlwaysTrue, 10565 AlwaysFalse, 10566 AlwaysEqual, // std::strong_ordering::equal from operator<=> 10567 }; 10568 10569 // C++2a [depr.array.comp]: 10570 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 10571 // operands of array type are deprecated. 10572 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() && 10573 RHSStripped->getType()->isArrayType()) { 10574 S.Diag(Loc, diag::warn_depr_array_comparison) 10575 << LHS->getSourceRange() << RHS->getSourceRange() 10576 << LHSStripped->getType() << RHSStripped->getType(); 10577 // Carry on to produce the tautological comparison warning, if this 10578 // expression is potentially-evaluated, we can resolve the array to a 10579 // non-weak declaration, and so on. 10580 } 10581 10582 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 10583 if (Expr::isSameComparisonOperand(LHS, RHS)) { 10584 unsigned Result; 10585 switch (Opc) { 10586 case BO_EQ: 10587 case BO_LE: 10588 case BO_GE: 10589 Result = AlwaysTrue; 10590 break; 10591 case BO_NE: 10592 case BO_LT: 10593 case BO_GT: 10594 Result = AlwaysFalse; 10595 break; 10596 case BO_Cmp: 10597 Result = AlwaysEqual; 10598 break; 10599 default: 10600 Result = AlwaysConstant; 10601 break; 10602 } 10603 S.DiagRuntimeBehavior(Loc, nullptr, 10604 S.PDiag(diag::warn_comparison_always) 10605 << 0 /*self-comparison*/ 10606 << Result); 10607 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 10608 // What is it always going to evaluate to? 10609 unsigned Result; 10610 switch (Opc) { 10611 case BO_EQ: // e.g. array1 == array2 10612 Result = AlwaysFalse; 10613 break; 10614 case BO_NE: // e.g. array1 != array2 10615 Result = AlwaysTrue; 10616 break; 10617 default: // e.g. array1 <= array2 10618 // The best we can say is 'a constant' 10619 Result = AlwaysConstant; 10620 break; 10621 } 10622 S.DiagRuntimeBehavior(Loc, nullptr, 10623 S.PDiag(diag::warn_comparison_always) 10624 << 1 /*array comparison*/ 10625 << Result); 10626 } 10627 } 10628 10629 if (isa<CastExpr>(LHSStripped)) 10630 LHSStripped = LHSStripped->IgnoreParenCasts(); 10631 if (isa<CastExpr>(RHSStripped)) 10632 RHSStripped = RHSStripped->IgnoreParenCasts(); 10633 10634 // Warn about comparisons against a string constant (unless the other 10635 // operand is null); the user probably wants string comparison function. 10636 Expr *LiteralString = nullptr; 10637 Expr *LiteralStringStripped = nullptr; 10638 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 10639 !RHSStripped->isNullPointerConstant(S.Context, 10640 Expr::NPC_ValueDependentIsNull)) { 10641 LiteralString = LHS; 10642 LiteralStringStripped = LHSStripped; 10643 } else if ((isa<StringLiteral>(RHSStripped) || 10644 isa<ObjCEncodeExpr>(RHSStripped)) && 10645 !LHSStripped->isNullPointerConstant(S.Context, 10646 Expr::NPC_ValueDependentIsNull)) { 10647 LiteralString = RHS; 10648 LiteralStringStripped = RHSStripped; 10649 } 10650 10651 if (LiteralString) { 10652 S.DiagRuntimeBehavior(Loc, nullptr, 10653 S.PDiag(diag::warn_stringcompare) 10654 << isa<ObjCEncodeExpr>(LiteralStringStripped) 10655 << LiteralString->getSourceRange()); 10656 } 10657 } 10658 10659 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 10660 switch (CK) { 10661 default: { 10662 #ifndef NDEBUG 10663 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 10664 << "\n"; 10665 #endif 10666 llvm_unreachable("unhandled cast kind"); 10667 } 10668 case CK_UserDefinedConversion: 10669 return ICK_Identity; 10670 case CK_LValueToRValue: 10671 return ICK_Lvalue_To_Rvalue; 10672 case CK_ArrayToPointerDecay: 10673 return ICK_Array_To_Pointer; 10674 case CK_FunctionToPointerDecay: 10675 return ICK_Function_To_Pointer; 10676 case CK_IntegralCast: 10677 return ICK_Integral_Conversion; 10678 case CK_FloatingCast: 10679 return ICK_Floating_Conversion; 10680 case CK_IntegralToFloating: 10681 case CK_FloatingToIntegral: 10682 return ICK_Floating_Integral; 10683 case CK_IntegralComplexCast: 10684 case CK_FloatingComplexCast: 10685 case CK_FloatingComplexToIntegralComplex: 10686 case CK_IntegralComplexToFloatingComplex: 10687 return ICK_Complex_Conversion; 10688 case CK_FloatingComplexToReal: 10689 case CK_FloatingRealToComplex: 10690 case CK_IntegralComplexToReal: 10691 case CK_IntegralRealToComplex: 10692 return ICK_Complex_Real; 10693 } 10694 } 10695 10696 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10697 QualType FromType, 10698 SourceLocation Loc) { 10699 // Check for a narrowing implicit conversion. 10700 StandardConversionSequence SCS; 10701 SCS.setAsIdentityConversion(); 10702 SCS.setToType(0, FromType); 10703 SCS.setToType(1, ToType); 10704 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10705 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10706 10707 APValue PreNarrowingValue; 10708 QualType PreNarrowingType; 10709 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10710 PreNarrowingType, 10711 /*IgnoreFloatToIntegralConversion*/ true)) { 10712 case NK_Dependent_Narrowing: 10713 // Implicit conversion to a narrower type, but the expression is 10714 // value-dependent so we can't tell whether it's actually narrowing. 10715 case NK_Not_Narrowing: 10716 return false; 10717 10718 case NK_Constant_Narrowing: 10719 // Implicit conversion to a narrower type, and the value is not a constant 10720 // expression. 10721 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10722 << /*Constant*/ 1 10723 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10724 return true; 10725 10726 case NK_Variable_Narrowing: 10727 // Implicit conversion to a narrower type, and the value is not a constant 10728 // expression. 10729 case NK_Type_Narrowing: 10730 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10731 << /*Constant*/ 0 << FromType << ToType; 10732 // TODO: It's not a constant expression, but what if the user intended it 10733 // to be? Can we produce notes to help them figure out why it isn't? 10734 return true; 10735 } 10736 llvm_unreachable("unhandled case in switch"); 10737 } 10738 10739 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10740 ExprResult &LHS, 10741 ExprResult &RHS, 10742 SourceLocation Loc) { 10743 QualType LHSType = LHS.get()->getType(); 10744 QualType RHSType = RHS.get()->getType(); 10745 // Dig out the original argument type and expression before implicit casts 10746 // were applied. These are the types/expressions we need to check the 10747 // [expr.spaceship] requirements against. 10748 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10749 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10750 QualType LHSStrippedType = LHSStripped.get()->getType(); 10751 QualType RHSStrippedType = RHSStripped.get()->getType(); 10752 10753 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10754 // other is not, the program is ill-formed. 10755 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10756 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10757 return QualType(); 10758 } 10759 10760 // FIXME: Consider combining this with checkEnumArithmeticConversions. 10761 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10762 RHSStrippedType->isEnumeralType(); 10763 if (NumEnumArgs == 1) { 10764 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10765 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10766 if (OtherTy->hasFloatingRepresentation()) { 10767 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10768 return QualType(); 10769 } 10770 } 10771 if (NumEnumArgs == 2) { 10772 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10773 // type E, the operator yields the result of converting the operands 10774 // to the underlying type of E and applying <=> to the converted operands. 10775 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10776 S.InvalidOperands(Loc, LHS, RHS); 10777 return QualType(); 10778 } 10779 QualType IntType = 10780 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 10781 assert(IntType->isArithmeticType()); 10782 10783 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10784 // promote the boolean type, and all other promotable integer types, to 10785 // avoid this. 10786 if (IntType->isPromotableIntegerType()) 10787 IntType = S.Context.getPromotedIntegerType(IntType); 10788 10789 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10790 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10791 LHSType = RHSType = IntType; 10792 } 10793 10794 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10795 // usual arithmetic conversions are applied to the operands. 10796 QualType Type = 10797 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10798 if (LHS.isInvalid() || RHS.isInvalid()) 10799 return QualType(); 10800 if (Type.isNull()) 10801 return S.InvalidOperands(Loc, LHS, RHS); 10802 10803 Optional<ComparisonCategoryType> CCT = 10804 getComparisonCategoryForBuiltinCmp(Type); 10805 if (!CCT) 10806 return S.InvalidOperands(Loc, LHS, RHS); 10807 10808 bool HasNarrowing = checkThreeWayNarrowingConversion( 10809 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10810 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10811 RHS.get()->getBeginLoc()); 10812 if (HasNarrowing) 10813 return QualType(); 10814 10815 assert(!Type.isNull() && "composite type for <=> has not been set"); 10816 10817 return S.CheckComparisonCategoryType( 10818 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 10819 } 10820 10821 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10822 ExprResult &RHS, 10823 SourceLocation Loc, 10824 BinaryOperatorKind Opc) { 10825 if (Opc == BO_Cmp) 10826 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10827 10828 // C99 6.5.8p3 / C99 6.5.9p4 10829 QualType Type = 10830 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 10831 if (LHS.isInvalid() || RHS.isInvalid()) 10832 return QualType(); 10833 if (Type.isNull()) 10834 return S.InvalidOperands(Loc, LHS, RHS); 10835 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10836 10837 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10838 return S.InvalidOperands(Loc, LHS, RHS); 10839 10840 // Check for comparisons of floating point operands using != and ==. 10841 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10842 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10843 10844 // The result of comparisons is 'bool' in C++, 'int' in C. 10845 return S.Context.getLogicalOperationType(); 10846 } 10847 10848 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 10849 if (!NullE.get()->getType()->isAnyPointerType()) 10850 return; 10851 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 10852 if (!E.get()->getType()->isAnyPointerType() && 10853 E.get()->isNullPointerConstant(Context, 10854 Expr::NPC_ValueDependentIsNotNull) == 10855 Expr::NPCK_ZeroExpression) { 10856 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 10857 if (CL->getValue() == 0) 10858 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10859 << NullValue 10860 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10861 NullValue ? "NULL" : "(void *)0"); 10862 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 10863 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 10864 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 10865 if (T == Context.CharTy) 10866 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 10867 << NullValue 10868 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 10869 NullValue ? "NULL" : "(void *)0"); 10870 } 10871 } 10872 } 10873 10874 // C99 6.5.8, C++ [expr.rel] 10875 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10876 SourceLocation Loc, 10877 BinaryOperatorKind Opc) { 10878 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10879 bool IsThreeWay = Opc == BO_Cmp; 10880 bool IsOrdered = IsRelational || IsThreeWay; 10881 auto IsAnyPointerType = [](ExprResult E) { 10882 QualType Ty = E.get()->getType(); 10883 return Ty->isPointerType() || Ty->isMemberPointerType(); 10884 }; 10885 10886 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10887 // type, array-to-pointer, ..., conversions are performed on both operands to 10888 // bring them to their composite type. 10889 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10890 // any type-related checks. 10891 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10892 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10893 if (LHS.isInvalid()) 10894 return QualType(); 10895 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10896 if (RHS.isInvalid()) 10897 return QualType(); 10898 } else { 10899 LHS = DefaultLvalueConversion(LHS.get()); 10900 if (LHS.isInvalid()) 10901 return QualType(); 10902 RHS = DefaultLvalueConversion(RHS.get()); 10903 if (RHS.isInvalid()) 10904 return QualType(); 10905 } 10906 10907 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 10908 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 10909 CheckPtrComparisonWithNullChar(LHS, RHS); 10910 CheckPtrComparisonWithNullChar(RHS, LHS); 10911 } 10912 10913 // Handle vector comparisons separately. 10914 if (LHS.get()->getType()->isVectorType() || 10915 RHS.get()->getType()->isVectorType()) 10916 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10917 10918 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10919 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10920 10921 QualType LHSType = LHS.get()->getType(); 10922 QualType RHSType = RHS.get()->getType(); 10923 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10924 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10925 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10926 10927 const Expr::NullPointerConstantKind LHSNullKind = 10928 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10929 const Expr::NullPointerConstantKind RHSNullKind = 10930 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10931 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10932 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10933 10934 auto computeResultTy = [&]() { 10935 if (Opc != BO_Cmp) 10936 return Context.getLogicalOperationType(); 10937 assert(getLangOpts().CPlusPlus); 10938 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10939 10940 QualType CompositeTy = LHS.get()->getType(); 10941 assert(!CompositeTy->isReferenceType()); 10942 10943 Optional<ComparisonCategoryType> CCT = 10944 getComparisonCategoryForBuiltinCmp(CompositeTy); 10945 if (!CCT) 10946 return InvalidOperands(Loc, LHS, RHS); 10947 10948 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 10949 // P0946R0: Comparisons between a null pointer constant and an object 10950 // pointer result in std::strong_equality, which is ill-formed under 10951 // P1959R0. 10952 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 10953 << (LHSIsNull ? LHS.get()->getSourceRange() 10954 : RHS.get()->getSourceRange()); 10955 return QualType(); 10956 } 10957 10958 return CheckComparisonCategoryType( 10959 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 10960 }; 10961 10962 if (!IsOrdered && LHSIsNull != RHSIsNull) { 10963 bool IsEquality = Opc == BO_EQ; 10964 if (RHSIsNull) 10965 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10966 RHS.get()->getSourceRange()); 10967 else 10968 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10969 LHS.get()->getSourceRange()); 10970 } 10971 10972 if ((LHSType->isIntegerType() && !LHSIsNull) || 10973 (RHSType->isIntegerType() && !RHSIsNull)) { 10974 // Skip normal pointer conversion checks in this case; we have better 10975 // diagnostics for this below. 10976 } else if (getLangOpts().CPlusPlus) { 10977 // Equality comparison of a function pointer to a void pointer is invalid, 10978 // but we allow it as an extension. 10979 // FIXME: If we really want to allow this, should it be part of composite 10980 // pointer type computation so it works in conditionals too? 10981 if (!IsOrdered && 10982 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10983 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10984 // This is a gcc extension compatibility comparison. 10985 // In a SFINAE context, we treat this as a hard error to maintain 10986 // conformance with the C++ standard. 10987 diagnoseFunctionPointerToVoidComparison( 10988 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10989 10990 if (isSFINAEContext()) 10991 return QualType(); 10992 10993 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10994 return computeResultTy(); 10995 } 10996 10997 // C++ [expr.eq]p2: 10998 // If at least one operand is a pointer [...] bring them to their 10999 // composite pointer type. 11000 // C++ [expr.spaceship]p6 11001 // If at least one of the operands is of pointer type, [...] bring them 11002 // to their composite pointer type. 11003 // C++ [expr.rel]p2: 11004 // If both operands are pointers, [...] bring them to their composite 11005 // pointer type. 11006 // For <=>, the only valid non-pointer types are arrays and functions, and 11007 // we already decayed those, so this is really the same as the relational 11008 // comparison rule. 11009 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11010 (IsOrdered ? 2 : 1) && 11011 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11012 RHSType->isObjCObjectPointerType()))) { 11013 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11014 return QualType(); 11015 return computeResultTy(); 11016 } 11017 } else if (LHSType->isPointerType() && 11018 RHSType->isPointerType()) { // C99 6.5.8p2 11019 // All of the following pointer-related warnings are GCC extensions, except 11020 // when handling null pointer constants. 11021 QualType LCanPointeeTy = 11022 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11023 QualType RCanPointeeTy = 11024 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11025 11026 // C99 6.5.9p2 and C99 6.5.8p2 11027 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11028 RCanPointeeTy.getUnqualifiedType())) { 11029 // Valid unless a relational comparison of function pointers 11030 if (IsRelational && LCanPointeeTy->isFunctionType()) { 11031 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11032 << LHSType << RHSType << LHS.get()->getSourceRange() 11033 << RHS.get()->getSourceRange(); 11034 } 11035 } else if (!IsRelational && 11036 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11037 // Valid unless comparison between non-null pointer and function pointer 11038 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11039 && !LHSIsNull && !RHSIsNull) 11040 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11041 /*isError*/false); 11042 } else { 11043 // Invalid 11044 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11045 } 11046 if (LCanPointeeTy != RCanPointeeTy) { 11047 // Treat NULL constant as a special case in OpenCL. 11048 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11049 const PointerType *LHSPtr = LHSType->castAs<PointerType>(); 11050 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) { 11051 Diag(Loc, 11052 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11053 << LHSType << RHSType << 0 /* comparison */ 11054 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11055 } 11056 } 11057 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11058 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11059 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11060 : CK_BitCast; 11061 if (LHSIsNull && !RHSIsNull) 11062 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11063 else 11064 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11065 } 11066 return computeResultTy(); 11067 } 11068 11069 if (getLangOpts().CPlusPlus) { 11070 // C++ [expr.eq]p4: 11071 // Two operands of type std::nullptr_t or one operand of type 11072 // std::nullptr_t and the other a null pointer constant compare equal. 11073 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11074 if (LHSType->isNullPtrType()) { 11075 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11076 return computeResultTy(); 11077 } 11078 if (RHSType->isNullPtrType()) { 11079 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11080 return computeResultTy(); 11081 } 11082 } 11083 11084 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11085 // These aren't covered by the composite pointer type rules. 11086 if (!IsOrdered && RHSType->isNullPtrType() && 11087 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11088 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11089 return computeResultTy(); 11090 } 11091 if (!IsOrdered && LHSType->isNullPtrType() && 11092 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11093 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11094 return computeResultTy(); 11095 } 11096 11097 if (IsRelational && 11098 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11099 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11100 // HACK: Relational comparison of nullptr_t against a pointer type is 11101 // invalid per DR583, but we allow it within std::less<> and friends, 11102 // since otherwise common uses of it break. 11103 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11104 // friends to have std::nullptr_t overload candidates. 11105 DeclContext *DC = CurContext; 11106 if (isa<FunctionDecl>(DC)) 11107 DC = DC->getParent(); 11108 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11109 if (CTSD->isInStdNamespace() && 11110 llvm::StringSwitch<bool>(CTSD->getName()) 11111 .Cases("less", "less_equal", "greater", "greater_equal", true) 11112 .Default(false)) { 11113 if (RHSType->isNullPtrType()) 11114 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11115 else 11116 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11117 return computeResultTy(); 11118 } 11119 } 11120 } 11121 11122 // C++ [expr.eq]p2: 11123 // If at least one operand is a pointer to member, [...] bring them to 11124 // their composite pointer type. 11125 if (!IsOrdered && 11126 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11127 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11128 return QualType(); 11129 else 11130 return computeResultTy(); 11131 } 11132 } 11133 11134 // Handle block pointer types. 11135 if (!IsOrdered && LHSType->isBlockPointerType() && 11136 RHSType->isBlockPointerType()) { 11137 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11138 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11139 11140 if (!LHSIsNull && !RHSIsNull && 11141 !Context.typesAreCompatible(lpointee, rpointee)) { 11142 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11143 << LHSType << RHSType << LHS.get()->getSourceRange() 11144 << RHS.get()->getSourceRange(); 11145 } 11146 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11147 return computeResultTy(); 11148 } 11149 11150 // Allow block pointers to be compared with null pointer constants. 11151 if (!IsOrdered 11152 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11153 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11154 if (!LHSIsNull && !RHSIsNull) { 11155 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11156 ->getPointeeType()->isVoidType()) 11157 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11158 ->getPointeeType()->isVoidType()))) 11159 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11160 << LHSType << RHSType << LHS.get()->getSourceRange() 11161 << RHS.get()->getSourceRange(); 11162 } 11163 if (LHSIsNull && !RHSIsNull) 11164 LHS = ImpCastExprToType(LHS.get(), RHSType, 11165 RHSType->isPointerType() ? CK_BitCast 11166 : CK_AnyPointerToBlockPointerCast); 11167 else 11168 RHS = ImpCastExprToType(RHS.get(), LHSType, 11169 LHSType->isPointerType() ? CK_BitCast 11170 : CK_AnyPointerToBlockPointerCast); 11171 return computeResultTy(); 11172 } 11173 11174 if (LHSType->isObjCObjectPointerType() || 11175 RHSType->isObjCObjectPointerType()) { 11176 const PointerType *LPT = LHSType->getAs<PointerType>(); 11177 const PointerType *RPT = RHSType->getAs<PointerType>(); 11178 if (LPT || RPT) { 11179 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11180 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11181 11182 if (!LPtrToVoid && !RPtrToVoid && 11183 !Context.typesAreCompatible(LHSType, RHSType)) { 11184 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11185 /*isError*/false); 11186 } 11187 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11188 // the RHS, but we have test coverage for this behavior. 11189 // FIXME: Consider using convertPointersToCompositeType in C++. 11190 if (LHSIsNull && !RHSIsNull) { 11191 Expr *E = LHS.get(); 11192 if (getLangOpts().ObjCAutoRefCount) 11193 CheckObjCConversion(SourceRange(), RHSType, E, 11194 CCK_ImplicitConversion); 11195 LHS = ImpCastExprToType(E, RHSType, 11196 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11197 } 11198 else { 11199 Expr *E = RHS.get(); 11200 if (getLangOpts().ObjCAutoRefCount) 11201 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11202 /*Diagnose=*/true, 11203 /*DiagnoseCFAudited=*/false, Opc); 11204 RHS = ImpCastExprToType(E, LHSType, 11205 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11206 } 11207 return computeResultTy(); 11208 } 11209 if (LHSType->isObjCObjectPointerType() && 11210 RHSType->isObjCObjectPointerType()) { 11211 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11212 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11213 /*isError*/false); 11214 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 11215 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 11216 11217 if (LHSIsNull && !RHSIsNull) 11218 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 11219 else 11220 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11221 return computeResultTy(); 11222 } 11223 11224 if (!IsOrdered && LHSType->isBlockPointerType() && 11225 RHSType->isBlockCompatibleObjCPointerType(Context)) { 11226 LHS = ImpCastExprToType(LHS.get(), RHSType, 11227 CK_BlockPointerToObjCPointerCast); 11228 return computeResultTy(); 11229 } else if (!IsOrdered && 11230 LHSType->isBlockCompatibleObjCPointerType(Context) && 11231 RHSType->isBlockPointerType()) { 11232 RHS = ImpCastExprToType(RHS.get(), LHSType, 11233 CK_BlockPointerToObjCPointerCast); 11234 return computeResultTy(); 11235 } 11236 } 11237 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 11238 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 11239 unsigned DiagID = 0; 11240 bool isError = false; 11241 if (LangOpts.DebuggerSupport) { 11242 // Under a debugger, allow the comparison of pointers to integers, 11243 // since users tend to want to compare addresses. 11244 } else if ((LHSIsNull && LHSType->isIntegerType()) || 11245 (RHSIsNull && RHSType->isIntegerType())) { 11246 if (IsOrdered) { 11247 isError = getLangOpts().CPlusPlus; 11248 DiagID = 11249 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 11250 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 11251 } 11252 } else if (getLangOpts().CPlusPlus) { 11253 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 11254 isError = true; 11255 } else if (IsOrdered) 11256 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 11257 else 11258 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 11259 11260 if (DiagID) { 11261 Diag(Loc, DiagID) 11262 << LHSType << RHSType << LHS.get()->getSourceRange() 11263 << RHS.get()->getSourceRange(); 11264 if (isError) 11265 return QualType(); 11266 } 11267 11268 if (LHSType->isIntegerType()) 11269 LHS = ImpCastExprToType(LHS.get(), RHSType, 11270 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11271 else 11272 RHS = ImpCastExprToType(RHS.get(), LHSType, 11273 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 11274 return computeResultTy(); 11275 } 11276 11277 // Handle block pointers. 11278 if (!IsOrdered && RHSIsNull 11279 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 11280 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11281 return computeResultTy(); 11282 } 11283 if (!IsOrdered && LHSIsNull 11284 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 11285 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11286 return computeResultTy(); 11287 } 11288 11289 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 11290 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 11291 return computeResultTy(); 11292 } 11293 11294 if (LHSType->isQueueT() && RHSType->isQueueT()) { 11295 return computeResultTy(); 11296 } 11297 11298 if (LHSIsNull && RHSType->isQueueT()) { 11299 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11300 return computeResultTy(); 11301 } 11302 11303 if (LHSType->isQueueT() && RHSIsNull) { 11304 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11305 return computeResultTy(); 11306 } 11307 } 11308 11309 return InvalidOperands(Loc, LHS, RHS); 11310 } 11311 11312 // Return a signed ext_vector_type that is of identical size and number of 11313 // elements. For floating point vectors, return an integer type of identical 11314 // size and number of elements. In the non ext_vector_type case, search from 11315 // the largest type to the smallest type to avoid cases where long long == long, 11316 // where long gets picked over long long. 11317 QualType Sema::GetSignedVectorType(QualType V) { 11318 const VectorType *VTy = V->castAs<VectorType>(); 11319 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 11320 11321 if (isa<ExtVectorType>(VTy)) { 11322 if (TypeSize == Context.getTypeSize(Context.CharTy)) 11323 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 11324 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11325 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 11326 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11327 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 11328 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11329 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 11330 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 11331 "Unhandled vector element size in vector compare"); 11332 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 11333 } 11334 11335 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 11336 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 11337 VectorType::GenericVector); 11338 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 11339 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 11340 VectorType::GenericVector); 11341 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 11342 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 11343 VectorType::GenericVector); 11344 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 11345 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 11346 VectorType::GenericVector); 11347 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 11348 "Unhandled vector element size in vector compare"); 11349 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 11350 VectorType::GenericVector); 11351 } 11352 11353 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 11354 /// operates on extended vector types. Instead of producing an IntTy result, 11355 /// like a scalar comparison, a vector comparison produces a vector of integer 11356 /// types. 11357 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11358 SourceLocation Loc, 11359 BinaryOperatorKind Opc) { 11360 if (Opc == BO_Cmp) { 11361 Diag(Loc, diag::err_three_way_vector_comparison); 11362 return QualType(); 11363 } 11364 11365 // Check to make sure we're operating on vectors of the same type and width, 11366 // Allowing one side to be a scalar of element type. 11367 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 11368 /*AllowBothBool*/true, 11369 /*AllowBoolConversions*/getLangOpts().ZVector); 11370 if (vType.isNull()) 11371 return vType; 11372 11373 QualType LHSType = LHS.get()->getType(); 11374 11375 // If AltiVec, the comparison results in a numeric type, i.e. 11376 // bool for C++, int for C 11377 if (getLangOpts().AltiVec && 11378 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 11379 return Context.getLogicalOperationType(); 11380 11381 // For non-floating point types, check for self-comparisons of the form 11382 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11383 // often indicate logic errors in the program. 11384 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11385 11386 // Check for comparisons of floating point operands using != and ==. 11387 if (BinaryOperator::isEqualityOp(Opc) && 11388 LHSType->hasFloatingRepresentation()) { 11389 assert(RHS.get()->getType()->hasFloatingRepresentation()); 11390 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11391 } 11392 11393 // Return a signed type for the vector. 11394 return GetSignedVectorType(vType); 11395 } 11396 11397 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 11398 const ExprResult &XorRHS, 11399 const SourceLocation Loc) { 11400 // Do not diagnose macros. 11401 if (Loc.isMacroID()) 11402 return; 11403 11404 bool Negative = false; 11405 bool ExplicitPlus = false; 11406 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 11407 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 11408 11409 if (!LHSInt) 11410 return; 11411 if (!RHSInt) { 11412 // Check negative literals. 11413 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 11414 UnaryOperatorKind Opc = UO->getOpcode(); 11415 if (Opc != UO_Minus && Opc != UO_Plus) 11416 return; 11417 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11418 if (!RHSInt) 11419 return; 11420 Negative = (Opc == UO_Minus); 11421 ExplicitPlus = !Negative; 11422 } else { 11423 return; 11424 } 11425 } 11426 11427 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 11428 llvm::APInt RightSideValue = RHSInt->getValue(); 11429 if (LeftSideValue != 2 && LeftSideValue != 10) 11430 return; 11431 11432 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 11433 return; 11434 11435 CharSourceRange ExprRange = CharSourceRange::getCharRange( 11436 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 11437 llvm::StringRef ExprStr = 11438 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 11439 11440 CharSourceRange XorRange = 11441 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11442 llvm::StringRef XorStr = 11443 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 11444 // Do not diagnose if xor keyword/macro is used. 11445 if (XorStr == "xor") 11446 return; 11447 11448 std::string LHSStr = std::string(Lexer::getSourceText( 11449 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 11450 S.getSourceManager(), S.getLangOpts())); 11451 std::string RHSStr = std::string(Lexer::getSourceText( 11452 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 11453 S.getSourceManager(), S.getLangOpts())); 11454 11455 if (Negative) { 11456 RightSideValue = -RightSideValue; 11457 RHSStr = "-" + RHSStr; 11458 } else if (ExplicitPlus) { 11459 RHSStr = "+" + RHSStr; 11460 } 11461 11462 StringRef LHSStrRef = LHSStr; 11463 StringRef RHSStrRef = RHSStr; 11464 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 11465 // literals. 11466 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 11467 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 11468 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 11469 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 11470 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 11471 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 11472 LHSStrRef.find('\'') != StringRef::npos || 11473 RHSStrRef.find('\'') != StringRef::npos) 11474 return; 11475 11476 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 11477 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 11478 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 11479 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 11480 std::string SuggestedExpr = "1 << " + RHSStr; 11481 bool Overflow = false; 11482 llvm::APInt One = (LeftSideValue - 1); 11483 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 11484 if (Overflow) { 11485 if (RightSideIntValue < 64) 11486 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11487 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 11488 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 11489 else if (RightSideIntValue == 64) 11490 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 11491 else 11492 return; 11493 } else { 11494 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 11495 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 11496 << PowValue.toString(10, true) 11497 << FixItHint::CreateReplacement( 11498 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 11499 } 11500 11501 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 11502 } else if (LeftSideValue == 10) { 11503 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 11504 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 11505 << ExprStr << XorValue.toString(10, true) << SuggestedValue 11506 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 11507 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 11508 } 11509 } 11510 11511 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11512 SourceLocation Loc) { 11513 // Ensure that either both operands are of the same vector type, or 11514 // one operand is of a vector type and the other is of its element type. 11515 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 11516 /*AllowBothBool*/true, 11517 /*AllowBoolConversions*/false); 11518 if (vType.isNull()) 11519 return InvalidOperands(Loc, LHS, RHS); 11520 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 11521 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 11522 return InvalidOperands(Loc, LHS, RHS); 11523 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 11524 // usage of the logical operators && and || with vectors in C. This 11525 // check could be notionally dropped. 11526 if (!getLangOpts().CPlusPlus && 11527 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 11528 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 11529 11530 return GetSignedVectorType(LHS.get()->getType()); 11531 } 11532 11533 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 11534 SourceLocation Loc, 11535 BinaryOperatorKind Opc) { 11536 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11537 11538 bool IsCompAssign = 11539 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 11540 11541 if (LHS.get()->getType()->isVectorType() || 11542 RHS.get()->getType()->isVectorType()) { 11543 if (LHS.get()->getType()->hasIntegerRepresentation() && 11544 RHS.get()->getType()->hasIntegerRepresentation()) 11545 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11546 /*AllowBothBool*/true, 11547 /*AllowBoolConversions*/getLangOpts().ZVector); 11548 return InvalidOperands(Loc, LHS, RHS); 11549 } 11550 11551 if (Opc == BO_And) 11552 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11553 11554 if (LHS.get()->getType()->hasFloatingRepresentation() || 11555 RHS.get()->getType()->hasFloatingRepresentation()) 11556 return InvalidOperands(Loc, LHS, RHS); 11557 11558 ExprResult LHSResult = LHS, RHSResult = RHS; 11559 QualType compType = UsualArithmeticConversions( 11560 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 11561 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 11562 return QualType(); 11563 LHS = LHSResult.get(); 11564 RHS = RHSResult.get(); 11565 11566 if (Opc == BO_Xor) 11567 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 11568 11569 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 11570 return compType; 11571 return InvalidOperands(Loc, LHS, RHS); 11572 } 11573 11574 // C99 6.5.[13,14] 11575 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11576 SourceLocation Loc, 11577 BinaryOperatorKind Opc) { 11578 // Check vector operands differently. 11579 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 11580 return CheckVectorLogicalOperands(LHS, RHS, Loc); 11581 11582 bool EnumConstantInBoolContext = false; 11583 for (const ExprResult &HS : {LHS, RHS}) { 11584 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 11585 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 11586 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 11587 EnumConstantInBoolContext = true; 11588 } 11589 } 11590 11591 if (EnumConstantInBoolContext) 11592 Diag(Loc, diag::warn_enum_constant_in_bool_context); 11593 11594 // Diagnose cases where the user write a logical and/or but probably meant a 11595 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 11596 // is a constant. 11597 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 11598 !LHS.get()->getType()->isBooleanType() && 11599 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 11600 // Don't warn in macros or template instantiations. 11601 !Loc.isMacroID() && !inTemplateInstantiation()) { 11602 // If the RHS can be constant folded, and if it constant folds to something 11603 // that isn't 0 or 1 (which indicate a potential logical operation that 11604 // happened to fold to true/false) then warn. 11605 // Parens on the RHS are ignored. 11606 Expr::EvalResult EVResult; 11607 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 11608 llvm::APSInt Result = EVResult.Val.getInt(); 11609 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 11610 !RHS.get()->getExprLoc().isMacroID()) || 11611 (Result != 0 && Result != 1)) { 11612 Diag(Loc, diag::warn_logical_instead_of_bitwise) 11613 << RHS.get()->getSourceRange() 11614 << (Opc == BO_LAnd ? "&&" : "||"); 11615 // Suggest replacing the logical operator with the bitwise version 11616 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 11617 << (Opc == BO_LAnd ? "&" : "|") 11618 << FixItHint::CreateReplacement(SourceRange( 11619 Loc, getLocForEndOfToken(Loc)), 11620 Opc == BO_LAnd ? "&" : "|"); 11621 if (Opc == BO_LAnd) 11622 // Suggest replacing "Foo() && kNonZero" with "Foo()" 11623 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 11624 << FixItHint::CreateRemoval( 11625 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 11626 RHS.get()->getEndLoc())); 11627 } 11628 } 11629 } 11630 11631 if (!Context.getLangOpts().CPlusPlus) { 11632 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 11633 // not operate on the built-in scalar and vector float types. 11634 if (Context.getLangOpts().OpenCL && 11635 Context.getLangOpts().OpenCLVersion < 120) { 11636 if (LHS.get()->getType()->isFloatingType() || 11637 RHS.get()->getType()->isFloatingType()) 11638 return InvalidOperands(Loc, LHS, RHS); 11639 } 11640 11641 LHS = UsualUnaryConversions(LHS.get()); 11642 if (LHS.isInvalid()) 11643 return QualType(); 11644 11645 RHS = UsualUnaryConversions(RHS.get()); 11646 if (RHS.isInvalid()) 11647 return QualType(); 11648 11649 if (!LHS.get()->getType()->isScalarType() || 11650 !RHS.get()->getType()->isScalarType()) 11651 return InvalidOperands(Loc, LHS, RHS); 11652 11653 return Context.IntTy; 11654 } 11655 11656 // The following is safe because we only use this method for 11657 // non-overloadable operands. 11658 11659 // C++ [expr.log.and]p1 11660 // C++ [expr.log.or]p1 11661 // The operands are both contextually converted to type bool. 11662 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 11663 if (LHSRes.isInvalid()) 11664 return InvalidOperands(Loc, LHS, RHS); 11665 LHS = LHSRes; 11666 11667 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 11668 if (RHSRes.isInvalid()) 11669 return InvalidOperands(Loc, LHS, RHS); 11670 RHS = RHSRes; 11671 11672 // C++ [expr.log.and]p2 11673 // C++ [expr.log.or]p2 11674 // The result is a bool. 11675 return Context.BoolTy; 11676 } 11677 11678 static bool IsReadonlyMessage(Expr *E, Sema &S) { 11679 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11680 if (!ME) return false; 11681 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 11682 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 11683 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 11684 if (!Base) return false; 11685 return Base->getMethodDecl() != nullptr; 11686 } 11687 11688 /// Is the given expression (which must be 'const') a reference to a 11689 /// variable which was originally non-const, but which has become 11690 /// 'const' due to being captured within a block? 11691 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 11692 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 11693 assert(E->isLValue() && E->getType().isConstQualified()); 11694 E = E->IgnoreParens(); 11695 11696 // Must be a reference to a declaration from an enclosing scope. 11697 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 11698 if (!DRE) return NCCK_None; 11699 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 11700 11701 // The declaration must be a variable which is not declared 'const'. 11702 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 11703 if (!var) return NCCK_None; 11704 if (var->getType().isConstQualified()) return NCCK_None; 11705 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 11706 11707 // Decide whether the first capture was for a block or a lambda. 11708 DeclContext *DC = S.CurContext, *Prev = nullptr; 11709 // Decide whether the first capture was for a block or a lambda. 11710 while (DC) { 11711 // For init-capture, it is possible that the variable belongs to the 11712 // template pattern of the current context. 11713 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 11714 if (var->isInitCapture() && 11715 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 11716 break; 11717 if (DC == var->getDeclContext()) 11718 break; 11719 Prev = DC; 11720 DC = DC->getParent(); 11721 } 11722 // Unless we have an init-capture, we've gone one step too far. 11723 if (!var->isInitCapture()) 11724 DC = Prev; 11725 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 11726 } 11727 11728 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 11729 Ty = Ty.getNonReferenceType(); 11730 if (IsDereference && Ty->isPointerType()) 11731 Ty = Ty->getPointeeType(); 11732 return !Ty.isConstQualified(); 11733 } 11734 11735 // Update err_typecheck_assign_const and note_typecheck_assign_const 11736 // when this enum is changed. 11737 enum { 11738 ConstFunction, 11739 ConstVariable, 11740 ConstMember, 11741 ConstMethod, 11742 NestedConstMember, 11743 ConstUnknown, // Keep as last element 11744 }; 11745 11746 /// Emit the "read-only variable not assignable" error and print notes to give 11747 /// more information about why the variable is not assignable, such as pointing 11748 /// to the declaration of a const variable, showing that a method is const, or 11749 /// that the function is returning a const reference. 11750 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 11751 SourceLocation Loc) { 11752 SourceRange ExprRange = E->getSourceRange(); 11753 11754 // Only emit one error on the first const found. All other consts will emit 11755 // a note to the error. 11756 bool DiagnosticEmitted = false; 11757 11758 // Track if the current expression is the result of a dereference, and if the 11759 // next checked expression is the result of a dereference. 11760 bool IsDereference = false; 11761 bool NextIsDereference = false; 11762 11763 // Loop to process MemberExpr chains. 11764 while (true) { 11765 IsDereference = NextIsDereference; 11766 11767 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 11768 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 11769 NextIsDereference = ME->isArrow(); 11770 const ValueDecl *VD = ME->getMemberDecl(); 11771 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 11772 // Mutable fields can be modified even if the class is const. 11773 if (Field->isMutable()) { 11774 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 11775 break; 11776 } 11777 11778 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 11779 if (!DiagnosticEmitted) { 11780 S.Diag(Loc, diag::err_typecheck_assign_const) 11781 << ExprRange << ConstMember << false /*static*/ << Field 11782 << Field->getType(); 11783 DiagnosticEmitted = true; 11784 } 11785 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11786 << ConstMember << false /*static*/ << Field << Field->getType() 11787 << Field->getSourceRange(); 11788 } 11789 E = ME->getBase(); 11790 continue; 11791 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 11792 if (VDecl->getType().isConstQualified()) { 11793 if (!DiagnosticEmitted) { 11794 S.Diag(Loc, diag::err_typecheck_assign_const) 11795 << ExprRange << ConstMember << true /*static*/ << VDecl 11796 << VDecl->getType(); 11797 DiagnosticEmitted = true; 11798 } 11799 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11800 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 11801 << VDecl->getSourceRange(); 11802 } 11803 // Static fields do not inherit constness from parents. 11804 break; 11805 } 11806 break; // End MemberExpr 11807 } else if (const ArraySubscriptExpr *ASE = 11808 dyn_cast<ArraySubscriptExpr>(E)) { 11809 E = ASE->getBase()->IgnoreParenImpCasts(); 11810 continue; 11811 } else if (const ExtVectorElementExpr *EVE = 11812 dyn_cast<ExtVectorElementExpr>(E)) { 11813 E = EVE->getBase()->IgnoreParenImpCasts(); 11814 continue; 11815 } 11816 break; 11817 } 11818 11819 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11820 // Function calls 11821 const FunctionDecl *FD = CE->getDirectCallee(); 11822 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 11823 if (!DiagnosticEmitted) { 11824 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11825 << ConstFunction << FD; 11826 DiagnosticEmitted = true; 11827 } 11828 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11829 diag::note_typecheck_assign_const) 11830 << ConstFunction << FD << FD->getReturnType() 11831 << FD->getReturnTypeSourceRange(); 11832 } 11833 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11834 // Point to variable declaration. 11835 if (const ValueDecl *VD = DRE->getDecl()) { 11836 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11837 if (!DiagnosticEmitted) { 11838 S.Diag(Loc, diag::err_typecheck_assign_const) 11839 << ExprRange << ConstVariable << VD << VD->getType(); 11840 DiagnosticEmitted = true; 11841 } 11842 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11843 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11844 } 11845 } 11846 } else if (isa<CXXThisExpr>(E)) { 11847 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11848 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11849 if (MD->isConst()) { 11850 if (!DiagnosticEmitted) { 11851 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11852 << ConstMethod << MD; 11853 DiagnosticEmitted = true; 11854 } 11855 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11856 << ConstMethod << MD << MD->getSourceRange(); 11857 } 11858 } 11859 } 11860 } 11861 11862 if (DiagnosticEmitted) 11863 return; 11864 11865 // Can't determine a more specific message, so display the generic error. 11866 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11867 } 11868 11869 enum OriginalExprKind { 11870 OEK_Variable, 11871 OEK_Member, 11872 OEK_LValue 11873 }; 11874 11875 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11876 const RecordType *Ty, 11877 SourceLocation Loc, SourceRange Range, 11878 OriginalExprKind OEK, 11879 bool &DiagnosticEmitted) { 11880 std::vector<const RecordType *> RecordTypeList; 11881 RecordTypeList.push_back(Ty); 11882 unsigned NextToCheckIndex = 0; 11883 // We walk the record hierarchy breadth-first to ensure that we print 11884 // diagnostics in field nesting order. 11885 while (RecordTypeList.size() > NextToCheckIndex) { 11886 bool IsNested = NextToCheckIndex > 0; 11887 for (const FieldDecl *Field : 11888 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 11889 // First, check every field for constness. 11890 QualType FieldTy = Field->getType(); 11891 if (FieldTy.isConstQualified()) { 11892 if (!DiagnosticEmitted) { 11893 S.Diag(Loc, diag::err_typecheck_assign_const) 11894 << Range << NestedConstMember << OEK << VD 11895 << IsNested << Field; 11896 DiagnosticEmitted = true; 11897 } 11898 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11899 << NestedConstMember << IsNested << Field 11900 << FieldTy << Field->getSourceRange(); 11901 } 11902 11903 // Then we append it to the list to check next in order. 11904 FieldTy = FieldTy.getCanonicalType(); 11905 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 11906 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 11907 RecordTypeList.push_back(FieldRecTy); 11908 } 11909 } 11910 ++NextToCheckIndex; 11911 } 11912 } 11913 11914 /// Emit an error for the case where a record we are trying to assign to has a 11915 /// const-qualified field somewhere in its hierarchy. 11916 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11917 SourceLocation Loc) { 11918 QualType Ty = E->getType(); 11919 assert(Ty->isRecordType() && "lvalue was not record?"); 11920 SourceRange Range = E->getSourceRange(); 11921 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11922 bool DiagEmitted = false; 11923 11924 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11925 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11926 Range, OEK_Member, DiagEmitted); 11927 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11928 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11929 Range, OEK_Variable, DiagEmitted); 11930 else 11931 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11932 Range, OEK_LValue, DiagEmitted); 11933 if (!DiagEmitted) 11934 DiagnoseConstAssignment(S, E, Loc); 11935 } 11936 11937 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11938 /// emit an error and return true. If so, return false. 11939 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11940 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11941 11942 S.CheckShadowingDeclModification(E, Loc); 11943 11944 SourceLocation OrigLoc = Loc; 11945 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11946 &Loc); 11947 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11948 IsLV = Expr::MLV_InvalidMessageExpression; 11949 if (IsLV == Expr::MLV_Valid) 11950 return false; 11951 11952 unsigned DiagID = 0; 11953 bool NeedType = false; 11954 switch (IsLV) { // C99 6.5.16p2 11955 case Expr::MLV_ConstQualified: 11956 // Use a specialized diagnostic when we're assigning to an object 11957 // from an enclosing function or block. 11958 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11959 if (NCCK == NCCK_Block) 11960 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11961 else 11962 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11963 break; 11964 } 11965 11966 // In ARC, use some specialized diagnostics for occasions where we 11967 // infer 'const'. These are always pseudo-strong variables. 11968 if (S.getLangOpts().ObjCAutoRefCount) { 11969 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11970 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11971 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11972 11973 // Use the normal diagnostic if it's pseudo-__strong but the 11974 // user actually wrote 'const'. 11975 if (var->isARCPseudoStrong() && 11976 (!var->getTypeSourceInfo() || 11977 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11978 // There are three pseudo-strong cases: 11979 // - self 11980 ObjCMethodDecl *method = S.getCurMethodDecl(); 11981 if (method && var == method->getSelfDecl()) { 11982 DiagID = method->isClassMethod() 11983 ? diag::err_typecheck_arc_assign_self_class_method 11984 : diag::err_typecheck_arc_assign_self; 11985 11986 // - Objective-C externally_retained attribute. 11987 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 11988 isa<ParmVarDecl>(var)) { 11989 DiagID = diag::err_typecheck_arc_assign_externally_retained; 11990 11991 // - fast enumeration variables 11992 } else { 11993 DiagID = diag::err_typecheck_arr_assign_enumeration; 11994 } 11995 11996 SourceRange Assign; 11997 if (Loc != OrigLoc) 11998 Assign = SourceRange(OrigLoc, OrigLoc); 11999 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12000 // We need to preserve the AST regardless, so migration tool 12001 // can do its job. 12002 return false; 12003 } 12004 } 12005 } 12006 12007 // If none of the special cases above are triggered, then this is a 12008 // simple const assignment. 12009 if (DiagID == 0) { 12010 DiagnoseConstAssignment(S, E, Loc); 12011 return true; 12012 } 12013 12014 break; 12015 case Expr::MLV_ConstAddrSpace: 12016 DiagnoseConstAssignment(S, E, Loc); 12017 return true; 12018 case Expr::MLV_ConstQualifiedField: 12019 DiagnoseRecursiveConstFields(S, E, Loc); 12020 return true; 12021 case Expr::MLV_ArrayType: 12022 case Expr::MLV_ArrayTemporary: 12023 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12024 NeedType = true; 12025 break; 12026 case Expr::MLV_NotObjectType: 12027 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12028 NeedType = true; 12029 break; 12030 case Expr::MLV_LValueCast: 12031 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12032 break; 12033 case Expr::MLV_Valid: 12034 llvm_unreachable("did not take early return for MLV_Valid"); 12035 case Expr::MLV_InvalidExpression: 12036 case Expr::MLV_MemberFunction: 12037 case Expr::MLV_ClassTemporary: 12038 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12039 break; 12040 case Expr::MLV_IncompleteType: 12041 case Expr::MLV_IncompleteVoidType: 12042 return S.RequireCompleteType(Loc, E->getType(), 12043 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12044 case Expr::MLV_DuplicateVectorComponents: 12045 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12046 break; 12047 case Expr::MLV_NoSetterProperty: 12048 llvm_unreachable("readonly properties should be processed differently"); 12049 case Expr::MLV_InvalidMessageExpression: 12050 DiagID = diag::err_readonly_message_assignment; 12051 break; 12052 case Expr::MLV_SubObjCPropertySetting: 12053 DiagID = diag::err_no_subobject_property_setting; 12054 break; 12055 } 12056 12057 SourceRange Assign; 12058 if (Loc != OrigLoc) 12059 Assign = SourceRange(OrigLoc, OrigLoc); 12060 if (NeedType) 12061 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12062 else 12063 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12064 return true; 12065 } 12066 12067 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12068 SourceLocation Loc, 12069 Sema &Sema) { 12070 if (Sema.inTemplateInstantiation()) 12071 return; 12072 if (Sema.isUnevaluatedContext()) 12073 return; 12074 if (Loc.isInvalid() || Loc.isMacroID()) 12075 return; 12076 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12077 return; 12078 12079 // C / C++ fields 12080 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12081 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12082 if (ML && MR) { 12083 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12084 return; 12085 const ValueDecl *LHSDecl = 12086 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12087 const ValueDecl *RHSDecl = 12088 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12089 if (LHSDecl != RHSDecl) 12090 return; 12091 if (LHSDecl->getType().isVolatileQualified()) 12092 return; 12093 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12094 if (RefTy->getPointeeType().isVolatileQualified()) 12095 return; 12096 12097 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12098 } 12099 12100 // Objective-C instance variables 12101 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12102 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12103 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12104 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12105 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12106 if (RL && RR && RL->getDecl() == RR->getDecl()) 12107 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12108 } 12109 } 12110 12111 // C99 6.5.16.1 12112 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12113 SourceLocation Loc, 12114 QualType CompoundType) { 12115 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12116 12117 // Verify that LHS is a modifiable lvalue, and emit error if not. 12118 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12119 return QualType(); 12120 12121 QualType LHSType = LHSExpr->getType(); 12122 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12123 CompoundType; 12124 // OpenCL v1.2 s6.1.1.1 p2: 12125 // The half data type can only be used to declare a pointer to a buffer that 12126 // contains half values 12127 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 12128 LHSType->isHalfType()) { 12129 Diag(Loc, diag::err_opencl_half_load_store) << 1 12130 << LHSType.getUnqualifiedType(); 12131 return QualType(); 12132 } 12133 12134 AssignConvertType ConvTy; 12135 if (CompoundType.isNull()) { 12136 Expr *RHSCheck = RHS.get(); 12137 12138 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 12139 12140 QualType LHSTy(LHSType); 12141 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 12142 if (RHS.isInvalid()) 12143 return QualType(); 12144 // Special case of NSObject attributes on c-style pointer types. 12145 if (ConvTy == IncompatiblePointer && 12146 ((Context.isObjCNSObjectType(LHSType) && 12147 RHSType->isObjCObjectPointerType()) || 12148 (Context.isObjCNSObjectType(RHSType) && 12149 LHSType->isObjCObjectPointerType()))) 12150 ConvTy = Compatible; 12151 12152 if (ConvTy == Compatible && 12153 LHSType->isObjCObjectType()) 12154 Diag(Loc, diag::err_objc_object_assignment) 12155 << LHSType; 12156 12157 // If the RHS is a unary plus or minus, check to see if they = and + are 12158 // right next to each other. If so, the user may have typo'd "x =+ 4" 12159 // instead of "x += 4". 12160 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 12161 RHSCheck = ICE->getSubExpr(); 12162 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 12163 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 12164 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 12165 // Only if the two operators are exactly adjacent. 12166 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 12167 // And there is a space or other character before the subexpr of the 12168 // unary +/-. We don't want to warn on "x=-1". 12169 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 12170 UO->getSubExpr()->getBeginLoc().isFileID()) { 12171 Diag(Loc, diag::warn_not_compound_assign) 12172 << (UO->getOpcode() == UO_Plus ? "+" : "-") 12173 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 12174 } 12175 } 12176 12177 if (ConvTy == Compatible) { 12178 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 12179 // Warn about retain cycles where a block captures the LHS, but 12180 // not if the LHS is a simple variable into which the block is 12181 // being stored...unless that variable can be captured by reference! 12182 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 12183 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 12184 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 12185 checkRetainCycles(LHSExpr, RHS.get()); 12186 } 12187 12188 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 12189 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 12190 // It is safe to assign a weak reference into a strong variable. 12191 // Although this code can still have problems: 12192 // id x = self.weakProp; 12193 // id y = self.weakProp; 12194 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12195 // paths through the function. This should be revisited if 12196 // -Wrepeated-use-of-weak is made flow-sensitive. 12197 // For ObjCWeak only, we do not warn if the assign is to a non-weak 12198 // variable, which will be valid for the current autorelease scope. 12199 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12200 RHS.get()->getBeginLoc())) 12201 getCurFunction()->markSafeWeakUse(RHS.get()); 12202 12203 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 12204 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 12205 } 12206 } 12207 } else { 12208 // Compound assignment "x += y" 12209 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 12210 } 12211 12212 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 12213 RHS.get(), AA_Assigning)) 12214 return QualType(); 12215 12216 CheckForNullPointerDereference(*this, LHSExpr); 12217 12218 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) { 12219 if (CompoundType.isNull()) { 12220 // C++2a [expr.ass]p5: 12221 // A simple-assignment whose left operand is of a volatile-qualified 12222 // type is deprecated unless the assignment is either a discarded-value 12223 // expression or an unevaluated operand 12224 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 12225 } else { 12226 // C++2a [expr.ass]p6: 12227 // [Compound-assignment] expressions are deprecated if E1 has 12228 // volatile-qualified type 12229 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 12230 } 12231 } 12232 12233 // C99 6.5.16p3: The type of an assignment expression is the type of the 12234 // left operand unless the left operand has qualified type, in which case 12235 // it is the unqualified version of the type of the left operand. 12236 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 12237 // is converted to the type of the assignment expression (above). 12238 // C++ 5.17p1: the type of the assignment expression is that of its left 12239 // operand. 12240 return (getLangOpts().CPlusPlus 12241 ? LHSType : LHSType.getUnqualifiedType()); 12242 } 12243 12244 // Only ignore explicit casts to void. 12245 static bool IgnoreCommaOperand(const Expr *E) { 12246 E = E->IgnoreParens(); 12247 12248 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 12249 if (CE->getCastKind() == CK_ToVoid) { 12250 return true; 12251 } 12252 12253 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 12254 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 12255 CE->getSubExpr()->getType()->isDependentType()) { 12256 return true; 12257 } 12258 } 12259 12260 return false; 12261 } 12262 12263 // Look for instances where it is likely the comma operator is confused with 12264 // another operator. There is a whitelist of acceptable expressions for the 12265 // left hand side of the comma operator, otherwise emit a warning. 12266 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 12267 // No warnings in macros 12268 if (Loc.isMacroID()) 12269 return; 12270 12271 // Don't warn in template instantiations. 12272 if (inTemplateInstantiation()) 12273 return; 12274 12275 // Scope isn't fine-grained enough to whitelist the specific cases, so 12276 // instead, skip more than needed, then call back into here with the 12277 // CommaVisitor in SemaStmt.cpp. 12278 // The whitelisted locations are the initialization and increment portions 12279 // of a for loop. The additional checks are on the condition of 12280 // if statements, do/while loops, and for loops. 12281 // Differences in scope flags for C89 mode requires the extra logic. 12282 const unsigned ForIncrementFlags = 12283 getLangOpts().C99 || getLangOpts().CPlusPlus 12284 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 12285 : Scope::ContinueScope | Scope::BreakScope; 12286 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 12287 const unsigned ScopeFlags = getCurScope()->getFlags(); 12288 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 12289 (ScopeFlags & ForInitFlags) == ForInitFlags) 12290 return; 12291 12292 // If there are multiple comma operators used together, get the RHS of the 12293 // of the comma operator as the LHS. 12294 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 12295 if (BO->getOpcode() != BO_Comma) 12296 break; 12297 LHS = BO->getRHS(); 12298 } 12299 12300 // Only allow some expressions on LHS to not warn. 12301 if (IgnoreCommaOperand(LHS)) 12302 return; 12303 12304 Diag(Loc, diag::warn_comma_operator); 12305 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 12306 << LHS->getSourceRange() 12307 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 12308 LangOpts.CPlusPlus ? "static_cast<void>(" 12309 : "(void)(") 12310 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 12311 ")"); 12312 } 12313 12314 // C99 6.5.17 12315 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 12316 SourceLocation Loc) { 12317 LHS = S.CheckPlaceholderExpr(LHS.get()); 12318 RHS = S.CheckPlaceholderExpr(RHS.get()); 12319 if (LHS.isInvalid() || RHS.isInvalid()) 12320 return QualType(); 12321 12322 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 12323 // operands, but not unary promotions. 12324 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 12325 12326 // So we treat the LHS as a ignored value, and in C++ we allow the 12327 // containing site to determine what should be done with the RHS. 12328 LHS = S.IgnoredValueConversions(LHS.get()); 12329 if (LHS.isInvalid()) 12330 return QualType(); 12331 12332 S.DiagnoseUnusedExprResult(LHS.get()); 12333 12334 if (!S.getLangOpts().CPlusPlus) { 12335 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 12336 if (RHS.isInvalid()) 12337 return QualType(); 12338 if (!RHS.get()->getType()->isVoidType()) 12339 S.RequireCompleteType(Loc, RHS.get()->getType(), 12340 diag::err_incomplete_type); 12341 } 12342 12343 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 12344 S.DiagnoseCommaOperator(LHS.get(), Loc); 12345 12346 return RHS.get()->getType(); 12347 } 12348 12349 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 12350 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 12351 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 12352 ExprValueKind &VK, 12353 ExprObjectKind &OK, 12354 SourceLocation OpLoc, 12355 bool IsInc, bool IsPrefix) { 12356 if (Op->isTypeDependent()) 12357 return S.Context.DependentTy; 12358 12359 QualType ResType = Op->getType(); 12360 // Atomic types can be used for increment / decrement where the non-atomic 12361 // versions can, so ignore the _Atomic() specifier for the purpose of 12362 // checking. 12363 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 12364 ResType = ResAtomicType->getValueType(); 12365 12366 assert(!ResType.isNull() && "no type for increment/decrement expression"); 12367 12368 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 12369 // Decrement of bool is not allowed. 12370 if (!IsInc) { 12371 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 12372 return QualType(); 12373 } 12374 // Increment of bool sets it to true, but is deprecated. 12375 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 12376 : diag::warn_increment_bool) 12377 << Op->getSourceRange(); 12378 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 12379 // Error on enum increments and decrements in C++ mode 12380 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 12381 return QualType(); 12382 } else if (ResType->isRealType()) { 12383 // OK! 12384 } else if (ResType->isPointerType()) { 12385 // C99 6.5.2.4p2, 6.5.6p2 12386 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 12387 return QualType(); 12388 } else if (ResType->isObjCObjectPointerType()) { 12389 // On modern runtimes, ObjC pointer arithmetic is forbidden. 12390 // Otherwise, we just need a complete type. 12391 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 12392 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 12393 return QualType(); 12394 } else if (ResType->isAnyComplexType()) { 12395 // C99 does not support ++/-- on complex types, we allow as an extension. 12396 S.Diag(OpLoc, diag::ext_integer_increment_complex) 12397 << ResType << Op->getSourceRange(); 12398 } else if (ResType->isPlaceholderType()) { 12399 ExprResult PR = S.CheckPlaceholderExpr(Op); 12400 if (PR.isInvalid()) return QualType(); 12401 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 12402 IsInc, IsPrefix); 12403 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 12404 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 12405 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 12406 (ResType->castAs<VectorType>()->getVectorKind() != 12407 VectorType::AltiVecBool)) { 12408 // The z vector extensions allow ++ and -- for non-bool vectors. 12409 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 12410 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 12411 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 12412 } else { 12413 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 12414 << ResType << int(IsInc) << Op->getSourceRange(); 12415 return QualType(); 12416 } 12417 // At this point, we know we have a real, complex or pointer type. 12418 // Now make sure the operand is a modifiable lvalue. 12419 if (CheckForModifiableLvalue(Op, OpLoc, S)) 12420 return QualType(); 12421 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) { 12422 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 12423 // An operand with volatile-qualified type is deprecated 12424 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 12425 << IsInc << ResType; 12426 } 12427 // In C++, a prefix increment is the same type as the operand. Otherwise 12428 // (in C or with postfix), the increment is the unqualified type of the 12429 // operand. 12430 if (IsPrefix && S.getLangOpts().CPlusPlus) { 12431 VK = VK_LValue; 12432 OK = Op->getObjectKind(); 12433 return ResType; 12434 } else { 12435 VK = VK_RValue; 12436 return ResType.getUnqualifiedType(); 12437 } 12438 } 12439 12440 12441 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 12442 /// This routine allows us to typecheck complex/recursive expressions 12443 /// where the declaration is needed for type checking. We only need to 12444 /// handle cases when the expression references a function designator 12445 /// or is an lvalue. Here are some examples: 12446 /// - &(x) => x 12447 /// - &*****f => f for f a function designator. 12448 /// - &s.xx => s 12449 /// - &s.zz[1].yy -> s, if zz is an array 12450 /// - *(x + 1) -> x, if x is an array 12451 /// - &"123"[2] -> 0 12452 /// - & __real__ x -> x 12453 static ValueDecl *getPrimaryDecl(Expr *E) { 12454 switch (E->getStmtClass()) { 12455 case Stmt::DeclRefExprClass: 12456 return cast<DeclRefExpr>(E)->getDecl(); 12457 case Stmt::MemberExprClass: 12458 // If this is an arrow operator, the address is an offset from 12459 // the base's value, so the object the base refers to is 12460 // irrelevant. 12461 if (cast<MemberExpr>(E)->isArrow()) 12462 return nullptr; 12463 // Otherwise, the expression refers to a part of the base 12464 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 12465 case Stmt::ArraySubscriptExprClass: { 12466 // FIXME: This code shouldn't be necessary! We should catch the implicit 12467 // promotion of register arrays earlier. 12468 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 12469 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 12470 if (ICE->getSubExpr()->getType()->isArrayType()) 12471 return getPrimaryDecl(ICE->getSubExpr()); 12472 } 12473 return nullptr; 12474 } 12475 case Stmt::UnaryOperatorClass: { 12476 UnaryOperator *UO = cast<UnaryOperator>(E); 12477 12478 switch(UO->getOpcode()) { 12479 case UO_Real: 12480 case UO_Imag: 12481 case UO_Extension: 12482 return getPrimaryDecl(UO->getSubExpr()); 12483 default: 12484 return nullptr; 12485 } 12486 } 12487 case Stmt::ParenExprClass: 12488 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 12489 case Stmt::ImplicitCastExprClass: 12490 // If the result of an implicit cast is an l-value, we care about 12491 // the sub-expression; otherwise, the result here doesn't matter. 12492 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 12493 default: 12494 return nullptr; 12495 } 12496 } 12497 12498 namespace { 12499 enum { 12500 AO_Bit_Field = 0, 12501 AO_Vector_Element = 1, 12502 AO_Property_Expansion = 2, 12503 AO_Register_Variable = 3, 12504 AO_No_Error = 4 12505 }; 12506 } 12507 /// Diagnose invalid operand for address of operations. 12508 /// 12509 /// \param Type The type of operand which cannot have its address taken. 12510 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 12511 Expr *E, unsigned Type) { 12512 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 12513 } 12514 12515 /// CheckAddressOfOperand - The operand of & must be either a function 12516 /// designator or an lvalue designating an object. If it is an lvalue, the 12517 /// object cannot be declared with storage class register or be a bit field. 12518 /// Note: The usual conversions are *not* applied to the operand of the & 12519 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 12520 /// In C++, the operand might be an overloaded function name, in which case 12521 /// we allow the '&' but retain the overloaded-function type. 12522 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 12523 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 12524 if (PTy->getKind() == BuiltinType::Overload) { 12525 Expr *E = OrigOp.get()->IgnoreParens(); 12526 if (!isa<OverloadExpr>(E)) { 12527 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 12528 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 12529 << OrigOp.get()->getSourceRange(); 12530 return QualType(); 12531 } 12532 12533 OverloadExpr *Ovl = cast<OverloadExpr>(E); 12534 if (isa<UnresolvedMemberExpr>(Ovl)) 12535 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 12536 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12537 << OrigOp.get()->getSourceRange(); 12538 return QualType(); 12539 } 12540 12541 return Context.OverloadTy; 12542 } 12543 12544 if (PTy->getKind() == BuiltinType::UnknownAny) 12545 return Context.UnknownAnyTy; 12546 12547 if (PTy->getKind() == BuiltinType::BoundMember) { 12548 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12549 << OrigOp.get()->getSourceRange(); 12550 return QualType(); 12551 } 12552 12553 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 12554 if (OrigOp.isInvalid()) return QualType(); 12555 } 12556 12557 if (OrigOp.get()->isTypeDependent()) 12558 return Context.DependentTy; 12559 12560 assert(!OrigOp.get()->getType()->isPlaceholderType()); 12561 12562 // Make sure to ignore parentheses in subsequent checks 12563 Expr *op = OrigOp.get()->IgnoreParens(); 12564 12565 // In OpenCL captures for blocks called as lambda functions 12566 // are located in the private address space. Blocks used in 12567 // enqueue_kernel can be located in a different address space 12568 // depending on a vendor implementation. Thus preventing 12569 // taking an address of the capture to avoid invalid AS casts. 12570 if (LangOpts.OpenCL) { 12571 auto* VarRef = dyn_cast<DeclRefExpr>(op); 12572 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 12573 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 12574 return QualType(); 12575 } 12576 } 12577 12578 if (getLangOpts().C99) { 12579 // Implement C99-only parts of addressof rules. 12580 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 12581 if (uOp->getOpcode() == UO_Deref) 12582 // Per C99 6.5.3.2, the address of a deref always returns a valid result 12583 // (assuming the deref expression is valid). 12584 return uOp->getSubExpr()->getType(); 12585 } 12586 // Technically, there should be a check for array subscript 12587 // expressions here, but the result of one is always an lvalue anyway. 12588 } 12589 ValueDecl *dcl = getPrimaryDecl(op); 12590 12591 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 12592 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12593 op->getBeginLoc())) 12594 return QualType(); 12595 12596 Expr::LValueClassification lval = op->ClassifyLValue(Context); 12597 unsigned AddressOfError = AO_No_Error; 12598 12599 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 12600 bool sfinae = (bool)isSFINAEContext(); 12601 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 12602 : diag::ext_typecheck_addrof_temporary) 12603 << op->getType() << op->getSourceRange(); 12604 if (sfinae) 12605 return QualType(); 12606 // Materialize the temporary as an lvalue so that we can take its address. 12607 OrigOp = op = 12608 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 12609 } else if (isa<ObjCSelectorExpr>(op)) { 12610 return Context.getPointerType(op->getType()); 12611 } else if (lval == Expr::LV_MemberFunction) { 12612 // If it's an instance method, make a member pointer. 12613 // The expression must have exactly the form &A::foo. 12614 12615 // If the underlying expression isn't a decl ref, give up. 12616 if (!isa<DeclRefExpr>(op)) { 12617 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 12618 << OrigOp.get()->getSourceRange(); 12619 return QualType(); 12620 } 12621 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 12622 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 12623 12624 // The id-expression was parenthesized. 12625 if (OrigOp.get() != DRE) { 12626 Diag(OpLoc, diag::err_parens_pointer_member_function) 12627 << OrigOp.get()->getSourceRange(); 12628 12629 // The method was named without a qualifier. 12630 } else if (!DRE->getQualifier()) { 12631 if (MD->getParent()->getName().empty()) 12632 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12633 << op->getSourceRange(); 12634 else { 12635 SmallString<32> Str; 12636 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 12637 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 12638 << op->getSourceRange() 12639 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 12640 } 12641 } 12642 12643 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 12644 if (isa<CXXDestructorDecl>(MD)) 12645 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 12646 12647 QualType MPTy = Context.getMemberPointerType( 12648 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 12649 // Under the MS ABI, lock down the inheritance model now. 12650 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12651 (void)isCompleteType(OpLoc, MPTy); 12652 return MPTy; 12653 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 12654 // C99 6.5.3.2p1 12655 // The operand must be either an l-value or a function designator 12656 if (!op->getType()->isFunctionType()) { 12657 // Use a special diagnostic for loads from property references. 12658 if (isa<PseudoObjectExpr>(op)) { 12659 AddressOfError = AO_Property_Expansion; 12660 } else { 12661 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 12662 << op->getType() << op->getSourceRange(); 12663 return QualType(); 12664 } 12665 } 12666 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 12667 // The operand cannot be a bit-field 12668 AddressOfError = AO_Bit_Field; 12669 } else if (op->getObjectKind() == OK_VectorComponent) { 12670 // The operand cannot be an element of a vector 12671 AddressOfError = AO_Vector_Element; 12672 } else if (dcl) { // C99 6.5.3.2p1 12673 // We have an lvalue with a decl. Make sure the decl is not declared 12674 // with the register storage-class specifier. 12675 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 12676 // in C++ it is not error to take address of a register 12677 // variable (c++03 7.1.1P3) 12678 if (vd->getStorageClass() == SC_Register && 12679 !getLangOpts().CPlusPlus) { 12680 AddressOfError = AO_Register_Variable; 12681 } 12682 } else if (isa<MSPropertyDecl>(dcl)) { 12683 AddressOfError = AO_Property_Expansion; 12684 } else if (isa<FunctionTemplateDecl>(dcl)) { 12685 return Context.OverloadTy; 12686 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 12687 // Okay: we can take the address of a field. 12688 // Could be a pointer to member, though, if there is an explicit 12689 // scope qualifier for the class. 12690 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 12691 DeclContext *Ctx = dcl->getDeclContext(); 12692 if (Ctx && Ctx->isRecord()) { 12693 if (dcl->getType()->isReferenceType()) { 12694 Diag(OpLoc, 12695 diag::err_cannot_form_pointer_to_member_of_reference_type) 12696 << dcl->getDeclName() << dcl->getType(); 12697 return QualType(); 12698 } 12699 12700 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 12701 Ctx = Ctx->getParent(); 12702 12703 QualType MPTy = Context.getMemberPointerType( 12704 op->getType(), 12705 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 12706 // Under the MS ABI, lock down the inheritance model now. 12707 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 12708 (void)isCompleteType(OpLoc, MPTy); 12709 return MPTy; 12710 } 12711 } 12712 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 12713 !isa<BindingDecl>(dcl)) 12714 llvm_unreachable("Unknown/unexpected decl type"); 12715 } 12716 12717 if (AddressOfError != AO_No_Error) { 12718 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 12719 return QualType(); 12720 } 12721 12722 if (lval == Expr::LV_IncompleteVoidType) { 12723 // Taking the address of a void variable is technically illegal, but we 12724 // allow it in cases which are otherwise valid. 12725 // Example: "extern void x; void* y = &x;". 12726 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 12727 } 12728 12729 // If the operand has type "type", the result has type "pointer to type". 12730 if (op->getType()->isObjCObjectType()) 12731 return Context.getObjCObjectPointerType(op->getType()); 12732 12733 CheckAddressOfPackedMember(op); 12734 12735 return Context.getPointerType(op->getType()); 12736 } 12737 12738 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 12739 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 12740 if (!DRE) 12741 return; 12742 const Decl *D = DRE->getDecl(); 12743 if (!D) 12744 return; 12745 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 12746 if (!Param) 12747 return; 12748 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 12749 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 12750 return; 12751 if (FunctionScopeInfo *FD = S.getCurFunction()) 12752 if (!FD->ModifiedNonNullParams.count(Param)) 12753 FD->ModifiedNonNullParams.insert(Param); 12754 } 12755 12756 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 12757 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 12758 SourceLocation OpLoc) { 12759 if (Op->isTypeDependent()) 12760 return S.Context.DependentTy; 12761 12762 ExprResult ConvResult = S.UsualUnaryConversions(Op); 12763 if (ConvResult.isInvalid()) 12764 return QualType(); 12765 Op = ConvResult.get(); 12766 QualType OpTy = Op->getType(); 12767 QualType Result; 12768 12769 if (isa<CXXReinterpretCastExpr>(Op)) { 12770 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 12771 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 12772 Op->getSourceRange()); 12773 } 12774 12775 if (const PointerType *PT = OpTy->getAs<PointerType>()) 12776 { 12777 Result = PT->getPointeeType(); 12778 } 12779 else if (const ObjCObjectPointerType *OPT = 12780 OpTy->getAs<ObjCObjectPointerType>()) 12781 Result = OPT->getPointeeType(); 12782 else { 12783 ExprResult PR = S.CheckPlaceholderExpr(Op); 12784 if (PR.isInvalid()) return QualType(); 12785 if (PR.get() != Op) 12786 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 12787 } 12788 12789 if (Result.isNull()) { 12790 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 12791 << OpTy << Op->getSourceRange(); 12792 return QualType(); 12793 } 12794 12795 // Note that per both C89 and C99, indirection is always legal, even if Result 12796 // is an incomplete type or void. It would be possible to warn about 12797 // dereferencing a void pointer, but it's completely well-defined, and such a 12798 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 12799 // for pointers to 'void' but is fine for any other pointer type: 12800 // 12801 // C++ [expr.unary.op]p1: 12802 // [...] the expression to which [the unary * operator] is applied shall 12803 // be a pointer to an object type, or a pointer to a function type 12804 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 12805 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 12806 << OpTy << Op->getSourceRange(); 12807 12808 // Dereferences are usually l-values... 12809 VK = VK_LValue; 12810 12811 // ...except that certain expressions are never l-values in C. 12812 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 12813 VK = VK_RValue; 12814 12815 return Result; 12816 } 12817 12818 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 12819 BinaryOperatorKind Opc; 12820 switch (Kind) { 12821 default: llvm_unreachable("Unknown binop!"); 12822 case tok::periodstar: Opc = BO_PtrMemD; break; 12823 case tok::arrowstar: Opc = BO_PtrMemI; break; 12824 case tok::star: Opc = BO_Mul; break; 12825 case tok::slash: Opc = BO_Div; break; 12826 case tok::percent: Opc = BO_Rem; break; 12827 case tok::plus: Opc = BO_Add; break; 12828 case tok::minus: Opc = BO_Sub; break; 12829 case tok::lessless: Opc = BO_Shl; break; 12830 case tok::greatergreater: Opc = BO_Shr; break; 12831 case tok::lessequal: Opc = BO_LE; break; 12832 case tok::less: Opc = BO_LT; break; 12833 case tok::greaterequal: Opc = BO_GE; break; 12834 case tok::greater: Opc = BO_GT; break; 12835 case tok::exclaimequal: Opc = BO_NE; break; 12836 case tok::equalequal: Opc = BO_EQ; break; 12837 case tok::spaceship: Opc = BO_Cmp; break; 12838 case tok::amp: Opc = BO_And; break; 12839 case tok::caret: Opc = BO_Xor; break; 12840 case tok::pipe: Opc = BO_Or; break; 12841 case tok::ampamp: Opc = BO_LAnd; break; 12842 case tok::pipepipe: Opc = BO_LOr; break; 12843 case tok::equal: Opc = BO_Assign; break; 12844 case tok::starequal: Opc = BO_MulAssign; break; 12845 case tok::slashequal: Opc = BO_DivAssign; break; 12846 case tok::percentequal: Opc = BO_RemAssign; break; 12847 case tok::plusequal: Opc = BO_AddAssign; break; 12848 case tok::minusequal: Opc = BO_SubAssign; break; 12849 case tok::lesslessequal: Opc = BO_ShlAssign; break; 12850 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 12851 case tok::ampequal: Opc = BO_AndAssign; break; 12852 case tok::caretequal: Opc = BO_XorAssign; break; 12853 case tok::pipeequal: Opc = BO_OrAssign; break; 12854 case tok::comma: Opc = BO_Comma; break; 12855 } 12856 return Opc; 12857 } 12858 12859 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12860 tok::TokenKind Kind) { 12861 UnaryOperatorKind Opc; 12862 switch (Kind) { 12863 default: llvm_unreachable("Unknown unary op!"); 12864 case tok::plusplus: Opc = UO_PreInc; break; 12865 case tok::minusminus: Opc = UO_PreDec; break; 12866 case tok::amp: Opc = UO_AddrOf; break; 12867 case tok::star: Opc = UO_Deref; break; 12868 case tok::plus: Opc = UO_Plus; break; 12869 case tok::minus: Opc = UO_Minus; break; 12870 case tok::tilde: Opc = UO_Not; break; 12871 case tok::exclaim: Opc = UO_LNot; break; 12872 case tok::kw___real: Opc = UO_Real; break; 12873 case tok::kw___imag: Opc = UO_Imag; break; 12874 case tok::kw___extension__: Opc = UO_Extension; break; 12875 } 12876 return Opc; 12877 } 12878 12879 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12880 /// This warning suppressed in the event of macro expansions. 12881 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12882 SourceLocation OpLoc, bool IsBuiltin) { 12883 if (S.inTemplateInstantiation()) 12884 return; 12885 if (S.isUnevaluatedContext()) 12886 return; 12887 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12888 return; 12889 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12890 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12891 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12892 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12893 if (!LHSDeclRef || !RHSDeclRef || 12894 LHSDeclRef->getLocation().isMacroID() || 12895 RHSDeclRef->getLocation().isMacroID()) 12896 return; 12897 const ValueDecl *LHSDecl = 12898 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12899 const ValueDecl *RHSDecl = 12900 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12901 if (LHSDecl != RHSDecl) 12902 return; 12903 if (LHSDecl->getType().isVolatileQualified()) 12904 return; 12905 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12906 if (RefTy->getPointeeType().isVolatileQualified()) 12907 return; 12908 12909 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12910 : diag::warn_self_assignment_overloaded) 12911 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12912 << RHSExpr->getSourceRange(); 12913 } 12914 12915 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12916 /// is usually indicative of introspection within the Objective-C pointer. 12917 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12918 SourceLocation OpLoc) { 12919 if (!S.getLangOpts().ObjC) 12920 return; 12921 12922 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12923 const Expr *LHS = L.get(); 12924 const Expr *RHS = R.get(); 12925 12926 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12927 ObjCPointerExpr = LHS; 12928 OtherExpr = RHS; 12929 } 12930 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12931 ObjCPointerExpr = RHS; 12932 OtherExpr = LHS; 12933 } 12934 12935 // This warning is deliberately made very specific to reduce false 12936 // positives with logic that uses '&' for hashing. This logic mainly 12937 // looks for code trying to introspect into tagged pointers, which 12938 // code should generally never do. 12939 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12940 unsigned Diag = diag::warn_objc_pointer_masking; 12941 // Determine if we are introspecting the result of performSelectorXXX. 12942 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12943 // Special case messages to -performSelector and friends, which 12944 // can return non-pointer values boxed in a pointer value. 12945 // Some clients may wish to silence warnings in this subcase. 12946 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12947 Selector S = ME->getSelector(); 12948 StringRef SelArg0 = S.getNameForSlot(0); 12949 if (SelArg0.startswith("performSelector")) 12950 Diag = diag::warn_objc_pointer_masking_performSelector; 12951 } 12952 12953 S.Diag(OpLoc, Diag) 12954 << ObjCPointerExpr->getSourceRange(); 12955 } 12956 } 12957 12958 static NamedDecl *getDeclFromExpr(Expr *E) { 12959 if (!E) 12960 return nullptr; 12961 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12962 return DRE->getDecl(); 12963 if (auto *ME = dyn_cast<MemberExpr>(E)) 12964 return ME->getMemberDecl(); 12965 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12966 return IRE->getDecl(); 12967 return nullptr; 12968 } 12969 12970 // This helper function promotes a binary operator's operands (which are of a 12971 // half vector type) to a vector of floats and then truncates the result to 12972 // a vector of either half or short. 12973 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12974 BinaryOperatorKind Opc, QualType ResultTy, 12975 ExprValueKind VK, ExprObjectKind OK, 12976 bool IsCompAssign, SourceLocation OpLoc, 12977 FPOptions FPFeatures) { 12978 auto &Context = S.getASTContext(); 12979 assert((isVector(ResultTy, Context.HalfTy) || 12980 isVector(ResultTy, Context.ShortTy)) && 12981 "Result must be a vector of half or short"); 12982 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12983 isVector(RHS.get()->getType(), Context.HalfTy) && 12984 "both operands expected to be a half vector"); 12985 12986 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12987 QualType BinOpResTy = RHS.get()->getType(); 12988 12989 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12990 // change BinOpResTy to a vector of ints. 12991 if (isVector(ResultTy, Context.ShortTy)) 12992 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12993 12994 if (IsCompAssign) 12995 return new (Context) CompoundAssignOperator( 12996 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12997 OpLoc, FPFeatures); 12998 12999 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13000 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 13001 VK, OK, OpLoc, FPFeatures); 13002 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13003 } 13004 13005 static std::pair<ExprResult, ExprResult> 13006 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13007 Expr *RHSExpr) { 13008 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13009 if (!S.getLangOpts().CPlusPlus) { 13010 // C cannot handle TypoExpr nodes on either side of a binop because it 13011 // doesn't handle dependent types properly, so make sure any TypoExprs have 13012 // been dealt with before checking the operands. 13013 LHS = S.CorrectDelayedTyposInExpr(LHS); 13014 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 13015 if (Opc != BO_Assign) 13016 return ExprResult(E); 13017 // Avoid correcting the RHS to the same Expr as the LHS. 13018 Decl *D = getDeclFromExpr(E); 13019 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13020 }); 13021 } 13022 return std::make_pair(LHS, RHS); 13023 } 13024 13025 /// Returns true if conversion between vectors of halfs and vectors of floats 13026 /// is needed. 13027 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13028 Expr *E0, Expr *E1 = nullptr) { 13029 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13030 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13031 return false; 13032 13033 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13034 QualType Ty = E->IgnoreImplicit()->getType(); 13035 13036 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13037 // to vectors of floats. Although the element type of the vectors is __fp16, 13038 // the vectors shouldn't be treated as storage-only types. See the 13039 // discussion here: https://reviews.llvm.org/rG825235c140e7 13040 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13041 if (VT->getVectorKind() == VectorType::NeonVector) 13042 return false; 13043 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13044 } 13045 return false; 13046 }; 13047 13048 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13049 } 13050 13051 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13052 /// operator @p Opc at location @c TokLoc. This routine only supports 13053 /// built-in operations; ActOnBinOp handles overloaded operators. 13054 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13055 BinaryOperatorKind Opc, 13056 Expr *LHSExpr, Expr *RHSExpr) { 13057 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13058 // The syntax only allows initializer lists on the RHS of assignment, 13059 // so we don't need to worry about accepting invalid code for 13060 // non-assignment operators. 13061 // C++11 5.17p9: 13062 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13063 // of x = {} is x = T(). 13064 InitializationKind Kind = InitializationKind::CreateDirectList( 13065 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13066 InitializedEntity Entity = 13067 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13068 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13069 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13070 if (Init.isInvalid()) 13071 return Init; 13072 RHSExpr = Init.get(); 13073 } 13074 13075 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13076 QualType ResultTy; // Result type of the binary operator. 13077 // The following two variables are used for compound assignment operators 13078 QualType CompLHSTy; // Type of LHS after promotions for computation 13079 QualType CompResultTy; // Type of computation result 13080 ExprValueKind VK = VK_RValue; 13081 ExprObjectKind OK = OK_Ordinary; 13082 bool ConvertHalfVec = false; 13083 13084 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13085 if (!LHS.isUsable() || !RHS.isUsable()) 13086 return ExprError(); 13087 13088 if (getLangOpts().OpenCL) { 13089 QualType LHSTy = LHSExpr->getType(); 13090 QualType RHSTy = RHSExpr->getType(); 13091 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13092 // the ATOMIC_VAR_INIT macro. 13093 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13094 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13095 if (BO_Assign == Opc) 13096 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13097 else 13098 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13099 return ExprError(); 13100 } 13101 13102 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13103 // only with a builtin functions and therefore should be disallowed here. 13104 if (LHSTy->isImageType() || RHSTy->isImageType() || 13105 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13106 LHSTy->isPipeType() || RHSTy->isPipeType() || 13107 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13108 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13109 return ExprError(); 13110 } 13111 } 13112 13113 // Diagnose operations on the unsupported types for OpenMP device compilation. 13114 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13115 if (Opc != BO_Assign && Opc != BO_Comma) { 13116 checkOpenMPDeviceExpr(LHSExpr); 13117 checkOpenMPDeviceExpr(RHSExpr); 13118 } 13119 } 13120 13121 switch (Opc) { 13122 case BO_Assign: 13123 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13124 if (getLangOpts().CPlusPlus && 13125 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13126 VK = LHS.get()->getValueKind(); 13127 OK = LHS.get()->getObjectKind(); 13128 } 13129 if (!ResultTy.isNull()) { 13130 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13131 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 13132 13133 // Avoid copying a block to the heap if the block is assigned to a local 13134 // auto variable that is declared in the same scope as the block. This 13135 // optimization is unsafe if the local variable is declared in an outer 13136 // scope. For example: 13137 // 13138 // BlockTy b; 13139 // { 13140 // b = ^{...}; 13141 // } 13142 // // It is unsafe to invoke the block here if it wasn't copied to the 13143 // // heap. 13144 // b(); 13145 13146 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 13147 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 13148 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 13149 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 13150 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13151 13152 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13153 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 13154 NTCUC_Assignment, NTCUK_Copy); 13155 } 13156 RecordModifiableNonNullParam(*this, LHS.get()); 13157 break; 13158 case BO_PtrMemD: 13159 case BO_PtrMemI: 13160 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 13161 Opc == BO_PtrMemI); 13162 break; 13163 case BO_Mul: 13164 case BO_Div: 13165 ConvertHalfVec = true; 13166 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 13167 Opc == BO_Div); 13168 break; 13169 case BO_Rem: 13170 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 13171 break; 13172 case BO_Add: 13173 ConvertHalfVec = true; 13174 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 13175 break; 13176 case BO_Sub: 13177 ConvertHalfVec = true; 13178 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 13179 break; 13180 case BO_Shl: 13181 case BO_Shr: 13182 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 13183 break; 13184 case BO_LE: 13185 case BO_LT: 13186 case BO_GE: 13187 case BO_GT: 13188 ConvertHalfVec = true; 13189 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13190 break; 13191 case BO_EQ: 13192 case BO_NE: 13193 ConvertHalfVec = true; 13194 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13195 break; 13196 case BO_Cmp: 13197 ConvertHalfVec = true; 13198 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 13199 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 13200 break; 13201 case BO_And: 13202 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 13203 LLVM_FALLTHROUGH; 13204 case BO_Xor: 13205 case BO_Or: 13206 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13207 break; 13208 case BO_LAnd: 13209 case BO_LOr: 13210 ConvertHalfVec = true; 13211 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 13212 break; 13213 case BO_MulAssign: 13214 case BO_DivAssign: 13215 ConvertHalfVec = true; 13216 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 13217 Opc == BO_DivAssign); 13218 CompLHSTy = CompResultTy; 13219 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13220 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13221 break; 13222 case BO_RemAssign: 13223 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 13224 CompLHSTy = CompResultTy; 13225 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13226 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13227 break; 13228 case BO_AddAssign: 13229 ConvertHalfVec = true; 13230 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 13231 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13232 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13233 break; 13234 case BO_SubAssign: 13235 ConvertHalfVec = true; 13236 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 13237 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13238 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13239 break; 13240 case BO_ShlAssign: 13241 case BO_ShrAssign: 13242 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 13243 CompLHSTy = CompResultTy; 13244 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13245 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13246 break; 13247 case BO_AndAssign: 13248 case BO_OrAssign: // fallthrough 13249 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 13250 LLVM_FALLTHROUGH; 13251 case BO_XorAssign: 13252 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 13253 CompLHSTy = CompResultTy; 13254 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 13255 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 13256 break; 13257 case BO_Comma: 13258 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 13259 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 13260 VK = RHS.get()->getValueKind(); 13261 OK = RHS.get()->getObjectKind(); 13262 } 13263 break; 13264 } 13265 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 13266 return ExprError(); 13267 13268 if (ResultTy->isRealFloatingType() && 13269 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest || 13270 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore)) 13271 // Mark the current function as usng floating point constrained intrinsics 13272 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13273 F->setUsesFPIntrin(true); 13274 } 13275 13276 // Some of the binary operations require promoting operands of half vector to 13277 // float vectors and truncating the result back to half vector. For now, we do 13278 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 13279 // arm64). 13280 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 13281 isVector(LHS.get()->getType(), Context.HalfTy) && 13282 "both sides are half vectors or neither sides are"); 13283 ConvertHalfVec = 13284 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 13285 13286 // Check for array bounds violations for both sides of the BinaryOperator 13287 CheckArrayAccess(LHS.get()); 13288 CheckArrayAccess(RHS.get()); 13289 13290 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 13291 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 13292 &Context.Idents.get("object_setClass"), 13293 SourceLocation(), LookupOrdinaryName); 13294 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 13295 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 13296 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 13297 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 13298 "object_setClass(") 13299 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 13300 ",") 13301 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 13302 } 13303 else 13304 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 13305 } 13306 else if (const ObjCIvarRefExpr *OIRE = 13307 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 13308 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 13309 13310 // Opc is not a compound assignment if CompResultTy is null. 13311 if (CompResultTy.isNull()) { 13312 if (ConvertHalfVec) 13313 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 13314 OpLoc, FPFeatures); 13315 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 13316 OK, OpLoc, FPFeatures); 13317 } 13318 13319 // Handle compound assignments. 13320 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 13321 OK_ObjCProperty) { 13322 VK = VK_LValue; 13323 OK = LHS.get()->getObjectKind(); 13324 } 13325 13326 if (ConvertHalfVec) 13327 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 13328 OpLoc, FPFeatures); 13329 13330 return new (Context) CompoundAssignOperator( 13331 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 13332 OpLoc, FPFeatures); 13333 } 13334 13335 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 13336 /// operators are mixed in a way that suggests that the programmer forgot that 13337 /// comparison operators have higher precedence. The most typical example of 13338 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 13339 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 13340 SourceLocation OpLoc, Expr *LHSExpr, 13341 Expr *RHSExpr) { 13342 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 13343 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 13344 13345 // Check that one of the sides is a comparison operator and the other isn't. 13346 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 13347 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 13348 if (isLeftComp == isRightComp) 13349 return; 13350 13351 // Bitwise operations are sometimes used as eager logical ops. 13352 // Don't diagnose this. 13353 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 13354 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 13355 if (isLeftBitwise || isRightBitwise) 13356 return; 13357 13358 SourceRange DiagRange = isLeftComp 13359 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 13360 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 13361 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 13362 SourceRange ParensRange = 13363 isLeftComp 13364 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 13365 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 13366 13367 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 13368 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 13369 SuggestParentheses(Self, OpLoc, 13370 Self.PDiag(diag::note_precedence_silence) << OpStr, 13371 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 13372 SuggestParentheses(Self, OpLoc, 13373 Self.PDiag(diag::note_precedence_bitwise_first) 13374 << BinaryOperator::getOpcodeStr(Opc), 13375 ParensRange); 13376 } 13377 13378 /// It accepts a '&&' expr that is inside a '||' one. 13379 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 13380 /// in parentheses. 13381 static void 13382 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 13383 BinaryOperator *Bop) { 13384 assert(Bop->getOpcode() == BO_LAnd); 13385 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 13386 << Bop->getSourceRange() << OpLoc; 13387 SuggestParentheses(Self, Bop->getOperatorLoc(), 13388 Self.PDiag(diag::note_precedence_silence) 13389 << Bop->getOpcodeStr(), 13390 Bop->getSourceRange()); 13391 } 13392 13393 /// Returns true if the given expression can be evaluated as a constant 13394 /// 'true'. 13395 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 13396 bool Res; 13397 return !E->isValueDependent() && 13398 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 13399 } 13400 13401 /// Returns true if the given expression can be evaluated as a constant 13402 /// 'false'. 13403 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 13404 bool Res; 13405 return !E->isValueDependent() && 13406 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 13407 } 13408 13409 /// Look for '&&' in the left hand of a '||' expr. 13410 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 13411 Expr *LHSExpr, Expr *RHSExpr) { 13412 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 13413 if (Bop->getOpcode() == BO_LAnd) { 13414 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 13415 if (EvaluatesAsFalse(S, RHSExpr)) 13416 return; 13417 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 13418 if (!EvaluatesAsTrue(S, Bop->getLHS())) 13419 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13420 } else if (Bop->getOpcode() == BO_LOr) { 13421 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 13422 // If it's "a || b && 1 || c" we didn't warn earlier for 13423 // "a || b && 1", but warn now. 13424 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 13425 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 13426 } 13427 } 13428 } 13429 } 13430 13431 /// Look for '&&' in the right hand of a '||' expr. 13432 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 13433 Expr *LHSExpr, Expr *RHSExpr) { 13434 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 13435 if (Bop->getOpcode() == BO_LAnd) { 13436 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 13437 if (EvaluatesAsFalse(S, LHSExpr)) 13438 return; 13439 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 13440 if (!EvaluatesAsTrue(S, Bop->getRHS())) 13441 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 13442 } 13443 } 13444 } 13445 13446 /// Look for bitwise op in the left or right hand of a bitwise op with 13447 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 13448 /// the '&' expression in parentheses. 13449 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 13450 SourceLocation OpLoc, Expr *SubExpr) { 13451 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13452 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 13453 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 13454 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 13455 << Bop->getSourceRange() << OpLoc; 13456 SuggestParentheses(S, Bop->getOperatorLoc(), 13457 S.PDiag(diag::note_precedence_silence) 13458 << Bop->getOpcodeStr(), 13459 Bop->getSourceRange()); 13460 } 13461 } 13462 } 13463 13464 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 13465 Expr *SubExpr, StringRef Shift) { 13466 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 13467 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 13468 StringRef Op = Bop->getOpcodeStr(); 13469 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 13470 << Bop->getSourceRange() << OpLoc << Shift << Op; 13471 SuggestParentheses(S, Bop->getOperatorLoc(), 13472 S.PDiag(diag::note_precedence_silence) << Op, 13473 Bop->getSourceRange()); 13474 } 13475 } 13476 } 13477 13478 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 13479 Expr *LHSExpr, Expr *RHSExpr) { 13480 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 13481 if (!OCE) 13482 return; 13483 13484 FunctionDecl *FD = OCE->getDirectCallee(); 13485 if (!FD || !FD->isOverloadedOperator()) 13486 return; 13487 13488 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 13489 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 13490 return; 13491 13492 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 13493 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 13494 << (Kind == OO_LessLess); 13495 SuggestParentheses(S, OCE->getOperatorLoc(), 13496 S.PDiag(diag::note_precedence_silence) 13497 << (Kind == OO_LessLess ? "<<" : ">>"), 13498 OCE->getSourceRange()); 13499 SuggestParentheses( 13500 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 13501 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 13502 } 13503 13504 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 13505 /// precedence. 13506 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 13507 SourceLocation OpLoc, Expr *LHSExpr, 13508 Expr *RHSExpr){ 13509 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 13510 if (BinaryOperator::isBitwiseOp(Opc)) 13511 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 13512 13513 // Diagnose "arg1 & arg2 | arg3" 13514 if ((Opc == BO_Or || Opc == BO_Xor) && 13515 !OpLoc.isMacroID()/* Don't warn in macros. */) { 13516 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 13517 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 13518 } 13519 13520 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 13521 // We don't warn for 'assert(a || b && "bad")' since this is safe. 13522 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 13523 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 13524 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 13525 } 13526 13527 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 13528 || Opc == BO_Shr) { 13529 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 13530 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 13531 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 13532 } 13533 13534 // Warn on overloaded shift operators and comparisons, such as: 13535 // cout << 5 == 4; 13536 if (BinaryOperator::isComparisonOp(Opc)) 13537 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 13538 } 13539 13540 // Binary Operators. 'Tok' is the token for the operator. 13541 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 13542 tok::TokenKind Kind, 13543 Expr *LHSExpr, Expr *RHSExpr) { 13544 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 13545 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 13546 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 13547 13548 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 13549 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 13550 13551 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 13552 } 13553 13554 /// Build an overloaded binary operator expression in the given scope. 13555 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 13556 BinaryOperatorKind Opc, 13557 Expr *LHS, Expr *RHS) { 13558 switch (Opc) { 13559 case BO_Assign: 13560 case BO_DivAssign: 13561 case BO_RemAssign: 13562 case BO_SubAssign: 13563 case BO_AndAssign: 13564 case BO_OrAssign: 13565 case BO_XorAssign: 13566 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 13567 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 13568 break; 13569 default: 13570 break; 13571 } 13572 13573 // Find all of the overloaded operators visible from this 13574 // point. We perform both an operator-name lookup from the local 13575 // scope and an argument-dependent lookup based on the types of 13576 // the arguments. 13577 UnresolvedSet<16> Functions; 13578 OverloadedOperatorKind OverOp 13579 = BinaryOperator::getOverloadedOperator(Opc); 13580 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 13581 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 13582 RHS->getType(), Functions); 13583 13584 // In C++20 onwards, we may have a second operator to look up. 13585 if (S.getLangOpts().CPlusPlus2a) { 13586 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 13587 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(), 13588 RHS->getType(), Functions); 13589 } 13590 13591 // Build the (potentially-overloaded, potentially-dependent) 13592 // binary operation. 13593 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 13594 } 13595 13596 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 13597 BinaryOperatorKind Opc, 13598 Expr *LHSExpr, Expr *RHSExpr) { 13599 ExprResult LHS, RHS; 13600 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13601 if (!LHS.isUsable() || !RHS.isUsable()) 13602 return ExprError(); 13603 LHSExpr = LHS.get(); 13604 RHSExpr = RHS.get(); 13605 13606 // We want to end up calling one of checkPseudoObjectAssignment 13607 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 13608 // both expressions are overloadable or either is type-dependent), 13609 // or CreateBuiltinBinOp (in any other case). We also want to get 13610 // any placeholder types out of the way. 13611 13612 // Handle pseudo-objects in the LHS. 13613 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 13614 // Assignments with a pseudo-object l-value need special analysis. 13615 if (pty->getKind() == BuiltinType::PseudoObject && 13616 BinaryOperator::isAssignmentOp(Opc)) 13617 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 13618 13619 // Don't resolve overloads if the other type is overloadable. 13620 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 13621 // We can't actually test that if we still have a placeholder, 13622 // though. Fortunately, none of the exceptions we see in that 13623 // code below are valid when the LHS is an overload set. Note 13624 // that an overload set can be dependently-typed, but it never 13625 // instantiates to having an overloadable type. 13626 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13627 if (resolvedRHS.isInvalid()) return ExprError(); 13628 RHSExpr = resolvedRHS.get(); 13629 13630 if (RHSExpr->isTypeDependent() || 13631 RHSExpr->getType()->isOverloadableType()) 13632 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13633 } 13634 13635 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 13636 // template, diagnose the missing 'template' keyword instead of diagnosing 13637 // an invalid use of a bound member function. 13638 // 13639 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 13640 // to C++1z [over.over]/1.4, but we already checked for that case above. 13641 if (Opc == BO_LT && inTemplateInstantiation() && 13642 (pty->getKind() == BuiltinType::BoundMember || 13643 pty->getKind() == BuiltinType::Overload)) { 13644 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 13645 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 13646 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 13647 return isa<FunctionTemplateDecl>(ND); 13648 })) { 13649 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 13650 : OE->getNameLoc(), 13651 diag::err_template_kw_missing) 13652 << OE->getName().getAsString() << ""; 13653 return ExprError(); 13654 } 13655 } 13656 13657 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 13658 if (LHS.isInvalid()) return ExprError(); 13659 LHSExpr = LHS.get(); 13660 } 13661 13662 // Handle pseudo-objects in the RHS. 13663 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 13664 // An overload in the RHS can potentially be resolved by the type 13665 // being assigned to. 13666 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 13667 if (getLangOpts().CPlusPlus && 13668 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 13669 LHSExpr->getType()->isOverloadableType())) 13670 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13671 13672 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13673 } 13674 13675 // Don't resolve overloads if the other type is overloadable. 13676 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 13677 LHSExpr->getType()->isOverloadableType()) 13678 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13679 13680 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 13681 if (!resolvedRHS.isUsable()) return ExprError(); 13682 RHSExpr = resolvedRHS.get(); 13683 } 13684 13685 if (getLangOpts().CPlusPlus) { 13686 // If either expression is type-dependent, always build an 13687 // overloaded op. 13688 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 13689 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13690 13691 // Otherwise, build an overloaded op if either expression has an 13692 // overloadable type. 13693 if (LHSExpr->getType()->isOverloadableType() || 13694 RHSExpr->getType()->isOverloadableType()) 13695 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 13696 } 13697 13698 // Build a built-in binary operation. 13699 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 13700 } 13701 13702 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 13703 if (T.isNull() || T->isDependentType()) 13704 return false; 13705 13706 if (!T->isPromotableIntegerType()) 13707 return true; 13708 13709 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 13710 } 13711 13712 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 13713 UnaryOperatorKind Opc, 13714 Expr *InputExpr) { 13715 ExprResult Input = InputExpr; 13716 ExprValueKind VK = VK_RValue; 13717 ExprObjectKind OK = OK_Ordinary; 13718 QualType resultType; 13719 bool CanOverflow = false; 13720 13721 bool ConvertHalfVec = false; 13722 if (getLangOpts().OpenCL) { 13723 QualType Ty = InputExpr->getType(); 13724 // The only legal unary operation for atomics is '&'. 13725 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 13726 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13727 // only with a builtin functions and therefore should be disallowed here. 13728 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 13729 || Ty->isBlockPointerType())) { 13730 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13731 << InputExpr->getType() 13732 << Input.get()->getSourceRange()); 13733 } 13734 } 13735 // Diagnose operations on the unsupported types for OpenMP device compilation. 13736 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) { 13737 if (UnaryOperator::isIncrementDecrementOp(Opc) || 13738 UnaryOperator::isArithmeticOp(Opc)) 13739 checkOpenMPDeviceExpr(InputExpr); 13740 } 13741 13742 switch (Opc) { 13743 case UO_PreInc: 13744 case UO_PreDec: 13745 case UO_PostInc: 13746 case UO_PostDec: 13747 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 13748 OpLoc, 13749 Opc == UO_PreInc || 13750 Opc == UO_PostInc, 13751 Opc == UO_PreInc || 13752 Opc == UO_PreDec); 13753 CanOverflow = isOverflowingIntegerType(Context, resultType); 13754 break; 13755 case UO_AddrOf: 13756 resultType = CheckAddressOfOperand(Input, OpLoc); 13757 CheckAddressOfNoDeref(InputExpr); 13758 RecordModifiableNonNullParam(*this, InputExpr); 13759 break; 13760 case UO_Deref: { 13761 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13762 if (Input.isInvalid()) return ExprError(); 13763 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 13764 break; 13765 } 13766 case UO_Plus: 13767 case UO_Minus: 13768 CanOverflow = Opc == UO_Minus && 13769 isOverflowingIntegerType(Context, Input.get()->getType()); 13770 Input = UsualUnaryConversions(Input.get()); 13771 if (Input.isInvalid()) return ExprError(); 13772 // Unary plus and minus require promoting an operand of half vector to a 13773 // float vector and truncating the result back to a half vector. For now, we 13774 // do this only when HalfArgsAndReturns is set (that is, when the target is 13775 // arm or arm64). 13776 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 13777 13778 // If the operand is a half vector, promote it to a float vector. 13779 if (ConvertHalfVec) 13780 Input = convertVector(Input.get(), Context.FloatTy, *this); 13781 resultType = Input.get()->getType(); 13782 if (resultType->isDependentType()) 13783 break; 13784 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 13785 break; 13786 else if (resultType->isVectorType() && 13787 // The z vector extensions don't allow + or - with bool vectors. 13788 (!Context.getLangOpts().ZVector || 13789 resultType->castAs<VectorType>()->getVectorKind() != 13790 VectorType::AltiVecBool)) 13791 break; 13792 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 13793 Opc == UO_Plus && 13794 resultType->isPointerType()) 13795 break; 13796 13797 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13798 << resultType << Input.get()->getSourceRange()); 13799 13800 case UO_Not: // bitwise complement 13801 Input = UsualUnaryConversions(Input.get()); 13802 if (Input.isInvalid()) 13803 return ExprError(); 13804 resultType = Input.get()->getType(); 13805 if (resultType->isDependentType()) 13806 break; 13807 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 13808 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 13809 // C99 does not support '~' for complex conjugation. 13810 Diag(OpLoc, diag::ext_integer_complement_complex) 13811 << resultType << Input.get()->getSourceRange(); 13812 else if (resultType->hasIntegerRepresentation()) 13813 break; 13814 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 13815 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 13816 // on vector float types. 13817 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13818 if (!T->isIntegerType()) 13819 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13820 << resultType << Input.get()->getSourceRange()); 13821 } else { 13822 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13823 << resultType << Input.get()->getSourceRange()); 13824 } 13825 break; 13826 13827 case UO_LNot: // logical negation 13828 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 13829 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 13830 if (Input.isInvalid()) return ExprError(); 13831 resultType = Input.get()->getType(); 13832 13833 // Though we still have to promote half FP to float... 13834 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 13835 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 13836 resultType = Context.FloatTy; 13837 } 13838 13839 if (resultType->isDependentType()) 13840 break; 13841 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 13842 // C99 6.5.3.3p1: ok, fallthrough; 13843 if (Context.getLangOpts().CPlusPlus) { 13844 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 13845 // operand contextually converted to bool. 13846 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 13847 ScalarTypeToBooleanCastKind(resultType)); 13848 } else if (Context.getLangOpts().OpenCL && 13849 Context.getLangOpts().OpenCLVersion < 120) { 13850 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13851 // operate on scalar float types. 13852 if (!resultType->isIntegerType() && !resultType->isPointerType()) 13853 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13854 << resultType << Input.get()->getSourceRange()); 13855 } 13856 } else if (resultType->isExtVectorType()) { 13857 if (Context.getLangOpts().OpenCL && 13858 Context.getLangOpts().OpenCLVersion < 120 && 13859 !Context.getLangOpts().OpenCLCPlusPlus) { 13860 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 13861 // operate on vector float types. 13862 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 13863 if (!T->isIntegerType()) 13864 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13865 << resultType << Input.get()->getSourceRange()); 13866 } 13867 // Vector logical not returns the signed variant of the operand type. 13868 resultType = GetSignedVectorType(resultType); 13869 break; 13870 } else { 13871 // FIXME: GCC's vector extension permits the usage of '!' with a vector 13872 // type in C++. We should allow that here too. 13873 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 13874 << resultType << Input.get()->getSourceRange()); 13875 } 13876 13877 // LNot always has type int. C99 6.5.3.3p5. 13878 // In C++, it's bool. C++ 5.3.1p8 13879 resultType = Context.getLogicalOperationType(); 13880 break; 13881 case UO_Real: 13882 case UO_Imag: 13883 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 13884 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 13885 // complex l-values to ordinary l-values and all other values to r-values. 13886 if (Input.isInvalid()) return ExprError(); 13887 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 13888 if (Input.get()->getValueKind() != VK_RValue && 13889 Input.get()->getObjectKind() == OK_Ordinary) 13890 VK = Input.get()->getValueKind(); 13891 } else if (!getLangOpts().CPlusPlus) { 13892 // In C, a volatile scalar is read by __imag. In C++, it is not. 13893 Input = DefaultLvalueConversion(Input.get()); 13894 } 13895 break; 13896 case UO_Extension: 13897 resultType = Input.get()->getType(); 13898 VK = Input.get()->getValueKind(); 13899 OK = Input.get()->getObjectKind(); 13900 break; 13901 case UO_Coawait: 13902 // It's unnecessary to represent the pass-through operator co_await in the 13903 // AST; just return the input expression instead. 13904 assert(!Input.get()->getType()->isDependentType() && 13905 "the co_await expression must be non-dependant before " 13906 "building operator co_await"); 13907 return Input; 13908 } 13909 if (resultType.isNull() || Input.isInvalid()) 13910 return ExprError(); 13911 13912 // Check for array bounds violations in the operand of the UnaryOperator, 13913 // except for the '*' and '&' operators that have to be handled specially 13914 // by CheckArrayAccess (as there are special cases like &array[arraysize] 13915 // that are explicitly defined as valid by the standard). 13916 if (Opc != UO_AddrOf && Opc != UO_Deref) 13917 CheckArrayAccess(Input.get()); 13918 13919 auto *UO = new (Context) 13920 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 13921 13922 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 13923 !isa<ArrayType>(UO->getType().getDesugaredType(Context))) 13924 ExprEvalContexts.back().PossibleDerefs.insert(UO); 13925 13926 // Convert the result back to a half vector. 13927 if (ConvertHalfVec) 13928 return convertVector(UO, Context.HalfTy, *this); 13929 return UO; 13930 } 13931 13932 /// Determine whether the given expression is a qualified member 13933 /// access expression, of a form that could be turned into a pointer to member 13934 /// with the address-of operator. 13935 bool Sema::isQualifiedMemberAccess(Expr *E) { 13936 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13937 if (!DRE->getQualifier()) 13938 return false; 13939 13940 ValueDecl *VD = DRE->getDecl(); 13941 if (!VD->isCXXClassMember()) 13942 return false; 13943 13944 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13945 return true; 13946 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13947 return Method->isInstance(); 13948 13949 return false; 13950 } 13951 13952 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13953 if (!ULE->getQualifier()) 13954 return false; 13955 13956 for (NamedDecl *D : ULE->decls()) { 13957 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13958 if (Method->isInstance()) 13959 return true; 13960 } else { 13961 // Overload set does not contain methods. 13962 break; 13963 } 13964 } 13965 13966 return false; 13967 } 13968 13969 return false; 13970 } 13971 13972 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13973 UnaryOperatorKind Opc, Expr *Input) { 13974 // First things first: handle placeholders so that the 13975 // overloaded-operator check considers the right type. 13976 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13977 // Increment and decrement of pseudo-object references. 13978 if (pty->getKind() == BuiltinType::PseudoObject && 13979 UnaryOperator::isIncrementDecrementOp(Opc)) 13980 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13981 13982 // extension is always a builtin operator. 13983 if (Opc == UO_Extension) 13984 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13985 13986 // & gets special logic for several kinds of placeholder. 13987 // The builtin code knows what to do. 13988 if (Opc == UO_AddrOf && 13989 (pty->getKind() == BuiltinType::Overload || 13990 pty->getKind() == BuiltinType::UnknownAny || 13991 pty->getKind() == BuiltinType::BoundMember)) 13992 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13993 13994 // Anything else needs to be handled now. 13995 ExprResult Result = CheckPlaceholderExpr(Input); 13996 if (Result.isInvalid()) return ExprError(); 13997 Input = Result.get(); 13998 } 13999 14000 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14001 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14002 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14003 // Find all of the overloaded operators visible from this 14004 // point. We perform both an operator-name lookup from the local 14005 // scope and an argument-dependent lookup based on the types of 14006 // the arguments. 14007 UnresolvedSet<16> Functions; 14008 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14009 if (S && OverOp != OO_None) 14010 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 14011 Functions); 14012 14013 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14014 } 14015 14016 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14017 } 14018 14019 // Unary Operators. 'Tok' is the token for the operator. 14020 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14021 tok::TokenKind Op, Expr *Input) { 14022 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14023 } 14024 14025 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14026 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14027 LabelDecl *TheDecl) { 14028 TheDecl->markUsed(Context); 14029 // Create the AST node. The address of a label always has type 'void*'. 14030 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14031 Context.getPointerType(Context.VoidTy)); 14032 } 14033 14034 void Sema::ActOnStartStmtExpr() { 14035 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14036 } 14037 14038 void Sema::ActOnStmtExprError() { 14039 // Note that function is also called by TreeTransform when leaving a 14040 // StmtExpr scope without rebuilding anything. 14041 14042 DiscardCleanupsInEvaluationContext(); 14043 PopExpressionEvaluationContext(); 14044 } 14045 14046 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14047 SourceLocation RPLoc) { 14048 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14049 } 14050 14051 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14052 SourceLocation RPLoc, unsigned TemplateDepth) { 14053 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14054 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14055 14056 if (hasAnyUnrecoverableErrorsInThisFunction()) 14057 DiscardCleanupsInEvaluationContext(); 14058 assert(!Cleanup.exprNeedsCleanups() && 14059 "cleanups within StmtExpr not correctly bound!"); 14060 PopExpressionEvaluationContext(); 14061 14062 // FIXME: there are a variety of strange constraints to enforce here, for 14063 // example, it is not possible to goto into a stmt expression apparently. 14064 // More semantic analysis is needed. 14065 14066 // If there are sub-stmts in the compound stmt, take the type of the last one 14067 // as the type of the stmtexpr. 14068 QualType Ty = Context.VoidTy; 14069 bool StmtExprMayBindToTemp = false; 14070 if (!Compound->body_empty()) { 14071 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14072 if (const auto *LastStmt = 14073 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14074 if (const Expr *Value = LastStmt->getExprStmt()) { 14075 StmtExprMayBindToTemp = true; 14076 Ty = Value->getType(); 14077 } 14078 } 14079 } 14080 14081 // FIXME: Check that expression type is complete/non-abstract; statement 14082 // expressions are not lvalues. 14083 Expr *ResStmtExpr = 14084 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14085 if (StmtExprMayBindToTemp) 14086 return MaybeBindToTemporary(ResStmtExpr); 14087 return ResStmtExpr; 14088 } 14089 14090 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 14091 if (ER.isInvalid()) 14092 return ExprError(); 14093 14094 // Do function/array conversion on the last expression, but not 14095 // lvalue-to-rvalue. However, initialize an unqualified type. 14096 ER = DefaultFunctionArrayConversion(ER.get()); 14097 if (ER.isInvalid()) 14098 return ExprError(); 14099 Expr *E = ER.get(); 14100 14101 if (E->isTypeDependent()) 14102 return E; 14103 14104 // In ARC, if the final expression ends in a consume, splice 14105 // the consume out and bind it later. In the alternate case 14106 // (when dealing with a retainable type), the result 14107 // initialization will create a produce. In both cases the 14108 // result will be +1, and we'll need to balance that out with 14109 // a bind. 14110 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 14111 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 14112 return Cast->getSubExpr(); 14113 14114 // FIXME: Provide a better location for the initialization. 14115 return PerformCopyInitialization( 14116 InitializedEntity::InitializeStmtExprResult( 14117 E->getBeginLoc(), E->getType().getUnqualifiedType()), 14118 SourceLocation(), E); 14119 } 14120 14121 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 14122 TypeSourceInfo *TInfo, 14123 ArrayRef<OffsetOfComponent> Components, 14124 SourceLocation RParenLoc) { 14125 QualType ArgTy = TInfo->getType(); 14126 bool Dependent = ArgTy->isDependentType(); 14127 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 14128 14129 // We must have at least one component that refers to the type, and the first 14130 // one is known to be a field designator. Verify that the ArgTy represents 14131 // a struct/union/class. 14132 if (!Dependent && !ArgTy->isRecordType()) 14133 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 14134 << ArgTy << TypeRange); 14135 14136 // Type must be complete per C99 7.17p3 because a declaring a variable 14137 // with an incomplete type would be ill-formed. 14138 if (!Dependent 14139 && RequireCompleteType(BuiltinLoc, ArgTy, 14140 diag::err_offsetof_incomplete_type, TypeRange)) 14141 return ExprError(); 14142 14143 bool DidWarnAboutNonPOD = false; 14144 QualType CurrentType = ArgTy; 14145 SmallVector<OffsetOfNode, 4> Comps; 14146 SmallVector<Expr*, 4> Exprs; 14147 for (const OffsetOfComponent &OC : Components) { 14148 if (OC.isBrackets) { 14149 // Offset of an array sub-field. TODO: Should we allow vector elements? 14150 if (!CurrentType->isDependentType()) { 14151 const ArrayType *AT = Context.getAsArrayType(CurrentType); 14152 if(!AT) 14153 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 14154 << CurrentType); 14155 CurrentType = AT->getElementType(); 14156 } else 14157 CurrentType = Context.DependentTy; 14158 14159 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 14160 if (IdxRval.isInvalid()) 14161 return ExprError(); 14162 Expr *Idx = IdxRval.get(); 14163 14164 // The expression must be an integral expression. 14165 // FIXME: An integral constant expression? 14166 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 14167 !Idx->getType()->isIntegerType()) 14168 return ExprError( 14169 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 14170 << Idx->getSourceRange()); 14171 14172 // Record this array index. 14173 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 14174 Exprs.push_back(Idx); 14175 continue; 14176 } 14177 14178 // Offset of a field. 14179 if (CurrentType->isDependentType()) { 14180 // We have the offset of a field, but we can't look into the dependent 14181 // type. Just record the identifier of the field. 14182 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 14183 CurrentType = Context.DependentTy; 14184 continue; 14185 } 14186 14187 // We need to have a complete type to look into. 14188 if (RequireCompleteType(OC.LocStart, CurrentType, 14189 diag::err_offsetof_incomplete_type)) 14190 return ExprError(); 14191 14192 // Look for the designated field. 14193 const RecordType *RC = CurrentType->getAs<RecordType>(); 14194 if (!RC) 14195 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 14196 << CurrentType); 14197 RecordDecl *RD = RC->getDecl(); 14198 14199 // C++ [lib.support.types]p5: 14200 // The macro offsetof accepts a restricted set of type arguments in this 14201 // International Standard. type shall be a POD structure or a POD union 14202 // (clause 9). 14203 // C++11 [support.types]p4: 14204 // If type is not a standard-layout class (Clause 9), the results are 14205 // undefined. 14206 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14207 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 14208 unsigned DiagID = 14209 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 14210 : diag::ext_offsetof_non_pod_type; 14211 14212 if (!IsSafe && !DidWarnAboutNonPOD && 14213 DiagRuntimeBehavior(BuiltinLoc, nullptr, 14214 PDiag(DiagID) 14215 << SourceRange(Components[0].LocStart, OC.LocEnd) 14216 << CurrentType)) 14217 DidWarnAboutNonPOD = true; 14218 } 14219 14220 // Look for the field. 14221 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 14222 LookupQualifiedName(R, RD); 14223 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 14224 IndirectFieldDecl *IndirectMemberDecl = nullptr; 14225 if (!MemberDecl) { 14226 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 14227 MemberDecl = IndirectMemberDecl->getAnonField(); 14228 } 14229 14230 if (!MemberDecl) 14231 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 14232 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 14233 OC.LocEnd)); 14234 14235 // C99 7.17p3: 14236 // (If the specified member is a bit-field, the behavior is undefined.) 14237 // 14238 // We diagnose this as an error. 14239 if (MemberDecl->isBitField()) { 14240 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 14241 << MemberDecl->getDeclName() 14242 << SourceRange(BuiltinLoc, RParenLoc); 14243 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 14244 return ExprError(); 14245 } 14246 14247 RecordDecl *Parent = MemberDecl->getParent(); 14248 if (IndirectMemberDecl) 14249 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 14250 14251 // If the member was found in a base class, introduce OffsetOfNodes for 14252 // the base class indirections. 14253 CXXBasePaths Paths; 14254 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 14255 Paths)) { 14256 if (Paths.getDetectedVirtual()) { 14257 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 14258 << MemberDecl->getDeclName() 14259 << SourceRange(BuiltinLoc, RParenLoc); 14260 return ExprError(); 14261 } 14262 14263 CXXBasePath &Path = Paths.front(); 14264 for (const CXXBasePathElement &B : Path) 14265 Comps.push_back(OffsetOfNode(B.Base)); 14266 } 14267 14268 if (IndirectMemberDecl) { 14269 for (auto *FI : IndirectMemberDecl->chain()) { 14270 assert(isa<FieldDecl>(FI)); 14271 Comps.push_back(OffsetOfNode(OC.LocStart, 14272 cast<FieldDecl>(FI), OC.LocEnd)); 14273 } 14274 } else 14275 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 14276 14277 CurrentType = MemberDecl->getType().getNonReferenceType(); 14278 } 14279 14280 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 14281 Comps, Exprs, RParenLoc); 14282 } 14283 14284 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 14285 SourceLocation BuiltinLoc, 14286 SourceLocation TypeLoc, 14287 ParsedType ParsedArgTy, 14288 ArrayRef<OffsetOfComponent> Components, 14289 SourceLocation RParenLoc) { 14290 14291 TypeSourceInfo *ArgTInfo; 14292 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 14293 if (ArgTy.isNull()) 14294 return ExprError(); 14295 14296 if (!ArgTInfo) 14297 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 14298 14299 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 14300 } 14301 14302 14303 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 14304 Expr *CondExpr, 14305 Expr *LHSExpr, Expr *RHSExpr, 14306 SourceLocation RPLoc) { 14307 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 14308 14309 ExprValueKind VK = VK_RValue; 14310 ExprObjectKind OK = OK_Ordinary; 14311 QualType resType; 14312 bool CondIsTrue = false; 14313 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 14314 resType = Context.DependentTy; 14315 } else { 14316 // The conditional expression is required to be a constant expression. 14317 llvm::APSInt condEval(32); 14318 ExprResult CondICE 14319 = VerifyIntegerConstantExpression(CondExpr, &condEval, 14320 diag::err_typecheck_choose_expr_requires_constant, false); 14321 if (CondICE.isInvalid()) 14322 return ExprError(); 14323 CondExpr = CondICE.get(); 14324 CondIsTrue = condEval.getZExtValue(); 14325 14326 // If the condition is > zero, then the AST type is the same as the LHSExpr. 14327 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 14328 14329 resType = ActiveExpr->getType(); 14330 VK = ActiveExpr->getValueKind(); 14331 OK = ActiveExpr->getObjectKind(); 14332 } 14333 14334 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 14335 resType, VK, OK, RPLoc, CondIsTrue); 14336 } 14337 14338 //===----------------------------------------------------------------------===// 14339 // Clang Extensions. 14340 //===----------------------------------------------------------------------===// 14341 14342 /// ActOnBlockStart - This callback is invoked when a block literal is started. 14343 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 14344 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 14345 14346 if (LangOpts.CPlusPlus) { 14347 MangleNumberingContext *MCtx; 14348 Decl *ManglingContextDecl; 14349 std::tie(MCtx, ManglingContextDecl) = 14350 getCurrentMangleNumberContext(Block->getDeclContext()); 14351 if (MCtx) { 14352 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 14353 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 14354 } 14355 } 14356 14357 PushBlockScope(CurScope, Block); 14358 CurContext->addDecl(Block); 14359 if (CurScope) 14360 PushDeclContext(CurScope, Block); 14361 else 14362 CurContext = Block; 14363 14364 getCurBlock()->HasImplicitReturnType = true; 14365 14366 // Enter a new evaluation context to insulate the block from any 14367 // cleanups from the enclosing full-expression. 14368 PushExpressionEvaluationContext( 14369 ExpressionEvaluationContext::PotentiallyEvaluated); 14370 } 14371 14372 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 14373 Scope *CurScope) { 14374 assert(ParamInfo.getIdentifier() == nullptr && 14375 "block-id should have no identifier!"); 14376 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 14377 BlockScopeInfo *CurBlock = getCurBlock(); 14378 14379 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 14380 QualType T = Sig->getType(); 14381 14382 // FIXME: We should allow unexpanded parameter packs here, but that would, 14383 // in turn, make the block expression contain unexpanded parameter packs. 14384 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 14385 // Drop the parameters. 14386 FunctionProtoType::ExtProtoInfo EPI; 14387 EPI.HasTrailingReturn = false; 14388 EPI.TypeQuals.addConst(); 14389 T = Context.getFunctionType(Context.DependentTy, None, EPI); 14390 Sig = Context.getTrivialTypeSourceInfo(T); 14391 } 14392 14393 // GetTypeForDeclarator always produces a function type for a block 14394 // literal signature. Furthermore, it is always a FunctionProtoType 14395 // unless the function was written with a typedef. 14396 assert(T->isFunctionType() && 14397 "GetTypeForDeclarator made a non-function block signature"); 14398 14399 // Look for an explicit signature in that function type. 14400 FunctionProtoTypeLoc ExplicitSignature; 14401 14402 if ((ExplicitSignature = Sig->getTypeLoc() 14403 .getAsAdjusted<FunctionProtoTypeLoc>())) { 14404 14405 // Check whether that explicit signature was synthesized by 14406 // GetTypeForDeclarator. If so, don't save that as part of the 14407 // written signature. 14408 if (ExplicitSignature.getLocalRangeBegin() == 14409 ExplicitSignature.getLocalRangeEnd()) { 14410 // This would be much cheaper if we stored TypeLocs instead of 14411 // TypeSourceInfos. 14412 TypeLoc Result = ExplicitSignature.getReturnLoc(); 14413 unsigned Size = Result.getFullDataSize(); 14414 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 14415 Sig->getTypeLoc().initializeFullCopy(Result, Size); 14416 14417 ExplicitSignature = FunctionProtoTypeLoc(); 14418 } 14419 } 14420 14421 CurBlock->TheDecl->setSignatureAsWritten(Sig); 14422 CurBlock->FunctionType = T; 14423 14424 const FunctionType *Fn = T->getAs<FunctionType>(); 14425 QualType RetTy = Fn->getReturnType(); 14426 bool isVariadic = 14427 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 14428 14429 CurBlock->TheDecl->setIsVariadic(isVariadic); 14430 14431 // Context.DependentTy is used as a placeholder for a missing block 14432 // return type. TODO: what should we do with declarators like: 14433 // ^ * { ... } 14434 // If the answer is "apply template argument deduction".... 14435 if (RetTy != Context.DependentTy) { 14436 CurBlock->ReturnType = RetTy; 14437 CurBlock->TheDecl->setBlockMissingReturnType(false); 14438 CurBlock->HasImplicitReturnType = false; 14439 } 14440 14441 // Push block parameters from the declarator if we had them. 14442 SmallVector<ParmVarDecl*, 8> Params; 14443 if (ExplicitSignature) { 14444 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 14445 ParmVarDecl *Param = ExplicitSignature.getParam(I); 14446 if (Param->getIdentifier() == nullptr && 14447 !Param->isImplicit() && 14448 !Param->isInvalidDecl() && 14449 !getLangOpts().CPlusPlus) 14450 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 14451 Params.push_back(Param); 14452 } 14453 14454 // Fake up parameter variables if we have a typedef, like 14455 // ^ fntype { ... } 14456 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 14457 for (const auto &I : Fn->param_types()) { 14458 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 14459 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 14460 Params.push_back(Param); 14461 } 14462 } 14463 14464 // Set the parameters on the block decl. 14465 if (!Params.empty()) { 14466 CurBlock->TheDecl->setParams(Params); 14467 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 14468 /*CheckParameterNames=*/false); 14469 } 14470 14471 // Finally we can process decl attributes. 14472 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 14473 14474 // Put the parameter variables in scope. 14475 for (auto AI : CurBlock->TheDecl->parameters()) { 14476 AI->setOwningFunction(CurBlock->TheDecl); 14477 14478 // If this has an identifier, add it to the scope stack. 14479 if (AI->getIdentifier()) { 14480 CheckShadow(CurBlock->TheScope, AI); 14481 14482 PushOnScopeChains(AI, CurBlock->TheScope); 14483 } 14484 } 14485 } 14486 14487 /// ActOnBlockError - If there is an error parsing a block, this callback 14488 /// is invoked to pop the information about the block from the action impl. 14489 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 14490 // Leave the expression-evaluation context. 14491 DiscardCleanupsInEvaluationContext(); 14492 PopExpressionEvaluationContext(); 14493 14494 // Pop off CurBlock, handle nested blocks. 14495 PopDeclContext(); 14496 PopFunctionScopeInfo(); 14497 } 14498 14499 /// ActOnBlockStmtExpr - This is called when the body of a block statement 14500 /// literal was successfully completed. ^(int x){...} 14501 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 14502 Stmt *Body, Scope *CurScope) { 14503 // If blocks are disabled, emit an error. 14504 if (!LangOpts.Blocks) 14505 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 14506 14507 // Leave the expression-evaluation context. 14508 if (hasAnyUnrecoverableErrorsInThisFunction()) 14509 DiscardCleanupsInEvaluationContext(); 14510 assert(!Cleanup.exprNeedsCleanups() && 14511 "cleanups within block not correctly bound!"); 14512 PopExpressionEvaluationContext(); 14513 14514 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 14515 BlockDecl *BD = BSI->TheDecl; 14516 14517 if (BSI->HasImplicitReturnType) 14518 deduceClosureReturnType(*BSI); 14519 14520 QualType RetTy = Context.VoidTy; 14521 if (!BSI->ReturnType.isNull()) 14522 RetTy = BSI->ReturnType; 14523 14524 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 14525 QualType BlockTy; 14526 14527 // If the user wrote a function type in some form, try to use that. 14528 if (!BSI->FunctionType.isNull()) { 14529 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 14530 14531 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 14532 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 14533 14534 // Turn protoless block types into nullary block types. 14535 if (isa<FunctionNoProtoType>(FTy)) { 14536 FunctionProtoType::ExtProtoInfo EPI; 14537 EPI.ExtInfo = Ext; 14538 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14539 14540 // Otherwise, if we don't need to change anything about the function type, 14541 // preserve its sugar structure. 14542 } else if (FTy->getReturnType() == RetTy && 14543 (!NoReturn || FTy->getNoReturnAttr())) { 14544 BlockTy = BSI->FunctionType; 14545 14546 // Otherwise, make the minimal modifications to the function type. 14547 } else { 14548 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 14549 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 14550 EPI.TypeQuals = Qualifiers(); 14551 EPI.ExtInfo = Ext; 14552 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 14553 } 14554 14555 // If we don't have a function type, just build one from nothing. 14556 } else { 14557 FunctionProtoType::ExtProtoInfo EPI; 14558 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 14559 BlockTy = Context.getFunctionType(RetTy, None, EPI); 14560 } 14561 14562 DiagnoseUnusedParameters(BD->parameters()); 14563 BlockTy = Context.getBlockPointerType(BlockTy); 14564 14565 // If needed, diagnose invalid gotos and switches in the block. 14566 if (getCurFunction()->NeedsScopeChecking() && 14567 !PP.isCodeCompletionEnabled()) 14568 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 14569 14570 BD->setBody(cast<CompoundStmt>(Body)); 14571 14572 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14573 DiagnoseUnguardedAvailabilityViolations(BD); 14574 14575 // Try to apply the named return value optimization. We have to check again 14576 // if we can do this, though, because blocks keep return statements around 14577 // to deduce an implicit return type. 14578 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 14579 !BD->isDependentContext()) 14580 computeNRVO(Body, BSI); 14581 14582 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 14583 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 14584 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 14585 NTCUK_Destruct|NTCUK_Copy); 14586 14587 PopDeclContext(); 14588 14589 // Pop the block scope now but keep it alive to the end of this function. 14590 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14591 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 14592 14593 // Set the captured variables on the block. 14594 SmallVector<BlockDecl::Capture, 4> Captures; 14595 for (Capture &Cap : BSI->Captures) { 14596 if (Cap.isInvalid() || Cap.isThisCapture()) 14597 continue; 14598 14599 VarDecl *Var = Cap.getVariable(); 14600 Expr *CopyExpr = nullptr; 14601 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 14602 if (const RecordType *Record = 14603 Cap.getCaptureType()->getAs<RecordType>()) { 14604 // The capture logic needs the destructor, so make sure we mark it. 14605 // Usually this is unnecessary because most local variables have 14606 // their destructors marked at declaration time, but parameters are 14607 // an exception because it's technically only the call site that 14608 // actually requires the destructor. 14609 if (isa<ParmVarDecl>(Var)) 14610 FinalizeVarWithDestructor(Var, Record); 14611 14612 // Enter a separate potentially-evaluated context while building block 14613 // initializers to isolate their cleanups from those of the block 14614 // itself. 14615 // FIXME: Is this appropriate even when the block itself occurs in an 14616 // unevaluated operand? 14617 EnterExpressionEvaluationContext EvalContext( 14618 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14619 14620 SourceLocation Loc = Cap.getLocation(); 14621 14622 ExprResult Result = BuildDeclarationNameExpr( 14623 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 14624 14625 // According to the blocks spec, the capture of a variable from 14626 // the stack requires a const copy constructor. This is not true 14627 // of the copy/move done to move a __block variable to the heap. 14628 if (!Result.isInvalid() && 14629 !Result.get()->getType().isConstQualified()) { 14630 Result = ImpCastExprToType(Result.get(), 14631 Result.get()->getType().withConst(), 14632 CK_NoOp, VK_LValue); 14633 } 14634 14635 if (!Result.isInvalid()) { 14636 Result = PerformCopyInitialization( 14637 InitializedEntity::InitializeBlock(Var->getLocation(), 14638 Cap.getCaptureType(), false), 14639 Loc, Result.get()); 14640 } 14641 14642 // Build a full-expression copy expression if initialization 14643 // succeeded and used a non-trivial constructor. Recover from 14644 // errors by pretending that the copy isn't necessary. 14645 if (!Result.isInvalid() && 14646 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14647 ->isTrivial()) { 14648 Result = MaybeCreateExprWithCleanups(Result); 14649 CopyExpr = Result.get(); 14650 } 14651 } 14652 } 14653 14654 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 14655 CopyExpr); 14656 Captures.push_back(NewCap); 14657 } 14658 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 14659 14660 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 14661 14662 // If the block isn't obviously global, i.e. it captures anything at 14663 // all, then we need to do a few things in the surrounding context: 14664 if (Result->getBlockDecl()->hasCaptures()) { 14665 // First, this expression has a new cleanup object. 14666 ExprCleanupObjects.push_back(Result->getBlockDecl()); 14667 Cleanup.setExprNeedsCleanups(true); 14668 14669 // It also gets a branch-protected scope if any of the captured 14670 // variables needs destruction. 14671 for (const auto &CI : Result->getBlockDecl()->captures()) { 14672 const VarDecl *var = CI.getVariable(); 14673 if (var->getType().isDestructedType() != QualType::DK_none) { 14674 setFunctionHasBranchProtectedScope(); 14675 break; 14676 } 14677 } 14678 } 14679 14680 if (getCurFunction()) 14681 getCurFunction()->addBlock(BD); 14682 14683 return Result; 14684 } 14685 14686 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 14687 SourceLocation RPLoc) { 14688 TypeSourceInfo *TInfo; 14689 GetTypeFromParser(Ty, &TInfo); 14690 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 14691 } 14692 14693 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 14694 Expr *E, TypeSourceInfo *TInfo, 14695 SourceLocation RPLoc) { 14696 Expr *OrigExpr = E; 14697 bool IsMS = false; 14698 14699 // CUDA device code does not support varargs. 14700 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 14701 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 14702 CUDAFunctionTarget T = IdentifyCUDATarget(F); 14703 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 14704 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 14705 } 14706 } 14707 14708 // NVPTX does not support va_arg expression. 14709 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 14710 Context.getTargetInfo().getTriple().isNVPTX()) 14711 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 14712 14713 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 14714 // as Microsoft ABI on an actual Microsoft platform, where 14715 // __builtin_ms_va_list and __builtin_va_list are the same.) 14716 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 14717 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 14718 QualType MSVaListType = Context.getBuiltinMSVaListType(); 14719 if (Context.hasSameType(MSVaListType, E->getType())) { 14720 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14721 return ExprError(); 14722 IsMS = true; 14723 } 14724 } 14725 14726 // Get the va_list type 14727 QualType VaListType = Context.getBuiltinVaListType(); 14728 if (!IsMS) { 14729 if (VaListType->isArrayType()) { 14730 // Deal with implicit array decay; for example, on x86-64, 14731 // va_list is an array, but it's supposed to decay to 14732 // a pointer for va_arg. 14733 VaListType = Context.getArrayDecayedType(VaListType); 14734 // Make sure the input expression also decays appropriately. 14735 ExprResult Result = UsualUnaryConversions(E); 14736 if (Result.isInvalid()) 14737 return ExprError(); 14738 E = Result.get(); 14739 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 14740 // If va_list is a record type and we are compiling in C++ mode, 14741 // check the argument using reference binding. 14742 InitializedEntity Entity = InitializedEntity::InitializeParameter( 14743 Context, Context.getLValueReferenceType(VaListType), false); 14744 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 14745 if (Init.isInvalid()) 14746 return ExprError(); 14747 E = Init.getAs<Expr>(); 14748 } else { 14749 // Otherwise, the va_list argument must be an l-value because 14750 // it is modified by va_arg. 14751 if (!E->isTypeDependent() && 14752 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 14753 return ExprError(); 14754 } 14755 } 14756 14757 if (!IsMS && !E->isTypeDependent() && 14758 !Context.hasSameType(VaListType, E->getType())) 14759 return ExprError( 14760 Diag(E->getBeginLoc(), 14761 diag::err_first_argument_to_va_arg_not_of_type_va_list) 14762 << OrigExpr->getType() << E->getSourceRange()); 14763 14764 if (!TInfo->getType()->isDependentType()) { 14765 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 14766 diag::err_second_parameter_to_va_arg_incomplete, 14767 TInfo->getTypeLoc())) 14768 return ExprError(); 14769 14770 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 14771 TInfo->getType(), 14772 diag::err_second_parameter_to_va_arg_abstract, 14773 TInfo->getTypeLoc())) 14774 return ExprError(); 14775 14776 if (!TInfo->getType().isPODType(Context)) { 14777 Diag(TInfo->getTypeLoc().getBeginLoc(), 14778 TInfo->getType()->isObjCLifetimeType() 14779 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 14780 : diag::warn_second_parameter_to_va_arg_not_pod) 14781 << TInfo->getType() 14782 << TInfo->getTypeLoc().getSourceRange(); 14783 } 14784 14785 // Check for va_arg where arguments of the given type will be promoted 14786 // (i.e. this va_arg is guaranteed to have undefined behavior). 14787 QualType PromoteType; 14788 if (TInfo->getType()->isPromotableIntegerType()) { 14789 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 14790 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 14791 PromoteType = QualType(); 14792 } 14793 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 14794 PromoteType = Context.DoubleTy; 14795 if (!PromoteType.isNull()) 14796 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 14797 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 14798 << TInfo->getType() 14799 << PromoteType 14800 << TInfo->getTypeLoc().getSourceRange()); 14801 } 14802 14803 QualType T = TInfo->getType().getNonLValueExprType(Context); 14804 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 14805 } 14806 14807 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 14808 // The type of __null will be int or long, depending on the size of 14809 // pointers on the target. 14810 QualType Ty; 14811 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 14812 if (pw == Context.getTargetInfo().getIntWidth()) 14813 Ty = Context.IntTy; 14814 else if (pw == Context.getTargetInfo().getLongWidth()) 14815 Ty = Context.LongTy; 14816 else if (pw == Context.getTargetInfo().getLongLongWidth()) 14817 Ty = Context.LongLongTy; 14818 else { 14819 llvm_unreachable("I don't know size of pointer!"); 14820 } 14821 14822 return new (Context) GNUNullExpr(Ty, TokenLoc); 14823 } 14824 14825 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 14826 SourceLocation BuiltinLoc, 14827 SourceLocation RPLoc) { 14828 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 14829 } 14830 14831 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 14832 SourceLocation BuiltinLoc, 14833 SourceLocation RPLoc, 14834 DeclContext *ParentContext) { 14835 return new (Context) 14836 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 14837 } 14838 14839 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 14840 bool Diagnose) { 14841 if (!getLangOpts().ObjC) 14842 return false; 14843 14844 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 14845 if (!PT) 14846 return false; 14847 14848 if (!PT->isObjCIdType()) { 14849 // Check if the destination is the 'NSString' interface. 14850 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 14851 if (!ID || !ID->getIdentifier()->isStr("NSString")) 14852 return false; 14853 } 14854 14855 // Ignore any parens, implicit casts (should only be 14856 // array-to-pointer decays), and not-so-opaque values. The last is 14857 // important for making this trigger for property assignments. 14858 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 14859 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 14860 if (OV->getSourceExpr()) 14861 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 14862 14863 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 14864 if (!SL || !SL->isAscii()) 14865 return false; 14866 if (Diagnose) { 14867 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 14868 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 14869 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 14870 } 14871 return true; 14872 } 14873 14874 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 14875 const Expr *SrcExpr) { 14876 if (!DstType->isFunctionPointerType() || 14877 !SrcExpr->getType()->isFunctionType()) 14878 return false; 14879 14880 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 14881 if (!DRE) 14882 return false; 14883 14884 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 14885 if (!FD) 14886 return false; 14887 14888 return !S.checkAddressOfFunctionIsAvailable(FD, 14889 /*Complain=*/true, 14890 SrcExpr->getBeginLoc()); 14891 } 14892 14893 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 14894 SourceLocation Loc, 14895 QualType DstType, QualType SrcType, 14896 Expr *SrcExpr, AssignmentAction Action, 14897 bool *Complained) { 14898 if (Complained) 14899 *Complained = false; 14900 14901 // Decode the result (notice that AST's are still created for extensions). 14902 bool CheckInferredResultType = false; 14903 bool isInvalid = false; 14904 unsigned DiagKind = 0; 14905 FixItHint Hint; 14906 ConversionFixItGenerator ConvHints; 14907 bool MayHaveConvFixit = false; 14908 bool MayHaveFunctionDiff = false; 14909 const ObjCInterfaceDecl *IFace = nullptr; 14910 const ObjCProtocolDecl *PDecl = nullptr; 14911 14912 switch (ConvTy) { 14913 case Compatible: 14914 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 14915 return false; 14916 14917 case PointerToInt: 14918 if (getLangOpts().CPlusPlus) { 14919 DiagKind = diag::err_typecheck_convert_pointer_int; 14920 isInvalid = true; 14921 } else { 14922 DiagKind = diag::ext_typecheck_convert_pointer_int; 14923 } 14924 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14925 MayHaveConvFixit = true; 14926 break; 14927 case IntToPointer: 14928 if (getLangOpts().CPlusPlus) { 14929 DiagKind = diag::err_typecheck_convert_int_pointer; 14930 isInvalid = true; 14931 } else { 14932 DiagKind = diag::ext_typecheck_convert_int_pointer; 14933 } 14934 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14935 MayHaveConvFixit = true; 14936 break; 14937 case IncompatibleFunctionPointer: 14938 if (getLangOpts().CPlusPlus) { 14939 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 14940 isInvalid = true; 14941 } else { 14942 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 14943 } 14944 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14945 MayHaveConvFixit = true; 14946 break; 14947 case IncompatiblePointer: 14948 if (Action == AA_Passing_CFAudited) { 14949 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 14950 } else if (getLangOpts().CPlusPlus) { 14951 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 14952 isInvalid = true; 14953 } else { 14954 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 14955 } 14956 CheckInferredResultType = DstType->isObjCObjectPointerType() && 14957 SrcType->isObjCObjectPointerType(); 14958 if (Hint.isNull() && !CheckInferredResultType) { 14959 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14960 } 14961 else if (CheckInferredResultType) { 14962 SrcType = SrcType.getUnqualifiedType(); 14963 DstType = DstType.getUnqualifiedType(); 14964 } 14965 MayHaveConvFixit = true; 14966 break; 14967 case IncompatiblePointerSign: 14968 if (getLangOpts().CPlusPlus) { 14969 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 14970 isInvalid = true; 14971 } else { 14972 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 14973 } 14974 break; 14975 case FunctionVoidPointer: 14976 if (getLangOpts().CPlusPlus) { 14977 DiagKind = diag::err_typecheck_convert_pointer_void_func; 14978 isInvalid = true; 14979 } else { 14980 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 14981 } 14982 break; 14983 case IncompatiblePointerDiscardsQualifiers: { 14984 // Perform array-to-pointer decay if necessary. 14985 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 14986 14987 isInvalid = true; 14988 14989 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 14990 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 14991 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 14992 DiagKind = diag::err_typecheck_incompatible_address_space; 14993 break; 14994 14995 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 14996 DiagKind = diag::err_typecheck_incompatible_ownership; 14997 break; 14998 } 14999 15000 llvm_unreachable("unknown error case for discarding qualifiers!"); 15001 // fallthrough 15002 } 15003 case CompatiblePointerDiscardsQualifiers: 15004 // If the qualifiers lost were because we were applying the 15005 // (deprecated) C++ conversion from a string literal to a char* 15006 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15007 // Ideally, this check would be performed in 15008 // checkPointerTypesForAssignment. However, that would require a 15009 // bit of refactoring (so that the second argument is an 15010 // expression, rather than a type), which should be done as part 15011 // of a larger effort to fix checkPointerTypesForAssignment for 15012 // C++ semantics. 15013 if (getLangOpts().CPlusPlus && 15014 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15015 return false; 15016 if (getLangOpts().CPlusPlus) { 15017 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15018 isInvalid = true; 15019 } else { 15020 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15021 } 15022 15023 break; 15024 case IncompatibleNestedPointerQualifiers: 15025 if (getLangOpts().CPlusPlus) { 15026 isInvalid = true; 15027 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15028 } else { 15029 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15030 } 15031 break; 15032 case IncompatibleNestedPointerAddressSpaceMismatch: 15033 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15034 isInvalid = true; 15035 break; 15036 case IntToBlockPointer: 15037 DiagKind = diag::err_int_to_block_pointer; 15038 isInvalid = true; 15039 break; 15040 case IncompatibleBlockPointer: 15041 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15042 isInvalid = true; 15043 break; 15044 case IncompatibleObjCQualifiedId: { 15045 if (SrcType->isObjCQualifiedIdType()) { 15046 const ObjCObjectPointerType *srcOPT = 15047 SrcType->castAs<ObjCObjectPointerType>(); 15048 for (auto *srcProto : srcOPT->quals()) { 15049 PDecl = srcProto; 15050 break; 15051 } 15052 if (const ObjCInterfaceType *IFaceT = 15053 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15054 IFace = IFaceT->getDecl(); 15055 } 15056 else if (DstType->isObjCQualifiedIdType()) { 15057 const ObjCObjectPointerType *dstOPT = 15058 DstType->castAs<ObjCObjectPointerType>(); 15059 for (auto *dstProto : dstOPT->quals()) { 15060 PDecl = dstProto; 15061 break; 15062 } 15063 if (const ObjCInterfaceType *IFaceT = 15064 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15065 IFace = IFaceT->getDecl(); 15066 } 15067 if (getLangOpts().CPlusPlus) { 15068 DiagKind = diag::err_incompatible_qualified_id; 15069 isInvalid = true; 15070 } else { 15071 DiagKind = diag::warn_incompatible_qualified_id; 15072 } 15073 break; 15074 } 15075 case IncompatibleVectors: 15076 if (getLangOpts().CPlusPlus) { 15077 DiagKind = diag::err_incompatible_vectors; 15078 isInvalid = true; 15079 } else { 15080 DiagKind = diag::warn_incompatible_vectors; 15081 } 15082 break; 15083 case IncompatibleObjCWeakRef: 15084 DiagKind = diag::err_arc_weak_unavailable_assign; 15085 isInvalid = true; 15086 break; 15087 case Incompatible: 15088 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 15089 if (Complained) 15090 *Complained = true; 15091 return true; 15092 } 15093 15094 DiagKind = diag::err_typecheck_convert_incompatible; 15095 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15096 MayHaveConvFixit = true; 15097 isInvalid = true; 15098 MayHaveFunctionDiff = true; 15099 break; 15100 } 15101 15102 QualType FirstType, SecondType; 15103 switch (Action) { 15104 case AA_Assigning: 15105 case AA_Initializing: 15106 // The destination type comes first. 15107 FirstType = DstType; 15108 SecondType = SrcType; 15109 break; 15110 15111 case AA_Returning: 15112 case AA_Passing: 15113 case AA_Passing_CFAudited: 15114 case AA_Converting: 15115 case AA_Sending: 15116 case AA_Casting: 15117 // The source type comes first. 15118 FirstType = SrcType; 15119 SecondType = DstType; 15120 break; 15121 } 15122 15123 PartialDiagnostic FDiag = PDiag(DiagKind); 15124 if (Action == AA_Passing_CFAudited) 15125 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 15126 else 15127 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 15128 15129 // If we can fix the conversion, suggest the FixIts. 15130 assert(ConvHints.isNull() || Hint.isNull()); 15131 if (!ConvHints.isNull()) { 15132 for (FixItHint &H : ConvHints.Hints) 15133 FDiag << H; 15134 } else { 15135 FDiag << Hint; 15136 } 15137 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 15138 15139 if (MayHaveFunctionDiff) 15140 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 15141 15142 Diag(Loc, FDiag); 15143 if ((DiagKind == diag::warn_incompatible_qualified_id || 15144 DiagKind == diag::err_incompatible_qualified_id) && 15145 PDecl && IFace && !IFace->hasDefinition()) 15146 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 15147 << IFace << PDecl; 15148 15149 if (SecondType == Context.OverloadTy) 15150 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 15151 FirstType, /*TakingAddress=*/true); 15152 15153 if (CheckInferredResultType) 15154 EmitRelatedResultTypeNote(SrcExpr); 15155 15156 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 15157 EmitRelatedResultTypeNoteForReturn(DstType); 15158 15159 if (Complained) 15160 *Complained = true; 15161 return isInvalid; 15162 } 15163 15164 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15165 llvm::APSInt *Result) { 15166 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 15167 public: 15168 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15169 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 15170 } 15171 } Diagnoser; 15172 15173 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 15174 } 15175 15176 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 15177 llvm::APSInt *Result, 15178 unsigned DiagID, 15179 bool AllowFold) { 15180 class IDDiagnoser : public VerifyICEDiagnoser { 15181 unsigned DiagID; 15182 15183 public: 15184 IDDiagnoser(unsigned DiagID) 15185 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 15186 15187 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 15188 S.Diag(Loc, DiagID) << SR; 15189 } 15190 } Diagnoser(DiagID); 15191 15192 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 15193 } 15194 15195 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 15196 SourceRange SR) { 15197 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 15198 } 15199 15200 ExprResult 15201 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 15202 VerifyICEDiagnoser &Diagnoser, 15203 bool AllowFold) { 15204 SourceLocation DiagLoc = E->getBeginLoc(); 15205 15206 if (getLangOpts().CPlusPlus11) { 15207 // C++11 [expr.const]p5: 15208 // If an expression of literal class type is used in a context where an 15209 // integral constant expression is required, then that class type shall 15210 // have a single non-explicit conversion function to an integral or 15211 // unscoped enumeration type 15212 ExprResult Converted; 15213 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 15214 public: 15215 CXX11ConvertDiagnoser(bool Silent) 15216 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 15217 Silent, true) {} 15218 15219 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15220 QualType T) override { 15221 return S.Diag(Loc, diag::err_ice_not_integral) << T; 15222 } 15223 15224 SemaDiagnosticBuilder diagnoseIncomplete( 15225 Sema &S, SourceLocation Loc, QualType T) override { 15226 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 15227 } 15228 15229 SemaDiagnosticBuilder diagnoseExplicitConv( 15230 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15231 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 15232 } 15233 15234 SemaDiagnosticBuilder noteExplicitConv( 15235 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15236 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15237 << ConvTy->isEnumeralType() << ConvTy; 15238 } 15239 15240 SemaDiagnosticBuilder diagnoseAmbiguous( 15241 Sema &S, SourceLocation Loc, QualType T) override { 15242 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 15243 } 15244 15245 SemaDiagnosticBuilder noteAmbiguous( 15246 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 15247 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 15248 << ConvTy->isEnumeralType() << ConvTy; 15249 } 15250 15251 SemaDiagnosticBuilder diagnoseConversion( 15252 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 15253 llvm_unreachable("conversion functions are permitted"); 15254 } 15255 } ConvertDiagnoser(Diagnoser.Suppress); 15256 15257 Converted = PerformContextualImplicitConversion(DiagLoc, E, 15258 ConvertDiagnoser); 15259 if (Converted.isInvalid()) 15260 return Converted; 15261 E = Converted.get(); 15262 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 15263 return ExprError(); 15264 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 15265 // An ICE must be of integral or unscoped enumeration type. 15266 if (!Diagnoser.Suppress) 15267 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15268 return ExprError(); 15269 } 15270 15271 ExprResult RValueExpr = DefaultLvalueConversion(E); 15272 if (RValueExpr.isInvalid()) 15273 return ExprError(); 15274 15275 E = RValueExpr.get(); 15276 15277 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 15278 // in the non-ICE case. 15279 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 15280 if (Result) 15281 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 15282 if (!isa<ConstantExpr>(E)) 15283 E = ConstantExpr::Create(Context, E); 15284 return E; 15285 } 15286 15287 Expr::EvalResult EvalResult; 15288 SmallVector<PartialDiagnosticAt, 8> Notes; 15289 EvalResult.Diag = &Notes; 15290 15291 // Try to evaluate the expression, and produce diagnostics explaining why it's 15292 // not a constant expression as a side-effect. 15293 bool Folded = 15294 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 15295 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 15296 15297 if (!isa<ConstantExpr>(E)) 15298 E = ConstantExpr::Create(Context, E, EvalResult.Val); 15299 15300 // In C++11, we can rely on diagnostics being produced for any expression 15301 // which is not a constant expression. If no diagnostics were produced, then 15302 // this is a constant expression. 15303 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 15304 if (Result) 15305 *Result = EvalResult.Val.getInt(); 15306 return E; 15307 } 15308 15309 // If our only note is the usual "invalid subexpression" note, just point 15310 // the caret at its location rather than producing an essentially 15311 // redundant note. 15312 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 15313 diag::note_invalid_subexpr_in_const_expr) { 15314 DiagLoc = Notes[0].first; 15315 Notes.clear(); 15316 } 15317 15318 if (!Folded || !AllowFold) { 15319 if (!Diagnoser.Suppress) { 15320 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 15321 for (const PartialDiagnosticAt &Note : Notes) 15322 Diag(Note.first, Note.second); 15323 } 15324 15325 return ExprError(); 15326 } 15327 15328 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 15329 for (const PartialDiagnosticAt &Note : Notes) 15330 Diag(Note.first, Note.second); 15331 15332 if (Result) 15333 *Result = EvalResult.Val.getInt(); 15334 return E; 15335 } 15336 15337 namespace { 15338 // Handle the case where we conclude a expression which we speculatively 15339 // considered to be unevaluated is actually evaluated. 15340 class TransformToPE : public TreeTransform<TransformToPE> { 15341 typedef TreeTransform<TransformToPE> BaseTransform; 15342 15343 public: 15344 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 15345 15346 // Make sure we redo semantic analysis 15347 bool AlwaysRebuild() { return true; } 15348 bool ReplacingOriginal() { return true; } 15349 15350 // We need to special-case DeclRefExprs referring to FieldDecls which 15351 // are not part of a member pointer formation; normal TreeTransforming 15352 // doesn't catch this case because of the way we represent them in the AST. 15353 // FIXME: This is a bit ugly; is it really the best way to handle this 15354 // case? 15355 // 15356 // Error on DeclRefExprs referring to FieldDecls. 15357 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15358 if (isa<FieldDecl>(E->getDecl()) && 15359 !SemaRef.isUnevaluatedContext()) 15360 return SemaRef.Diag(E->getLocation(), 15361 diag::err_invalid_non_static_member_use) 15362 << E->getDecl() << E->getSourceRange(); 15363 15364 return BaseTransform::TransformDeclRefExpr(E); 15365 } 15366 15367 // Exception: filter out member pointer formation 15368 ExprResult TransformUnaryOperator(UnaryOperator *E) { 15369 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 15370 return E; 15371 15372 return BaseTransform::TransformUnaryOperator(E); 15373 } 15374 15375 // The body of a lambda-expression is in a separate expression evaluation 15376 // context so never needs to be transformed. 15377 // FIXME: Ideally we wouldn't transform the closure type either, and would 15378 // just recreate the capture expressions and lambda expression. 15379 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 15380 return SkipLambdaBody(E, Body); 15381 } 15382 }; 15383 } 15384 15385 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 15386 assert(isUnevaluatedContext() && 15387 "Should only transform unevaluated expressions"); 15388 ExprEvalContexts.back().Context = 15389 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 15390 if (isUnevaluatedContext()) 15391 return E; 15392 return TransformToPE(*this).TransformExpr(E); 15393 } 15394 15395 void 15396 Sema::PushExpressionEvaluationContext( 15397 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 15398 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15399 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 15400 LambdaContextDecl, ExprContext); 15401 Cleanup.reset(); 15402 if (!MaybeODRUseExprs.empty()) 15403 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 15404 } 15405 15406 void 15407 Sema::PushExpressionEvaluationContext( 15408 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 15409 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 15410 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 15411 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 15412 } 15413 15414 namespace { 15415 15416 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 15417 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 15418 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 15419 if (E->getOpcode() == UO_Deref) 15420 return CheckPossibleDeref(S, E->getSubExpr()); 15421 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 15422 return CheckPossibleDeref(S, E->getBase()); 15423 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 15424 return CheckPossibleDeref(S, E->getBase()); 15425 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 15426 QualType Inner; 15427 QualType Ty = E->getType(); 15428 if (const auto *Ptr = Ty->getAs<PointerType>()) 15429 Inner = Ptr->getPointeeType(); 15430 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 15431 Inner = Arr->getElementType(); 15432 else 15433 return nullptr; 15434 15435 if (Inner->hasAttr(attr::NoDeref)) 15436 return E; 15437 } 15438 return nullptr; 15439 } 15440 15441 } // namespace 15442 15443 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 15444 for (const Expr *E : Rec.PossibleDerefs) { 15445 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 15446 if (DeclRef) { 15447 const ValueDecl *Decl = DeclRef->getDecl(); 15448 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 15449 << Decl->getName() << E->getSourceRange(); 15450 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 15451 } else { 15452 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 15453 << E->getSourceRange(); 15454 } 15455 } 15456 Rec.PossibleDerefs.clear(); 15457 } 15458 15459 /// Check whether E, which is either a discarded-value expression or an 15460 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 15461 /// and if so, remove it from the list of volatile-qualified assignments that 15462 /// we are going to warn are deprecated. 15463 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 15464 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a) 15465 return; 15466 15467 // Note: ignoring parens here is not justified by the standard rules, but 15468 // ignoring parentheses seems like a more reasonable approach, and this only 15469 // drives a deprecation warning so doesn't affect conformance. 15470 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 15471 if (BO->getOpcode() == BO_Assign) { 15472 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 15473 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 15474 LHSs.end()); 15475 } 15476 } 15477 } 15478 15479 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 15480 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 15481 RebuildingImmediateInvocation) 15482 return E; 15483 15484 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 15485 /// It's OK if this fails; we'll also remove this in 15486 /// HandleImmediateInvocations, but catching it here allows us to avoid 15487 /// walking the AST looking for it in simple cases. 15488 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 15489 if (auto *DeclRef = 15490 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 15491 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 15492 15493 E = MaybeCreateExprWithCleanups(E); 15494 15495 ConstantExpr *Res = ConstantExpr::Create( 15496 getASTContext(), E.get(), 15497 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(), 15498 getASTContext()), 15499 /*IsImmediateInvocation*/ true); 15500 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 15501 return Res; 15502 } 15503 15504 static void EvaluateAndDiagnoseImmediateInvocation( 15505 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 15506 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 15507 Expr::EvalResult Eval; 15508 Eval.Diag = &Notes; 15509 ConstantExpr *CE = Candidate.getPointer(); 15510 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 15511 SemaRef.getASTContext(), true); 15512 if (!Result || !Notes.empty()) { 15513 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 15514 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 15515 InnerExpr = FunctionalCast->getSubExpr(); 15516 FunctionDecl *FD = nullptr; 15517 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 15518 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 15519 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 15520 FD = Call->getConstructor(); 15521 else 15522 llvm_unreachable("unhandled decl kind"); 15523 assert(FD->isConsteval()); 15524 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 15525 for (auto &Note : Notes) 15526 SemaRef.Diag(Note.first, Note.second); 15527 return; 15528 } 15529 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 15530 } 15531 15532 static void RemoveNestedImmediateInvocation( 15533 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 15534 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 15535 struct ComplexRemove : TreeTransform<ComplexRemove> { 15536 using Base = TreeTransform<ComplexRemove>; 15537 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15538 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 15539 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 15540 CurrentII; 15541 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 15542 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 15543 SmallVector<Sema::ImmediateInvocationCandidate, 15544 4>::reverse_iterator Current) 15545 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 15546 void RemoveImmediateInvocation(ConstantExpr* E) { 15547 auto It = std::find_if(CurrentII, IISet.rend(), 15548 [E](Sema::ImmediateInvocationCandidate Elem) { 15549 return Elem.getPointer() == E; 15550 }); 15551 assert(It != IISet.rend() && 15552 "ConstantExpr marked IsImmediateInvocation should " 15553 "be present"); 15554 It->setInt(1); // Mark as deleted 15555 } 15556 ExprResult TransformConstantExpr(ConstantExpr *E) { 15557 if (!E->isImmediateInvocation()) 15558 return Base::TransformConstantExpr(E); 15559 RemoveImmediateInvocation(E); 15560 return Base::TransformExpr(E->getSubExpr()); 15561 } 15562 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 15563 /// we need to remove its DeclRefExpr from the DRSet. 15564 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 15565 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 15566 return Base::TransformCXXOperatorCallExpr(E); 15567 } 15568 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 15569 /// here. 15570 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 15571 if (!Init) 15572 return Init; 15573 /// ConstantExpr are the first layer of implicit node to be removed so if 15574 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 15575 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 15576 if (CE->isImmediateInvocation()) 15577 RemoveImmediateInvocation(CE); 15578 return Base::TransformInitializer(Init, NotCopyInit); 15579 } 15580 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 15581 DRSet.erase(E); 15582 return E; 15583 } 15584 bool AlwaysRebuild() { return false; } 15585 bool ReplacingOriginal() { return true; } 15586 bool AllowSkippingCXXConstructExpr() { 15587 bool Res = AllowSkippingFirstCXXConstructExpr; 15588 AllowSkippingFirstCXXConstructExpr = true; 15589 return Res; 15590 } 15591 bool AllowSkippingFirstCXXConstructExpr = true; 15592 } Transformer(SemaRef, Rec.ReferenceToConsteval, 15593 Rec.ImmediateInvocationCandidates, It); 15594 15595 /// CXXConstructExpr with a single argument are getting skipped by 15596 /// TreeTransform in some situtation because they could be implicit. This 15597 /// can only occur for the top-level CXXConstructExpr because it is used 15598 /// nowhere in the expression being transformed therefore will not be rebuilt. 15599 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 15600 /// skipping the first CXXConstructExpr. 15601 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 15602 Transformer.AllowSkippingFirstCXXConstructExpr = false; 15603 15604 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 15605 assert(Res.isUsable()); 15606 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 15607 It->getPointer()->setSubExpr(Res.get()); 15608 } 15609 15610 static void 15611 HandleImmediateInvocations(Sema &SemaRef, 15612 Sema::ExpressionEvaluationContextRecord &Rec) { 15613 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 15614 Rec.ReferenceToConsteval.size() == 0) || 15615 SemaRef.RebuildingImmediateInvocation) 15616 return; 15617 15618 /// When we have more then 1 ImmediateInvocationCandidates we need to check 15619 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 15620 /// need to remove ReferenceToConsteval in the immediate invocation. 15621 if (Rec.ImmediateInvocationCandidates.size() > 1) { 15622 15623 /// Prevent sema calls during the tree transform from adding pointers that 15624 /// are already in the sets. 15625 llvm::SaveAndRestore<bool> DisableIITracking( 15626 SemaRef.RebuildingImmediateInvocation, true); 15627 15628 /// Prevent diagnostic during tree transfrom as they are duplicates 15629 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 15630 15631 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 15632 It != Rec.ImmediateInvocationCandidates.rend(); It++) 15633 if (!It->getInt()) 15634 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 15635 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 15636 Rec.ReferenceToConsteval.size()) { 15637 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 15638 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 15639 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 15640 bool VisitDeclRefExpr(DeclRefExpr *E) { 15641 DRSet.erase(E); 15642 return DRSet.size(); 15643 } 15644 } Visitor(Rec.ReferenceToConsteval); 15645 Visitor.TraverseStmt( 15646 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 15647 } 15648 for (auto CE : Rec.ImmediateInvocationCandidates) 15649 if (!CE.getInt()) 15650 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 15651 for (auto DR : Rec.ReferenceToConsteval) { 15652 auto *FD = cast<FunctionDecl>(DR->getDecl()); 15653 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 15654 << FD; 15655 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 15656 } 15657 } 15658 15659 void Sema::PopExpressionEvaluationContext() { 15660 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 15661 unsigned NumTypos = Rec.NumTypos; 15662 15663 if (!Rec.Lambdas.empty()) { 15664 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 15665 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 15666 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 15667 unsigned D; 15668 if (Rec.isUnevaluated()) { 15669 // C++11 [expr.prim.lambda]p2: 15670 // A lambda-expression shall not appear in an unevaluated operand 15671 // (Clause 5). 15672 D = diag::err_lambda_unevaluated_operand; 15673 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 15674 // C++1y [expr.const]p2: 15675 // A conditional-expression e is a core constant expression unless the 15676 // evaluation of e, following the rules of the abstract machine, would 15677 // evaluate [...] a lambda-expression. 15678 D = diag::err_lambda_in_constant_expression; 15679 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 15680 // C++17 [expr.prim.lamda]p2: 15681 // A lambda-expression shall not appear [...] in a template-argument. 15682 D = diag::err_lambda_in_invalid_context; 15683 } else 15684 llvm_unreachable("Couldn't infer lambda error message."); 15685 15686 for (const auto *L : Rec.Lambdas) 15687 Diag(L->getBeginLoc(), D); 15688 } 15689 } 15690 15691 WarnOnPendingNoDerefs(Rec); 15692 HandleImmediateInvocations(*this, Rec); 15693 15694 // Warn on any volatile-qualified simple-assignments that are not discarded- 15695 // value expressions nor unevaluated operands (those cases get removed from 15696 // this list by CheckUnusedVolatileAssignment). 15697 for (auto *BO : Rec.VolatileAssignmentLHSs) 15698 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 15699 << BO->getType(); 15700 15701 // When are coming out of an unevaluated context, clear out any 15702 // temporaries that we may have created as part of the evaluation of 15703 // the expression in that context: they aren't relevant because they 15704 // will never be constructed. 15705 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 15706 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 15707 ExprCleanupObjects.end()); 15708 Cleanup = Rec.ParentCleanup; 15709 CleanupVarDeclMarking(); 15710 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 15711 // Otherwise, merge the contexts together. 15712 } else { 15713 Cleanup.mergeFrom(Rec.ParentCleanup); 15714 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 15715 Rec.SavedMaybeODRUseExprs.end()); 15716 } 15717 15718 // Pop the current expression evaluation context off the stack. 15719 ExprEvalContexts.pop_back(); 15720 15721 // The global expression evaluation context record is never popped. 15722 ExprEvalContexts.back().NumTypos += NumTypos; 15723 } 15724 15725 void Sema::DiscardCleanupsInEvaluationContext() { 15726 ExprCleanupObjects.erase( 15727 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 15728 ExprCleanupObjects.end()); 15729 Cleanup.reset(); 15730 MaybeODRUseExprs.clear(); 15731 } 15732 15733 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 15734 ExprResult Result = CheckPlaceholderExpr(E); 15735 if (Result.isInvalid()) 15736 return ExprError(); 15737 E = Result.get(); 15738 if (!E->getType()->isVariablyModifiedType()) 15739 return E; 15740 return TransformToPotentiallyEvaluated(E); 15741 } 15742 15743 /// Are we in a context that is potentially constant evaluated per C++20 15744 /// [expr.const]p12? 15745 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 15746 /// C++2a [expr.const]p12: 15747 // An expression or conversion is potentially constant evaluated if it is 15748 switch (SemaRef.ExprEvalContexts.back().Context) { 15749 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15750 // -- a manifestly constant-evaluated expression, 15751 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15752 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15753 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15754 // -- a potentially-evaluated expression, 15755 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15756 // -- an immediate subexpression of a braced-init-list, 15757 15758 // -- [FIXME] an expression of the form & cast-expression that occurs 15759 // within a templated entity 15760 // -- a subexpression of one of the above that is not a subexpression of 15761 // a nested unevaluated operand. 15762 return true; 15763 15764 case Sema::ExpressionEvaluationContext::Unevaluated: 15765 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15766 // Expressions in this context are never evaluated. 15767 return false; 15768 } 15769 llvm_unreachable("Invalid context"); 15770 } 15771 15772 /// Return true if this function has a calling convention that requires mangling 15773 /// in the size of the parameter pack. 15774 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 15775 // These manglings don't do anything on non-Windows or non-x86 platforms, so 15776 // we don't need parameter type sizes. 15777 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 15778 if (!TT.isOSWindows() || !TT.isX86()) 15779 return false; 15780 15781 // If this is C++ and this isn't an extern "C" function, parameters do not 15782 // need to be complete. In this case, C++ mangling will apply, which doesn't 15783 // use the size of the parameters. 15784 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 15785 return false; 15786 15787 // Stdcall, fastcall, and vectorcall need this special treatment. 15788 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15789 switch (CC) { 15790 case CC_X86StdCall: 15791 case CC_X86FastCall: 15792 case CC_X86VectorCall: 15793 return true; 15794 default: 15795 break; 15796 } 15797 return false; 15798 } 15799 15800 /// Require that all of the parameter types of function be complete. Normally, 15801 /// parameter types are only required to be complete when a function is called 15802 /// or defined, but to mangle functions with certain calling conventions, the 15803 /// mangler needs to know the size of the parameter list. In this situation, 15804 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 15805 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 15806 /// result in a linker error. Clang doesn't implement this behavior, and instead 15807 /// attempts to error at compile time. 15808 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 15809 SourceLocation Loc) { 15810 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 15811 FunctionDecl *FD; 15812 ParmVarDecl *Param; 15813 15814 public: 15815 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 15816 : FD(FD), Param(Param) {} 15817 15818 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15819 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 15820 StringRef CCName; 15821 switch (CC) { 15822 case CC_X86StdCall: 15823 CCName = "stdcall"; 15824 break; 15825 case CC_X86FastCall: 15826 CCName = "fastcall"; 15827 break; 15828 case CC_X86VectorCall: 15829 CCName = "vectorcall"; 15830 break; 15831 default: 15832 llvm_unreachable("CC does not need mangling"); 15833 } 15834 15835 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 15836 << Param->getDeclName() << FD->getDeclName() << CCName; 15837 } 15838 }; 15839 15840 for (ParmVarDecl *Param : FD->parameters()) { 15841 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 15842 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 15843 } 15844 } 15845 15846 namespace { 15847 enum class OdrUseContext { 15848 /// Declarations in this context are not odr-used. 15849 None, 15850 /// Declarations in this context are formally odr-used, but this is a 15851 /// dependent context. 15852 Dependent, 15853 /// Declarations in this context are odr-used but not actually used (yet). 15854 FormallyOdrUsed, 15855 /// Declarations in this context are used. 15856 Used 15857 }; 15858 } 15859 15860 /// Are we within a context in which references to resolved functions or to 15861 /// variables result in odr-use? 15862 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 15863 OdrUseContext Result; 15864 15865 switch (SemaRef.ExprEvalContexts.back().Context) { 15866 case Sema::ExpressionEvaluationContext::Unevaluated: 15867 case Sema::ExpressionEvaluationContext::UnevaluatedList: 15868 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 15869 return OdrUseContext::None; 15870 15871 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 15872 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 15873 Result = OdrUseContext::Used; 15874 break; 15875 15876 case Sema::ExpressionEvaluationContext::DiscardedStatement: 15877 Result = OdrUseContext::FormallyOdrUsed; 15878 break; 15879 15880 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15881 // A default argument formally results in odr-use, but doesn't actually 15882 // result in a use in any real sense until it itself is used. 15883 Result = OdrUseContext::FormallyOdrUsed; 15884 break; 15885 } 15886 15887 if (SemaRef.CurContext->isDependentContext()) 15888 return OdrUseContext::Dependent; 15889 15890 return Result; 15891 } 15892 15893 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 15894 return Func->isConstexpr() && 15895 (Func->isImplicitlyInstantiable() || !Func->isUserProvided()); 15896 } 15897 15898 /// Mark a function referenced, and check whether it is odr-used 15899 /// (C++ [basic.def.odr]p2, C99 6.9p3) 15900 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 15901 bool MightBeOdrUse) { 15902 assert(Func && "No function?"); 15903 15904 Func->setReferenced(); 15905 15906 // Recursive functions aren't really used until they're used from some other 15907 // context. 15908 bool IsRecursiveCall = CurContext == Func; 15909 15910 // C++11 [basic.def.odr]p3: 15911 // A function whose name appears as a potentially-evaluated expression is 15912 // odr-used if it is the unique lookup result or the selected member of a 15913 // set of overloaded functions [...]. 15914 // 15915 // We (incorrectly) mark overload resolution as an unevaluated context, so we 15916 // can just check that here. 15917 OdrUseContext OdrUse = 15918 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 15919 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 15920 OdrUse = OdrUseContext::FormallyOdrUsed; 15921 15922 // Trivial default constructors and destructors are never actually used. 15923 // FIXME: What about other special members? 15924 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 15925 OdrUse == OdrUseContext::Used) { 15926 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 15927 if (Constructor->isDefaultConstructor()) 15928 OdrUse = OdrUseContext::FormallyOdrUsed; 15929 if (isa<CXXDestructorDecl>(Func)) 15930 OdrUse = OdrUseContext::FormallyOdrUsed; 15931 } 15932 15933 // C++20 [expr.const]p12: 15934 // A function [...] is needed for constant evaluation if it is [...] a 15935 // constexpr function that is named by an expression that is potentially 15936 // constant evaluated 15937 bool NeededForConstantEvaluation = 15938 isPotentiallyConstantEvaluatedContext(*this) && 15939 isImplicitlyDefinableConstexprFunction(Func); 15940 15941 // Determine whether we require a function definition to exist, per 15942 // C++11 [temp.inst]p3: 15943 // Unless a function template specialization has been explicitly 15944 // instantiated or explicitly specialized, the function template 15945 // specialization is implicitly instantiated when the specialization is 15946 // referenced in a context that requires a function definition to exist. 15947 // C++20 [temp.inst]p7: 15948 // The existence of a definition of a [...] function is considered to 15949 // affect the semantics of the program if the [...] function is needed for 15950 // constant evaluation by an expression 15951 // C++20 [basic.def.odr]p10: 15952 // Every program shall contain exactly one definition of every non-inline 15953 // function or variable that is odr-used in that program outside of a 15954 // discarded statement 15955 // C++20 [special]p1: 15956 // The implementation will implicitly define [defaulted special members] 15957 // if they are odr-used or needed for constant evaluation. 15958 // 15959 // Note that we skip the implicit instantiation of templates that are only 15960 // used in unused default arguments or by recursive calls to themselves. 15961 // This is formally non-conforming, but seems reasonable in practice. 15962 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 15963 NeededForConstantEvaluation); 15964 15965 // C++14 [temp.expl.spec]p6: 15966 // If a template [...] is explicitly specialized then that specialization 15967 // shall be declared before the first use of that specialization that would 15968 // cause an implicit instantiation to take place, in every translation unit 15969 // in which such a use occurs 15970 if (NeedDefinition && 15971 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 15972 Func->getMemberSpecializationInfo())) 15973 checkSpecializationVisibility(Loc, Func); 15974 15975 if (getLangOpts().CUDA) 15976 CheckCUDACall(Loc, Func); 15977 15978 // If we need a definition, try to create one. 15979 if (NeedDefinition && !Func->getBody()) { 15980 runWithSufficientStackSpace(Loc, [&] { 15981 if (CXXConstructorDecl *Constructor = 15982 dyn_cast<CXXConstructorDecl>(Func)) { 15983 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 15984 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 15985 if (Constructor->isDefaultConstructor()) { 15986 if (Constructor->isTrivial() && 15987 !Constructor->hasAttr<DLLExportAttr>()) 15988 return; 15989 DefineImplicitDefaultConstructor(Loc, Constructor); 15990 } else if (Constructor->isCopyConstructor()) { 15991 DefineImplicitCopyConstructor(Loc, Constructor); 15992 } else if (Constructor->isMoveConstructor()) { 15993 DefineImplicitMoveConstructor(Loc, Constructor); 15994 } 15995 } else if (Constructor->getInheritedConstructor()) { 15996 DefineInheritingConstructor(Loc, Constructor); 15997 } 15998 } else if (CXXDestructorDecl *Destructor = 15999 dyn_cast<CXXDestructorDecl>(Func)) { 16000 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16001 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16002 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16003 return; 16004 DefineImplicitDestructor(Loc, Destructor); 16005 } 16006 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16007 MarkVTableUsed(Loc, Destructor->getParent()); 16008 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16009 if (MethodDecl->isOverloadedOperator() && 16010 MethodDecl->getOverloadedOperator() == OO_Equal) { 16011 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16012 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16013 if (MethodDecl->isCopyAssignmentOperator()) 16014 DefineImplicitCopyAssignment(Loc, MethodDecl); 16015 else if (MethodDecl->isMoveAssignmentOperator()) 16016 DefineImplicitMoveAssignment(Loc, MethodDecl); 16017 } 16018 } else if (isa<CXXConversionDecl>(MethodDecl) && 16019 MethodDecl->getParent()->isLambda()) { 16020 CXXConversionDecl *Conversion = 16021 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16022 if (Conversion->isLambdaToBlockPointerConversion()) 16023 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16024 else 16025 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16026 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16027 MarkVTableUsed(Loc, MethodDecl->getParent()); 16028 } 16029 16030 if (Func->isDefaulted() && !Func->isDeleted()) { 16031 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16032 if (DCK != DefaultedComparisonKind::None) 16033 DefineDefaultedComparison(Loc, Func, DCK); 16034 } 16035 16036 // Implicit instantiation of function templates and member functions of 16037 // class templates. 16038 if (Func->isImplicitlyInstantiable()) { 16039 TemplateSpecializationKind TSK = 16040 Func->getTemplateSpecializationKindForInstantiation(); 16041 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 16042 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 16043 if (FirstInstantiation) { 16044 PointOfInstantiation = Loc; 16045 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 16046 } else if (TSK != TSK_ImplicitInstantiation) { 16047 // Use the point of use as the point of instantiation, instead of the 16048 // point of explicit instantiation (which we track as the actual point 16049 // of instantiation). This gives better backtraces in diagnostics. 16050 PointOfInstantiation = Loc; 16051 } 16052 16053 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 16054 Func->isConstexpr()) { 16055 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 16056 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 16057 CodeSynthesisContexts.size()) 16058 PendingLocalImplicitInstantiations.push_back( 16059 std::make_pair(Func, PointOfInstantiation)); 16060 else if (Func->isConstexpr()) 16061 // Do not defer instantiations of constexpr functions, to avoid the 16062 // expression evaluator needing to call back into Sema if it sees a 16063 // call to such a function. 16064 InstantiateFunctionDefinition(PointOfInstantiation, Func); 16065 else { 16066 Func->setInstantiationIsPending(true); 16067 PendingInstantiations.push_back( 16068 std::make_pair(Func, PointOfInstantiation)); 16069 // Notify the consumer that a function was implicitly instantiated. 16070 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 16071 } 16072 } 16073 } else { 16074 // Walk redefinitions, as some of them may be instantiable. 16075 for (auto i : Func->redecls()) { 16076 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 16077 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 16078 } 16079 } 16080 }); 16081 } 16082 16083 // C++14 [except.spec]p17: 16084 // An exception-specification is considered to be needed when: 16085 // - the function is odr-used or, if it appears in an unevaluated operand, 16086 // would be odr-used if the expression were potentially-evaluated; 16087 // 16088 // Note, we do this even if MightBeOdrUse is false. That indicates that the 16089 // function is a pure virtual function we're calling, and in that case the 16090 // function was selected by overload resolution and we need to resolve its 16091 // exception specification for a different reason. 16092 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 16093 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 16094 ResolveExceptionSpec(Loc, FPT); 16095 16096 // If this is the first "real" use, act on that. 16097 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 16098 // Keep track of used but undefined functions. 16099 if (!Func->isDefined()) { 16100 if (mightHaveNonExternalLinkage(Func)) 16101 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16102 else if (Func->getMostRecentDecl()->isInlined() && 16103 !LangOpts.GNUInline && 16104 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 16105 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16106 else if (isExternalWithNoLinkageType(Func)) 16107 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 16108 } 16109 16110 // Some x86 Windows calling conventions mangle the size of the parameter 16111 // pack into the name. Computing the size of the parameters requires the 16112 // parameter types to be complete. Check that now. 16113 if (funcHasParameterSizeMangling(*this, Func)) 16114 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 16115 16116 Func->markUsed(Context); 16117 } 16118 } 16119 16120 /// Directly mark a variable odr-used. Given a choice, prefer to use 16121 /// MarkVariableReferenced since it does additional checks and then 16122 /// calls MarkVarDeclODRUsed. 16123 /// If the variable must be captured: 16124 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 16125 /// - else capture it in the DeclContext that maps to the 16126 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 16127 static void 16128 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 16129 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 16130 // Keep track of used but undefined variables. 16131 // FIXME: We shouldn't suppress this warning for static data members. 16132 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 16133 (!Var->isExternallyVisible() || Var->isInline() || 16134 SemaRef.isExternalWithNoLinkageType(Var)) && 16135 !(Var->isStaticDataMember() && Var->hasInit())) { 16136 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 16137 if (old.isInvalid()) 16138 old = Loc; 16139 } 16140 QualType CaptureType, DeclRefType; 16141 if (SemaRef.LangOpts.OpenMP) 16142 SemaRef.tryCaptureOpenMPLambdas(Var); 16143 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 16144 /*EllipsisLoc*/ SourceLocation(), 16145 /*BuildAndDiagnose*/ true, 16146 CaptureType, DeclRefType, 16147 FunctionScopeIndexToStopAt); 16148 16149 Var->markUsed(SemaRef.Context); 16150 } 16151 16152 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 16153 SourceLocation Loc, 16154 unsigned CapturingScopeIndex) { 16155 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 16156 } 16157 16158 static void 16159 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 16160 ValueDecl *var, DeclContext *DC) { 16161 DeclContext *VarDC = var->getDeclContext(); 16162 16163 // If the parameter still belongs to the translation unit, then 16164 // we're actually just using one parameter in the declaration of 16165 // the next. 16166 if (isa<ParmVarDecl>(var) && 16167 isa<TranslationUnitDecl>(VarDC)) 16168 return; 16169 16170 // For C code, don't diagnose about capture if we're not actually in code 16171 // right now; it's impossible to write a non-constant expression outside of 16172 // function context, so we'll get other (more useful) diagnostics later. 16173 // 16174 // For C++, things get a bit more nasty... it would be nice to suppress this 16175 // diagnostic for certain cases like using a local variable in an array bound 16176 // for a member of a local class, but the correct predicate is not obvious. 16177 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 16178 return; 16179 16180 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 16181 unsigned ContextKind = 3; // unknown 16182 if (isa<CXXMethodDecl>(VarDC) && 16183 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 16184 ContextKind = 2; 16185 } else if (isa<FunctionDecl>(VarDC)) { 16186 ContextKind = 0; 16187 } else if (isa<BlockDecl>(VarDC)) { 16188 ContextKind = 1; 16189 } 16190 16191 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 16192 << var << ValueKind << ContextKind << VarDC; 16193 S.Diag(var->getLocation(), diag::note_entity_declared_at) 16194 << var; 16195 16196 // FIXME: Add additional diagnostic info about class etc. which prevents 16197 // capture. 16198 } 16199 16200 16201 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 16202 bool &SubCapturesAreNested, 16203 QualType &CaptureType, 16204 QualType &DeclRefType) { 16205 // Check whether we've already captured it. 16206 if (CSI->CaptureMap.count(Var)) { 16207 // If we found a capture, any subcaptures are nested. 16208 SubCapturesAreNested = true; 16209 16210 // Retrieve the capture type for this variable. 16211 CaptureType = CSI->getCapture(Var).getCaptureType(); 16212 16213 // Compute the type of an expression that refers to this variable. 16214 DeclRefType = CaptureType.getNonReferenceType(); 16215 16216 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 16217 // are mutable in the sense that user can change their value - they are 16218 // private instances of the captured declarations. 16219 const Capture &Cap = CSI->getCapture(Var); 16220 if (Cap.isCopyCapture() && 16221 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 16222 !(isa<CapturedRegionScopeInfo>(CSI) && 16223 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 16224 DeclRefType.addConst(); 16225 return true; 16226 } 16227 return false; 16228 } 16229 16230 // Only block literals, captured statements, and lambda expressions can 16231 // capture; other scopes don't work. 16232 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 16233 SourceLocation Loc, 16234 const bool Diagnose, Sema &S) { 16235 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 16236 return getLambdaAwareParentOfDeclContext(DC); 16237 else if (Var->hasLocalStorage()) { 16238 if (Diagnose) 16239 diagnoseUncapturableValueReference(S, Loc, Var, DC); 16240 } 16241 return nullptr; 16242 } 16243 16244 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16245 // certain types of variables (unnamed, variably modified types etc.) 16246 // so check for eligibility. 16247 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 16248 SourceLocation Loc, 16249 const bool Diagnose, Sema &S) { 16250 16251 bool IsBlock = isa<BlockScopeInfo>(CSI); 16252 bool IsLambda = isa<LambdaScopeInfo>(CSI); 16253 16254 // Lambdas are not allowed to capture unnamed variables 16255 // (e.g. anonymous unions). 16256 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 16257 // assuming that's the intent. 16258 if (IsLambda && !Var->getDeclName()) { 16259 if (Diagnose) { 16260 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 16261 S.Diag(Var->getLocation(), diag::note_declared_at); 16262 } 16263 return false; 16264 } 16265 16266 // Prohibit variably-modified types in blocks; they're difficult to deal with. 16267 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 16268 if (Diagnose) { 16269 S.Diag(Loc, diag::err_ref_vm_type); 16270 S.Diag(Var->getLocation(), diag::note_previous_decl) 16271 << Var->getDeclName(); 16272 } 16273 return false; 16274 } 16275 // Prohibit structs with flexible array members too. 16276 // We cannot capture what is in the tail end of the struct. 16277 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 16278 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 16279 if (Diagnose) { 16280 if (IsBlock) 16281 S.Diag(Loc, diag::err_ref_flexarray_type); 16282 else 16283 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 16284 << Var->getDeclName(); 16285 S.Diag(Var->getLocation(), diag::note_previous_decl) 16286 << Var->getDeclName(); 16287 } 16288 return false; 16289 } 16290 } 16291 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16292 // Lambdas and captured statements are not allowed to capture __block 16293 // variables; they don't support the expected semantics. 16294 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 16295 if (Diagnose) { 16296 S.Diag(Loc, diag::err_capture_block_variable) 16297 << Var->getDeclName() << !IsLambda; 16298 S.Diag(Var->getLocation(), diag::note_previous_decl) 16299 << Var->getDeclName(); 16300 } 16301 return false; 16302 } 16303 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 16304 if (S.getLangOpts().OpenCL && IsBlock && 16305 Var->getType()->isBlockPointerType()) { 16306 if (Diagnose) 16307 S.Diag(Loc, diag::err_opencl_block_ref_block); 16308 return false; 16309 } 16310 16311 return true; 16312 } 16313 16314 // Returns true if the capture by block was successful. 16315 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 16316 SourceLocation Loc, 16317 const bool BuildAndDiagnose, 16318 QualType &CaptureType, 16319 QualType &DeclRefType, 16320 const bool Nested, 16321 Sema &S, bool Invalid) { 16322 bool ByRef = false; 16323 16324 // Blocks are not allowed to capture arrays, excepting OpenCL. 16325 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 16326 // (decayed to pointers). 16327 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 16328 if (BuildAndDiagnose) { 16329 S.Diag(Loc, diag::err_ref_array_type); 16330 S.Diag(Var->getLocation(), diag::note_previous_decl) 16331 << Var->getDeclName(); 16332 Invalid = true; 16333 } else { 16334 return false; 16335 } 16336 } 16337 16338 // Forbid the block-capture of autoreleasing variables. 16339 if (!Invalid && 16340 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16341 if (BuildAndDiagnose) { 16342 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 16343 << /*block*/ 0; 16344 S.Diag(Var->getLocation(), diag::note_previous_decl) 16345 << Var->getDeclName(); 16346 Invalid = true; 16347 } else { 16348 return false; 16349 } 16350 } 16351 16352 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 16353 if (const auto *PT = CaptureType->getAs<PointerType>()) { 16354 QualType PointeeTy = PT->getPointeeType(); 16355 16356 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 16357 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 16358 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 16359 if (BuildAndDiagnose) { 16360 SourceLocation VarLoc = Var->getLocation(); 16361 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 16362 S.Diag(VarLoc, diag::note_declare_parameter_strong); 16363 } 16364 } 16365 } 16366 16367 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 16368 if (HasBlocksAttr || CaptureType->isReferenceType() || 16369 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 16370 // Block capture by reference does not change the capture or 16371 // declaration reference types. 16372 ByRef = true; 16373 } else { 16374 // Block capture by copy introduces 'const'. 16375 CaptureType = CaptureType.getNonReferenceType().withConst(); 16376 DeclRefType = CaptureType; 16377 } 16378 16379 // Actually capture the variable. 16380 if (BuildAndDiagnose) 16381 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 16382 CaptureType, Invalid); 16383 16384 return !Invalid; 16385 } 16386 16387 16388 /// Capture the given variable in the captured region. 16389 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 16390 VarDecl *Var, 16391 SourceLocation Loc, 16392 const bool BuildAndDiagnose, 16393 QualType &CaptureType, 16394 QualType &DeclRefType, 16395 const bool RefersToCapturedVariable, 16396 Sema &S, bool Invalid) { 16397 // By default, capture variables by reference. 16398 bool ByRef = true; 16399 // Using an LValue reference type is consistent with Lambdas (see below). 16400 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 16401 if (S.isOpenMPCapturedDecl(Var)) { 16402 bool HasConst = DeclRefType.isConstQualified(); 16403 DeclRefType = DeclRefType.getUnqualifiedType(); 16404 // Don't lose diagnostics about assignments to const. 16405 if (HasConst) 16406 DeclRefType.addConst(); 16407 } 16408 // Do not capture firstprivates in tasks. 16409 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 16410 OMPC_unknown) 16411 return true; 16412 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 16413 RSI->OpenMPCaptureLevel); 16414 } 16415 16416 if (ByRef) 16417 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16418 else 16419 CaptureType = DeclRefType; 16420 16421 // Actually capture the variable. 16422 if (BuildAndDiagnose) 16423 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 16424 Loc, SourceLocation(), CaptureType, Invalid); 16425 16426 return !Invalid; 16427 } 16428 16429 /// Capture the given variable in the lambda. 16430 static bool captureInLambda(LambdaScopeInfo *LSI, 16431 VarDecl *Var, 16432 SourceLocation Loc, 16433 const bool BuildAndDiagnose, 16434 QualType &CaptureType, 16435 QualType &DeclRefType, 16436 const bool RefersToCapturedVariable, 16437 const Sema::TryCaptureKind Kind, 16438 SourceLocation EllipsisLoc, 16439 const bool IsTopScope, 16440 Sema &S, bool Invalid) { 16441 // Determine whether we are capturing by reference or by value. 16442 bool ByRef = false; 16443 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 16444 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 16445 } else { 16446 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 16447 } 16448 16449 // Compute the type of the field that will capture this variable. 16450 if (ByRef) { 16451 // C++11 [expr.prim.lambda]p15: 16452 // An entity is captured by reference if it is implicitly or 16453 // explicitly captured but not captured by copy. It is 16454 // unspecified whether additional unnamed non-static data 16455 // members are declared in the closure type for entities 16456 // captured by reference. 16457 // 16458 // FIXME: It is not clear whether we want to build an lvalue reference 16459 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 16460 // to do the former, while EDG does the latter. Core issue 1249 will 16461 // clarify, but for now we follow GCC because it's a more permissive and 16462 // easily defensible position. 16463 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 16464 } else { 16465 // C++11 [expr.prim.lambda]p14: 16466 // For each entity captured by copy, an unnamed non-static 16467 // data member is declared in the closure type. The 16468 // declaration order of these members is unspecified. The type 16469 // of such a data member is the type of the corresponding 16470 // captured entity if the entity is not a reference to an 16471 // object, or the referenced type otherwise. [Note: If the 16472 // captured entity is a reference to a function, the 16473 // corresponding data member is also a reference to a 16474 // function. - end note ] 16475 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 16476 if (!RefType->getPointeeType()->isFunctionType()) 16477 CaptureType = RefType->getPointeeType(); 16478 } 16479 16480 // Forbid the lambda copy-capture of autoreleasing variables. 16481 if (!Invalid && 16482 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 16483 if (BuildAndDiagnose) { 16484 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 16485 S.Diag(Var->getLocation(), diag::note_previous_decl) 16486 << Var->getDeclName(); 16487 Invalid = true; 16488 } else { 16489 return false; 16490 } 16491 } 16492 16493 // Make sure that by-copy captures are of a complete and non-abstract type. 16494 if (!Invalid && BuildAndDiagnose) { 16495 if (!CaptureType->isDependentType() && 16496 S.RequireCompleteSizedType( 16497 Loc, CaptureType, 16498 diag::err_capture_of_incomplete_or_sizeless_type, 16499 Var->getDeclName())) 16500 Invalid = true; 16501 else if (S.RequireNonAbstractType(Loc, CaptureType, 16502 diag::err_capture_of_abstract_type)) 16503 Invalid = true; 16504 } 16505 } 16506 16507 // Compute the type of a reference to this captured variable. 16508 if (ByRef) 16509 DeclRefType = CaptureType.getNonReferenceType(); 16510 else { 16511 // C++ [expr.prim.lambda]p5: 16512 // The closure type for a lambda-expression has a public inline 16513 // function call operator [...]. This function call operator is 16514 // declared const (9.3.1) if and only if the lambda-expression's 16515 // parameter-declaration-clause is not followed by mutable. 16516 DeclRefType = CaptureType.getNonReferenceType(); 16517 if (!LSI->Mutable && !CaptureType->isReferenceType()) 16518 DeclRefType.addConst(); 16519 } 16520 16521 // Add the capture. 16522 if (BuildAndDiagnose) 16523 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 16524 Loc, EllipsisLoc, CaptureType, Invalid); 16525 16526 return !Invalid; 16527 } 16528 16529 bool Sema::tryCaptureVariable( 16530 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 16531 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 16532 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 16533 // An init-capture is notionally from the context surrounding its 16534 // declaration, but its parent DC is the lambda class. 16535 DeclContext *VarDC = Var->getDeclContext(); 16536 if (Var->isInitCapture()) 16537 VarDC = VarDC->getParent(); 16538 16539 DeclContext *DC = CurContext; 16540 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 16541 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 16542 // We need to sync up the Declaration Context with the 16543 // FunctionScopeIndexToStopAt 16544 if (FunctionScopeIndexToStopAt) { 16545 unsigned FSIndex = FunctionScopes.size() - 1; 16546 while (FSIndex != MaxFunctionScopesIndex) { 16547 DC = getLambdaAwareParentOfDeclContext(DC); 16548 --FSIndex; 16549 } 16550 } 16551 16552 16553 // If the variable is declared in the current context, there is no need to 16554 // capture it. 16555 if (VarDC == DC) return true; 16556 16557 // Capture global variables if it is required to use private copy of this 16558 // variable. 16559 bool IsGlobal = !Var->hasLocalStorage(); 16560 if (IsGlobal && 16561 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 16562 MaxFunctionScopesIndex))) 16563 return true; 16564 Var = Var->getCanonicalDecl(); 16565 16566 // Walk up the stack to determine whether we can capture the variable, 16567 // performing the "simple" checks that don't depend on type. We stop when 16568 // we've either hit the declared scope of the variable or find an existing 16569 // capture of that variable. We start from the innermost capturing-entity 16570 // (the DC) and ensure that all intervening capturing-entities 16571 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 16572 // declcontext can either capture the variable or have already captured 16573 // the variable. 16574 CaptureType = Var->getType(); 16575 DeclRefType = CaptureType.getNonReferenceType(); 16576 bool Nested = false; 16577 bool Explicit = (Kind != TryCapture_Implicit); 16578 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 16579 do { 16580 // Only block literals, captured statements, and lambda expressions can 16581 // capture; other scopes don't work. 16582 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 16583 ExprLoc, 16584 BuildAndDiagnose, 16585 *this); 16586 // We need to check for the parent *first* because, if we *have* 16587 // private-captured a global variable, we need to recursively capture it in 16588 // intermediate blocks, lambdas, etc. 16589 if (!ParentDC) { 16590 if (IsGlobal) { 16591 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 16592 break; 16593 } 16594 return true; 16595 } 16596 16597 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 16598 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 16599 16600 16601 // Check whether we've already captured it. 16602 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 16603 DeclRefType)) { 16604 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 16605 break; 16606 } 16607 // If we are instantiating a generic lambda call operator body, 16608 // we do not want to capture new variables. What was captured 16609 // during either a lambdas transformation or initial parsing 16610 // should be used. 16611 if (isGenericLambdaCallOperatorSpecialization(DC)) { 16612 if (BuildAndDiagnose) { 16613 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16614 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 16615 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16616 Diag(Var->getLocation(), diag::note_previous_decl) 16617 << Var->getDeclName(); 16618 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 16619 } else 16620 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 16621 } 16622 return true; 16623 } 16624 16625 // Try to capture variable-length arrays types. 16626 if (Var->getType()->isVariablyModifiedType()) { 16627 // We're going to walk down into the type and look for VLA 16628 // expressions. 16629 QualType QTy = Var->getType(); 16630 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16631 QTy = PVD->getOriginalType(); 16632 captureVariablyModifiedType(Context, QTy, CSI); 16633 } 16634 16635 if (getLangOpts().OpenMP) { 16636 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16637 // OpenMP private variables should not be captured in outer scope, so 16638 // just break here. Similarly, global variables that are captured in a 16639 // target region should not be captured outside the scope of the region. 16640 if (RSI->CapRegionKind == CR_OpenMP) { 16641 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 16642 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 16643 // If the variable is private (i.e. not captured) and has variably 16644 // modified type, we still need to capture the type for correct 16645 // codegen in all regions, associated with the construct. Currently, 16646 // it is captured in the innermost captured region only. 16647 if (IsOpenMPPrivateDecl != OMPC_unknown && 16648 Var->getType()->isVariablyModifiedType()) { 16649 QualType QTy = Var->getType(); 16650 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 16651 QTy = PVD->getOriginalType(); 16652 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 16653 I < E; ++I) { 16654 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 16655 FunctionScopes[FunctionScopesIndex - I]); 16656 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 16657 "Wrong number of captured regions associated with the " 16658 "OpenMP construct."); 16659 captureVariablyModifiedType(Context, QTy, OuterRSI); 16660 } 16661 } 16662 bool IsTargetCap = 16663 IsOpenMPPrivateDecl != OMPC_private && 16664 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 16665 RSI->OpenMPCaptureLevel); 16666 // Do not capture global if it is not privatized in outer regions. 16667 bool IsGlobalCap = 16668 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 16669 RSI->OpenMPCaptureLevel); 16670 16671 // When we detect target captures we are looking from inside the 16672 // target region, therefore we need to propagate the capture from the 16673 // enclosing region. Therefore, the capture is not initially nested. 16674 if (IsTargetCap) 16675 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 16676 16677 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 16678 (IsGlobal && !IsGlobalCap)) { 16679 Nested = !IsTargetCap; 16680 DeclRefType = DeclRefType.getUnqualifiedType(); 16681 CaptureType = Context.getLValueReferenceType(DeclRefType); 16682 break; 16683 } 16684 } 16685 } 16686 } 16687 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 16688 // No capture-default, and this is not an explicit capture 16689 // so cannot capture this variable. 16690 if (BuildAndDiagnose) { 16691 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 16692 Diag(Var->getLocation(), diag::note_previous_decl) 16693 << Var->getDeclName(); 16694 if (cast<LambdaScopeInfo>(CSI)->Lambda) 16695 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 16696 diag::note_lambda_decl); 16697 // FIXME: If we error out because an outer lambda can not implicitly 16698 // capture a variable that an inner lambda explicitly captures, we 16699 // should have the inner lambda do the explicit capture - because 16700 // it makes for cleaner diagnostics later. This would purely be done 16701 // so that the diagnostic does not misleadingly claim that a variable 16702 // can not be captured by a lambda implicitly even though it is captured 16703 // explicitly. Suggestion: 16704 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 16705 // at the function head 16706 // - cache the StartingDeclContext - this must be a lambda 16707 // - captureInLambda in the innermost lambda the variable. 16708 } 16709 return true; 16710 } 16711 16712 FunctionScopesIndex--; 16713 DC = ParentDC; 16714 Explicit = false; 16715 } while (!VarDC->Equals(DC)); 16716 16717 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 16718 // computing the type of the capture at each step, checking type-specific 16719 // requirements, and adding captures if requested. 16720 // If the variable had already been captured previously, we start capturing 16721 // at the lambda nested within that one. 16722 bool Invalid = false; 16723 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 16724 ++I) { 16725 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 16726 16727 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 16728 // certain types of variables (unnamed, variably modified types etc.) 16729 // so check for eligibility. 16730 if (!Invalid) 16731 Invalid = 16732 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 16733 16734 // After encountering an error, if we're actually supposed to capture, keep 16735 // capturing in nested contexts to suppress any follow-on diagnostics. 16736 if (Invalid && !BuildAndDiagnose) 16737 return true; 16738 16739 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 16740 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16741 DeclRefType, Nested, *this, Invalid); 16742 Nested = true; 16743 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 16744 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose, 16745 CaptureType, DeclRefType, Nested, 16746 *this, Invalid); 16747 Nested = true; 16748 } else { 16749 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 16750 Invalid = 16751 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 16752 DeclRefType, Nested, Kind, EllipsisLoc, 16753 /*IsTopScope*/ I == N - 1, *this, Invalid); 16754 Nested = true; 16755 } 16756 16757 if (Invalid && !BuildAndDiagnose) 16758 return true; 16759 } 16760 return Invalid; 16761 } 16762 16763 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 16764 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 16765 QualType CaptureType; 16766 QualType DeclRefType; 16767 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 16768 /*BuildAndDiagnose=*/true, CaptureType, 16769 DeclRefType, nullptr); 16770 } 16771 16772 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 16773 QualType CaptureType; 16774 QualType DeclRefType; 16775 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16776 /*BuildAndDiagnose=*/false, CaptureType, 16777 DeclRefType, nullptr); 16778 } 16779 16780 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 16781 QualType CaptureType; 16782 QualType DeclRefType; 16783 16784 // Determine whether we can capture this variable. 16785 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 16786 /*BuildAndDiagnose=*/false, CaptureType, 16787 DeclRefType, nullptr)) 16788 return QualType(); 16789 16790 return DeclRefType; 16791 } 16792 16793 namespace { 16794 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 16795 // The produced TemplateArgumentListInfo* points to data stored within this 16796 // object, so should only be used in contexts where the pointer will not be 16797 // used after the CopiedTemplateArgs object is destroyed. 16798 class CopiedTemplateArgs { 16799 bool HasArgs; 16800 TemplateArgumentListInfo TemplateArgStorage; 16801 public: 16802 template<typename RefExpr> 16803 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 16804 if (HasArgs) 16805 E->copyTemplateArgumentsInto(TemplateArgStorage); 16806 } 16807 operator TemplateArgumentListInfo*() 16808 #ifdef __has_cpp_attribute 16809 #if __has_cpp_attribute(clang::lifetimebound) 16810 [[clang::lifetimebound]] 16811 #endif 16812 #endif 16813 { 16814 return HasArgs ? &TemplateArgStorage : nullptr; 16815 } 16816 }; 16817 } 16818 16819 /// Walk the set of potential results of an expression and mark them all as 16820 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 16821 /// 16822 /// \return A new expression if we found any potential results, ExprEmpty() if 16823 /// not, and ExprError() if we diagnosed an error. 16824 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 16825 NonOdrUseReason NOUR) { 16826 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 16827 // an object that satisfies the requirements for appearing in a 16828 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 16829 // is immediately applied." This function handles the lvalue-to-rvalue 16830 // conversion part. 16831 // 16832 // If we encounter a node that claims to be an odr-use but shouldn't be, we 16833 // transform it into the relevant kind of non-odr-use node and rebuild the 16834 // tree of nodes leading to it. 16835 // 16836 // This is a mini-TreeTransform that only transforms a restricted subset of 16837 // nodes (and only certain operands of them). 16838 16839 // Rebuild a subexpression. 16840 auto Rebuild = [&](Expr *Sub) { 16841 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 16842 }; 16843 16844 // Check whether a potential result satisfies the requirements of NOUR. 16845 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 16846 // Any entity other than a VarDecl is always odr-used whenever it's named 16847 // in a potentially-evaluated expression. 16848 auto *VD = dyn_cast<VarDecl>(D); 16849 if (!VD) 16850 return true; 16851 16852 // C++2a [basic.def.odr]p4: 16853 // A variable x whose name appears as a potentially-evalauted expression 16854 // e is odr-used by e unless 16855 // -- x is a reference that is usable in constant expressions, or 16856 // -- x is a variable of non-reference type that is usable in constant 16857 // expressions and has no mutable subobjects, and e is an element of 16858 // the set of potential results of an expression of 16859 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 16860 // conversion is applied, or 16861 // -- x is a variable of non-reference type, and e is an element of the 16862 // set of potential results of a discarded-value expression to which 16863 // the lvalue-to-rvalue conversion is not applied 16864 // 16865 // We check the first bullet and the "potentially-evaluated" condition in 16866 // BuildDeclRefExpr. We check the type requirements in the second bullet 16867 // in CheckLValueToRValueConversionOperand below. 16868 switch (NOUR) { 16869 case NOUR_None: 16870 case NOUR_Unevaluated: 16871 llvm_unreachable("unexpected non-odr-use-reason"); 16872 16873 case NOUR_Constant: 16874 // Constant references were handled when they were built. 16875 if (VD->getType()->isReferenceType()) 16876 return true; 16877 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 16878 if (RD->hasMutableFields()) 16879 return true; 16880 if (!VD->isUsableInConstantExpressions(S.Context)) 16881 return true; 16882 break; 16883 16884 case NOUR_Discarded: 16885 if (VD->getType()->isReferenceType()) 16886 return true; 16887 break; 16888 } 16889 return false; 16890 }; 16891 16892 // Mark that this expression does not constitute an odr-use. 16893 auto MarkNotOdrUsed = [&] { 16894 S.MaybeODRUseExprs.erase(E); 16895 if (LambdaScopeInfo *LSI = S.getCurLambda()) 16896 LSI->markVariableExprAsNonODRUsed(E); 16897 }; 16898 16899 // C++2a [basic.def.odr]p2: 16900 // The set of potential results of an expression e is defined as follows: 16901 switch (E->getStmtClass()) { 16902 // -- If e is an id-expression, ... 16903 case Expr::DeclRefExprClass: { 16904 auto *DRE = cast<DeclRefExpr>(E); 16905 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 16906 break; 16907 16908 // Rebuild as a non-odr-use DeclRefExpr. 16909 MarkNotOdrUsed(); 16910 return DeclRefExpr::Create( 16911 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 16912 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 16913 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 16914 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 16915 } 16916 16917 case Expr::FunctionParmPackExprClass: { 16918 auto *FPPE = cast<FunctionParmPackExpr>(E); 16919 // If any of the declarations in the pack is odr-used, then the expression 16920 // as a whole constitutes an odr-use. 16921 for (VarDecl *D : *FPPE) 16922 if (IsPotentialResultOdrUsed(D)) 16923 return ExprEmpty(); 16924 16925 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 16926 // nothing cares about whether we marked this as an odr-use, but it might 16927 // be useful for non-compiler tools. 16928 MarkNotOdrUsed(); 16929 break; 16930 } 16931 16932 // -- If e is a subscripting operation with an array operand... 16933 case Expr::ArraySubscriptExprClass: { 16934 auto *ASE = cast<ArraySubscriptExpr>(E); 16935 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 16936 if (!OldBase->getType()->isArrayType()) 16937 break; 16938 ExprResult Base = Rebuild(OldBase); 16939 if (!Base.isUsable()) 16940 return Base; 16941 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 16942 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 16943 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 16944 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 16945 ASE->getRBracketLoc()); 16946 } 16947 16948 case Expr::MemberExprClass: { 16949 auto *ME = cast<MemberExpr>(E); 16950 // -- If e is a class member access expression [...] naming a non-static 16951 // data member... 16952 if (isa<FieldDecl>(ME->getMemberDecl())) { 16953 ExprResult Base = Rebuild(ME->getBase()); 16954 if (!Base.isUsable()) 16955 return Base; 16956 return MemberExpr::Create( 16957 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 16958 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 16959 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 16960 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 16961 ME->getObjectKind(), ME->isNonOdrUse()); 16962 } 16963 16964 if (ME->getMemberDecl()->isCXXInstanceMember()) 16965 break; 16966 16967 // -- If e is a class member access expression naming a static data member, 16968 // ... 16969 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 16970 break; 16971 16972 // Rebuild as a non-odr-use MemberExpr. 16973 MarkNotOdrUsed(); 16974 return MemberExpr::Create( 16975 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 16976 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 16977 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 16978 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 16979 return ExprEmpty(); 16980 } 16981 16982 case Expr::BinaryOperatorClass: { 16983 auto *BO = cast<BinaryOperator>(E); 16984 Expr *LHS = BO->getLHS(); 16985 Expr *RHS = BO->getRHS(); 16986 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 16987 if (BO->getOpcode() == BO_PtrMemD) { 16988 ExprResult Sub = Rebuild(LHS); 16989 if (!Sub.isUsable()) 16990 return Sub; 16991 LHS = Sub.get(); 16992 // -- If e is a comma expression, ... 16993 } else if (BO->getOpcode() == BO_Comma) { 16994 ExprResult Sub = Rebuild(RHS); 16995 if (!Sub.isUsable()) 16996 return Sub; 16997 RHS = Sub.get(); 16998 } else { 16999 break; 17000 } 17001 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 17002 LHS, RHS); 17003 } 17004 17005 // -- If e has the form (e1)... 17006 case Expr::ParenExprClass: { 17007 auto *PE = cast<ParenExpr>(E); 17008 ExprResult Sub = Rebuild(PE->getSubExpr()); 17009 if (!Sub.isUsable()) 17010 return Sub; 17011 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 17012 } 17013 17014 // -- If e is a glvalue conditional expression, ... 17015 // We don't apply this to a binary conditional operator. FIXME: Should we? 17016 case Expr::ConditionalOperatorClass: { 17017 auto *CO = cast<ConditionalOperator>(E); 17018 ExprResult LHS = Rebuild(CO->getLHS()); 17019 if (LHS.isInvalid()) 17020 return ExprError(); 17021 ExprResult RHS = Rebuild(CO->getRHS()); 17022 if (RHS.isInvalid()) 17023 return ExprError(); 17024 if (!LHS.isUsable() && !RHS.isUsable()) 17025 return ExprEmpty(); 17026 if (!LHS.isUsable()) 17027 LHS = CO->getLHS(); 17028 if (!RHS.isUsable()) 17029 RHS = CO->getRHS(); 17030 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 17031 CO->getCond(), LHS.get(), RHS.get()); 17032 } 17033 17034 // [Clang extension] 17035 // -- If e has the form __extension__ e1... 17036 case Expr::UnaryOperatorClass: { 17037 auto *UO = cast<UnaryOperator>(E); 17038 if (UO->getOpcode() != UO_Extension) 17039 break; 17040 ExprResult Sub = Rebuild(UO->getSubExpr()); 17041 if (!Sub.isUsable()) 17042 return Sub; 17043 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 17044 Sub.get()); 17045 } 17046 17047 // [Clang extension] 17048 // -- If e has the form _Generic(...), the set of potential results is the 17049 // union of the sets of potential results of the associated expressions. 17050 case Expr::GenericSelectionExprClass: { 17051 auto *GSE = cast<GenericSelectionExpr>(E); 17052 17053 SmallVector<Expr *, 4> AssocExprs; 17054 bool AnyChanged = false; 17055 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 17056 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 17057 if (AssocExpr.isInvalid()) 17058 return ExprError(); 17059 if (AssocExpr.isUsable()) { 17060 AssocExprs.push_back(AssocExpr.get()); 17061 AnyChanged = true; 17062 } else { 17063 AssocExprs.push_back(OrigAssocExpr); 17064 } 17065 } 17066 17067 return AnyChanged ? S.CreateGenericSelectionExpr( 17068 GSE->getGenericLoc(), GSE->getDefaultLoc(), 17069 GSE->getRParenLoc(), GSE->getControllingExpr(), 17070 GSE->getAssocTypeSourceInfos(), AssocExprs) 17071 : ExprEmpty(); 17072 } 17073 17074 // [Clang extension] 17075 // -- If e has the form __builtin_choose_expr(...), the set of potential 17076 // results is the union of the sets of potential results of the 17077 // second and third subexpressions. 17078 case Expr::ChooseExprClass: { 17079 auto *CE = cast<ChooseExpr>(E); 17080 17081 ExprResult LHS = Rebuild(CE->getLHS()); 17082 if (LHS.isInvalid()) 17083 return ExprError(); 17084 17085 ExprResult RHS = Rebuild(CE->getLHS()); 17086 if (RHS.isInvalid()) 17087 return ExprError(); 17088 17089 if (!LHS.get() && !RHS.get()) 17090 return ExprEmpty(); 17091 if (!LHS.isUsable()) 17092 LHS = CE->getLHS(); 17093 if (!RHS.isUsable()) 17094 RHS = CE->getRHS(); 17095 17096 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 17097 RHS.get(), CE->getRParenLoc()); 17098 } 17099 17100 // Step through non-syntactic nodes. 17101 case Expr::ConstantExprClass: { 17102 auto *CE = cast<ConstantExpr>(E); 17103 ExprResult Sub = Rebuild(CE->getSubExpr()); 17104 if (!Sub.isUsable()) 17105 return Sub; 17106 return ConstantExpr::Create(S.Context, Sub.get()); 17107 } 17108 17109 // We could mostly rely on the recursive rebuilding to rebuild implicit 17110 // casts, but not at the top level, so rebuild them here. 17111 case Expr::ImplicitCastExprClass: { 17112 auto *ICE = cast<ImplicitCastExpr>(E); 17113 // Only step through the narrow set of cast kinds we expect to encounter. 17114 // Anything else suggests we've left the region in which potential results 17115 // can be found. 17116 switch (ICE->getCastKind()) { 17117 case CK_NoOp: 17118 case CK_DerivedToBase: 17119 case CK_UncheckedDerivedToBase: { 17120 ExprResult Sub = Rebuild(ICE->getSubExpr()); 17121 if (!Sub.isUsable()) 17122 return Sub; 17123 CXXCastPath Path(ICE->path()); 17124 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 17125 ICE->getValueKind(), &Path); 17126 } 17127 17128 default: 17129 break; 17130 } 17131 break; 17132 } 17133 17134 default: 17135 break; 17136 } 17137 17138 // Can't traverse through this node. Nothing to do. 17139 return ExprEmpty(); 17140 } 17141 17142 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 17143 // Check whether the operand is or contains an object of non-trivial C union 17144 // type. 17145 if (E->getType().isVolatileQualified() && 17146 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 17147 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 17148 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 17149 Sema::NTCUC_LValueToRValueVolatile, 17150 NTCUK_Destruct|NTCUK_Copy); 17151 17152 // C++2a [basic.def.odr]p4: 17153 // [...] an expression of non-volatile-qualified non-class type to which 17154 // the lvalue-to-rvalue conversion is applied [...] 17155 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 17156 return E; 17157 17158 ExprResult Result = 17159 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 17160 if (Result.isInvalid()) 17161 return ExprError(); 17162 return Result.get() ? Result : E; 17163 } 17164 17165 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 17166 Res = CorrectDelayedTyposInExpr(Res); 17167 17168 if (!Res.isUsable()) 17169 return Res; 17170 17171 // If a constant-expression is a reference to a variable where we delay 17172 // deciding whether it is an odr-use, just assume we will apply the 17173 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 17174 // (a non-type template argument), we have special handling anyway. 17175 return CheckLValueToRValueConversionOperand(Res.get()); 17176 } 17177 17178 void Sema::CleanupVarDeclMarking() { 17179 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 17180 // call. 17181 MaybeODRUseExprSet LocalMaybeODRUseExprs; 17182 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 17183 17184 for (Expr *E : LocalMaybeODRUseExprs) { 17185 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 17186 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 17187 DRE->getLocation(), *this); 17188 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 17189 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 17190 *this); 17191 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 17192 for (VarDecl *VD : *FP) 17193 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 17194 } else { 17195 llvm_unreachable("Unexpected expression"); 17196 } 17197 } 17198 17199 assert(MaybeODRUseExprs.empty() && 17200 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 17201 } 17202 17203 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 17204 VarDecl *Var, Expr *E) { 17205 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 17206 isa<FunctionParmPackExpr>(E)) && 17207 "Invalid Expr argument to DoMarkVarDeclReferenced"); 17208 Var->setReferenced(); 17209 17210 if (Var->isInvalidDecl()) 17211 return; 17212 17213 auto *MSI = Var->getMemberSpecializationInfo(); 17214 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 17215 : Var->getTemplateSpecializationKind(); 17216 17217 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 17218 bool UsableInConstantExpr = 17219 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 17220 17221 // C++20 [expr.const]p12: 17222 // A variable [...] is needed for constant evaluation if it is [...] a 17223 // variable whose name appears as a potentially constant evaluated 17224 // expression that is either a contexpr variable or is of non-volatile 17225 // const-qualified integral type or of reference type 17226 bool NeededForConstantEvaluation = 17227 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 17228 17229 bool NeedDefinition = 17230 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 17231 17232 VarTemplateSpecializationDecl *VarSpec = 17233 dyn_cast<VarTemplateSpecializationDecl>(Var); 17234 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 17235 "Can't instantiate a partial template specialization."); 17236 17237 // If this might be a member specialization of a static data member, check 17238 // the specialization is visible. We already did the checks for variable 17239 // template specializations when we created them. 17240 if (NeedDefinition && TSK != TSK_Undeclared && 17241 !isa<VarTemplateSpecializationDecl>(Var)) 17242 SemaRef.checkSpecializationVisibility(Loc, Var); 17243 17244 // Perform implicit instantiation of static data members, static data member 17245 // templates of class templates, and variable template specializations. Delay 17246 // instantiations of variable templates, except for those that could be used 17247 // in a constant expression. 17248 if (NeedDefinition && isTemplateInstantiation(TSK)) { 17249 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 17250 // instantiation declaration if a variable is usable in a constant 17251 // expression (among other cases). 17252 bool TryInstantiating = 17253 TSK == TSK_ImplicitInstantiation || 17254 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 17255 17256 if (TryInstantiating) { 17257 SourceLocation PointOfInstantiation = 17258 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 17259 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17260 if (FirstInstantiation) { 17261 PointOfInstantiation = Loc; 17262 if (MSI) 17263 MSI->setPointOfInstantiation(PointOfInstantiation); 17264 else 17265 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17266 } 17267 17268 bool InstantiationDependent = false; 17269 bool IsNonDependent = 17270 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 17271 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 17272 : true; 17273 17274 // Do not instantiate specializations that are still type-dependent. 17275 if (IsNonDependent) { 17276 if (UsableInConstantExpr) { 17277 // Do not defer instantiations of variables that could be used in a 17278 // constant expression. 17279 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 17280 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 17281 }); 17282 } else if (FirstInstantiation || 17283 isa<VarTemplateSpecializationDecl>(Var)) { 17284 // FIXME: For a specialization of a variable template, we don't 17285 // distinguish between "declaration and type implicitly instantiated" 17286 // and "implicit instantiation of definition requested", so we have 17287 // no direct way to avoid enqueueing the pending instantiation 17288 // multiple times. 17289 SemaRef.PendingInstantiations 17290 .push_back(std::make_pair(Var, PointOfInstantiation)); 17291 } 17292 } 17293 } 17294 } 17295 17296 // C++2a [basic.def.odr]p4: 17297 // A variable x whose name appears as a potentially-evaluated expression e 17298 // is odr-used by e unless 17299 // -- x is a reference that is usable in constant expressions 17300 // -- x is a variable of non-reference type that is usable in constant 17301 // expressions and has no mutable subobjects [FIXME], and e is an 17302 // element of the set of potential results of an expression of 17303 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17304 // conversion is applied 17305 // -- x is a variable of non-reference type, and e is an element of the set 17306 // of potential results of a discarded-value expression to which the 17307 // lvalue-to-rvalue conversion is not applied [FIXME] 17308 // 17309 // We check the first part of the second bullet here, and 17310 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 17311 // FIXME: To get the third bullet right, we need to delay this even for 17312 // variables that are not usable in constant expressions. 17313 17314 // If we already know this isn't an odr-use, there's nothing more to do. 17315 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 17316 if (DRE->isNonOdrUse()) 17317 return; 17318 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 17319 if (ME->isNonOdrUse()) 17320 return; 17321 17322 switch (OdrUse) { 17323 case OdrUseContext::None: 17324 assert((!E || isa<FunctionParmPackExpr>(E)) && 17325 "missing non-odr-use marking for unevaluated decl ref"); 17326 break; 17327 17328 case OdrUseContext::FormallyOdrUsed: 17329 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 17330 // behavior. 17331 break; 17332 17333 case OdrUseContext::Used: 17334 // If we might later find that this expression isn't actually an odr-use, 17335 // delay the marking. 17336 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 17337 SemaRef.MaybeODRUseExprs.insert(E); 17338 else 17339 MarkVarDeclODRUsed(Var, Loc, SemaRef); 17340 break; 17341 17342 case OdrUseContext::Dependent: 17343 // If this is a dependent context, we don't need to mark variables as 17344 // odr-used, but we may still need to track them for lambda capture. 17345 // FIXME: Do we also need to do this inside dependent typeid expressions 17346 // (which are modeled as unevaluated at this point)? 17347 const bool RefersToEnclosingScope = 17348 (SemaRef.CurContext != Var->getDeclContext() && 17349 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 17350 if (RefersToEnclosingScope) { 17351 LambdaScopeInfo *const LSI = 17352 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 17353 if (LSI && (!LSI->CallOperator || 17354 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 17355 // If a variable could potentially be odr-used, defer marking it so 17356 // until we finish analyzing the full expression for any 17357 // lvalue-to-rvalue 17358 // or discarded value conversions that would obviate odr-use. 17359 // Add it to the list of potential captures that will be analyzed 17360 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 17361 // unless the variable is a reference that was initialized by a constant 17362 // expression (this will never need to be captured or odr-used). 17363 // 17364 // FIXME: We can simplify this a lot after implementing P0588R1. 17365 assert(E && "Capture variable should be used in an expression."); 17366 if (!Var->getType()->isReferenceType() || 17367 !Var->isUsableInConstantExpressions(SemaRef.Context)) 17368 LSI->addPotentialCapture(E->IgnoreParens()); 17369 } 17370 } 17371 break; 17372 } 17373 } 17374 17375 /// Mark a variable referenced, and check whether it is odr-used 17376 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 17377 /// used directly for normal expressions referring to VarDecl. 17378 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 17379 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 17380 } 17381 17382 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 17383 Decl *D, Expr *E, bool MightBeOdrUse) { 17384 if (SemaRef.isInOpenMPDeclareTargetContext()) 17385 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 17386 17387 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 17388 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 17389 return; 17390 } 17391 17392 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 17393 17394 // If this is a call to a method via a cast, also mark the method in the 17395 // derived class used in case codegen can devirtualize the call. 17396 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 17397 if (!ME) 17398 return; 17399 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 17400 if (!MD) 17401 return; 17402 // Only attempt to devirtualize if this is truly a virtual call. 17403 bool IsVirtualCall = MD->isVirtual() && 17404 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 17405 if (!IsVirtualCall) 17406 return; 17407 17408 // If it's possible to devirtualize the call, mark the called function 17409 // referenced. 17410 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 17411 ME->getBase(), SemaRef.getLangOpts().AppleKext); 17412 if (DM) 17413 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 17414 } 17415 17416 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 17417 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 17418 // TODO: update this with DR# once a defect report is filed. 17419 // C++11 defect. The address of a pure member should not be an ODR use, even 17420 // if it's a qualified reference. 17421 bool OdrUse = true; 17422 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 17423 if (Method->isVirtual() && 17424 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 17425 OdrUse = false; 17426 17427 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 17428 if (!isConstantEvaluated() && FD->isConsteval() && 17429 !RebuildingImmediateInvocation) 17430 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 17431 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 17432 } 17433 17434 /// Perform reference-marking and odr-use handling for a MemberExpr. 17435 void Sema::MarkMemberReferenced(MemberExpr *E) { 17436 // C++11 [basic.def.odr]p2: 17437 // A non-overloaded function whose name appears as a potentially-evaluated 17438 // expression or a member of a set of candidate functions, if selected by 17439 // overload resolution when referred to from a potentially-evaluated 17440 // expression, is odr-used, unless it is a pure virtual function and its 17441 // name is not explicitly qualified. 17442 bool MightBeOdrUse = true; 17443 if (E->performsVirtualDispatch(getLangOpts())) { 17444 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 17445 if (Method->isPure()) 17446 MightBeOdrUse = false; 17447 } 17448 SourceLocation Loc = 17449 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 17450 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 17451 } 17452 17453 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 17454 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 17455 for (VarDecl *VD : *E) 17456 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 17457 } 17458 17459 /// Perform marking for a reference to an arbitrary declaration. It 17460 /// marks the declaration referenced, and performs odr-use checking for 17461 /// functions and variables. This method should not be used when building a 17462 /// normal expression which refers to a variable. 17463 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 17464 bool MightBeOdrUse) { 17465 if (MightBeOdrUse) { 17466 if (auto *VD = dyn_cast<VarDecl>(D)) { 17467 MarkVariableReferenced(Loc, VD); 17468 return; 17469 } 17470 } 17471 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 17472 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 17473 return; 17474 } 17475 D->setReferenced(); 17476 } 17477 17478 namespace { 17479 // Mark all of the declarations used by a type as referenced. 17480 // FIXME: Not fully implemented yet! We need to have a better understanding 17481 // of when we're entering a context we should not recurse into. 17482 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 17483 // TreeTransforms rebuilding the type in a new context. Rather than 17484 // duplicating the TreeTransform logic, we should consider reusing it here. 17485 // Currently that causes problems when rebuilding LambdaExprs. 17486 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 17487 Sema &S; 17488 SourceLocation Loc; 17489 17490 public: 17491 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 17492 17493 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 17494 17495 bool TraverseTemplateArgument(const TemplateArgument &Arg); 17496 }; 17497 } 17498 17499 bool MarkReferencedDecls::TraverseTemplateArgument( 17500 const TemplateArgument &Arg) { 17501 { 17502 // A non-type template argument is a constant-evaluated context. 17503 EnterExpressionEvaluationContext Evaluated( 17504 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 17505 if (Arg.getKind() == TemplateArgument::Declaration) { 17506 if (Decl *D = Arg.getAsDecl()) 17507 S.MarkAnyDeclReferenced(Loc, D, true); 17508 } else if (Arg.getKind() == TemplateArgument::Expression) { 17509 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 17510 } 17511 } 17512 17513 return Inherited::TraverseTemplateArgument(Arg); 17514 } 17515 17516 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 17517 MarkReferencedDecls Marker(*this, Loc); 17518 Marker.TraverseType(T); 17519 } 17520 17521 namespace { 17522 /// Helper class that marks all of the declarations referenced by 17523 /// potentially-evaluated subexpressions as "referenced". 17524 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 17525 public: 17526 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 17527 bool SkipLocalVariables; 17528 17529 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 17530 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 17531 17532 void visitUsedDecl(SourceLocation Loc, Decl *D) { 17533 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 17534 } 17535 17536 void VisitDeclRefExpr(DeclRefExpr *E) { 17537 // If we were asked not to visit local variables, don't. 17538 if (SkipLocalVariables) { 17539 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 17540 if (VD->hasLocalStorage()) 17541 return; 17542 } 17543 S.MarkDeclRefReferenced(E); 17544 } 17545 17546 void VisitMemberExpr(MemberExpr *E) { 17547 S.MarkMemberReferenced(E); 17548 Visit(E->getBase()); 17549 } 17550 }; 17551 } // namespace 17552 17553 /// Mark any declarations that appear within this expression or any 17554 /// potentially-evaluated subexpressions as "referenced". 17555 /// 17556 /// \param SkipLocalVariables If true, don't mark local variables as 17557 /// 'referenced'. 17558 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 17559 bool SkipLocalVariables) { 17560 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 17561 } 17562 17563 /// Emit a diagnostic that describes an effect on the run-time behavior 17564 /// of the program being compiled. 17565 /// 17566 /// This routine emits the given diagnostic when the code currently being 17567 /// type-checked is "potentially evaluated", meaning that there is a 17568 /// possibility that the code will actually be executable. Code in sizeof() 17569 /// expressions, code used only during overload resolution, etc., are not 17570 /// potentially evaluated. This routine will suppress such diagnostics or, 17571 /// in the absolutely nutty case of potentially potentially evaluated 17572 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 17573 /// later. 17574 /// 17575 /// This routine should be used for all diagnostics that describe the run-time 17576 /// behavior of a program, such as passing a non-POD value through an ellipsis. 17577 /// Failure to do so will likely result in spurious diagnostics or failures 17578 /// during overload resolution or within sizeof/alignof/typeof/typeid. 17579 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 17580 const PartialDiagnostic &PD) { 17581 switch (ExprEvalContexts.back().Context) { 17582 case ExpressionEvaluationContext::Unevaluated: 17583 case ExpressionEvaluationContext::UnevaluatedList: 17584 case ExpressionEvaluationContext::UnevaluatedAbstract: 17585 case ExpressionEvaluationContext::DiscardedStatement: 17586 // The argument will never be evaluated, so don't complain. 17587 break; 17588 17589 case ExpressionEvaluationContext::ConstantEvaluated: 17590 // Relevant diagnostics should be produced by constant evaluation. 17591 break; 17592 17593 case ExpressionEvaluationContext::PotentiallyEvaluated: 17594 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17595 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 17596 FunctionScopes.back()->PossiblyUnreachableDiags. 17597 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 17598 return true; 17599 } 17600 17601 // The initializer of a constexpr variable or of the first declaration of a 17602 // static data member is not syntactically a constant evaluated constant, 17603 // but nonetheless is always required to be a constant expression, so we 17604 // can skip diagnosing. 17605 // FIXME: Using the mangling context here is a hack. 17606 if (auto *VD = dyn_cast_or_null<VarDecl>( 17607 ExprEvalContexts.back().ManglingContextDecl)) { 17608 if (VD->isConstexpr() || 17609 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 17610 break; 17611 // FIXME: For any other kind of variable, we should build a CFG for its 17612 // initializer and check whether the context in question is reachable. 17613 } 17614 17615 Diag(Loc, PD); 17616 return true; 17617 } 17618 17619 return false; 17620 } 17621 17622 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 17623 const PartialDiagnostic &PD) { 17624 return DiagRuntimeBehavior( 17625 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 17626 } 17627 17628 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 17629 CallExpr *CE, FunctionDecl *FD) { 17630 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 17631 return false; 17632 17633 // If we're inside a decltype's expression, don't check for a valid return 17634 // type or construct temporaries until we know whether this is the last call. 17635 if (ExprEvalContexts.back().ExprContext == 17636 ExpressionEvaluationContextRecord::EK_Decltype) { 17637 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 17638 return false; 17639 } 17640 17641 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 17642 FunctionDecl *FD; 17643 CallExpr *CE; 17644 17645 public: 17646 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 17647 : FD(FD), CE(CE) { } 17648 17649 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17650 if (!FD) { 17651 S.Diag(Loc, diag::err_call_incomplete_return) 17652 << T << CE->getSourceRange(); 17653 return; 17654 } 17655 17656 S.Diag(Loc, diag::err_call_function_incomplete_return) 17657 << CE->getSourceRange() << FD->getDeclName() << T; 17658 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 17659 << FD->getDeclName(); 17660 } 17661 } Diagnoser(FD, CE); 17662 17663 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 17664 return true; 17665 17666 return false; 17667 } 17668 17669 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 17670 // will prevent this condition from triggering, which is what we want. 17671 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 17672 SourceLocation Loc; 17673 17674 unsigned diagnostic = diag::warn_condition_is_assignment; 17675 bool IsOrAssign = false; 17676 17677 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 17678 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 17679 return; 17680 17681 IsOrAssign = Op->getOpcode() == BO_OrAssign; 17682 17683 // Greylist some idioms by putting them into a warning subcategory. 17684 if (ObjCMessageExpr *ME 17685 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 17686 Selector Sel = ME->getSelector(); 17687 17688 // self = [<foo> init...] 17689 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 17690 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17691 17692 // <foo> = [<bar> nextObject] 17693 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 17694 diagnostic = diag::warn_condition_is_idiomatic_assignment; 17695 } 17696 17697 Loc = Op->getOperatorLoc(); 17698 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 17699 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 17700 return; 17701 17702 IsOrAssign = Op->getOperator() == OO_PipeEqual; 17703 Loc = Op->getOperatorLoc(); 17704 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 17705 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 17706 else { 17707 // Not an assignment. 17708 return; 17709 } 17710 17711 Diag(Loc, diagnostic) << E->getSourceRange(); 17712 17713 SourceLocation Open = E->getBeginLoc(); 17714 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 17715 Diag(Loc, diag::note_condition_assign_silence) 17716 << FixItHint::CreateInsertion(Open, "(") 17717 << FixItHint::CreateInsertion(Close, ")"); 17718 17719 if (IsOrAssign) 17720 Diag(Loc, diag::note_condition_or_assign_to_comparison) 17721 << FixItHint::CreateReplacement(Loc, "!="); 17722 else 17723 Diag(Loc, diag::note_condition_assign_to_comparison) 17724 << FixItHint::CreateReplacement(Loc, "=="); 17725 } 17726 17727 /// Redundant parentheses over an equality comparison can indicate 17728 /// that the user intended an assignment used as condition. 17729 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 17730 // Don't warn if the parens came from a macro. 17731 SourceLocation parenLoc = ParenE->getBeginLoc(); 17732 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 17733 return; 17734 // Don't warn for dependent expressions. 17735 if (ParenE->isTypeDependent()) 17736 return; 17737 17738 Expr *E = ParenE->IgnoreParens(); 17739 17740 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 17741 if (opE->getOpcode() == BO_EQ && 17742 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 17743 == Expr::MLV_Valid) { 17744 SourceLocation Loc = opE->getOperatorLoc(); 17745 17746 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 17747 SourceRange ParenERange = ParenE->getSourceRange(); 17748 Diag(Loc, diag::note_equality_comparison_silence) 17749 << FixItHint::CreateRemoval(ParenERange.getBegin()) 17750 << FixItHint::CreateRemoval(ParenERange.getEnd()); 17751 Diag(Loc, diag::note_equality_comparison_to_assign) 17752 << FixItHint::CreateReplacement(Loc, "="); 17753 } 17754 } 17755 17756 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 17757 bool IsConstexpr) { 17758 DiagnoseAssignmentAsCondition(E); 17759 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 17760 DiagnoseEqualityWithExtraParens(parenE); 17761 17762 ExprResult result = CheckPlaceholderExpr(E); 17763 if (result.isInvalid()) return ExprError(); 17764 E = result.get(); 17765 17766 if (!E->isTypeDependent()) { 17767 if (getLangOpts().CPlusPlus) 17768 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 17769 17770 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 17771 if (ERes.isInvalid()) 17772 return ExprError(); 17773 E = ERes.get(); 17774 17775 QualType T = E->getType(); 17776 if (!T->isScalarType()) { // C99 6.8.4.1p1 17777 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 17778 << T << E->getSourceRange(); 17779 return ExprError(); 17780 } 17781 CheckBoolLikeConversion(E, Loc); 17782 } 17783 17784 return E; 17785 } 17786 17787 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 17788 Expr *SubExpr, ConditionKind CK) { 17789 // Empty conditions are valid in for-statements. 17790 if (!SubExpr) 17791 return ConditionResult(); 17792 17793 ExprResult Cond; 17794 switch (CK) { 17795 case ConditionKind::Boolean: 17796 Cond = CheckBooleanCondition(Loc, SubExpr); 17797 break; 17798 17799 case ConditionKind::ConstexprIf: 17800 Cond = CheckBooleanCondition(Loc, SubExpr, true); 17801 break; 17802 17803 case ConditionKind::Switch: 17804 Cond = CheckSwitchCondition(Loc, SubExpr); 17805 break; 17806 } 17807 if (Cond.isInvalid()) 17808 return ConditionError(); 17809 17810 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 17811 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 17812 if (!FullExpr.get()) 17813 return ConditionError(); 17814 17815 return ConditionResult(*this, nullptr, FullExpr, 17816 CK == ConditionKind::ConstexprIf); 17817 } 17818 17819 namespace { 17820 /// A visitor for rebuilding a call to an __unknown_any expression 17821 /// to have an appropriate type. 17822 struct RebuildUnknownAnyFunction 17823 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 17824 17825 Sema &S; 17826 17827 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 17828 17829 ExprResult VisitStmt(Stmt *S) { 17830 llvm_unreachable("unexpected statement!"); 17831 } 17832 17833 ExprResult VisitExpr(Expr *E) { 17834 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 17835 << E->getSourceRange(); 17836 return ExprError(); 17837 } 17838 17839 /// Rebuild an expression which simply semantically wraps another 17840 /// expression which it shares the type and value kind of. 17841 template <class T> ExprResult rebuildSugarExpr(T *E) { 17842 ExprResult SubResult = Visit(E->getSubExpr()); 17843 if (SubResult.isInvalid()) return ExprError(); 17844 17845 Expr *SubExpr = SubResult.get(); 17846 E->setSubExpr(SubExpr); 17847 E->setType(SubExpr->getType()); 17848 E->setValueKind(SubExpr->getValueKind()); 17849 assert(E->getObjectKind() == OK_Ordinary); 17850 return E; 17851 } 17852 17853 ExprResult VisitParenExpr(ParenExpr *E) { 17854 return rebuildSugarExpr(E); 17855 } 17856 17857 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17858 return rebuildSugarExpr(E); 17859 } 17860 17861 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17862 ExprResult SubResult = Visit(E->getSubExpr()); 17863 if (SubResult.isInvalid()) return ExprError(); 17864 17865 Expr *SubExpr = SubResult.get(); 17866 E->setSubExpr(SubExpr); 17867 E->setType(S.Context.getPointerType(SubExpr->getType())); 17868 assert(E->getValueKind() == VK_RValue); 17869 assert(E->getObjectKind() == OK_Ordinary); 17870 return E; 17871 } 17872 17873 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 17874 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 17875 17876 E->setType(VD->getType()); 17877 17878 assert(E->getValueKind() == VK_RValue); 17879 if (S.getLangOpts().CPlusPlus && 17880 !(isa<CXXMethodDecl>(VD) && 17881 cast<CXXMethodDecl>(VD)->isInstance())) 17882 E->setValueKind(VK_LValue); 17883 17884 return E; 17885 } 17886 17887 ExprResult VisitMemberExpr(MemberExpr *E) { 17888 return resolveDecl(E, E->getMemberDecl()); 17889 } 17890 17891 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17892 return resolveDecl(E, E->getDecl()); 17893 } 17894 }; 17895 } 17896 17897 /// Given a function expression of unknown-any type, try to rebuild it 17898 /// to have a function type. 17899 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 17900 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 17901 if (Result.isInvalid()) return ExprError(); 17902 return S.DefaultFunctionArrayConversion(Result.get()); 17903 } 17904 17905 namespace { 17906 /// A visitor for rebuilding an expression of type __unknown_anytype 17907 /// into one which resolves the type directly on the referring 17908 /// expression. Strict preservation of the original source 17909 /// structure is not a goal. 17910 struct RebuildUnknownAnyExpr 17911 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 17912 17913 Sema &S; 17914 17915 /// The current destination type. 17916 QualType DestType; 17917 17918 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 17919 : S(S), DestType(CastType) {} 17920 17921 ExprResult VisitStmt(Stmt *S) { 17922 llvm_unreachable("unexpected statement!"); 17923 } 17924 17925 ExprResult VisitExpr(Expr *E) { 17926 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 17927 << E->getSourceRange(); 17928 return ExprError(); 17929 } 17930 17931 ExprResult VisitCallExpr(CallExpr *E); 17932 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 17933 17934 /// Rebuild an expression which simply semantically wraps another 17935 /// expression which it shares the type and value kind of. 17936 template <class T> ExprResult rebuildSugarExpr(T *E) { 17937 ExprResult SubResult = Visit(E->getSubExpr()); 17938 if (SubResult.isInvalid()) return ExprError(); 17939 Expr *SubExpr = SubResult.get(); 17940 E->setSubExpr(SubExpr); 17941 E->setType(SubExpr->getType()); 17942 E->setValueKind(SubExpr->getValueKind()); 17943 assert(E->getObjectKind() == OK_Ordinary); 17944 return E; 17945 } 17946 17947 ExprResult VisitParenExpr(ParenExpr *E) { 17948 return rebuildSugarExpr(E); 17949 } 17950 17951 ExprResult VisitUnaryExtension(UnaryOperator *E) { 17952 return rebuildSugarExpr(E); 17953 } 17954 17955 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 17956 const PointerType *Ptr = DestType->getAs<PointerType>(); 17957 if (!Ptr) { 17958 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 17959 << E->getSourceRange(); 17960 return ExprError(); 17961 } 17962 17963 if (isa<CallExpr>(E->getSubExpr())) { 17964 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 17965 << E->getSourceRange(); 17966 return ExprError(); 17967 } 17968 17969 assert(E->getValueKind() == VK_RValue); 17970 assert(E->getObjectKind() == OK_Ordinary); 17971 E->setType(DestType); 17972 17973 // Build the sub-expression as if it were an object of the pointee type. 17974 DestType = Ptr->getPointeeType(); 17975 ExprResult SubResult = Visit(E->getSubExpr()); 17976 if (SubResult.isInvalid()) return ExprError(); 17977 E->setSubExpr(SubResult.get()); 17978 return E; 17979 } 17980 17981 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 17982 17983 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 17984 17985 ExprResult VisitMemberExpr(MemberExpr *E) { 17986 return resolveDecl(E, E->getMemberDecl()); 17987 } 17988 17989 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 17990 return resolveDecl(E, E->getDecl()); 17991 } 17992 }; 17993 } 17994 17995 /// Rebuilds a call expression which yielded __unknown_anytype. 17996 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 17997 Expr *CalleeExpr = E->getCallee(); 17998 17999 enum FnKind { 18000 FK_MemberFunction, 18001 FK_FunctionPointer, 18002 FK_BlockPointer 18003 }; 18004 18005 FnKind Kind; 18006 QualType CalleeType = CalleeExpr->getType(); 18007 if (CalleeType == S.Context.BoundMemberTy) { 18008 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 18009 Kind = FK_MemberFunction; 18010 CalleeType = Expr::findBoundMemberType(CalleeExpr); 18011 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 18012 CalleeType = Ptr->getPointeeType(); 18013 Kind = FK_FunctionPointer; 18014 } else { 18015 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 18016 Kind = FK_BlockPointer; 18017 } 18018 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 18019 18020 // Verify that this is a legal result type of a function. 18021 if (DestType->isArrayType() || DestType->isFunctionType()) { 18022 unsigned diagID = diag::err_func_returning_array_function; 18023 if (Kind == FK_BlockPointer) 18024 diagID = diag::err_block_returning_array_function; 18025 18026 S.Diag(E->getExprLoc(), diagID) 18027 << DestType->isFunctionType() << DestType; 18028 return ExprError(); 18029 } 18030 18031 // Otherwise, go ahead and set DestType as the call's result. 18032 E->setType(DestType.getNonLValueExprType(S.Context)); 18033 E->setValueKind(Expr::getValueKindForType(DestType)); 18034 assert(E->getObjectKind() == OK_Ordinary); 18035 18036 // Rebuild the function type, replacing the result type with DestType. 18037 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 18038 if (Proto) { 18039 // __unknown_anytype(...) is a special case used by the debugger when 18040 // it has no idea what a function's signature is. 18041 // 18042 // We want to build this call essentially under the K&R 18043 // unprototyped rules, but making a FunctionNoProtoType in C++ 18044 // would foul up all sorts of assumptions. However, we cannot 18045 // simply pass all arguments as variadic arguments, nor can we 18046 // portably just call the function under a non-variadic type; see 18047 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 18048 // However, it turns out that in practice it is generally safe to 18049 // call a function declared as "A foo(B,C,D);" under the prototype 18050 // "A foo(B,C,D,...);". The only known exception is with the 18051 // Windows ABI, where any variadic function is implicitly cdecl 18052 // regardless of its normal CC. Therefore we change the parameter 18053 // types to match the types of the arguments. 18054 // 18055 // This is a hack, but it is far superior to moving the 18056 // corresponding target-specific code from IR-gen to Sema/AST. 18057 18058 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 18059 SmallVector<QualType, 8> ArgTypes; 18060 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 18061 ArgTypes.reserve(E->getNumArgs()); 18062 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 18063 Expr *Arg = E->getArg(i); 18064 QualType ArgType = Arg->getType(); 18065 if (E->isLValue()) { 18066 ArgType = S.Context.getLValueReferenceType(ArgType); 18067 } else if (E->isXValue()) { 18068 ArgType = S.Context.getRValueReferenceType(ArgType); 18069 } 18070 ArgTypes.push_back(ArgType); 18071 } 18072 ParamTypes = ArgTypes; 18073 } 18074 DestType = S.Context.getFunctionType(DestType, ParamTypes, 18075 Proto->getExtProtoInfo()); 18076 } else { 18077 DestType = S.Context.getFunctionNoProtoType(DestType, 18078 FnType->getExtInfo()); 18079 } 18080 18081 // Rebuild the appropriate pointer-to-function type. 18082 switch (Kind) { 18083 case FK_MemberFunction: 18084 // Nothing to do. 18085 break; 18086 18087 case FK_FunctionPointer: 18088 DestType = S.Context.getPointerType(DestType); 18089 break; 18090 18091 case FK_BlockPointer: 18092 DestType = S.Context.getBlockPointerType(DestType); 18093 break; 18094 } 18095 18096 // Finally, we can recurse. 18097 ExprResult CalleeResult = Visit(CalleeExpr); 18098 if (!CalleeResult.isUsable()) return ExprError(); 18099 E->setCallee(CalleeResult.get()); 18100 18101 // Bind a temporary if necessary. 18102 return S.MaybeBindToTemporary(E); 18103 } 18104 18105 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 18106 // Verify that this is a legal result type of a call. 18107 if (DestType->isArrayType() || DestType->isFunctionType()) { 18108 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 18109 << DestType->isFunctionType() << DestType; 18110 return ExprError(); 18111 } 18112 18113 // Rewrite the method result type if available. 18114 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 18115 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 18116 Method->setReturnType(DestType); 18117 } 18118 18119 // Change the type of the message. 18120 E->setType(DestType.getNonReferenceType()); 18121 E->setValueKind(Expr::getValueKindForType(DestType)); 18122 18123 return S.MaybeBindToTemporary(E); 18124 } 18125 18126 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 18127 // The only case we should ever see here is a function-to-pointer decay. 18128 if (E->getCastKind() == CK_FunctionToPointerDecay) { 18129 assert(E->getValueKind() == VK_RValue); 18130 assert(E->getObjectKind() == OK_Ordinary); 18131 18132 E->setType(DestType); 18133 18134 // Rebuild the sub-expression as the pointee (function) type. 18135 DestType = DestType->castAs<PointerType>()->getPointeeType(); 18136 18137 ExprResult Result = Visit(E->getSubExpr()); 18138 if (!Result.isUsable()) return ExprError(); 18139 18140 E->setSubExpr(Result.get()); 18141 return E; 18142 } else if (E->getCastKind() == CK_LValueToRValue) { 18143 assert(E->getValueKind() == VK_RValue); 18144 assert(E->getObjectKind() == OK_Ordinary); 18145 18146 assert(isa<BlockPointerType>(E->getType())); 18147 18148 E->setType(DestType); 18149 18150 // The sub-expression has to be a lvalue reference, so rebuild it as such. 18151 DestType = S.Context.getLValueReferenceType(DestType); 18152 18153 ExprResult Result = Visit(E->getSubExpr()); 18154 if (!Result.isUsable()) return ExprError(); 18155 18156 E->setSubExpr(Result.get()); 18157 return E; 18158 } else { 18159 llvm_unreachable("Unhandled cast type!"); 18160 } 18161 } 18162 18163 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 18164 ExprValueKind ValueKind = VK_LValue; 18165 QualType Type = DestType; 18166 18167 // We know how to make this work for certain kinds of decls: 18168 18169 // - functions 18170 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 18171 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 18172 DestType = Ptr->getPointeeType(); 18173 ExprResult Result = resolveDecl(E, VD); 18174 if (Result.isInvalid()) return ExprError(); 18175 return S.ImpCastExprToType(Result.get(), Type, 18176 CK_FunctionToPointerDecay, VK_RValue); 18177 } 18178 18179 if (!Type->isFunctionType()) { 18180 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 18181 << VD << E->getSourceRange(); 18182 return ExprError(); 18183 } 18184 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 18185 // We must match the FunctionDecl's type to the hack introduced in 18186 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 18187 // type. See the lengthy commentary in that routine. 18188 QualType FDT = FD->getType(); 18189 const FunctionType *FnType = FDT->castAs<FunctionType>(); 18190 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 18191 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 18192 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 18193 SourceLocation Loc = FD->getLocation(); 18194 FunctionDecl *NewFD = FunctionDecl::Create( 18195 S.Context, FD->getDeclContext(), Loc, Loc, 18196 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 18197 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 18198 /*ConstexprKind*/ CSK_unspecified); 18199 18200 if (FD->getQualifier()) 18201 NewFD->setQualifierInfo(FD->getQualifierLoc()); 18202 18203 SmallVector<ParmVarDecl*, 16> Params; 18204 for (const auto &AI : FT->param_types()) { 18205 ParmVarDecl *Param = 18206 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 18207 Param->setScopeInfo(0, Params.size()); 18208 Params.push_back(Param); 18209 } 18210 NewFD->setParams(Params); 18211 DRE->setDecl(NewFD); 18212 VD = DRE->getDecl(); 18213 } 18214 } 18215 18216 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 18217 if (MD->isInstance()) { 18218 ValueKind = VK_RValue; 18219 Type = S.Context.BoundMemberTy; 18220 } 18221 18222 // Function references aren't l-values in C. 18223 if (!S.getLangOpts().CPlusPlus) 18224 ValueKind = VK_RValue; 18225 18226 // - variables 18227 } else if (isa<VarDecl>(VD)) { 18228 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 18229 Type = RefTy->getPointeeType(); 18230 } else if (Type->isFunctionType()) { 18231 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 18232 << VD << E->getSourceRange(); 18233 return ExprError(); 18234 } 18235 18236 // - nothing else 18237 } else { 18238 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 18239 << VD << E->getSourceRange(); 18240 return ExprError(); 18241 } 18242 18243 // Modifying the declaration like this is friendly to IR-gen but 18244 // also really dangerous. 18245 VD->setType(DestType); 18246 E->setType(Type); 18247 E->setValueKind(ValueKind); 18248 return E; 18249 } 18250 18251 /// Check a cast of an unknown-any type. We intentionally only 18252 /// trigger this for C-style casts. 18253 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 18254 Expr *CastExpr, CastKind &CastKind, 18255 ExprValueKind &VK, CXXCastPath &Path) { 18256 // The type we're casting to must be either void or complete. 18257 if (!CastType->isVoidType() && 18258 RequireCompleteType(TypeRange.getBegin(), CastType, 18259 diag::err_typecheck_cast_to_incomplete)) 18260 return ExprError(); 18261 18262 // Rewrite the casted expression from scratch. 18263 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 18264 if (!result.isUsable()) return ExprError(); 18265 18266 CastExpr = result.get(); 18267 VK = CastExpr->getValueKind(); 18268 CastKind = CK_NoOp; 18269 18270 return CastExpr; 18271 } 18272 18273 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 18274 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 18275 } 18276 18277 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 18278 Expr *arg, QualType ¶mType) { 18279 // If the syntactic form of the argument is not an explicit cast of 18280 // any sort, just do default argument promotion. 18281 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 18282 if (!castArg) { 18283 ExprResult result = DefaultArgumentPromotion(arg); 18284 if (result.isInvalid()) return ExprError(); 18285 paramType = result.get()->getType(); 18286 return result; 18287 } 18288 18289 // Otherwise, use the type that was written in the explicit cast. 18290 assert(!arg->hasPlaceholderType()); 18291 paramType = castArg->getTypeAsWritten(); 18292 18293 // Copy-initialize a parameter of that type. 18294 InitializedEntity entity = 18295 InitializedEntity::InitializeParameter(Context, paramType, 18296 /*consumed*/ false); 18297 return PerformCopyInitialization(entity, callLoc, arg); 18298 } 18299 18300 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 18301 Expr *orig = E; 18302 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 18303 while (true) { 18304 E = E->IgnoreParenImpCasts(); 18305 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 18306 E = call->getCallee(); 18307 diagID = diag::err_uncasted_call_of_unknown_any; 18308 } else { 18309 break; 18310 } 18311 } 18312 18313 SourceLocation loc; 18314 NamedDecl *d; 18315 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 18316 loc = ref->getLocation(); 18317 d = ref->getDecl(); 18318 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 18319 loc = mem->getMemberLoc(); 18320 d = mem->getMemberDecl(); 18321 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 18322 diagID = diag::err_uncasted_call_of_unknown_any; 18323 loc = msg->getSelectorStartLoc(); 18324 d = msg->getMethodDecl(); 18325 if (!d) { 18326 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 18327 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 18328 << orig->getSourceRange(); 18329 return ExprError(); 18330 } 18331 } else { 18332 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 18333 << E->getSourceRange(); 18334 return ExprError(); 18335 } 18336 18337 S.Diag(loc, diagID) << d << orig->getSourceRange(); 18338 18339 // Never recoverable. 18340 return ExprError(); 18341 } 18342 18343 /// Check for operands with placeholder types and complain if found. 18344 /// Returns ExprError() if there was an error and no recovery was possible. 18345 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 18346 if (!getLangOpts().CPlusPlus) { 18347 // C cannot handle TypoExpr nodes on either side of a binop because it 18348 // doesn't handle dependent types properly, so make sure any TypoExprs have 18349 // been dealt with before checking the operands. 18350 ExprResult Result = CorrectDelayedTyposInExpr(E); 18351 if (!Result.isUsable()) return ExprError(); 18352 E = Result.get(); 18353 } 18354 18355 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 18356 if (!placeholderType) return E; 18357 18358 switch (placeholderType->getKind()) { 18359 18360 // Overloaded expressions. 18361 case BuiltinType::Overload: { 18362 // Try to resolve a single function template specialization. 18363 // This is obligatory. 18364 ExprResult Result = E; 18365 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 18366 return Result; 18367 18368 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 18369 // leaves Result unchanged on failure. 18370 Result = E; 18371 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 18372 return Result; 18373 18374 // If that failed, try to recover with a call. 18375 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 18376 /*complain*/ true); 18377 return Result; 18378 } 18379 18380 // Bound member functions. 18381 case BuiltinType::BoundMember: { 18382 ExprResult result = E; 18383 const Expr *BME = E->IgnoreParens(); 18384 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 18385 // Try to give a nicer diagnostic if it is a bound member that we recognize. 18386 if (isa<CXXPseudoDestructorExpr>(BME)) { 18387 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 18388 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 18389 if (ME->getMemberNameInfo().getName().getNameKind() == 18390 DeclarationName::CXXDestructorName) 18391 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 18392 } 18393 tryToRecoverWithCall(result, PD, 18394 /*complain*/ true); 18395 return result; 18396 } 18397 18398 // ARC unbridged casts. 18399 case BuiltinType::ARCUnbridgedCast: { 18400 Expr *realCast = stripARCUnbridgedCast(E); 18401 diagnoseARCUnbridgedCast(realCast); 18402 return realCast; 18403 } 18404 18405 // Expressions of unknown type. 18406 case BuiltinType::UnknownAny: 18407 return diagnoseUnknownAnyExpr(*this, E); 18408 18409 // Pseudo-objects. 18410 case BuiltinType::PseudoObject: 18411 return checkPseudoObjectRValue(E); 18412 18413 case BuiltinType::BuiltinFn: { 18414 // Accept __noop without parens by implicitly converting it to a call expr. 18415 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 18416 if (DRE) { 18417 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 18418 if (FD->getBuiltinID() == Builtin::BI__noop) { 18419 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 18420 CK_BuiltinFnToFnPtr) 18421 .get(); 18422 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 18423 VK_RValue, SourceLocation()); 18424 } 18425 } 18426 18427 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 18428 return ExprError(); 18429 } 18430 18431 // Expressions of unknown type. 18432 case BuiltinType::OMPArraySection: 18433 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 18434 return ExprError(); 18435 18436 // Everything else should be impossible. 18437 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 18438 case BuiltinType::Id: 18439 #include "clang/Basic/OpenCLImageTypes.def" 18440 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 18441 case BuiltinType::Id: 18442 #include "clang/Basic/OpenCLExtensionTypes.def" 18443 #define SVE_TYPE(Name, Id, SingletonId) \ 18444 case BuiltinType::Id: 18445 #include "clang/Basic/AArch64SVEACLETypes.def" 18446 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 18447 #define PLACEHOLDER_TYPE(Id, SingletonId) 18448 #include "clang/AST/BuiltinTypes.def" 18449 break; 18450 } 18451 18452 llvm_unreachable("invalid placeholder type!"); 18453 } 18454 18455 bool Sema::CheckCaseExpression(Expr *E) { 18456 if (E->isTypeDependent()) 18457 return true; 18458 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 18459 return E->getType()->isIntegralOrEnumerationType(); 18460 return false; 18461 } 18462 18463 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 18464 ExprResult 18465 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 18466 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 18467 "Unknown Objective-C Boolean value!"); 18468 QualType BoolT = Context.ObjCBuiltinBoolTy; 18469 if (!Context.getBOOLDecl()) { 18470 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 18471 Sema::LookupOrdinaryName); 18472 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 18473 NamedDecl *ND = Result.getFoundDecl(); 18474 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 18475 Context.setBOOLDecl(TD); 18476 } 18477 } 18478 if (Context.getBOOLDecl()) 18479 BoolT = Context.getBOOLType(); 18480 return new (Context) 18481 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 18482 } 18483 18484 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 18485 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 18486 SourceLocation RParen) { 18487 18488 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 18489 18490 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 18491 return Spec.getPlatform() == Platform; 18492 }); 18493 18494 VersionTuple Version; 18495 if (Spec != AvailSpecs.end()) 18496 Version = Spec->getVersion(); 18497 18498 // The use of `@available` in the enclosing function should be analyzed to 18499 // warn when it's used inappropriately (i.e. not if(@available)). 18500 if (getCurFunctionOrMethodDecl()) 18501 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 18502 else if (getCurBlock() || getCurLambda()) 18503 getCurFunction()->HasPotentialAvailabilityViolations = true; 18504 18505 return new (Context) 18506 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 18507 } 18508 18509 bool Sema::IsDependentFunctionNameExpr(Expr *E) { 18510 assert(E->isTypeDependent()); 18511 return isa<UnresolvedLookupExpr>(E); 18512 } 18513 18514 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 18515 ArrayRef<Expr *> SubExprs) { 18516 // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress 18517 // bogus diagnostics and this trick does not work in C. 18518 // FIXME: use containsErrors() to suppress unwanted diags in C. 18519 if (!Context.getLangOpts().RecoveryAST) 18520 return ExprError(); 18521 18522 if (isSFINAEContext()) 18523 return ExprError(); 18524 18525 return RecoveryExpr::Create(Context, Begin, End, SubExprs); 18526 } 18527