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/OperationKinds.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/Builtins.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/ADT/STLExtras.h" 50 #include "llvm/ADT/StringExtras.h" 51 #include "llvm/Support/ConvertUTF.h" 52 #include "llvm/Support/SaveAndRestore.h" 53 54 using namespace clang; 55 using namespace sema; 56 using llvm::RoundingMode; 57 58 /// Determine whether the use of this declaration is valid, without 59 /// emitting diagnostics. 60 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 61 // See if this is an auto-typed variable whose initializer we are parsing. 62 if (ParsingInitForAutoVars.count(D)) 63 return false; 64 65 // See if this is a deleted function. 66 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 67 if (FD->isDeleted()) 68 return false; 69 70 // If the function has a deduced return type, and we can't deduce it, 71 // then we can't use it either. 72 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 73 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 74 return false; 75 76 // See if this is an aligned allocation/deallocation function that is 77 // unavailable. 78 if (TreatUnavailableAsInvalid && 79 isUnavailableAlignedAllocationFunction(*FD)) 80 return false; 81 } 82 83 // See if this function is unavailable. 84 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 85 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 86 return false; 87 88 if (isa<UnresolvedUsingIfExistsDecl>(D)) 89 return false; 90 91 return true; 92 } 93 94 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 95 // Warn if this is used but marked unused. 96 if (const auto *A = D->getAttr<UnusedAttr>()) { 97 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 98 // should diagnose them. 99 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 100 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 101 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 102 if (DC && !DC->hasAttr<UnusedAttr>()) 103 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 104 } 105 } 106 } 107 108 /// Emit a note explaining that this function is deleted. 109 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 110 assert(Decl && Decl->isDeleted()); 111 112 if (Decl->isDefaulted()) { 113 // If the method was explicitly defaulted, point at that declaration. 114 if (!Decl->isImplicit()) 115 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 116 117 // Try to diagnose why this special member function was implicitly 118 // deleted. This might fail, if that reason no longer applies. 119 DiagnoseDeletedDefaultedFunction(Decl); 120 return; 121 } 122 123 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 124 if (Ctor && Ctor->isInheritingConstructor()) 125 return NoteDeletedInheritingConstructor(Ctor); 126 127 Diag(Decl->getLocation(), diag::note_availability_specified_here) 128 << Decl << 1; 129 } 130 131 /// Determine whether a FunctionDecl was ever declared with an 132 /// explicit storage class. 133 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 134 for (auto I : D->redecls()) { 135 if (I->getStorageClass() != SC_None) 136 return true; 137 } 138 return false; 139 } 140 141 /// Check whether we're in an extern inline function and referring to a 142 /// variable or function with internal linkage (C11 6.7.4p3). 143 /// 144 /// This is only a warning because we used to silently accept this code, but 145 /// in many cases it will not behave correctly. This is not enabled in C++ mode 146 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 147 /// and so while there may still be user mistakes, most of the time we can't 148 /// prove that there are errors. 149 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 150 const NamedDecl *D, 151 SourceLocation Loc) { 152 // This is disabled under C++; there are too many ways for this to fire in 153 // contexts where the warning is a false positive, or where it is technically 154 // correct but benign. 155 if (S.getLangOpts().CPlusPlus) 156 return; 157 158 // Check if this is an inlined function or method. 159 FunctionDecl *Current = S.getCurFunctionDecl(); 160 if (!Current) 161 return; 162 if (!Current->isInlined()) 163 return; 164 if (!Current->isExternallyVisible()) 165 return; 166 167 // Check if the decl has internal linkage. 168 if (D->getFormalLinkage() != InternalLinkage) 169 return; 170 171 // Downgrade from ExtWarn to Extension if 172 // (1) the supposedly external inline function is in the main file, 173 // and probably won't be included anywhere else. 174 // (2) the thing we're referencing is a pure function. 175 // (3) the thing we're referencing is another inline function. 176 // This last can give us false negatives, but it's better than warning on 177 // wrappers for simple C library functions. 178 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 179 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 180 if (!DowngradeWarning && UsedFn) 181 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 182 183 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 184 : diag::ext_internal_in_extern_inline) 185 << /*IsVar=*/!UsedFn << D; 186 187 S.MaybeSuggestAddingStaticToDecl(Current); 188 189 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 190 << D; 191 } 192 193 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 194 const FunctionDecl *First = Cur->getFirstDecl(); 195 196 // Suggest "static" on the function, if possible. 197 if (!hasAnyExplicitStorageClass(First)) { 198 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 199 Diag(DeclBegin, diag::note_convert_inline_to_static) 200 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 201 } 202 } 203 204 /// Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 217 const ObjCInterfaceDecl *UnknownObjCClass, 218 bool ObjCPropertyAccess, 219 bool AvoidPartialAvailabilityChecks, 220 ObjCInterfaceDecl *ClassReceiver) { 221 SourceLocation Loc = Locs.front(); 222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 223 // If there were any diagnostics suppressed by template argument deduction, 224 // emit them now. 225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 226 if (Pos != SuppressedDiagnostics.end()) { 227 for (const PartialDiagnosticAt &Suppressed : Pos->second) 228 Diag(Suppressed.first, Suppressed.second); 229 230 // Clear out the list of suppressed diagnostics, so that we don't emit 231 // them again for this specialization. However, we don't obsolete this 232 // entry from the table, because we want to avoid ever emitting these 233 // diagnostics again. 234 Pos->second.clear(); 235 } 236 237 // C++ [basic.start.main]p3: 238 // The function 'main' shall not be used within a program. 239 if (cast<FunctionDecl>(D)->isMain()) 240 Diag(Loc, diag::ext_main_used); 241 242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 243 } 244 245 // See if this is an auto-typed variable whose initializer we are parsing. 246 if (ParsingInitForAutoVars.count(D)) { 247 if (isa<BindingDecl>(D)) { 248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 249 << D->getDeclName(); 250 } else { 251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 252 << D->getDeclName() << cast<VarDecl>(D)->getType(); 253 } 254 return true; 255 } 256 257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 258 // See if this is a deleted function. 259 if (FD->isDeleted()) { 260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 261 if (Ctor && Ctor->isInheritingConstructor()) 262 Diag(Loc, diag::err_deleted_inherited_ctor_use) 263 << Ctor->getParent() 264 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 265 else 266 Diag(Loc, diag::err_deleted_function_use); 267 NoteDeletedFunction(FD); 268 return true; 269 } 270 271 // [expr.prim.id]p4 272 // A program that refers explicitly or implicitly to a function with a 273 // trailing requires-clause whose constraint-expression is not satisfied, 274 // other than to declare it, is ill-formed. [...] 275 // 276 // See if this is a function with constraints that need to be satisfied. 277 // Check this before deducing the return type, as it might instantiate the 278 // definition. 279 if (FD->getTrailingRequiresClause()) { 280 ConstraintSatisfaction Satisfaction; 281 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 282 // A diagnostic will have already been generated (non-constant 283 // constraint expression, for example) 284 return true; 285 if (!Satisfaction.IsSatisfied) { 286 Diag(Loc, 287 diag::err_reference_to_function_with_unsatisfied_constraints) 288 << D; 289 DiagnoseUnsatisfiedConstraint(Satisfaction); 290 return true; 291 } 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 300 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 301 return true; 302 303 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 304 return true; 305 } 306 307 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 308 // Lambdas are only default-constructible or assignable in C++2a onwards. 309 if (MD->getParent()->isLambda() && 310 ((isa<CXXConstructorDecl>(MD) && 311 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 312 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 313 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 314 << !isa<CXXConstructorDecl>(MD); 315 } 316 } 317 318 auto getReferencedObjCProp = [](const NamedDecl *D) -> 319 const ObjCPropertyDecl * { 320 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 321 return MD->findPropertyDecl(); 322 return nullptr; 323 }; 324 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 325 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 326 return true; 327 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 328 return true; 329 } 330 331 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 332 // Only the variables omp_in and omp_out are allowed in the combiner. 333 // Only the variables omp_priv and omp_orig are allowed in the 334 // initializer-clause. 335 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 336 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 337 isa<VarDecl>(D)) { 338 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 339 << getCurFunction()->HasOMPDeclareReductionCombiner; 340 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 341 return true; 342 } 343 344 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 345 // List-items in map clauses on this construct may only refer to the declared 346 // variable var and entities that could be referenced by a procedure defined 347 // at the same location 348 if (LangOpts.OpenMP && isa<VarDecl>(D) && 349 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 350 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 351 << getOpenMPDeclareMapperVarName(); 352 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 353 return true; 354 } 355 356 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 357 Diag(Loc, diag::err_use_of_empty_using_if_exists); 358 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 359 return true; 360 } 361 362 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 363 AvoidPartialAvailabilityChecks, ClassReceiver); 364 365 DiagnoseUnusedOfDecl(*this, D, Loc); 366 367 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 368 369 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 370 if (auto *VD = dyn_cast<ValueDecl>(D)) 371 checkDeviceDecl(VD, Loc); 372 373 if (!Context.getTargetInfo().isTLSSupported()) 374 if (const auto *VD = dyn_cast<VarDecl>(D)) 375 if (VD->getTLSKind() != VarDecl::TLS_None) 376 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 377 } 378 379 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 380 !isUnevaluatedContext()) { 381 // C++ [expr.prim.req.nested] p3 382 // A local parameter shall only appear as an unevaluated operand 383 // (Clause 8) within the constraint-expression. 384 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 385 << D; 386 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 387 return true; 388 } 389 390 return false; 391 } 392 393 /// DiagnoseSentinelCalls - This routine checks whether a call or 394 /// message-send is to a declaration with the sentinel attribute, and 395 /// if so, it checks that the requirements of the sentinel are 396 /// satisfied. 397 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 398 ArrayRef<Expr *> Args) { 399 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 400 if (!attr) 401 return; 402 403 // The number of formal parameters of the declaration. 404 unsigned numFormalParams; 405 406 // The kind of declaration. This is also an index into a %select in 407 // the diagnostic. 408 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 409 410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 411 numFormalParams = MD->param_size(); 412 calleeType = CT_Method; 413 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 414 numFormalParams = FD->param_size(); 415 calleeType = CT_Function; 416 } else if (isa<VarDecl>(D)) { 417 QualType type = cast<ValueDecl>(D)->getType(); 418 const FunctionType *fn = nullptr; 419 if (const PointerType *ptr = type->getAs<PointerType>()) { 420 fn = ptr->getPointeeType()->getAs<FunctionType>(); 421 if (!fn) return; 422 calleeType = CT_Function; 423 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 424 fn = ptr->getPointeeType()->castAs<FunctionType>(); 425 calleeType = CT_Block; 426 } else { 427 return; 428 } 429 430 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 431 numFormalParams = proto->getNumParams(); 432 } else { 433 numFormalParams = 0; 434 } 435 } else { 436 return; 437 } 438 439 // "nullPos" is the number of formal parameters at the end which 440 // effectively count as part of the variadic arguments. This is 441 // useful if you would prefer to not have *any* formal parameters, 442 // but the language forces you to have at least one. 443 unsigned nullPos = attr->getNullPos(); 444 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 445 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 446 447 // The number of arguments which should follow the sentinel. 448 unsigned numArgsAfterSentinel = attr->getSentinel(); 449 450 // If there aren't enough arguments for all the formal parameters, 451 // the sentinel, and the args after the sentinel, complain. 452 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 453 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 454 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 455 return; 456 } 457 458 // Otherwise, find the sentinel expression. 459 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 460 if (!sentinelExpr) return; 461 if (sentinelExpr->isValueDependent()) return; 462 if (Context.isSentinelNullExpr(sentinelExpr)) return; 463 464 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 465 // or 'NULL' if those are actually defined in the context. Only use 466 // 'nil' for ObjC methods, where it's much more likely that the 467 // variadic arguments form a list of object pointers. 468 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 510 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 511 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 512 return ExprError(); 513 514 E = ImpCastExprToType(E, Context.getPointerType(Ty), 515 CK_FunctionToPointerDecay).get(); 516 } else if (Ty->isArrayType()) { 517 // In C90 mode, arrays only promote to pointers if the array expression is 518 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 519 // type 'array of type' is converted to an expression that has type 'pointer 520 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 521 // that has type 'array of type' ...". The relevant change is "an lvalue" 522 // (C90) to "an expression" (C99). 523 // 524 // C++ 4.2p1: 525 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 526 // T" can be converted to an rvalue of type "pointer to T". 527 // 528 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 529 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 530 CK_ArrayToPointerDecay); 531 if (Res.isInvalid()) 532 return ExprError(); 533 E = Res.get(); 534 } 535 } 536 return E; 537 } 538 539 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 540 // Check to see if we are dereferencing a null pointer. If so, 541 // and if not volatile-qualified, this is undefined behavior that the 542 // optimizer will delete, so warn about it. People sometimes try to use this 543 // to get a deterministic trap and are surprised by clang's behavior. This 544 // only handles the pattern "*null", which is a very syntactic check. 545 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 546 if (UO && UO->getOpcode() == UO_Deref && 547 UO->getSubExpr()->getType()->isPointerType()) { 548 const LangAS AS = 549 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 550 if ((!isTargetAddressSpace(AS) || 551 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 552 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 553 S.Context, Expr::NPC_ValueDependentIsNotNull) && 554 !UO->getType().isVolatileQualified()) { 555 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 556 S.PDiag(diag::warn_indirection_through_null) 557 << UO->getSubExpr()->getSourceRange()); 558 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 559 S.PDiag(diag::note_indirection_through_null)); 560 } 561 } 562 } 563 564 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 565 SourceLocation AssignLoc, 566 const Expr* RHS) { 567 const ObjCIvarDecl *IV = OIRE->getDecl(); 568 if (!IV) 569 return; 570 571 DeclarationName MemberName = IV->getDeclName(); 572 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 573 if (!Member || !Member->isStr("isa")) 574 return; 575 576 const Expr *Base = OIRE->getBase(); 577 QualType BaseType = Base->getType(); 578 if (OIRE->isArrow()) 579 BaseType = BaseType->getPointeeType(); 580 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 581 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 582 ObjCInterfaceDecl *ClassDeclared = nullptr; 583 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 584 if (!ClassDeclared->getSuperClass() 585 && (*ClassDeclared->ivar_begin()) == IV) { 586 if (RHS) { 587 NamedDecl *ObjectSetClass = 588 S.LookupSingleName(S.TUScope, 589 &S.Context.Idents.get("object_setClass"), 590 SourceLocation(), S.LookupOrdinaryName); 591 if (ObjectSetClass) { 592 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_setClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 598 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 599 } 600 else 601 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 602 } else { 603 NamedDecl *ObjectGetClass = 604 S.LookupSingleName(S.TUScope, 605 &S.Context.Idents.get("object_getClass"), 606 SourceLocation(), S.LookupOrdinaryName); 607 if (ObjectGetClass) 608 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 609 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 610 "object_getClass(") 611 << FixItHint::CreateReplacement( 612 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 613 else 614 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 615 } 616 S.Diag(IV->getLocation(), diag::note_ivar_decl); 617 } 618 } 619 } 620 621 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 622 // Handle any placeholder expressions which made it here. 623 if (E->getType()->isPlaceholderType()) { 624 ExprResult result = CheckPlaceholderExpr(E); 625 if (result.isInvalid()) return ExprError(); 626 E = result.get(); 627 } 628 629 // C++ [conv.lval]p1: 630 // A glvalue of a non-function, non-array type T can be 631 // converted to a prvalue. 632 if (!E->isGLValue()) return E; 633 634 QualType T = E->getType(); 635 assert(!T.isNull() && "r-value conversion on typeless expression?"); 636 637 // lvalue-to-rvalue conversion cannot be applied to function or array types. 638 if (T->isFunctionType() || T->isArrayType()) 639 return E; 640 641 // We don't want to throw lvalue-to-rvalue casts on top of 642 // expressions of certain types in C++. 643 if (getLangOpts().CPlusPlus && 644 (E->getType() == Context.OverloadTy || 645 T->isDependentType() || 646 T->isRecordType())) 647 return E; 648 649 // The C standard is actually really unclear on this point, and 650 // DR106 tells us what the result should be but not why. It's 651 // generally best to say that void types just doesn't undergo 652 // lvalue-to-rvalue at all. Note that expressions of unqualified 653 // 'void' type are never l-values, but qualified void can be. 654 if (T->isVoidType()) 655 return E; 656 657 // OpenCL usually rejects direct accesses to values of 'half' type. 658 if (getLangOpts().OpenCL && 659 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 660 T->isHalfType()) { 661 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 662 << 0 << T; 663 return ExprError(); 664 } 665 666 CheckForNullPointerDereference(*this, E); 667 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 668 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 669 &Context.Idents.get("object_getClass"), 670 SourceLocation(), LookupOrdinaryName); 671 if (ObjectGetClass) 672 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 673 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 674 << FixItHint::CreateReplacement( 675 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 676 else 677 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 678 } 679 else if (const ObjCIvarRefExpr *OIRE = 680 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 681 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 682 683 // C++ [conv.lval]p1: 684 // [...] If T is a non-class type, the type of the prvalue is the 685 // cv-unqualified version of T. Otherwise, the type of the 686 // rvalue is T. 687 // 688 // C99 6.3.2.1p2: 689 // If the lvalue has qualified type, the value has the unqualified 690 // version of the type of the lvalue; otherwise, the value has the 691 // type of the lvalue. 692 if (T.hasQualifiers()) 693 T = T.getUnqualifiedType(); 694 695 // Under the MS ABI, lock down the inheritance model now. 696 if (T->isMemberPointerType() && 697 Context.getTargetInfo().getCXXABI().isMicrosoft()) 698 (void)isCompleteType(E->getExprLoc(), T); 699 700 ExprResult Res = CheckLValueToRValueConversionOperand(E); 701 if (Res.isInvalid()) 702 return Res; 703 E = Res.get(); 704 705 // Loading a __weak object implicitly retains the value, so we need a cleanup to 706 // balance that. 707 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 708 Cleanup.setExprNeedsCleanups(true); 709 710 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 711 Cleanup.setExprNeedsCleanups(true); 712 713 // C++ [conv.lval]p3: 714 // If T is cv std::nullptr_t, the result is a null pointer constant. 715 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 716 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 717 CurFPFeatureOverrides()); 718 719 // C11 6.3.2.1p2: 720 // ... if the lvalue has atomic type, the value has the non-atomic version 721 // of the type of the lvalue ... 722 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 723 T = Atomic->getValueType().getUnqualifiedType(); 724 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 725 nullptr, VK_PRValue, FPOptionsOverride()); 726 } 727 728 return Res; 729 } 730 731 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 732 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 733 if (Res.isInvalid()) 734 return ExprError(); 735 Res = DefaultLvalueConversion(Res.get()); 736 if (Res.isInvalid()) 737 return ExprError(); 738 return Res; 739 } 740 741 /// CallExprUnaryConversions - a special case of an unary conversion 742 /// performed on a function designator of a call expression. 743 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 744 QualType Ty = E->getType(); 745 ExprResult Res = E; 746 // Only do implicit cast for a function type, but not for a pointer 747 // to function type. 748 if (Ty->isFunctionType()) { 749 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 750 CK_FunctionToPointerDecay); 751 if (Res.isInvalid()) 752 return ExprError(); 753 } 754 Res = DefaultLvalueConversion(Res.get()); 755 if (Res.isInvalid()) 756 return ExprError(); 757 return Res.get(); 758 } 759 760 /// UsualUnaryConversions - Performs various conversions that are common to most 761 /// operators (C99 6.3). The conversions of array and function types are 762 /// sometimes suppressed. For example, the array->pointer conversion doesn't 763 /// apply if the array is an argument to the sizeof or address (&) operators. 764 /// In these instances, this routine should *not* be called. 765 ExprResult Sema::UsualUnaryConversions(Expr *E) { 766 // First, convert to an r-value. 767 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 768 if (Res.isInvalid()) 769 return ExprError(); 770 E = Res.get(); 771 772 QualType Ty = E->getType(); 773 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 774 775 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 776 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType()) { 777 switch (EvalMethod) { 778 default: 779 llvm_unreachable("Unrecognized float evaluation method"); 780 break; 781 case LangOptions::FEM_TargetDefault: 782 // Float evaluation method not defined, use FEM_Source. 783 break; 784 case LangOptions::FEM_Double: 785 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 786 // Widen the expression to double. 787 return Ty->isComplexType() 788 ? ImpCastExprToType(E, 789 Context.getComplexType(Context.DoubleTy), 790 CK_FloatingComplexCast) 791 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 792 break; 793 case LangOptions::FEM_Extended: 794 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 795 // Widen the expression to long double. 796 return Ty->isComplexType() 797 ? ImpCastExprToType( 798 E, Context.getComplexType(Context.LongDoubleTy), 799 CK_FloatingComplexCast) 800 : ImpCastExprToType(E, Context.LongDoubleTy, 801 CK_FloatingCast); 802 break; 803 } 804 } 805 806 // Half FP have to be promoted to float unless it is natively supported 807 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 808 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 809 810 // Try to perform integral promotions if the object has a theoretically 811 // promotable type. 812 if (Ty->isIntegralOrUnscopedEnumerationType()) { 813 // C99 6.3.1.1p2: 814 // 815 // The following may be used in an expression wherever an int or 816 // unsigned int may be used: 817 // - an object or expression with an integer type whose integer 818 // conversion rank is less than or equal to the rank of int 819 // and unsigned int. 820 // - A bit-field of type _Bool, int, signed int, or unsigned int. 821 // 822 // If an int can represent all values of the original type, the 823 // value is converted to an int; otherwise, it is converted to an 824 // unsigned int. These are called the integer promotions. All 825 // other types are unchanged by the integer promotions. 826 827 QualType PTy = Context.isPromotableBitField(E); 828 if (!PTy.isNull()) { 829 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 830 return E; 831 } 832 if (Ty->isPromotableIntegerType()) { 833 QualType PT = Context.getPromotedIntegerType(Ty); 834 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 835 return E; 836 } 837 } 838 return E; 839 } 840 841 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 842 /// do not have a prototype. Arguments that have type float or __fp16 843 /// are promoted to double. All other argument types are converted by 844 /// UsualUnaryConversions(). 845 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 846 QualType Ty = E->getType(); 847 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 848 849 ExprResult Res = UsualUnaryConversions(E); 850 if (Res.isInvalid()) 851 return ExprError(); 852 E = Res.get(); 853 854 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 855 // promote to double. 856 // Note that default argument promotion applies only to float (and 857 // half/fp16); it does not apply to _Float16. 858 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 859 if (BTy && (BTy->getKind() == BuiltinType::Half || 860 BTy->getKind() == BuiltinType::Float)) { 861 if (getLangOpts().OpenCL && 862 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 863 if (BTy->getKind() == BuiltinType::Half) { 864 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 865 } 866 } else { 867 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 868 } 869 } 870 if (BTy && 871 getLangOpts().getExtendIntArgs() == 872 LangOptions::ExtendArgsKind::ExtendTo64 && 873 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 874 Context.getTypeSizeInChars(BTy) < 875 Context.getTypeSizeInChars(Context.LongLongTy)) { 876 E = (Ty->isUnsignedIntegerType()) 877 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 878 .get() 879 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 880 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 881 "Unexpected typesize for LongLongTy"); 882 } 883 884 // C++ performs lvalue-to-rvalue conversion as a default argument 885 // promotion, even on class types, but note: 886 // C++11 [conv.lval]p2: 887 // When an lvalue-to-rvalue conversion occurs in an unevaluated 888 // operand or a subexpression thereof the value contained in the 889 // referenced object is not accessed. Otherwise, if the glvalue 890 // has a class type, the conversion copy-initializes a temporary 891 // of type T from the glvalue and the result of the conversion 892 // is a prvalue for the temporary. 893 // FIXME: add some way to gate this entire thing for correctness in 894 // potentially potentially evaluated contexts. 895 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 896 ExprResult Temp = PerformCopyInitialization( 897 InitializedEntity::InitializeTemporary(E->getType()), 898 E->getExprLoc(), E); 899 if (Temp.isInvalid()) 900 return ExprError(); 901 E = Temp.get(); 902 } 903 904 return E; 905 } 906 907 /// Determine the degree of POD-ness for an expression. 908 /// Incomplete types are considered POD, since this check can be performed 909 /// when we're in an unevaluated context. 910 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 911 if (Ty->isIncompleteType()) { 912 // C++11 [expr.call]p7: 913 // After these conversions, if the argument does not have arithmetic, 914 // enumeration, pointer, pointer to member, or class type, the program 915 // is ill-formed. 916 // 917 // Since we've already performed array-to-pointer and function-to-pointer 918 // decay, the only such type in C++ is cv void. This also handles 919 // initializer lists as variadic arguments. 920 if (Ty->isVoidType()) 921 return VAK_Invalid; 922 923 if (Ty->isObjCObjectType()) 924 return VAK_Invalid; 925 return VAK_Valid; 926 } 927 928 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 929 return VAK_Invalid; 930 931 if (Ty.isCXX98PODType(Context)) 932 return VAK_Valid; 933 934 // C++11 [expr.call]p7: 935 // Passing a potentially-evaluated argument of class type (Clause 9) 936 // having a non-trivial copy constructor, a non-trivial move constructor, 937 // or a non-trivial destructor, with no corresponding parameter, 938 // is conditionally-supported with implementation-defined semantics. 939 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 940 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 941 if (!Record->hasNonTrivialCopyConstructor() && 942 !Record->hasNonTrivialMoveConstructor() && 943 !Record->hasNonTrivialDestructor()) 944 return VAK_ValidInCXX11; 945 946 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 947 return VAK_Valid; 948 949 if (Ty->isObjCObjectType()) 950 return VAK_Invalid; 951 952 if (getLangOpts().MSVCCompat) 953 return VAK_MSVCUndefined; 954 955 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 956 // permitted to reject them. We should consider doing so. 957 return VAK_Undefined; 958 } 959 960 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 961 // Don't allow one to pass an Objective-C interface to a vararg. 962 const QualType &Ty = E->getType(); 963 VarArgKind VAK = isValidVarArgType(Ty); 964 965 // Complain about passing non-POD types through varargs. 966 switch (VAK) { 967 case VAK_ValidInCXX11: 968 DiagRuntimeBehavior( 969 E->getBeginLoc(), nullptr, 970 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 971 LLVM_FALLTHROUGH; 972 case VAK_Valid: 973 if (Ty->isRecordType()) { 974 // This is unlikely to be what the user intended. If the class has a 975 // 'c_str' member function, the user probably meant to call that. 976 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 977 PDiag(diag::warn_pass_class_arg_to_vararg) 978 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 979 } 980 break; 981 982 case VAK_Undefined: 983 case VAK_MSVCUndefined: 984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 985 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 986 << getLangOpts().CPlusPlus11 << Ty << CT); 987 break; 988 989 case VAK_Invalid: 990 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 991 Diag(E->getBeginLoc(), 992 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 993 << Ty << CT; 994 else if (Ty->isObjCObjectType()) 995 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 996 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 997 << Ty << CT); 998 else 999 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1000 << isa<InitListExpr>(E) << Ty << CT; 1001 break; 1002 } 1003 } 1004 1005 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1006 /// will create a trap if the resulting type is not a POD type. 1007 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1008 FunctionDecl *FDecl) { 1009 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1010 // Strip the unbridged-cast placeholder expression off, if applicable. 1011 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1012 (CT == VariadicMethod || 1013 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1014 E = stripARCUnbridgedCast(E); 1015 1016 // Otherwise, do normal placeholder checking. 1017 } else { 1018 ExprResult ExprRes = CheckPlaceholderExpr(E); 1019 if (ExprRes.isInvalid()) 1020 return ExprError(); 1021 E = ExprRes.get(); 1022 } 1023 } 1024 1025 ExprResult ExprRes = DefaultArgumentPromotion(E); 1026 if (ExprRes.isInvalid()) 1027 return ExprError(); 1028 1029 // Copy blocks to the heap. 1030 if (ExprRes.get()->getType()->isBlockPointerType()) 1031 maybeExtendBlockObject(ExprRes); 1032 1033 E = ExprRes.get(); 1034 1035 // Diagnostics regarding non-POD argument types are 1036 // emitted along with format string checking in Sema::CheckFunctionCall(). 1037 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1038 // Turn this into a trap. 1039 CXXScopeSpec SS; 1040 SourceLocation TemplateKWLoc; 1041 UnqualifiedId Name; 1042 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1043 E->getBeginLoc()); 1044 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1045 /*HasTrailingLParen=*/true, 1046 /*IsAddressOfOperand=*/false); 1047 if (TrapFn.isInvalid()) 1048 return ExprError(); 1049 1050 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1051 None, E->getEndLoc()); 1052 if (Call.isInvalid()) 1053 return ExprError(); 1054 1055 ExprResult Comma = 1056 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1057 if (Comma.isInvalid()) 1058 return ExprError(); 1059 return Comma.get(); 1060 } 1061 1062 if (!getLangOpts().CPlusPlus && 1063 RequireCompleteType(E->getExprLoc(), E->getType(), 1064 diag::err_call_incomplete_argument)) 1065 return ExprError(); 1066 1067 return E; 1068 } 1069 1070 /// Converts an integer to complex float type. Helper function of 1071 /// UsualArithmeticConversions() 1072 /// 1073 /// \return false if the integer expression is an integer type and is 1074 /// successfully converted to the complex type. 1075 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1076 ExprResult &ComplexExpr, 1077 QualType IntTy, 1078 QualType ComplexTy, 1079 bool SkipCast) { 1080 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1081 if (SkipCast) return false; 1082 if (IntTy->isIntegerType()) { 1083 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1084 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1085 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1086 CK_FloatingRealToComplex); 1087 } else { 1088 assert(IntTy->isComplexIntegerType()); 1089 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1090 CK_IntegralComplexToFloatingComplex); 1091 } 1092 return false; 1093 } 1094 1095 /// Handle arithmetic conversion with complex types. Helper function of 1096 /// UsualArithmeticConversions() 1097 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1098 ExprResult &RHS, QualType LHSType, 1099 QualType RHSType, 1100 bool IsCompAssign) { 1101 // if we have an integer operand, the result is the complex type. 1102 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1103 /*skipCast*/false)) 1104 return LHSType; 1105 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1106 /*skipCast*/IsCompAssign)) 1107 return RHSType; 1108 1109 // This handles complex/complex, complex/float, or float/complex. 1110 // When both operands are complex, the shorter operand is converted to the 1111 // type of the longer, and that is the type of the result. This corresponds 1112 // to what is done when combining two real floating-point operands. 1113 // The fun begins when size promotion occur across type domains. 1114 // From H&S 6.3.4: When one operand is complex and the other is a real 1115 // floating-point type, the less precise type is converted, within it's 1116 // real or complex domain, to the precision of the other type. For example, 1117 // when combining a "long double" with a "double _Complex", the 1118 // "double _Complex" is promoted to "long double _Complex". 1119 1120 // Compute the rank of the two types, regardless of whether they are complex. 1121 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1122 1123 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1124 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1125 QualType LHSElementType = 1126 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1127 QualType RHSElementType = 1128 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1129 1130 QualType ResultType = S.Context.getComplexType(LHSElementType); 1131 if (Order < 0) { 1132 // Promote the precision of the LHS if not an assignment. 1133 ResultType = S.Context.getComplexType(RHSElementType); 1134 if (!IsCompAssign) { 1135 if (LHSComplexType) 1136 LHS = 1137 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1138 else 1139 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1140 } 1141 } else if (Order > 0) { 1142 // Promote the precision of the RHS. 1143 if (RHSComplexType) 1144 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1145 else 1146 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1147 } 1148 return ResultType; 1149 } 1150 1151 /// Handle arithmetic conversion from integer to float. Helper function 1152 /// of UsualArithmeticConversions() 1153 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1154 ExprResult &IntExpr, 1155 QualType FloatTy, QualType IntTy, 1156 bool ConvertFloat, bool ConvertInt) { 1157 if (IntTy->isIntegerType()) { 1158 if (ConvertInt) 1159 // Convert intExpr to the lhs floating point type. 1160 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1161 CK_IntegralToFloating); 1162 return FloatTy; 1163 } 1164 1165 // Convert both sides to the appropriate complex float. 1166 assert(IntTy->isComplexIntegerType()); 1167 QualType result = S.Context.getComplexType(FloatTy); 1168 1169 // _Complex int -> _Complex float 1170 if (ConvertInt) 1171 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1172 CK_IntegralComplexToFloatingComplex); 1173 1174 // float -> _Complex float 1175 if (ConvertFloat) 1176 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1177 CK_FloatingRealToComplex); 1178 1179 return result; 1180 } 1181 1182 /// Handle arithmethic conversion with floating point types. Helper 1183 /// function of UsualArithmeticConversions() 1184 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1185 ExprResult &RHS, QualType LHSType, 1186 QualType RHSType, bool IsCompAssign) { 1187 bool LHSFloat = LHSType->isRealFloatingType(); 1188 bool RHSFloat = RHSType->isRealFloatingType(); 1189 1190 // N1169 4.1.4: If one of the operands has a floating type and the other 1191 // operand has a fixed-point type, the fixed-point operand 1192 // is converted to the floating type [...] 1193 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1194 if (LHSFloat) 1195 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1196 else if (!IsCompAssign) 1197 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1198 return LHSFloat ? LHSType : RHSType; 1199 } 1200 1201 // If we have two real floating types, convert the smaller operand 1202 // to the bigger result. 1203 if (LHSFloat && RHSFloat) { 1204 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1205 if (order > 0) { 1206 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1207 return LHSType; 1208 } 1209 1210 assert(order < 0 && "illegal float comparison"); 1211 if (!IsCompAssign) 1212 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1213 return RHSType; 1214 } 1215 1216 if (LHSFloat) { 1217 // Half FP has to be promoted to float unless it is natively supported 1218 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1219 LHSType = S.Context.FloatTy; 1220 1221 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1222 /*ConvertFloat=*/!IsCompAssign, 1223 /*ConvertInt=*/ true); 1224 } 1225 assert(RHSFloat); 1226 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1227 /*ConvertFloat=*/ true, 1228 /*ConvertInt=*/!IsCompAssign); 1229 } 1230 1231 /// Diagnose attempts to convert between __float128 and long double if 1232 /// there is no support for such conversion. Helper function of 1233 /// UsualArithmeticConversions(). 1234 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1235 QualType RHSType) { 1236 /* No issue converting if at least one of the types is not a floating point 1237 type or the two types have the same rank. 1238 */ 1239 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1240 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1241 return false; 1242 1243 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1244 "The remaining types must be floating point types."); 1245 1246 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1247 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1248 1249 QualType LHSElemType = LHSComplex ? 1250 LHSComplex->getElementType() : LHSType; 1251 QualType RHSElemType = RHSComplex ? 1252 RHSComplex->getElementType() : RHSType; 1253 1254 // No issue if the two types have the same representation 1255 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1256 &S.Context.getFloatTypeSemantics(RHSElemType)) 1257 return false; 1258 1259 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1260 RHSElemType == S.Context.LongDoubleTy); 1261 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1262 RHSElemType == S.Context.Float128Ty); 1263 1264 // We've handled the situation where __float128 and long double have the same 1265 // representation. We allow all conversions for all possible long double types 1266 // except PPC's double double. 1267 return Float128AndLongDouble && 1268 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1269 &llvm::APFloat::PPCDoubleDouble()); 1270 } 1271 1272 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1273 1274 namespace { 1275 /// These helper callbacks are placed in an anonymous namespace to 1276 /// permit their use as function template parameters. 1277 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1278 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1279 } 1280 1281 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1282 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1283 CK_IntegralComplexCast); 1284 } 1285 } 1286 1287 /// Handle integer arithmetic conversions. Helper function of 1288 /// UsualArithmeticConversions() 1289 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1290 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1291 ExprResult &RHS, QualType LHSType, 1292 QualType RHSType, bool IsCompAssign) { 1293 // The rules for this case are in C99 6.3.1.8 1294 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1295 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1296 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1297 if (LHSSigned == RHSSigned) { 1298 // Same signedness; use the higher-ranked type 1299 if (order >= 0) { 1300 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1301 return LHSType; 1302 } else if (!IsCompAssign) 1303 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1304 return RHSType; 1305 } else if (order != (LHSSigned ? 1 : -1)) { 1306 // The unsigned type has greater than or equal rank to the 1307 // signed type, so use the unsigned type 1308 if (RHSSigned) { 1309 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1310 return LHSType; 1311 } else if (!IsCompAssign) 1312 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1313 return RHSType; 1314 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1315 // The two types are different widths; if we are here, that 1316 // means the signed type is larger than the unsigned type, so 1317 // use the signed type. 1318 if (LHSSigned) { 1319 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1320 return LHSType; 1321 } else if (!IsCompAssign) 1322 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1323 return RHSType; 1324 } else { 1325 // The signed type is higher-ranked than the unsigned type, 1326 // but isn't actually any bigger (like unsigned int and long 1327 // on most 32-bit systems). Use the unsigned type corresponding 1328 // to the signed type. 1329 QualType result = 1330 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1331 RHS = (*doRHSCast)(S, RHS.get(), result); 1332 if (!IsCompAssign) 1333 LHS = (*doLHSCast)(S, LHS.get(), result); 1334 return result; 1335 } 1336 } 1337 1338 /// Handle conversions with GCC complex int extension. Helper function 1339 /// of UsualArithmeticConversions() 1340 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1341 ExprResult &RHS, QualType LHSType, 1342 QualType RHSType, 1343 bool IsCompAssign) { 1344 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1345 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1346 1347 if (LHSComplexInt && RHSComplexInt) { 1348 QualType LHSEltType = LHSComplexInt->getElementType(); 1349 QualType RHSEltType = RHSComplexInt->getElementType(); 1350 QualType ScalarType = 1351 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1352 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1353 1354 return S.Context.getComplexType(ScalarType); 1355 } 1356 1357 if (LHSComplexInt) { 1358 QualType LHSEltType = LHSComplexInt->getElementType(); 1359 QualType ScalarType = 1360 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1361 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1362 QualType ComplexType = S.Context.getComplexType(ScalarType); 1363 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1364 CK_IntegralRealToComplex); 1365 1366 return ComplexType; 1367 } 1368 1369 assert(RHSComplexInt); 1370 1371 QualType RHSEltType = RHSComplexInt->getElementType(); 1372 QualType ScalarType = 1373 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1374 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1375 QualType ComplexType = S.Context.getComplexType(ScalarType); 1376 1377 if (!IsCompAssign) 1378 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1379 CK_IntegralRealToComplex); 1380 return ComplexType; 1381 } 1382 1383 /// Return the rank of a given fixed point or integer type. The value itself 1384 /// doesn't matter, but the values must be increasing with proper increasing 1385 /// rank as described in N1169 4.1.1. 1386 static unsigned GetFixedPointRank(QualType Ty) { 1387 const auto *BTy = Ty->getAs<BuiltinType>(); 1388 assert(BTy && "Expected a builtin type."); 1389 1390 switch (BTy->getKind()) { 1391 case BuiltinType::ShortFract: 1392 case BuiltinType::UShortFract: 1393 case BuiltinType::SatShortFract: 1394 case BuiltinType::SatUShortFract: 1395 return 1; 1396 case BuiltinType::Fract: 1397 case BuiltinType::UFract: 1398 case BuiltinType::SatFract: 1399 case BuiltinType::SatUFract: 1400 return 2; 1401 case BuiltinType::LongFract: 1402 case BuiltinType::ULongFract: 1403 case BuiltinType::SatLongFract: 1404 case BuiltinType::SatULongFract: 1405 return 3; 1406 case BuiltinType::ShortAccum: 1407 case BuiltinType::UShortAccum: 1408 case BuiltinType::SatShortAccum: 1409 case BuiltinType::SatUShortAccum: 1410 return 4; 1411 case BuiltinType::Accum: 1412 case BuiltinType::UAccum: 1413 case BuiltinType::SatAccum: 1414 case BuiltinType::SatUAccum: 1415 return 5; 1416 case BuiltinType::LongAccum: 1417 case BuiltinType::ULongAccum: 1418 case BuiltinType::SatLongAccum: 1419 case BuiltinType::SatULongAccum: 1420 return 6; 1421 default: 1422 if (BTy->isInteger()) 1423 return 0; 1424 llvm_unreachable("Unexpected fixed point or integer type"); 1425 } 1426 } 1427 1428 /// handleFixedPointConversion - Fixed point operations between fixed 1429 /// point types and integers or other fixed point types do not fall under 1430 /// usual arithmetic conversion since these conversions could result in loss 1431 /// of precsision (N1169 4.1.4). These operations should be calculated with 1432 /// the full precision of their result type (N1169 4.1.6.2.1). 1433 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1434 QualType RHSTy) { 1435 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1436 "Expected at least one of the operands to be a fixed point type"); 1437 assert((LHSTy->isFixedPointOrIntegerType() || 1438 RHSTy->isFixedPointOrIntegerType()) && 1439 "Special fixed point arithmetic operation conversions are only " 1440 "applied to ints or other fixed point types"); 1441 1442 // If one operand has signed fixed-point type and the other operand has 1443 // unsigned fixed-point type, then the unsigned fixed-point operand is 1444 // converted to its corresponding signed fixed-point type and the resulting 1445 // type is the type of the converted operand. 1446 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1447 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1448 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1449 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1450 1451 // The result type is the type with the highest rank, whereby a fixed-point 1452 // conversion rank is always greater than an integer conversion rank; if the 1453 // type of either of the operands is a saturating fixedpoint type, the result 1454 // type shall be the saturating fixed-point type corresponding to the type 1455 // with the highest rank; the resulting value is converted (taking into 1456 // account rounding and overflow) to the precision of the resulting type. 1457 // Same ranks between signed and unsigned types are resolved earlier, so both 1458 // types are either signed or both unsigned at this point. 1459 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1460 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1461 1462 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1463 1464 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1465 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1466 1467 return ResultTy; 1468 } 1469 1470 /// Check that the usual arithmetic conversions can be performed on this pair of 1471 /// expressions that might be of enumeration type. 1472 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1473 SourceLocation Loc, 1474 Sema::ArithConvKind ACK) { 1475 // C++2a [expr.arith.conv]p1: 1476 // If one operand is of enumeration type and the other operand is of a 1477 // different enumeration type or a floating-point type, this behavior is 1478 // deprecated ([depr.arith.conv.enum]). 1479 // 1480 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1481 // Eventually we will presumably reject these cases (in C++23 onwards?). 1482 QualType L = LHS->getType(), R = RHS->getType(); 1483 bool LEnum = L->isUnscopedEnumerationType(), 1484 REnum = R->isUnscopedEnumerationType(); 1485 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1486 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1487 (REnum && L->isFloatingType())) { 1488 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1489 ? diag::warn_arith_conv_enum_float_cxx20 1490 : diag::warn_arith_conv_enum_float) 1491 << LHS->getSourceRange() << RHS->getSourceRange() 1492 << (int)ACK << LEnum << L << R; 1493 } else if (!IsCompAssign && LEnum && REnum && 1494 !S.Context.hasSameUnqualifiedType(L, R)) { 1495 unsigned DiagID; 1496 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1497 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1498 // If either enumeration type is unnamed, it's less likely that the 1499 // user cares about this, but this situation is still deprecated in 1500 // C++2a. Use a different warning group. 1501 DiagID = S.getLangOpts().CPlusPlus20 1502 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1503 : diag::warn_arith_conv_mixed_anon_enum_types; 1504 } else if (ACK == Sema::ACK_Conditional) { 1505 // Conditional expressions are separated out because they have 1506 // historically had a different warning flag. 1507 DiagID = S.getLangOpts().CPlusPlus20 1508 ? diag::warn_conditional_mixed_enum_types_cxx20 1509 : diag::warn_conditional_mixed_enum_types; 1510 } else if (ACK == Sema::ACK_Comparison) { 1511 // Comparison expressions are separated out because they have 1512 // historically had a different warning flag. 1513 DiagID = S.getLangOpts().CPlusPlus20 1514 ? diag::warn_comparison_mixed_enum_types_cxx20 1515 : diag::warn_comparison_mixed_enum_types; 1516 } else { 1517 DiagID = S.getLangOpts().CPlusPlus20 1518 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1519 : diag::warn_arith_conv_mixed_enum_types; 1520 } 1521 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1522 << (int)ACK << L << R; 1523 } 1524 } 1525 1526 /// UsualArithmeticConversions - Performs various conversions that are common to 1527 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1528 /// routine returns the first non-arithmetic type found. The client is 1529 /// responsible for emitting appropriate error diagnostics. 1530 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1531 SourceLocation Loc, 1532 ArithConvKind ACK) { 1533 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1534 1535 if (ACK != ACK_CompAssign) { 1536 LHS = UsualUnaryConversions(LHS.get()); 1537 if (LHS.isInvalid()) 1538 return QualType(); 1539 } 1540 1541 RHS = UsualUnaryConversions(RHS.get()); 1542 if (RHS.isInvalid()) 1543 return QualType(); 1544 1545 // For conversion purposes, we ignore any qualifiers. 1546 // For example, "const float" and "float" are equivalent. 1547 QualType LHSType = 1548 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1549 QualType RHSType = 1550 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1551 1552 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1553 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1554 LHSType = AtomicLHS->getValueType(); 1555 1556 // If both types are identical, no conversion is needed. 1557 if (LHSType == RHSType) 1558 return LHSType; 1559 1560 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1561 // The caller can deal with this (e.g. pointer + int). 1562 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1563 return QualType(); 1564 1565 // Apply unary and bitfield promotions to the LHS's type. 1566 QualType LHSUnpromotedType = LHSType; 1567 if (LHSType->isPromotableIntegerType()) 1568 LHSType = Context.getPromotedIntegerType(LHSType); 1569 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1570 if (!LHSBitfieldPromoteTy.isNull()) 1571 LHSType = LHSBitfieldPromoteTy; 1572 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1573 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1574 1575 // If both types are identical, no conversion is needed. 1576 if (LHSType == RHSType) 1577 return LHSType; 1578 1579 // At this point, we have two different arithmetic types. 1580 1581 // Diagnose attempts to convert between __float128 and long double where 1582 // such conversions currently can't be handled. 1583 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1584 return QualType(); 1585 1586 // Handle complex types first (C99 6.3.1.8p1). 1587 if (LHSType->isComplexType() || RHSType->isComplexType()) 1588 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1589 ACK == ACK_CompAssign); 1590 1591 // Now handle "real" floating types (i.e. float, double, long double). 1592 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1593 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1594 ACK == ACK_CompAssign); 1595 1596 // Handle GCC complex int extension. 1597 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1598 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1599 ACK == ACK_CompAssign); 1600 1601 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1602 return handleFixedPointConversion(*this, LHSType, RHSType); 1603 1604 // Finally, we have two differing integer types. 1605 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1606 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1607 } 1608 1609 //===----------------------------------------------------------------------===// 1610 // Semantic Analysis for various Expression Types 1611 //===----------------------------------------------------------------------===// 1612 1613 1614 ExprResult 1615 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1616 SourceLocation DefaultLoc, 1617 SourceLocation RParenLoc, 1618 Expr *ControllingExpr, 1619 ArrayRef<ParsedType> ArgTypes, 1620 ArrayRef<Expr *> ArgExprs) { 1621 unsigned NumAssocs = ArgTypes.size(); 1622 assert(NumAssocs == ArgExprs.size()); 1623 1624 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1625 for (unsigned i = 0; i < NumAssocs; ++i) { 1626 if (ArgTypes[i]) 1627 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1628 else 1629 Types[i] = nullptr; 1630 } 1631 1632 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1633 ControllingExpr, 1634 llvm::makeArrayRef(Types, NumAssocs), 1635 ArgExprs); 1636 delete [] Types; 1637 return ER; 1638 } 1639 1640 ExprResult 1641 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1642 SourceLocation DefaultLoc, 1643 SourceLocation RParenLoc, 1644 Expr *ControllingExpr, 1645 ArrayRef<TypeSourceInfo *> Types, 1646 ArrayRef<Expr *> Exprs) { 1647 unsigned NumAssocs = Types.size(); 1648 assert(NumAssocs == Exprs.size()); 1649 1650 // Decay and strip qualifiers for the controlling expression type, and handle 1651 // placeholder type replacement. See committee discussion from WG14 DR423. 1652 { 1653 EnterExpressionEvaluationContext Unevaluated( 1654 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1655 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1656 if (R.isInvalid()) 1657 return ExprError(); 1658 ControllingExpr = R.get(); 1659 } 1660 1661 // The controlling expression is an unevaluated operand, so side effects are 1662 // likely unintended. 1663 if (!inTemplateInstantiation() && 1664 ControllingExpr->HasSideEffects(Context, false)) 1665 Diag(ControllingExpr->getExprLoc(), 1666 diag::warn_side_effects_unevaluated_context); 1667 1668 bool TypeErrorFound = false, 1669 IsResultDependent = ControllingExpr->isTypeDependent(), 1670 ContainsUnexpandedParameterPack 1671 = ControllingExpr->containsUnexpandedParameterPack(); 1672 1673 for (unsigned i = 0; i < NumAssocs; ++i) { 1674 if (Exprs[i]->containsUnexpandedParameterPack()) 1675 ContainsUnexpandedParameterPack = true; 1676 1677 if (Types[i]) { 1678 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1679 ContainsUnexpandedParameterPack = true; 1680 1681 if (Types[i]->getType()->isDependentType()) { 1682 IsResultDependent = true; 1683 } else { 1684 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1685 // complete object type other than a variably modified type." 1686 unsigned D = 0; 1687 if (Types[i]->getType()->isIncompleteType()) 1688 D = diag::err_assoc_type_incomplete; 1689 else if (!Types[i]->getType()->isObjectType()) 1690 D = diag::err_assoc_type_nonobject; 1691 else if (Types[i]->getType()->isVariablyModifiedType()) 1692 D = diag::err_assoc_type_variably_modified; 1693 1694 if (D != 0) { 1695 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1696 << Types[i]->getTypeLoc().getSourceRange() 1697 << Types[i]->getType(); 1698 TypeErrorFound = true; 1699 } 1700 1701 // C11 6.5.1.1p2 "No two generic associations in the same generic 1702 // selection shall specify compatible types." 1703 for (unsigned j = i+1; j < NumAssocs; ++j) 1704 if (Types[j] && !Types[j]->getType()->isDependentType() && 1705 Context.typesAreCompatible(Types[i]->getType(), 1706 Types[j]->getType())) { 1707 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1708 diag::err_assoc_compatible_types) 1709 << Types[j]->getTypeLoc().getSourceRange() 1710 << Types[j]->getType() 1711 << Types[i]->getType(); 1712 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1713 diag::note_compat_assoc) 1714 << Types[i]->getTypeLoc().getSourceRange() 1715 << Types[i]->getType(); 1716 TypeErrorFound = true; 1717 } 1718 } 1719 } 1720 } 1721 if (TypeErrorFound) 1722 return ExprError(); 1723 1724 // If we determined that the generic selection is result-dependent, don't 1725 // try to compute the result expression. 1726 if (IsResultDependent) 1727 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1728 Exprs, DefaultLoc, RParenLoc, 1729 ContainsUnexpandedParameterPack); 1730 1731 SmallVector<unsigned, 1> CompatIndices; 1732 unsigned DefaultIndex = -1U; 1733 for (unsigned i = 0; i < NumAssocs; ++i) { 1734 if (!Types[i]) 1735 DefaultIndex = i; 1736 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1737 Types[i]->getType())) 1738 CompatIndices.push_back(i); 1739 } 1740 1741 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1742 // type compatible with at most one of the types named in its generic 1743 // association list." 1744 if (CompatIndices.size() > 1) { 1745 // We strip parens here because the controlling expression is typically 1746 // parenthesized in macro definitions. 1747 ControllingExpr = ControllingExpr->IgnoreParens(); 1748 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1749 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1750 << (unsigned)CompatIndices.size(); 1751 for (unsigned I : CompatIndices) { 1752 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1753 diag::note_compat_assoc) 1754 << Types[I]->getTypeLoc().getSourceRange() 1755 << Types[I]->getType(); 1756 } 1757 return ExprError(); 1758 } 1759 1760 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1761 // its controlling expression shall have type compatible with exactly one of 1762 // the types named in its generic association list." 1763 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1764 // We strip parens here because the controlling expression is typically 1765 // parenthesized in macro definitions. 1766 ControllingExpr = ControllingExpr->IgnoreParens(); 1767 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1768 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1769 return ExprError(); 1770 } 1771 1772 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1773 // type name that is compatible with the type of the controlling expression, 1774 // then the result expression of the generic selection is the expression 1775 // in that generic association. Otherwise, the result expression of the 1776 // generic selection is the expression in the default generic association." 1777 unsigned ResultIndex = 1778 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1779 1780 return GenericSelectionExpr::Create( 1781 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1782 ContainsUnexpandedParameterPack, ResultIndex); 1783 } 1784 1785 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1786 /// location of the token and the offset of the ud-suffix within it. 1787 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1788 unsigned Offset) { 1789 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1790 S.getLangOpts()); 1791 } 1792 1793 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1794 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1795 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1796 IdentifierInfo *UDSuffix, 1797 SourceLocation UDSuffixLoc, 1798 ArrayRef<Expr*> Args, 1799 SourceLocation LitEndLoc) { 1800 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1801 1802 QualType ArgTy[2]; 1803 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1804 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1805 if (ArgTy[ArgIdx]->isArrayType()) 1806 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1807 } 1808 1809 DeclarationName OpName = 1810 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1811 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1812 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1813 1814 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1815 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1816 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1817 /*AllowStringTemplatePack*/ false, 1818 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1819 return ExprError(); 1820 1821 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1822 } 1823 1824 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1825 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1826 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1827 /// multiple tokens. However, the common case is that StringToks points to one 1828 /// string. 1829 /// 1830 ExprResult 1831 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1832 assert(!StringToks.empty() && "Must have at least one string!"); 1833 1834 StringLiteralParser Literal(StringToks, PP); 1835 if (Literal.hadError) 1836 return ExprError(); 1837 1838 SmallVector<SourceLocation, 4> StringTokLocs; 1839 for (const Token &Tok : StringToks) 1840 StringTokLocs.push_back(Tok.getLocation()); 1841 1842 QualType CharTy = Context.CharTy; 1843 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1844 if (Literal.isWide()) { 1845 CharTy = Context.getWideCharType(); 1846 Kind = StringLiteral::Wide; 1847 } else if (Literal.isUTF8()) { 1848 if (getLangOpts().Char8) 1849 CharTy = Context.Char8Ty; 1850 Kind = StringLiteral::UTF8; 1851 } else if (Literal.isUTF16()) { 1852 CharTy = Context.Char16Ty; 1853 Kind = StringLiteral::UTF16; 1854 } else if (Literal.isUTF32()) { 1855 CharTy = Context.Char32Ty; 1856 Kind = StringLiteral::UTF32; 1857 } else if (Literal.isPascal()) { 1858 CharTy = Context.UnsignedCharTy; 1859 } 1860 1861 // Warn on initializing an array of char from a u8 string literal; this 1862 // becomes ill-formed in C++2a. 1863 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1864 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1865 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1866 1867 // Create removals for all 'u8' prefixes in the string literal(s). This 1868 // ensures C++2a compatibility (but may change the program behavior when 1869 // built by non-Clang compilers for which the execution character set is 1870 // not always UTF-8). 1871 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1872 SourceLocation RemovalDiagLoc; 1873 for (const Token &Tok : StringToks) { 1874 if (Tok.getKind() == tok::utf8_string_literal) { 1875 if (RemovalDiagLoc.isInvalid()) 1876 RemovalDiagLoc = Tok.getLocation(); 1877 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1878 Tok.getLocation(), 1879 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1880 getSourceManager(), getLangOpts()))); 1881 } 1882 } 1883 Diag(RemovalDiagLoc, RemovalDiag); 1884 } 1885 1886 QualType StrTy = 1887 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1888 1889 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1890 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1891 Kind, Literal.Pascal, StrTy, 1892 &StringTokLocs[0], 1893 StringTokLocs.size()); 1894 if (Literal.getUDSuffix().empty()) 1895 return Lit; 1896 1897 // We're building a user-defined literal. 1898 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1899 SourceLocation UDSuffixLoc = 1900 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1901 Literal.getUDSuffixOffset()); 1902 1903 // Make sure we're allowed user-defined literals here. 1904 if (!UDLScope) 1905 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1906 1907 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1908 // operator "" X (str, len) 1909 QualType SizeType = Context.getSizeType(); 1910 1911 DeclarationName OpName = 1912 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1913 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1914 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1915 1916 QualType ArgTy[] = { 1917 Context.getArrayDecayedType(StrTy), SizeType 1918 }; 1919 1920 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1921 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1922 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1923 /*AllowStringTemplatePack*/ true, 1924 /*DiagnoseMissing*/ true, Lit)) { 1925 1926 case LOLR_Cooked: { 1927 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1928 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1929 StringTokLocs[0]); 1930 Expr *Args[] = { Lit, LenArg }; 1931 1932 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1933 } 1934 1935 case LOLR_Template: { 1936 TemplateArgumentListInfo ExplicitArgs; 1937 TemplateArgument Arg(Lit); 1938 TemplateArgumentLocInfo ArgInfo(Lit); 1939 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1940 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1941 &ExplicitArgs); 1942 } 1943 1944 case LOLR_StringTemplatePack: { 1945 TemplateArgumentListInfo ExplicitArgs; 1946 1947 unsigned CharBits = Context.getIntWidth(CharTy); 1948 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1949 llvm::APSInt Value(CharBits, CharIsUnsigned); 1950 1951 TemplateArgument TypeArg(CharTy); 1952 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1953 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1954 1955 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1956 Value = Lit->getCodeUnit(I); 1957 TemplateArgument Arg(Context, Value, CharTy); 1958 TemplateArgumentLocInfo ArgInfo; 1959 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1960 } 1961 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1962 &ExplicitArgs); 1963 } 1964 case LOLR_Raw: 1965 case LOLR_ErrorNoDiagnostic: 1966 llvm_unreachable("unexpected literal operator lookup result"); 1967 case LOLR_Error: 1968 return ExprError(); 1969 } 1970 llvm_unreachable("unexpected literal operator lookup result"); 1971 } 1972 1973 DeclRefExpr * 1974 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1975 SourceLocation Loc, 1976 const CXXScopeSpec *SS) { 1977 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1978 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1979 } 1980 1981 DeclRefExpr * 1982 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1983 const DeclarationNameInfo &NameInfo, 1984 const CXXScopeSpec *SS, NamedDecl *FoundD, 1985 SourceLocation TemplateKWLoc, 1986 const TemplateArgumentListInfo *TemplateArgs) { 1987 NestedNameSpecifierLoc NNS = 1988 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1989 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1990 TemplateArgs); 1991 } 1992 1993 // CUDA/HIP: Check whether a captured reference variable is referencing a 1994 // host variable in a device or host device lambda. 1995 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1996 VarDecl *VD) { 1997 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1998 return false; 1999 assert(VD->getType()->isReferenceType()); 2000 2001 // Check whether the reference variable is referencing a host variable. 2002 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 2003 if (!DRE) 2004 return false; 2005 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2006 if (!Referee || !Referee->hasGlobalStorage() || 2007 Referee->hasAttr<CUDADeviceAttr>()) 2008 return false; 2009 2010 // Check whether the current function is a device or host device lambda. 2011 // Check whether the reference variable is a capture by getDeclContext() 2012 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2013 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2014 if (MD && MD->getParent()->isLambda() && 2015 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2016 VD->getDeclContext() != MD) 2017 return true; 2018 2019 return false; 2020 } 2021 2022 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2023 // A declaration named in an unevaluated operand never constitutes an odr-use. 2024 if (isUnevaluatedContext()) 2025 return NOUR_Unevaluated; 2026 2027 // C++2a [basic.def.odr]p4: 2028 // A variable x whose name appears as a potentially-evaluated expression e 2029 // is odr-used by e unless [...] x is a reference that is usable in 2030 // constant expressions. 2031 // CUDA/HIP: 2032 // If a reference variable referencing a host variable is captured in a 2033 // device or host device lambda, the value of the referee must be copied 2034 // to the capture and the reference variable must be treated as odr-use 2035 // since the value of the referee is not known at compile time and must 2036 // be loaded from the captured. 2037 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2038 if (VD->getType()->isReferenceType() && 2039 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2040 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2041 VD->isUsableInConstantExpressions(Context)) 2042 return NOUR_Constant; 2043 } 2044 2045 // All remaining non-variable cases constitute an odr-use. For variables, we 2046 // need to wait and see how the expression is used. 2047 return NOUR_None; 2048 } 2049 2050 /// BuildDeclRefExpr - Build an expression that references a 2051 /// declaration that does not require a closure capture. 2052 DeclRefExpr * 2053 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2054 const DeclarationNameInfo &NameInfo, 2055 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2056 SourceLocation TemplateKWLoc, 2057 const TemplateArgumentListInfo *TemplateArgs) { 2058 bool RefersToCapturedVariable = 2059 isa<VarDecl>(D) && 2060 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2061 2062 DeclRefExpr *E = DeclRefExpr::Create( 2063 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2064 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2065 MarkDeclRefReferenced(E); 2066 2067 // C++ [except.spec]p17: 2068 // An exception-specification is considered to be needed when: 2069 // - in an expression, the function is the unique lookup result or 2070 // the selected member of a set of overloaded functions. 2071 // 2072 // We delay doing this until after we've built the function reference and 2073 // marked it as used so that: 2074 // a) if the function is defaulted, we get errors from defining it before / 2075 // instead of errors from computing its exception specification, and 2076 // b) if the function is a defaulted comparison, we can use the body we 2077 // build when defining it as input to the exception specification 2078 // computation rather than computing a new body. 2079 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2080 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2081 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2082 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2083 } 2084 } 2085 2086 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2087 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2088 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2089 getCurFunction()->recordUseOfWeak(E); 2090 2091 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2092 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2093 FD = IFD->getAnonField(); 2094 if (FD) { 2095 UnusedPrivateFields.remove(FD); 2096 // Just in case we're building an illegal pointer-to-member. 2097 if (FD->isBitField()) 2098 E->setObjectKind(OK_BitField); 2099 } 2100 2101 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2102 // designates a bit-field. 2103 if (auto *BD = dyn_cast<BindingDecl>(D)) 2104 if (auto *BE = BD->getBinding()) 2105 E->setObjectKind(BE->getObjectKind()); 2106 2107 return E; 2108 } 2109 2110 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2111 /// possibly a list of template arguments. 2112 /// 2113 /// If this produces template arguments, it is permitted to call 2114 /// DecomposeTemplateName. 2115 /// 2116 /// This actually loses a lot of source location information for 2117 /// non-standard name kinds; we should consider preserving that in 2118 /// some way. 2119 void 2120 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2121 TemplateArgumentListInfo &Buffer, 2122 DeclarationNameInfo &NameInfo, 2123 const TemplateArgumentListInfo *&TemplateArgs) { 2124 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2125 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2126 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2127 2128 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2129 Id.TemplateId->NumArgs); 2130 translateTemplateArguments(TemplateArgsPtr, Buffer); 2131 2132 TemplateName TName = Id.TemplateId->Template.get(); 2133 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2134 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2135 TemplateArgs = &Buffer; 2136 } else { 2137 NameInfo = GetNameFromUnqualifiedId(Id); 2138 TemplateArgs = nullptr; 2139 } 2140 } 2141 2142 static void emitEmptyLookupTypoDiagnostic( 2143 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2144 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2145 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2146 DeclContext *Ctx = 2147 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2148 if (!TC) { 2149 // Emit a special diagnostic for failed member lookups. 2150 // FIXME: computing the declaration context might fail here (?) 2151 if (Ctx) 2152 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2153 << SS.getRange(); 2154 else 2155 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2156 return; 2157 } 2158 2159 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2160 bool DroppedSpecifier = 2161 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2162 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2163 ? diag::note_implicit_param_decl 2164 : diag::note_previous_decl; 2165 if (!Ctx) 2166 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2167 SemaRef.PDiag(NoteID)); 2168 else 2169 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2170 << Typo << Ctx << DroppedSpecifier 2171 << SS.getRange(), 2172 SemaRef.PDiag(NoteID)); 2173 } 2174 2175 /// Diagnose a lookup that found results in an enclosing class during error 2176 /// recovery. This usually indicates that the results were found in a dependent 2177 /// base class that could not be searched as part of a template definition. 2178 /// Always issues a diagnostic (though this may be only a warning in MS 2179 /// compatibility mode). 2180 /// 2181 /// Return \c true if the error is unrecoverable, or \c false if the caller 2182 /// should attempt to recover using these lookup results. 2183 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2184 // During a default argument instantiation the CurContext points 2185 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2186 // function parameter list, hence add an explicit check. 2187 bool isDefaultArgument = 2188 !CodeSynthesisContexts.empty() && 2189 CodeSynthesisContexts.back().Kind == 2190 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2191 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2192 bool isInstance = CurMethod && CurMethod->isInstance() && 2193 R.getNamingClass() == CurMethod->getParent() && 2194 !isDefaultArgument; 2195 2196 // There are two ways we can find a class-scope declaration during template 2197 // instantiation that we did not find in the template definition: if it is a 2198 // member of a dependent base class, or if it is declared after the point of 2199 // use in the same class. Distinguish these by comparing the class in which 2200 // the member was found to the naming class of the lookup. 2201 unsigned DiagID = diag::err_found_in_dependent_base; 2202 unsigned NoteID = diag::note_member_declared_at; 2203 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2204 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2205 : diag::err_found_later_in_class; 2206 } else if (getLangOpts().MSVCCompat) { 2207 DiagID = diag::ext_found_in_dependent_base; 2208 NoteID = diag::note_dependent_member_use; 2209 } 2210 2211 if (isInstance) { 2212 // Give a code modification hint to insert 'this->'. 2213 Diag(R.getNameLoc(), DiagID) 2214 << R.getLookupName() 2215 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2216 CheckCXXThisCapture(R.getNameLoc()); 2217 } else { 2218 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2219 // they're not shadowed). 2220 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2221 } 2222 2223 for (NamedDecl *D : R) 2224 Diag(D->getLocation(), NoteID); 2225 2226 // Return true if we are inside a default argument instantiation 2227 // and the found name refers to an instance member function, otherwise 2228 // the caller will try to create an implicit member call and this is wrong 2229 // for default arguments. 2230 // 2231 // FIXME: Is this special case necessary? We could allow the caller to 2232 // diagnose this. 2233 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2234 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2235 return true; 2236 } 2237 2238 // Tell the callee to try to recover. 2239 return false; 2240 } 2241 2242 /// Diagnose an empty lookup. 2243 /// 2244 /// \return false if new lookup candidates were found 2245 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2246 CorrectionCandidateCallback &CCC, 2247 TemplateArgumentListInfo *ExplicitTemplateArgs, 2248 ArrayRef<Expr *> Args, TypoExpr **Out) { 2249 DeclarationName Name = R.getLookupName(); 2250 2251 unsigned diagnostic = diag::err_undeclared_var_use; 2252 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2253 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2254 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2255 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2256 diagnostic = diag::err_undeclared_use; 2257 diagnostic_suggest = diag::err_undeclared_use_suggest; 2258 } 2259 2260 // If the original lookup was an unqualified lookup, fake an 2261 // unqualified lookup. This is useful when (for example) the 2262 // original lookup would not have found something because it was a 2263 // dependent name. 2264 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2265 while (DC) { 2266 if (isa<CXXRecordDecl>(DC)) { 2267 LookupQualifiedName(R, DC); 2268 2269 if (!R.empty()) { 2270 // Don't give errors about ambiguities in this lookup. 2271 R.suppressDiagnostics(); 2272 2273 // If there's a best viable function among the results, only mention 2274 // that one in the notes. 2275 OverloadCandidateSet Candidates(R.getNameLoc(), 2276 OverloadCandidateSet::CSK_Normal); 2277 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2278 OverloadCandidateSet::iterator Best; 2279 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2280 OR_Success) { 2281 R.clear(); 2282 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2283 R.resolveKind(); 2284 } 2285 2286 return DiagnoseDependentMemberLookup(R); 2287 } 2288 2289 R.clear(); 2290 } 2291 2292 DC = DC->getLookupParent(); 2293 } 2294 2295 // We didn't find anything, so try to correct for a typo. 2296 TypoCorrection Corrected; 2297 if (S && Out) { 2298 SourceLocation TypoLoc = R.getNameLoc(); 2299 assert(!ExplicitTemplateArgs && 2300 "Diagnosing an empty lookup with explicit template args!"); 2301 *Out = CorrectTypoDelayed( 2302 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2303 [=](const TypoCorrection &TC) { 2304 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2305 diagnostic, diagnostic_suggest); 2306 }, 2307 nullptr, CTK_ErrorRecovery); 2308 if (*Out) 2309 return true; 2310 } else if (S && 2311 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2312 S, &SS, CCC, CTK_ErrorRecovery))) { 2313 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2314 bool DroppedSpecifier = 2315 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2316 R.setLookupName(Corrected.getCorrection()); 2317 2318 bool AcceptableWithRecovery = false; 2319 bool AcceptableWithoutRecovery = false; 2320 NamedDecl *ND = Corrected.getFoundDecl(); 2321 if (ND) { 2322 if (Corrected.isOverloaded()) { 2323 OverloadCandidateSet OCS(R.getNameLoc(), 2324 OverloadCandidateSet::CSK_Normal); 2325 OverloadCandidateSet::iterator Best; 2326 for (NamedDecl *CD : Corrected) { 2327 if (FunctionTemplateDecl *FTD = 2328 dyn_cast<FunctionTemplateDecl>(CD)) 2329 AddTemplateOverloadCandidate( 2330 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2331 Args, OCS); 2332 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2333 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2334 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2335 Args, OCS); 2336 } 2337 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2338 case OR_Success: 2339 ND = Best->FoundDecl; 2340 Corrected.setCorrectionDecl(ND); 2341 break; 2342 default: 2343 // FIXME: Arbitrarily pick the first declaration for the note. 2344 Corrected.setCorrectionDecl(ND); 2345 break; 2346 } 2347 } 2348 R.addDecl(ND); 2349 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2350 CXXRecordDecl *Record = nullptr; 2351 if (Corrected.getCorrectionSpecifier()) { 2352 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2353 Record = Ty->getAsCXXRecordDecl(); 2354 } 2355 if (!Record) 2356 Record = cast<CXXRecordDecl>( 2357 ND->getDeclContext()->getRedeclContext()); 2358 R.setNamingClass(Record); 2359 } 2360 2361 auto *UnderlyingND = ND->getUnderlyingDecl(); 2362 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2363 isa<FunctionTemplateDecl>(UnderlyingND); 2364 // FIXME: If we ended up with a typo for a type name or 2365 // Objective-C class name, we're in trouble because the parser 2366 // is in the wrong place to recover. Suggest the typo 2367 // correction, but don't make it a fix-it since we're not going 2368 // to recover well anyway. 2369 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2370 getAsTypeTemplateDecl(UnderlyingND) || 2371 isa<ObjCInterfaceDecl>(UnderlyingND); 2372 } else { 2373 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2374 // because we aren't able to recover. 2375 AcceptableWithoutRecovery = true; 2376 } 2377 2378 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2379 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2380 ? diag::note_implicit_param_decl 2381 : diag::note_previous_decl; 2382 if (SS.isEmpty()) 2383 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2384 PDiag(NoteID), AcceptableWithRecovery); 2385 else 2386 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2387 << Name << computeDeclContext(SS, false) 2388 << DroppedSpecifier << SS.getRange(), 2389 PDiag(NoteID), AcceptableWithRecovery); 2390 2391 // Tell the callee whether to try to recover. 2392 return !AcceptableWithRecovery; 2393 } 2394 } 2395 R.clear(); 2396 2397 // Emit a special diagnostic for failed member lookups. 2398 // FIXME: computing the declaration context might fail here (?) 2399 if (!SS.isEmpty()) { 2400 Diag(R.getNameLoc(), diag::err_no_member) 2401 << Name << computeDeclContext(SS, false) 2402 << SS.getRange(); 2403 return true; 2404 } 2405 2406 // Give up, we can't recover. 2407 Diag(R.getNameLoc(), diagnostic) << Name; 2408 return true; 2409 } 2410 2411 /// In Microsoft mode, if we are inside a template class whose parent class has 2412 /// dependent base classes, and we can't resolve an unqualified identifier, then 2413 /// assume the identifier is a member of a dependent base class. We can only 2414 /// recover successfully in static methods, instance methods, and other contexts 2415 /// where 'this' is available. This doesn't precisely match MSVC's 2416 /// instantiation model, but it's close enough. 2417 static Expr * 2418 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2419 DeclarationNameInfo &NameInfo, 2420 SourceLocation TemplateKWLoc, 2421 const TemplateArgumentListInfo *TemplateArgs) { 2422 // Only try to recover from lookup into dependent bases in static methods or 2423 // contexts where 'this' is available. 2424 QualType ThisType = S.getCurrentThisType(); 2425 const CXXRecordDecl *RD = nullptr; 2426 if (!ThisType.isNull()) 2427 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2428 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2429 RD = MD->getParent(); 2430 if (!RD || !RD->hasAnyDependentBases()) 2431 return nullptr; 2432 2433 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2434 // is available, suggest inserting 'this->' as a fixit. 2435 SourceLocation Loc = NameInfo.getLoc(); 2436 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2437 DB << NameInfo.getName() << RD; 2438 2439 if (!ThisType.isNull()) { 2440 DB << FixItHint::CreateInsertion(Loc, "this->"); 2441 return CXXDependentScopeMemberExpr::Create( 2442 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2443 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2444 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2445 } 2446 2447 // Synthesize a fake NNS that points to the derived class. This will 2448 // perform name lookup during template instantiation. 2449 CXXScopeSpec SS; 2450 auto *NNS = 2451 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2452 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2453 return DependentScopeDeclRefExpr::Create( 2454 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2455 TemplateArgs); 2456 } 2457 2458 ExprResult 2459 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2460 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2461 bool HasTrailingLParen, bool IsAddressOfOperand, 2462 CorrectionCandidateCallback *CCC, 2463 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2464 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2465 "cannot be direct & operand and have a trailing lparen"); 2466 if (SS.isInvalid()) 2467 return ExprError(); 2468 2469 TemplateArgumentListInfo TemplateArgsBuffer; 2470 2471 // Decompose the UnqualifiedId into the following data. 2472 DeclarationNameInfo NameInfo; 2473 const TemplateArgumentListInfo *TemplateArgs; 2474 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2475 2476 DeclarationName Name = NameInfo.getName(); 2477 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2478 SourceLocation NameLoc = NameInfo.getLoc(); 2479 2480 if (II && II->isEditorPlaceholder()) { 2481 // FIXME: When typed placeholders are supported we can create a typed 2482 // placeholder expression node. 2483 return ExprError(); 2484 } 2485 2486 // C++ [temp.dep.expr]p3: 2487 // An id-expression is type-dependent if it contains: 2488 // -- an identifier that was declared with a dependent type, 2489 // (note: handled after lookup) 2490 // -- a template-id that is dependent, 2491 // (note: handled in BuildTemplateIdExpr) 2492 // -- a conversion-function-id that specifies a dependent type, 2493 // -- a nested-name-specifier that contains a class-name that 2494 // names a dependent type. 2495 // Determine whether this is a member of an unknown specialization; 2496 // we need to handle these differently. 2497 bool DependentID = false; 2498 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2499 Name.getCXXNameType()->isDependentType()) { 2500 DependentID = true; 2501 } else if (SS.isSet()) { 2502 if (DeclContext *DC = computeDeclContext(SS, false)) { 2503 if (RequireCompleteDeclContext(SS, DC)) 2504 return ExprError(); 2505 } else { 2506 DependentID = true; 2507 } 2508 } 2509 2510 if (DependentID) 2511 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2512 IsAddressOfOperand, TemplateArgs); 2513 2514 // Perform the required lookup. 2515 LookupResult R(*this, NameInfo, 2516 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2517 ? LookupObjCImplicitSelfParam 2518 : LookupOrdinaryName); 2519 if (TemplateKWLoc.isValid() || TemplateArgs) { 2520 // Lookup the template name again to correctly establish the context in 2521 // which it was found. This is really unfortunate as we already did the 2522 // lookup to determine that it was a template name in the first place. If 2523 // this becomes a performance hit, we can work harder to preserve those 2524 // results until we get here but it's likely not worth it. 2525 bool MemberOfUnknownSpecialization; 2526 AssumedTemplateKind AssumedTemplate; 2527 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2528 MemberOfUnknownSpecialization, TemplateKWLoc, 2529 &AssumedTemplate)) 2530 return ExprError(); 2531 2532 if (MemberOfUnknownSpecialization || 2533 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2534 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2535 IsAddressOfOperand, TemplateArgs); 2536 } else { 2537 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2538 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2539 2540 // If the result might be in a dependent base class, this is a dependent 2541 // id-expression. 2542 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2543 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2544 IsAddressOfOperand, TemplateArgs); 2545 2546 // If this reference is in an Objective-C method, then we need to do 2547 // some special Objective-C lookup, too. 2548 if (IvarLookupFollowUp) { 2549 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2550 if (E.isInvalid()) 2551 return ExprError(); 2552 2553 if (Expr *Ex = E.getAs<Expr>()) 2554 return Ex; 2555 } 2556 } 2557 2558 if (R.isAmbiguous()) 2559 return ExprError(); 2560 2561 // This could be an implicitly declared function reference (legal in C90, 2562 // extension in C99, forbidden in C++). 2563 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2564 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2565 if (D) R.addDecl(D); 2566 } 2567 2568 // Determine whether this name might be a candidate for 2569 // argument-dependent lookup. 2570 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2571 2572 if (R.empty() && !ADL) { 2573 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2574 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2575 TemplateKWLoc, TemplateArgs)) 2576 return E; 2577 } 2578 2579 // Don't diagnose an empty lookup for inline assembly. 2580 if (IsInlineAsmIdentifier) 2581 return ExprError(); 2582 2583 // If this name wasn't predeclared and if this is not a function 2584 // call, diagnose the problem. 2585 TypoExpr *TE = nullptr; 2586 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2587 : nullptr); 2588 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2589 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2590 "Typo correction callback misconfigured"); 2591 if (CCC) { 2592 // Make sure the callback knows what the typo being diagnosed is. 2593 CCC->setTypoName(II); 2594 if (SS.isValid()) 2595 CCC->setTypoNNS(SS.getScopeRep()); 2596 } 2597 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2598 // a template name, but we happen to have always already looked up the name 2599 // before we get here if it must be a template name. 2600 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2601 None, &TE)) { 2602 if (TE && KeywordReplacement) { 2603 auto &State = getTypoExprState(TE); 2604 auto BestTC = State.Consumer->getNextCorrection(); 2605 if (BestTC.isKeyword()) { 2606 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2607 if (State.DiagHandler) 2608 State.DiagHandler(BestTC); 2609 KeywordReplacement->startToken(); 2610 KeywordReplacement->setKind(II->getTokenID()); 2611 KeywordReplacement->setIdentifierInfo(II); 2612 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2613 // Clean up the state associated with the TypoExpr, since it has 2614 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2615 clearDelayedTypo(TE); 2616 // Signal that a correction to a keyword was performed by returning a 2617 // valid-but-null ExprResult. 2618 return (Expr*)nullptr; 2619 } 2620 State.Consumer->resetCorrectionStream(); 2621 } 2622 return TE ? TE : ExprError(); 2623 } 2624 2625 assert(!R.empty() && 2626 "DiagnoseEmptyLookup returned false but added no results"); 2627 2628 // If we found an Objective-C instance variable, let 2629 // LookupInObjCMethod build the appropriate expression to 2630 // reference the ivar. 2631 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2632 R.clear(); 2633 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2634 // In a hopelessly buggy code, Objective-C instance variable 2635 // lookup fails and no expression will be built to reference it. 2636 if (!E.isInvalid() && !E.get()) 2637 return ExprError(); 2638 return E; 2639 } 2640 } 2641 2642 // This is guaranteed from this point on. 2643 assert(!R.empty() || ADL); 2644 2645 // Check whether this might be a C++ implicit instance member access. 2646 // C++ [class.mfct.non-static]p3: 2647 // When an id-expression that is not part of a class member access 2648 // syntax and not used to form a pointer to member is used in the 2649 // body of a non-static member function of class X, if name lookup 2650 // resolves the name in the id-expression to a non-static non-type 2651 // member of some class C, the id-expression is transformed into a 2652 // class member access expression using (*this) as the 2653 // postfix-expression to the left of the . operator. 2654 // 2655 // But we don't actually need to do this for '&' operands if R 2656 // resolved to a function or overloaded function set, because the 2657 // expression is ill-formed if it actually works out to be a 2658 // non-static member function: 2659 // 2660 // C++ [expr.ref]p4: 2661 // Otherwise, if E1.E2 refers to a non-static member function. . . 2662 // [t]he expression can be used only as the left-hand operand of a 2663 // member function call. 2664 // 2665 // There are other safeguards against such uses, but it's important 2666 // to get this right here so that we don't end up making a 2667 // spuriously dependent expression if we're inside a dependent 2668 // instance method. 2669 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2670 bool MightBeImplicitMember; 2671 if (!IsAddressOfOperand) 2672 MightBeImplicitMember = true; 2673 else if (!SS.isEmpty()) 2674 MightBeImplicitMember = false; 2675 else if (R.isOverloadedResult()) 2676 MightBeImplicitMember = false; 2677 else if (R.isUnresolvableResult()) 2678 MightBeImplicitMember = true; 2679 else 2680 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2681 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2682 isa<MSPropertyDecl>(R.getFoundDecl()); 2683 2684 if (MightBeImplicitMember) 2685 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2686 R, TemplateArgs, S); 2687 } 2688 2689 if (TemplateArgs || TemplateKWLoc.isValid()) { 2690 2691 // In C++1y, if this is a variable template id, then check it 2692 // in BuildTemplateIdExpr(). 2693 // The single lookup result must be a variable template declaration. 2694 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2695 Id.TemplateId->Kind == TNK_Var_template) { 2696 assert(R.getAsSingle<VarTemplateDecl>() && 2697 "There should only be one declaration found."); 2698 } 2699 2700 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2701 } 2702 2703 return BuildDeclarationNameExpr(SS, R, ADL); 2704 } 2705 2706 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2707 /// declaration name, generally during template instantiation. 2708 /// There's a large number of things which don't need to be done along 2709 /// this path. 2710 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2711 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2712 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2713 DeclContext *DC = computeDeclContext(SS, false); 2714 if (!DC) 2715 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2716 NameInfo, /*TemplateArgs=*/nullptr); 2717 2718 if (RequireCompleteDeclContext(SS, DC)) 2719 return ExprError(); 2720 2721 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2722 LookupQualifiedName(R, DC); 2723 2724 if (R.isAmbiguous()) 2725 return ExprError(); 2726 2727 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2728 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2729 NameInfo, /*TemplateArgs=*/nullptr); 2730 2731 if (R.empty()) { 2732 // Don't diagnose problems with invalid record decl, the secondary no_member 2733 // diagnostic during template instantiation is likely bogus, e.g. if a class 2734 // is invalid because it's derived from an invalid base class, then missing 2735 // members were likely supposed to be inherited. 2736 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2737 if (CD->isInvalidDecl()) 2738 return ExprError(); 2739 Diag(NameInfo.getLoc(), diag::err_no_member) 2740 << NameInfo.getName() << DC << SS.getRange(); 2741 return ExprError(); 2742 } 2743 2744 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2745 // Diagnose a missing typename if this resolved unambiguously to a type in 2746 // a dependent context. If we can recover with a type, downgrade this to 2747 // a warning in Microsoft compatibility mode. 2748 unsigned DiagID = diag::err_typename_missing; 2749 if (RecoveryTSI && getLangOpts().MSVCCompat) 2750 DiagID = diag::ext_typename_missing; 2751 SourceLocation Loc = SS.getBeginLoc(); 2752 auto D = Diag(Loc, DiagID); 2753 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2754 << SourceRange(Loc, NameInfo.getEndLoc()); 2755 2756 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2757 // context. 2758 if (!RecoveryTSI) 2759 return ExprError(); 2760 2761 // Only issue the fixit if we're prepared to recover. 2762 D << FixItHint::CreateInsertion(Loc, "typename "); 2763 2764 // Recover by pretending this was an elaborated type. 2765 QualType Ty = Context.getTypeDeclType(TD); 2766 TypeLocBuilder TLB; 2767 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2768 2769 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2770 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2771 QTL.setElaboratedKeywordLoc(SourceLocation()); 2772 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2773 2774 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2775 2776 return ExprEmpty(); 2777 } 2778 2779 // Defend against this resolving to an implicit member access. We usually 2780 // won't get here if this might be a legitimate a class member (we end up in 2781 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2782 // a pointer-to-member or in an unevaluated context in C++11. 2783 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2784 return BuildPossibleImplicitMemberExpr(SS, 2785 /*TemplateKWLoc=*/SourceLocation(), 2786 R, /*TemplateArgs=*/nullptr, S); 2787 2788 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2789 } 2790 2791 /// The parser has read a name in, and Sema has detected that we're currently 2792 /// inside an ObjC method. Perform some additional checks and determine if we 2793 /// should form a reference to an ivar. 2794 /// 2795 /// Ideally, most of this would be done by lookup, but there's 2796 /// actually quite a lot of extra work involved. 2797 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2798 IdentifierInfo *II) { 2799 SourceLocation Loc = Lookup.getNameLoc(); 2800 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2801 2802 // Check for error condition which is already reported. 2803 if (!CurMethod) 2804 return DeclResult(true); 2805 2806 // There are two cases to handle here. 1) scoped lookup could have failed, 2807 // in which case we should look for an ivar. 2) scoped lookup could have 2808 // found a decl, but that decl is outside the current instance method (i.e. 2809 // a global variable). In these two cases, we do a lookup for an ivar with 2810 // this name, if the lookup sucedes, we replace it our current decl. 2811 2812 // If we're in a class method, we don't normally want to look for 2813 // ivars. But if we don't find anything else, and there's an 2814 // ivar, that's an error. 2815 bool IsClassMethod = CurMethod->isClassMethod(); 2816 2817 bool LookForIvars; 2818 if (Lookup.empty()) 2819 LookForIvars = true; 2820 else if (IsClassMethod) 2821 LookForIvars = false; 2822 else 2823 LookForIvars = (Lookup.isSingleResult() && 2824 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2825 ObjCInterfaceDecl *IFace = nullptr; 2826 if (LookForIvars) { 2827 IFace = CurMethod->getClassInterface(); 2828 ObjCInterfaceDecl *ClassDeclared; 2829 ObjCIvarDecl *IV = nullptr; 2830 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2831 // Diagnose using an ivar in a class method. 2832 if (IsClassMethod) { 2833 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2834 return DeclResult(true); 2835 } 2836 2837 // Diagnose the use of an ivar outside of the declaring class. 2838 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2839 !declaresSameEntity(ClassDeclared, IFace) && 2840 !getLangOpts().DebuggerSupport) 2841 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2842 2843 // Success. 2844 return IV; 2845 } 2846 } else if (CurMethod->isInstanceMethod()) { 2847 // We should warn if a local variable hides an ivar. 2848 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2849 ObjCInterfaceDecl *ClassDeclared; 2850 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2851 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2852 declaresSameEntity(IFace, ClassDeclared)) 2853 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2854 } 2855 } 2856 } else if (Lookup.isSingleResult() && 2857 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2858 // If accessing a stand-alone ivar in a class method, this is an error. 2859 if (const ObjCIvarDecl *IV = 2860 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2861 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2862 return DeclResult(true); 2863 } 2864 } 2865 2866 // Didn't encounter an error, didn't find an ivar. 2867 return DeclResult(false); 2868 } 2869 2870 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2871 ObjCIvarDecl *IV) { 2872 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2873 assert(CurMethod && CurMethod->isInstanceMethod() && 2874 "should not reference ivar from this context"); 2875 2876 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2877 assert(IFace && "should not reference ivar from this context"); 2878 2879 // If we're referencing an invalid decl, just return this as a silent 2880 // error node. The error diagnostic was already emitted on the decl. 2881 if (IV->isInvalidDecl()) 2882 return ExprError(); 2883 2884 // Check if referencing a field with __attribute__((deprecated)). 2885 if (DiagnoseUseOfDecl(IV, Loc)) 2886 return ExprError(); 2887 2888 // FIXME: This should use a new expr for a direct reference, don't 2889 // turn this into Self->ivar, just return a BareIVarExpr or something. 2890 IdentifierInfo &II = Context.Idents.get("self"); 2891 UnqualifiedId SelfName; 2892 SelfName.setImplicitSelfParam(&II); 2893 CXXScopeSpec SelfScopeSpec; 2894 SourceLocation TemplateKWLoc; 2895 ExprResult SelfExpr = 2896 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2897 /*HasTrailingLParen=*/false, 2898 /*IsAddressOfOperand=*/false); 2899 if (SelfExpr.isInvalid()) 2900 return ExprError(); 2901 2902 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2903 if (SelfExpr.isInvalid()) 2904 return ExprError(); 2905 2906 MarkAnyDeclReferenced(Loc, IV, true); 2907 2908 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2909 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2910 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2911 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2912 2913 ObjCIvarRefExpr *Result = new (Context) 2914 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2915 IV->getLocation(), SelfExpr.get(), true, true); 2916 2917 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2918 if (!isUnevaluatedContext() && 2919 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2920 getCurFunction()->recordUseOfWeak(Result); 2921 } 2922 if (getLangOpts().ObjCAutoRefCount) 2923 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2924 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2925 2926 return Result; 2927 } 2928 2929 /// The parser has read a name in, and Sema has detected that we're currently 2930 /// inside an ObjC method. Perform some additional checks and determine if we 2931 /// should form a reference to an ivar. If so, build an expression referencing 2932 /// that ivar. 2933 ExprResult 2934 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2935 IdentifierInfo *II, bool AllowBuiltinCreation) { 2936 // FIXME: Integrate this lookup step into LookupParsedName. 2937 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2938 if (Ivar.isInvalid()) 2939 return ExprError(); 2940 if (Ivar.isUsable()) 2941 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2942 cast<ObjCIvarDecl>(Ivar.get())); 2943 2944 if (Lookup.empty() && II && AllowBuiltinCreation) 2945 LookupBuiltin(Lookup); 2946 2947 // Sentinel value saying that we didn't do anything special. 2948 return ExprResult(false); 2949 } 2950 2951 /// Cast a base object to a member's actual type. 2952 /// 2953 /// There are two relevant checks: 2954 /// 2955 /// C++ [class.access.base]p7: 2956 /// 2957 /// If a class member access operator [...] is used to access a non-static 2958 /// data member or non-static member function, the reference is ill-formed if 2959 /// the left operand [...] cannot be implicitly converted to a pointer to the 2960 /// naming class of the right operand. 2961 /// 2962 /// C++ [expr.ref]p7: 2963 /// 2964 /// If E2 is a non-static data member or a non-static member function, the 2965 /// program is ill-formed if the class of which E2 is directly a member is an 2966 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2967 /// 2968 /// Note that the latter check does not consider access; the access of the 2969 /// "real" base class is checked as appropriate when checking the access of the 2970 /// member name. 2971 ExprResult 2972 Sema::PerformObjectMemberConversion(Expr *From, 2973 NestedNameSpecifier *Qualifier, 2974 NamedDecl *FoundDecl, 2975 NamedDecl *Member) { 2976 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2977 if (!RD) 2978 return From; 2979 2980 QualType DestRecordType; 2981 QualType DestType; 2982 QualType FromRecordType; 2983 QualType FromType = From->getType(); 2984 bool PointerConversions = false; 2985 if (isa<FieldDecl>(Member)) { 2986 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2987 auto FromPtrType = FromType->getAs<PointerType>(); 2988 DestRecordType = Context.getAddrSpaceQualType( 2989 DestRecordType, FromPtrType 2990 ? FromType->getPointeeType().getAddressSpace() 2991 : FromType.getAddressSpace()); 2992 2993 if (FromPtrType) { 2994 DestType = Context.getPointerType(DestRecordType); 2995 FromRecordType = FromPtrType->getPointeeType(); 2996 PointerConversions = true; 2997 } else { 2998 DestType = DestRecordType; 2999 FromRecordType = FromType; 3000 } 3001 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 3002 if (Method->isStatic()) 3003 return From; 3004 3005 DestType = Method->getThisType(); 3006 DestRecordType = DestType->getPointeeType(); 3007 3008 if (FromType->getAs<PointerType>()) { 3009 FromRecordType = FromType->getPointeeType(); 3010 PointerConversions = true; 3011 } else { 3012 FromRecordType = FromType; 3013 DestType = DestRecordType; 3014 } 3015 3016 LangAS FromAS = FromRecordType.getAddressSpace(); 3017 LangAS DestAS = DestRecordType.getAddressSpace(); 3018 if (FromAS != DestAS) { 3019 QualType FromRecordTypeWithoutAS = 3020 Context.removeAddrSpaceQualType(FromRecordType); 3021 QualType FromTypeWithDestAS = 3022 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3023 if (PointerConversions) 3024 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3025 From = ImpCastExprToType(From, FromTypeWithDestAS, 3026 CK_AddressSpaceConversion, From->getValueKind()) 3027 .get(); 3028 } 3029 } else { 3030 // No conversion necessary. 3031 return From; 3032 } 3033 3034 if (DestType->isDependentType() || FromType->isDependentType()) 3035 return From; 3036 3037 // If the unqualified types are the same, no conversion is necessary. 3038 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3039 return From; 3040 3041 SourceRange FromRange = From->getSourceRange(); 3042 SourceLocation FromLoc = FromRange.getBegin(); 3043 3044 ExprValueKind VK = From->getValueKind(); 3045 3046 // C++ [class.member.lookup]p8: 3047 // [...] Ambiguities can often be resolved by qualifying a name with its 3048 // class name. 3049 // 3050 // If the member was a qualified name and the qualified referred to a 3051 // specific base subobject type, we'll cast to that intermediate type 3052 // first and then to the object in which the member is declared. That allows 3053 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3054 // 3055 // class Base { public: int x; }; 3056 // class Derived1 : public Base { }; 3057 // class Derived2 : public Base { }; 3058 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3059 // 3060 // void VeryDerived::f() { 3061 // x = 17; // error: ambiguous base subobjects 3062 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3063 // } 3064 if (Qualifier && Qualifier->getAsType()) { 3065 QualType QType = QualType(Qualifier->getAsType(), 0); 3066 assert(QType->isRecordType() && "lookup done with non-record type"); 3067 3068 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3069 3070 // In C++98, the qualifier type doesn't actually have to be a base 3071 // type of the object type, in which case we just ignore it. 3072 // Otherwise build the appropriate casts. 3073 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3074 CXXCastPath BasePath; 3075 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3076 FromLoc, FromRange, &BasePath)) 3077 return ExprError(); 3078 3079 if (PointerConversions) 3080 QType = Context.getPointerType(QType); 3081 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3082 VK, &BasePath).get(); 3083 3084 FromType = QType; 3085 FromRecordType = QRecordType; 3086 3087 // If the qualifier type was the same as the destination type, 3088 // we're done. 3089 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3090 return From; 3091 } 3092 } 3093 3094 CXXCastPath BasePath; 3095 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3096 FromLoc, FromRange, &BasePath, 3097 /*IgnoreAccess=*/true)) 3098 return ExprError(); 3099 3100 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3101 VK, &BasePath); 3102 } 3103 3104 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3105 const LookupResult &R, 3106 bool HasTrailingLParen) { 3107 // Only when used directly as the postfix-expression of a call. 3108 if (!HasTrailingLParen) 3109 return false; 3110 3111 // Never if a scope specifier was provided. 3112 if (SS.isSet()) 3113 return false; 3114 3115 // Only in C++ or ObjC++. 3116 if (!getLangOpts().CPlusPlus) 3117 return false; 3118 3119 // Turn off ADL when we find certain kinds of declarations during 3120 // normal lookup: 3121 for (NamedDecl *D : R) { 3122 // C++0x [basic.lookup.argdep]p3: 3123 // -- a declaration of a class member 3124 // Since using decls preserve this property, we check this on the 3125 // original decl. 3126 if (D->isCXXClassMember()) 3127 return false; 3128 3129 // C++0x [basic.lookup.argdep]p3: 3130 // -- a block-scope function declaration that is not a 3131 // using-declaration 3132 // NOTE: we also trigger this for function templates (in fact, we 3133 // don't check the decl type at all, since all other decl types 3134 // turn off ADL anyway). 3135 if (isa<UsingShadowDecl>(D)) 3136 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3137 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3138 return false; 3139 3140 // C++0x [basic.lookup.argdep]p3: 3141 // -- a declaration that is neither a function or a function 3142 // template 3143 // And also for builtin functions. 3144 if (isa<FunctionDecl>(D)) { 3145 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3146 3147 // But also builtin functions. 3148 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3149 return false; 3150 } else if (!isa<FunctionTemplateDecl>(D)) 3151 return false; 3152 } 3153 3154 return true; 3155 } 3156 3157 3158 /// Diagnoses obvious problems with the use of the given declaration 3159 /// as an expression. This is only actually called for lookups that 3160 /// were not overloaded, and it doesn't promise that the declaration 3161 /// will in fact be used. 3162 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3163 if (D->isInvalidDecl()) 3164 return true; 3165 3166 if (isa<TypedefNameDecl>(D)) { 3167 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3168 return true; 3169 } 3170 3171 if (isa<ObjCInterfaceDecl>(D)) { 3172 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3173 return true; 3174 } 3175 3176 if (isa<NamespaceDecl>(D)) { 3177 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3178 return true; 3179 } 3180 3181 return false; 3182 } 3183 3184 // Certain multiversion types should be treated as overloaded even when there is 3185 // only one result. 3186 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3187 assert(R.isSingleResult() && "Expected only a single result"); 3188 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3189 return FD && 3190 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3191 } 3192 3193 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3194 LookupResult &R, bool NeedsADL, 3195 bool AcceptInvalidDecl) { 3196 // If this is a single, fully-resolved result and we don't need ADL, 3197 // just build an ordinary singleton decl ref. 3198 if (!NeedsADL && R.isSingleResult() && 3199 !R.getAsSingle<FunctionTemplateDecl>() && 3200 !ShouldLookupResultBeMultiVersionOverload(R)) 3201 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3202 R.getRepresentativeDecl(), nullptr, 3203 AcceptInvalidDecl); 3204 3205 // We only need to check the declaration if there's exactly one 3206 // result, because in the overloaded case the results can only be 3207 // functions and function templates. 3208 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3209 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3210 return ExprError(); 3211 3212 // Otherwise, just build an unresolved lookup expression. Suppress 3213 // any lookup-related diagnostics; we'll hash these out later, when 3214 // we've picked a target. 3215 R.suppressDiagnostics(); 3216 3217 UnresolvedLookupExpr *ULE 3218 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3219 SS.getWithLocInContext(Context), 3220 R.getLookupNameInfo(), 3221 NeedsADL, R.isOverloadedResult(), 3222 R.begin(), R.end()); 3223 3224 return ULE; 3225 } 3226 3227 static void 3228 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3229 ValueDecl *var, DeclContext *DC); 3230 3231 /// Complete semantic analysis for a reference to the given declaration. 3232 ExprResult Sema::BuildDeclarationNameExpr( 3233 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3234 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3235 bool AcceptInvalidDecl) { 3236 assert(D && "Cannot refer to a NULL declaration"); 3237 assert(!isa<FunctionTemplateDecl>(D) && 3238 "Cannot refer unambiguously to a function template"); 3239 3240 SourceLocation Loc = NameInfo.getLoc(); 3241 if (CheckDeclInExpr(*this, Loc, D)) 3242 return ExprError(); 3243 3244 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3245 // Specifically diagnose references to class templates that are missing 3246 // a template argument list. 3247 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3248 return ExprError(); 3249 } 3250 3251 // Make sure that we're referring to a value. 3252 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3253 Diag(Loc, diag::err_ref_non_value) 3254 << D << SS.getRange(); 3255 Diag(D->getLocation(), diag::note_declared_at); 3256 return ExprError(); 3257 } 3258 3259 // Check whether this declaration can be used. Note that we suppress 3260 // this check when we're going to perform argument-dependent lookup 3261 // on this function name, because this might not be the function 3262 // that overload resolution actually selects. 3263 if (DiagnoseUseOfDecl(D, Loc)) 3264 return ExprError(); 3265 3266 auto *VD = cast<ValueDecl>(D); 3267 3268 // Only create DeclRefExpr's for valid Decl's. 3269 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3270 return ExprError(); 3271 3272 // Handle members of anonymous structs and unions. If we got here, 3273 // and the reference is to a class member indirect field, then this 3274 // must be the subject of a pointer-to-member expression. 3275 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3276 if (!indirectField->isCXXClassMember()) 3277 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3278 indirectField); 3279 3280 { 3281 QualType type = VD->getType(); 3282 if (type.isNull()) 3283 return ExprError(); 3284 ExprValueKind valueKind = VK_PRValue; 3285 3286 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3287 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3288 // is expanded by some outer '...' in the context of the use. 3289 type = type.getNonPackExpansionType(); 3290 3291 switch (D->getKind()) { 3292 // Ignore all the non-ValueDecl kinds. 3293 #define ABSTRACT_DECL(kind) 3294 #define VALUE(type, base) 3295 #define DECL(type, base) \ 3296 case Decl::type: 3297 #include "clang/AST/DeclNodes.inc" 3298 llvm_unreachable("invalid value decl kind"); 3299 3300 // These shouldn't make it here. 3301 case Decl::ObjCAtDefsField: 3302 llvm_unreachable("forming non-member reference to ivar?"); 3303 3304 // Enum constants are always r-values and never references. 3305 // Unresolved using declarations are dependent. 3306 case Decl::EnumConstant: 3307 case Decl::UnresolvedUsingValue: 3308 case Decl::OMPDeclareReduction: 3309 case Decl::OMPDeclareMapper: 3310 valueKind = VK_PRValue; 3311 break; 3312 3313 // Fields and indirect fields that got here must be for 3314 // pointer-to-member expressions; we just call them l-values for 3315 // internal consistency, because this subexpression doesn't really 3316 // exist in the high-level semantics. 3317 case Decl::Field: 3318 case Decl::IndirectField: 3319 case Decl::ObjCIvar: 3320 assert(getLangOpts().CPlusPlus && 3321 "building reference to field in C?"); 3322 3323 // These can't have reference type in well-formed programs, but 3324 // for internal consistency we do this anyway. 3325 type = type.getNonReferenceType(); 3326 valueKind = VK_LValue; 3327 break; 3328 3329 // Non-type template parameters are either l-values or r-values 3330 // depending on the type. 3331 case Decl::NonTypeTemplateParm: { 3332 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3333 type = reftype->getPointeeType(); 3334 valueKind = VK_LValue; // even if the parameter is an r-value reference 3335 break; 3336 } 3337 3338 // [expr.prim.id.unqual]p2: 3339 // If the entity is a template parameter object for a template 3340 // parameter of type T, the type of the expression is const T. 3341 // [...] The expression is an lvalue if the entity is a [...] template 3342 // parameter object. 3343 if (type->isRecordType()) { 3344 type = type.getUnqualifiedType().withConst(); 3345 valueKind = VK_LValue; 3346 break; 3347 } 3348 3349 // For non-references, we need to strip qualifiers just in case 3350 // the template parameter was declared as 'const int' or whatever. 3351 valueKind = VK_PRValue; 3352 type = type.getUnqualifiedType(); 3353 break; 3354 } 3355 3356 case Decl::Var: 3357 case Decl::VarTemplateSpecialization: 3358 case Decl::VarTemplatePartialSpecialization: 3359 case Decl::Decomposition: 3360 case Decl::OMPCapturedExpr: 3361 // In C, "extern void blah;" is valid and is an r-value. 3362 if (!getLangOpts().CPlusPlus && 3363 !type.hasQualifiers() && 3364 type->isVoidType()) { 3365 valueKind = VK_PRValue; 3366 break; 3367 } 3368 LLVM_FALLTHROUGH; 3369 3370 case Decl::ImplicitParam: 3371 case Decl::ParmVar: { 3372 // These are always l-values. 3373 valueKind = VK_LValue; 3374 type = type.getNonReferenceType(); 3375 3376 // FIXME: Does the addition of const really only apply in 3377 // potentially-evaluated contexts? Since the variable isn't actually 3378 // captured in an unevaluated context, it seems that the answer is no. 3379 if (!isUnevaluatedContext()) { 3380 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3381 if (!CapturedType.isNull()) 3382 type = CapturedType; 3383 } 3384 3385 break; 3386 } 3387 3388 case Decl::Binding: { 3389 // These are always lvalues. 3390 valueKind = VK_LValue; 3391 type = type.getNonReferenceType(); 3392 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3393 // decides how that's supposed to work. 3394 auto *BD = cast<BindingDecl>(VD); 3395 if (BD->getDeclContext() != CurContext) { 3396 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3397 if (DD && DD->hasLocalStorage()) 3398 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3399 } 3400 break; 3401 } 3402 3403 case Decl::Function: { 3404 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3405 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3406 type = Context.BuiltinFnTy; 3407 valueKind = VK_PRValue; 3408 break; 3409 } 3410 } 3411 3412 const FunctionType *fty = type->castAs<FunctionType>(); 3413 3414 // If we're referring to a function with an __unknown_anytype 3415 // result type, make the entire expression __unknown_anytype. 3416 if (fty->getReturnType() == Context.UnknownAnyTy) { 3417 type = Context.UnknownAnyTy; 3418 valueKind = VK_PRValue; 3419 break; 3420 } 3421 3422 // Functions are l-values in C++. 3423 if (getLangOpts().CPlusPlus) { 3424 valueKind = VK_LValue; 3425 break; 3426 } 3427 3428 // C99 DR 316 says that, if a function type comes from a 3429 // function definition (without a prototype), that type is only 3430 // used for checking compatibility. Therefore, when referencing 3431 // the function, we pretend that we don't have the full function 3432 // type. 3433 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3434 isa<FunctionProtoType>(fty)) 3435 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3436 fty->getExtInfo()); 3437 3438 // Functions are r-values in C. 3439 valueKind = VK_PRValue; 3440 break; 3441 } 3442 3443 case Decl::CXXDeductionGuide: 3444 llvm_unreachable("building reference to deduction guide"); 3445 3446 case Decl::MSProperty: 3447 case Decl::MSGuid: 3448 case Decl::TemplateParamObject: 3449 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3450 // capture in OpenMP, or duplicated between host and device? 3451 valueKind = VK_LValue; 3452 break; 3453 3454 case Decl::CXXMethod: 3455 // If we're referring to a method with an __unknown_anytype 3456 // result type, make the entire expression __unknown_anytype. 3457 // This should only be possible with a type written directly. 3458 if (const FunctionProtoType *proto 3459 = dyn_cast<FunctionProtoType>(VD->getType())) 3460 if (proto->getReturnType() == Context.UnknownAnyTy) { 3461 type = Context.UnknownAnyTy; 3462 valueKind = VK_PRValue; 3463 break; 3464 } 3465 3466 // C++ methods are l-values if static, r-values if non-static. 3467 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3468 valueKind = VK_LValue; 3469 break; 3470 } 3471 LLVM_FALLTHROUGH; 3472 3473 case Decl::CXXConversion: 3474 case Decl::CXXDestructor: 3475 case Decl::CXXConstructor: 3476 valueKind = VK_PRValue; 3477 break; 3478 } 3479 3480 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3481 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3482 TemplateArgs); 3483 } 3484 } 3485 3486 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3487 SmallString<32> &Target) { 3488 Target.resize(CharByteWidth * (Source.size() + 1)); 3489 char *ResultPtr = &Target[0]; 3490 const llvm::UTF8 *ErrorPtr; 3491 bool success = 3492 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3493 (void)success; 3494 assert(success); 3495 Target.resize(ResultPtr - &Target[0]); 3496 } 3497 3498 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3499 PredefinedExpr::IdentKind IK) { 3500 // Pick the current block, lambda, captured statement or function. 3501 Decl *currentDecl = nullptr; 3502 if (const BlockScopeInfo *BSI = getCurBlock()) 3503 currentDecl = BSI->TheDecl; 3504 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3505 currentDecl = LSI->CallOperator; 3506 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3507 currentDecl = CSI->TheCapturedDecl; 3508 else 3509 currentDecl = getCurFunctionOrMethodDecl(); 3510 3511 if (!currentDecl) { 3512 Diag(Loc, diag::ext_predef_outside_function); 3513 currentDecl = Context.getTranslationUnitDecl(); 3514 } 3515 3516 QualType ResTy; 3517 StringLiteral *SL = nullptr; 3518 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3519 ResTy = Context.DependentTy; 3520 else { 3521 // Pre-defined identifiers are of type char[x], where x is the length of 3522 // the string. 3523 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3524 unsigned Length = Str.length(); 3525 3526 llvm::APInt LengthI(32, Length + 1); 3527 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3528 ResTy = 3529 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3530 SmallString<32> RawChars; 3531 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3532 Str, RawChars); 3533 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3534 ArrayType::Normal, 3535 /*IndexTypeQuals*/ 0); 3536 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3537 /*Pascal*/ false, ResTy, Loc); 3538 } else { 3539 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3540 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3541 ArrayType::Normal, 3542 /*IndexTypeQuals*/ 0); 3543 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3544 /*Pascal*/ false, ResTy, Loc); 3545 } 3546 } 3547 3548 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3549 } 3550 3551 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3552 SourceLocation LParen, 3553 SourceLocation RParen, 3554 TypeSourceInfo *TSI) { 3555 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3556 } 3557 3558 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3559 SourceLocation LParen, 3560 SourceLocation RParen, 3561 ParsedType ParsedTy) { 3562 TypeSourceInfo *TSI = nullptr; 3563 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3564 3565 if (Ty.isNull()) 3566 return ExprError(); 3567 if (!TSI) 3568 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3569 3570 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3571 } 3572 3573 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3574 PredefinedExpr::IdentKind IK; 3575 3576 switch (Kind) { 3577 default: llvm_unreachable("Unknown simple primary expr!"); 3578 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3579 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3580 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3581 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3582 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3583 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3584 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3585 } 3586 3587 return BuildPredefinedExpr(Loc, IK); 3588 } 3589 3590 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3591 SmallString<16> CharBuffer; 3592 bool Invalid = false; 3593 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3594 if (Invalid) 3595 return ExprError(); 3596 3597 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3598 PP, Tok.getKind()); 3599 if (Literal.hadError()) 3600 return ExprError(); 3601 3602 QualType Ty; 3603 if (Literal.isWide()) 3604 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3605 else if (Literal.isUTF8() && getLangOpts().Char8) 3606 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3607 else if (Literal.isUTF16()) 3608 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3609 else if (Literal.isUTF32()) 3610 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3611 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3612 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3613 else 3614 Ty = Context.CharTy; // 'x' -> char in C++ 3615 3616 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3617 if (Literal.isWide()) 3618 Kind = CharacterLiteral::Wide; 3619 else if (Literal.isUTF16()) 3620 Kind = CharacterLiteral::UTF16; 3621 else if (Literal.isUTF32()) 3622 Kind = CharacterLiteral::UTF32; 3623 else if (Literal.isUTF8()) 3624 Kind = CharacterLiteral::UTF8; 3625 3626 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3627 Tok.getLocation()); 3628 3629 if (Literal.getUDSuffix().empty()) 3630 return Lit; 3631 3632 // We're building a user-defined literal. 3633 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3634 SourceLocation UDSuffixLoc = 3635 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3636 3637 // Make sure we're allowed user-defined literals here. 3638 if (!UDLScope) 3639 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3640 3641 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3642 // operator "" X (ch) 3643 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3644 Lit, Tok.getLocation()); 3645 } 3646 3647 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3648 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3649 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3650 Context.IntTy, Loc); 3651 } 3652 3653 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3654 QualType Ty, SourceLocation Loc) { 3655 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3656 3657 using llvm::APFloat; 3658 APFloat Val(Format); 3659 3660 APFloat::opStatus result = Literal.GetFloatValue(Val); 3661 3662 // Overflow is always an error, but underflow is only an error if 3663 // we underflowed to zero (APFloat reports denormals as underflow). 3664 if ((result & APFloat::opOverflow) || 3665 ((result & APFloat::opUnderflow) && Val.isZero())) { 3666 unsigned diagnostic; 3667 SmallString<20> buffer; 3668 if (result & APFloat::opOverflow) { 3669 diagnostic = diag::warn_float_overflow; 3670 APFloat::getLargest(Format).toString(buffer); 3671 } else { 3672 diagnostic = diag::warn_float_underflow; 3673 APFloat::getSmallest(Format).toString(buffer); 3674 } 3675 3676 S.Diag(Loc, diagnostic) 3677 << Ty 3678 << StringRef(buffer.data(), buffer.size()); 3679 } 3680 3681 bool isExact = (result == APFloat::opOK); 3682 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3683 } 3684 3685 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3686 assert(E && "Invalid expression"); 3687 3688 if (E->isValueDependent()) 3689 return false; 3690 3691 QualType QT = E->getType(); 3692 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3693 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3694 return true; 3695 } 3696 3697 llvm::APSInt ValueAPS; 3698 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3699 3700 if (R.isInvalid()) 3701 return true; 3702 3703 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3704 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3705 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3706 << toString(ValueAPS, 10) << ValueIsPositive; 3707 return true; 3708 } 3709 3710 return false; 3711 } 3712 3713 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3714 // Fast path for a single digit (which is quite common). A single digit 3715 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3716 if (Tok.getLength() == 1) { 3717 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3718 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3719 } 3720 3721 SmallString<128> SpellingBuffer; 3722 // NumericLiteralParser wants to overread by one character. Add padding to 3723 // the buffer in case the token is copied to the buffer. If getSpelling() 3724 // returns a StringRef to the memory buffer, it should have a null char at 3725 // the EOF, so it is also safe. 3726 SpellingBuffer.resize(Tok.getLength() + 1); 3727 3728 // Get the spelling of the token, which eliminates trigraphs, etc. 3729 bool Invalid = false; 3730 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3731 if (Invalid) 3732 return ExprError(); 3733 3734 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3735 PP.getSourceManager(), PP.getLangOpts(), 3736 PP.getTargetInfo(), PP.getDiagnostics()); 3737 if (Literal.hadError) 3738 return ExprError(); 3739 3740 if (Literal.hasUDSuffix()) { 3741 // We're building a user-defined literal. 3742 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3743 SourceLocation UDSuffixLoc = 3744 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3745 3746 // Make sure we're allowed user-defined literals here. 3747 if (!UDLScope) 3748 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3749 3750 QualType CookedTy; 3751 if (Literal.isFloatingLiteral()) { 3752 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3753 // long double, the literal is treated as a call of the form 3754 // operator "" X (f L) 3755 CookedTy = Context.LongDoubleTy; 3756 } else { 3757 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3758 // unsigned long long, the literal is treated as a call of the form 3759 // operator "" X (n ULL) 3760 CookedTy = Context.UnsignedLongLongTy; 3761 } 3762 3763 DeclarationName OpName = 3764 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3765 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3766 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3767 3768 SourceLocation TokLoc = Tok.getLocation(); 3769 3770 // Perform literal operator lookup to determine if we're building a raw 3771 // literal or a cooked one. 3772 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3773 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3774 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3775 /*AllowStringTemplatePack*/ false, 3776 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3777 case LOLR_ErrorNoDiagnostic: 3778 // Lookup failure for imaginary constants isn't fatal, there's still the 3779 // GNU extension producing _Complex types. 3780 break; 3781 case LOLR_Error: 3782 return ExprError(); 3783 case LOLR_Cooked: { 3784 Expr *Lit; 3785 if (Literal.isFloatingLiteral()) { 3786 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3787 } else { 3788 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3789 if (Literal.GetIntegerValue(ResultVal)) 3790 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3791 << /* Unsigned */ 1; 3792 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3793 Tok.getLocation()); 3794 } 3795 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3796 } 3797 3798 case LOLR_Raw: { 3799 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3800 // literal is treated as a call of the form 3801 // operator "" X ("n") 3802 unsigned Length = Literal.getUDSuffixOffset(); 3803 QualType StrTy = Context.getConstantArrayType( 3804 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3805 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3806 Expr *Lit = StringLiteral::Create( 3807 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3808 /*Pascal*/false, StrTy, &TokLoc, 1); 3809 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3810 } 3811 3812 case LOLR_Template: { 3813 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3814 // template), L is treated as a call fo the form 3815 // operator "" X <'c1', 'c2', ... 'ck'>() 3816 // where n is the source character sequence c1 c2 ... ck. 3817 TemplateArgumentListInfo ExplicitArgs; 3818 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3819 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3820 llvm::APSInt Value(CharBits, CharIsUnsigned); 3821 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3822 Value = TokSpelling[I]; 3823 TemplateArgument Arg(Context, Value, Context.CharTy); 3824 TemplateArgumentLocInfo ArgInfo; 3825 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3826 } 3827 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3828 &ExplicitArgs); 3829 } 3830 case LOLR_StringTemplatePack: 3831 llvm_unreachable("unexpected literal operator lookup result"); 3832 } 3833 } 3834 3835 Expr *Res; 3836 3837 if (Literal.isFixedPointLiteral()) { 3838 QualType Ty; 3839 3840 if (Literal.isAccum) { 3841 if (Literal.isHalf) { 3842 Ty = Context.ShortAccumTy; 3843 } else if (Literal.isLong) { 3844 Ty = Context.LongAccumTy; 3845 } else { 3846 Ty = Context.AccumTy; 3847 } 3848 } else if (Literal.isFract) { 3849 if (Literal.isHalf) { 3850 Ty = Context.ShortFractTy; 3851 } else if (Literal.isLong) { 3852 Ty = Context.LongFractTy; 3853 } else { 3854 Ty = Context.FractTy; 3855 } 3856 } 3857 3858 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3859 3860 bool isSigned = !Literal.isUnsigned; 3861 unsigned scale = Context.getFixedPointScale(Ty); 3862 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3863 3864 llvm::APInt Val(bit_width, 0, isSigned); 3865 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3866 bool ValIsZero = Val.isNullValue() && !Overflowed; 3867 3868 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3869 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3870 // Clause 6.4.4 - The value of a constant shall be in the range of 3871 // representable values for its type, with exception for constants of a 3872 // fract type with a value of exactly 1; such a constant shall denote 3873 // the maximal value for the type. 3874 --Val; 3875 else if (Val.ugt(MaxVal) || Overflowed) 3876 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3877 3878 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3879 Tok.getLocation(), scale); 3880 } else if (Literal.isFloatingLiteral()) { 3881 QualType Ty; 3882 if (Literal.isHalf){ 3883 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3884 Ty = Context.HalfTy; 3885 else { 3886 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3887 return ExprError(); 3888 } 3889 } else if (Literal.isFloat) 3890 Ty = Context.FloatTy; 3891 else if (Literal.isLong) 3892 Ty = Context.LongDoubleTy; 3893 else if (Literal.isFloat16) 3894 Ty = Context.Float16Ty; 3895 else if (Literal.isFloat128) 3896 Ty = Context.Float128Ty; 3897 else 3898 Ty = Context.DoubleTy; 3899 3900 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3901 3902 if (Ty == Context.DoubleTy) { 3903 if (getLangOpts().SinglePrecisionConstants) { 3904 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3905 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3906 } 3907 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3908 "cl_khr_fp64", getLangOpts())) { 3909 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3910 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3911 << (getLangOpts().OpenCLVersion >= 300); 3912 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3913 } 3914 } 3915 } else if (!Literal.isIntegerLiteral()) { 3916 return ExprError(); 3917 } else { 3918 QualType Ty; 3919 3920 // 'long long' is a C99 or C++11 feature. 3921 if (!getLangOpts().C99 && Literal.isLongLong) { 3922 if (getLangOpts().CPlusPlus) 3923 Diag(Tok.getLocation(), 3924 getLangOpts().CPlusPlus11 ? 3925 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3926 else 3927 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3928 } 3929 3930 // 'z/uz' literals are a C++2b feature. 3931 if (Literal.isSizeT) 3932 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3933 ? getLangOpts().CPlusPlus2b 3934 ? diag::warn_cxx20_compat_size_t_suffix 3935 : diag::ext_cxx2b_size_t_suffix 3936 : diag::err_cxx2b_size_t_suffix); 3937 3938 // Get the value in the widest-possible width. 3939 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3940 llvm::APInt ResultVal(MaxWidth, 0); 3941 3942 if (Literal.GetIntegerValue(ResultVal)) { 3943 // If this value didn't fit into uintmax_t, error and force to ull. 3944 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3945 << /* Unsigned */ 1; 3946 Ty = Context.UnsignedLongLongTy; 3947 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3948 "long long is not intmax_t?"); 3949 } else { 3950 // If this value fits into a ULL, try to figure out what else it fits into 3951 // according to the rules of C99 6.4.4.1p5. 3952 3953 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3954 // be an unsigned int. 3955 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3956 3957 // Check from smallest to largest, picking the smallest type we can. 3958 unsigned Width = 0; 3959 3960 // Microsoft specific integer suffixes are explicitly sized. 3961 if (Literal.MicrosoftInteger) { 3962 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3963 Width = 8; 3964 Ty = Context.CharTy; 3965 } else { 3966 Width = Literal.MicrosoftInteger; 3967 Ty = Context.getIntTypeForBitwidth(Width, 3968 /*Signed=*/!Literal.isUnsigned); 3969 } 3970 } 3971 3972 // Check C++2b size_t literals. 3973 if (Literal.isSizeT) { 3974 assert(!Literal.MicrosoftInteger && 3975 "size_t literals can't be Microsoft literals"); 3976 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3977 Context.getTargetInfo().getSizeType()); 3978 3979 // Does it fit in size_t? 3980 if (ResultVal.isIntN(SizeTSize)) { 3981 // Does it fit in ssize_t? 3982 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3983 Ty = Context.getSignedSizeType(); 3984 else if (AllowUnsigned) 3985 Ty = Context.getSizeType(); 3986 Width = SizeTSize; 3987 } 3988 } 3989 3990 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3991 !Literal.isSizeT) { 3992 // Are int/unsigned possibilities? 3993 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3994 3995 // Does it fit in a unsigned int? 3996 if (ResultVal.isIntN(IntSize)) { 3997 // Does it fit in a signed int? 3998 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3999 Ty = Context.IntTy; 4000 else if (AllowUnsigned) 4001 Ty = Context.UnsignedIntTy; 4002 Width = IntSize; 4003 } 4004 } 4005 4006 // Are long/unsigned long possibilities? 4007 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4008 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4009 4010 // Does it fit in a unsigned long? 4011 if (ResultVal.isIntN(LongSize)) { 4012 // Does it fit in a signed long? 4013 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4014 Ty = Context.LongTy; 4015 else if (AllowUnsigned) 4016 Ty = Context.UnsignedLongTy; 4017 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4018 // is compatible. 4019 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4020 const unsigned LongLongSize = 4021 Context.getTargetInfo().getLongLongWidth(); 4022 Diag(Tok.getLocation(), 4023 getLangOpts().CPlusPlus 4024 ? Literal.isLong 4025 ? diag::warn_old_implicitly_unsigned_long_cxx 4026 : /*C++98 UB*/ diag:: 4027 ext_old_implicitly_unsigned_long_cxx 4028 : diag::warn_old_implicitly_unsigned_long) 4029 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4030 : /*will be ill-formed*/ 1); 4031 Ty = Context.UnsignedLongTy; 4032 } 4033 Width = LongSize; 4034 } 4035 } 4036 4037 // Check long long if needed. 4038 if (Ty.isNull() && !Literal.isSizeT) { 4039 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4040 4041 // Does it fit in a unsigned long long? 4042 if (ResultVal.isIntN(LongLongSize)) { 4043 // Does it fit in a signed long long? 4044 // To be compatible with MSVC, hex integer literals ending with the 4045 // LL or i64 suffix are always signed in Microsoft mode. 4046 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4047 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4048 Ty = Context.LongLongTy; 4049 else if (AllowUnsigned) 4050 Ty = Context.UnsignedLongLongTy; 4051 Width = LongLongSize; 4052 } 4053 } 4054 4055 // If we still couldn't decide a type, we either have 'size_t' literal 4056 // that is out of range, or a decimal literal that does not fit in a 4057 // signed long long and has no U suffix. 4058 if (Ty.isNull()) { 4059 if (Literal.isSizeT) 4060 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4061 << Literal.isUnsigned; 4062 else 4063 Diag(Tok.getLocation(), 4064 diag::ext_integer_literal_too_large_for_signed); 4065 Ty = Context.UnsignedLongLongTy; 4066 Width = Context.getTargetInfo().getLongLongWidth(); 4067 } 4068 4069 if (ResultVal.getBitWidth() != Width) 4070 ResultVal = ResultVal.trunc(Width); 4071 } 4072 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4073 } 4074 4075 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4076 if (Literal.isImaginary) { 4077 Res = new (Context) ImaginaryLiteral(Res, 4078 Context.getComplexType(Res->getType())); 4079 4080 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4081 } 4082 return Res; 4083 } 4084 4085 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4086 assert(E && "ActOnParenExpr() missing expr"); 4087 QualType ExprTy = E->getType(); 4088 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4089 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4090 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4091 return new (Context) ParenExpr(L, R, E); 4092 } 4093 4094 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4095 SourceLocation Loc, 4096 SourceRange ArgRange) { 4097 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4098 // scalar or vector data type argument..." 4099 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4100 // type (C99 6.2.5p18) or void. 4101 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4102 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4103 << T << ArgRange; 4104 return true; 4105 } 4106 4107 assert((T->isVoidType() || !T->isIncompleteType()) && 4108 "Scalar types should always be complete"); 4109 return false; 4110 } 4111 4112 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4113 SourceLocation Loc, 4114 SourceRange ArgRange, 4115 UnaryExprOrTypeTrait TraitKind) { 4116 // Invalid types must be hard errors for SFINAE in C++. 4117 if (S.LangOpts.CPlusPlus) 4118 return true; 4119 4120 // C99 6.5.3.4p1: 4121 if (T->isFunctionType() && 4122 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4123 TraitKind == UETT_PreferredAlignOf)) { 4124 // sizeof(function)/alignof(function) is allowed as an extension. 4125 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4126 << getTraitSpelling(TraitKind) << ArgRange; 4127 return false; 4128 } 4129 4130 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4131 // this is an error (OpenCL v1.1 s6.3.k) 4132 if (T->isVoidType()) { 4133 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4134 : diag::ext_sizeof_alignof_void_type; 4135 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4136 return false; 4137 } 4138 4139 return true; 4140 } 4141 4142 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4143 SourceLocation Loc, 4144 SourceRange ArgRange, 4145 UnaryExprOrTypeTrait TraitKind) { 4146 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4147 // runtime doesn't allow it. 4148 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4149 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4150 << T << (TraitKind == UETT_SizeOf) 4151 << ArgRange; 4152 return true; 4153 } 4154 4155 return false; 4156 } 4157 4158 /// Check whether E is a pointer from a decayed array type (the decayed 4159 /// pointer type is equal to T) and emit a warning if it is. 4160 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4161 Expr *E) { 4162 // Don't warn if the operation changed the type. 4163 if (T != E->getType()) 4164 return; 4165 4166 // Now look for array decays. 4167 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4168 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4169 return; 4170 4171 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4172 << ICE->getType() 4173 << ICE->getSubExpr()->getType(); 4174 } 4175 4176 /// Check the constraints on expression operands to unary type expression 4177 /// and type traits. 4178 /// 4179 /// Completes any types necessary and validates the constraints on the operand 4180 /// expression. The logic mostly mirrors the type-based overload, but may modify 4181 /// the expression as it completes the type for that expression through template 4182 /// instantiation, etc. 4183 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4184 UnaryExprOrTypeTrait ExprKind) { 4185 QualType ExprTy = E->getType(); 4186 assert(!ExprTy->isReferenceType()); 4187 4188 bool IsUnevaluatedOperand = 4189 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4190 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4191 if (IsUnevaluatedOperand) { 4192 ExprResult Result = CheckUnevaluatedOperand(E); 4193 if (Result.isInvalid()) 4194 return true; 4195 E = Result.get(); 4196 } 4197 4198 // The operand for sizeof and alignof is in an unevaluated expression context, 4199 // so side effects could result in unintended consequences. 4200 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4201 // used to build SFINAE gadgets. 4202 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4203 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4204 !E->isInstantiationDependent() && 4205 E->HasSideEffects(Context, false)) 4206 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4207 4208 if (ExprKind == UETT_VecStep) 4209 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4210 E->getSourceRange()); 4211 4212 // Explicitly list some types as extensions. 4213 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4214 E->getSourceRange(), ExprKind)) 4215 return false; 4216 4217 // 'alignof' applied to an expression only requires the base element type of 4218 // the expression to be complete. 'sizeof' requires the expression's type to 4219 // be complete (and will attempt to complete it if it's an array of unknown 4220 // bound). 4221 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4222 if (RequireCompleteSizedType( 4223 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4224 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4225 getTraitSpelling(ExprKind), E->getSourceRange())) 4226 return true; 4227 } else { 4228 if (RequireCompleteSizedExprType( 4229 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4230 getTraitSpelling(ExprKind), E->getSourceRange())) 4231 return true; 4232 } 4233 4234 // Completing the expression's type may have changed it. 4235 ExprTy = E->getType(); 4236 assert(!ExprTy->isReferenceType()); 4237 4238 if (ExprTy->isFunctionType()) { 4239 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4240 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4241 return true; 4242 } 4243 4244 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4245 E->getSourceRange(), ExprKind)) 4246 return true; 4247 4248 if (ExprKind == UETT_SizeOf) { 4249 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4250 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4251 QualType OType = PVD->getOriginalType(); 4252 QualType Type = PVD->getType(); 4253 if (Type->isPointerType() && OType->isArrayType()) { 4254 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4255 << Type << OType; 4256 Diag(PVD->getLocation(), diag::note_declared_at); 4257 } 4258 } 4259 } 4260 4261 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4262 // decays into a pointer and returns an unintended result. This is most 4263 // likely a typo for "sizeof(array) op x". 4264 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4265 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4266 BO->getLHS()); 4267 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4268 BO->getRHS()); 4269 } 4270 } 4271 4272 return false; 4273 } 4274 4275 /// Check the constraints on operands to unary expression and type 4276 /// traits. 4277 /// 4278 /// This will complete any types necessary, and validate the various constraints 4279 /// on those operands. 4280 /// 4281 /// The UsualUnaryConversions() function is *not* called by this routine. 4282 /// C99 6.3.2.1p[2-4] all state: 4283 /// Except when it is the operand of the sizeof operator ... 4284 /// 4285 /// C++ [expr.sizeof]p4 4286 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4287 /// standard conversions are not applied to the operand of sizeof. 4288 /// 4289 /// This policy is followed for all of the unary trait expressions. 4290 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4291 SourceLocation OpLoc, 4292 SourceRange ExprRange, 4293 UnaryExprOrTypeTrait ExprKind) { 4294 if (ExprType->isDependentType()) 4295 return false; 4296 4297 // C++ [expr.sizeof]p2: 4298 // When applied to a reference or a reference type, the result 4299 // is the size of the referenced type. 4300 // C++11 [expr.alignof]p3: 4301 // When alignof is applied to a reference type, the result 4302 // shall be the alignment of the referenced type. 4303 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4304 ExprType = Ref->getPointeeType(); 4305 4306 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4307 // When alignof or _Alignof is applied to an array type, the result 4308 // is the alignment of the element type. 4309 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4310 ExprKind == UETT_OpenMPRequiredSimdAlign) 4311 ExprType = Context.getBaseElementType(ExprType); 4312 4313 if (ExprKind == UETT_VecStep) 4314 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4315 4316 // Explicitly list some types as extensions. 4317 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4318 ExprKind)) 4319 return false; 4320 4321 if (RequireCompleteSizedType( 4322 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4323 getTraitSpelling(ExprKind), ExprRange)) 4324 return true; 4325 4326 if (ExprType->isFunctionType()) { 4327 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4328 << getTraitSpelling(ExprKind) << ExprRange; 4329 return true; 4330 } 4331 4332 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4333 ExprKind)) 4334 return true; 4335 4336 return false; 4337 } 4338 4339 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4340 // Cannot know anything else if the expression is dependent. 4341 if (E->isTypeDependent()) 4342 return false; 4343 4344 if (E->getObjectKind() == OK_BitField) { 4345 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4346 << 1 << E->getSourceRange(); 4347 return true; 4348 } 4349 4350 ValueDecl *D = nullptr; 4351 Expr *Inner = E->IgnoreParens(); 4352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4353 D = DRE->getDecl(); 4354 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4355 D = ME->getMemberDecl(); 4356 } 4357 4358 // If it's a field, require the containing struct to have a 4359 // complete definition so that we can compute the layout. 4360 // 4361 // This can happen in C++11 onwards, either by naming the member 4362 // in a way that is not transformed into a member access expression 4363 // (in an unevaluated operand, for instance), or by naming the member 4364 // in a trailing-return-type. 4365 // 4366 // For the record, since __alignof__ on expressions is a GCC 4367 // extension, GCC seems to permit this but always gives the 4368 // nonsensical answer 0. 4369 // 4370 // We don't really need the layout here --- we could instead just 4371 // directly check for all the appropriate alignment-lowing 4372 // attributes --- but that would require duplicating a lot of 4373 // logic that just isn't worth duplicating for such a marginal 4374 // use-case. 4375 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4376 // Fast path this check, since we at least know the record has a 4377 // definition if we can find a member of it. 4378 if (!FD->getParent()->isCompleteDefinition()) { 4379 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4380 << E->getSourceRange(); 4381 return true; 4382 } 4383 4384 // Otherwise, if it's a field, and the field doesn't have 4385 // reference type, then it must have a complete type (or be a 4386 // flexible array member, which we explicitly want to 4387 // white-list anyway), which makes the following checks trivial. 4388 if (!FD->getType()->isReferenceType()) 4389 return false; 4390 } 4391 4392 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4393 } 4394 4395 bool Sema::CheckVecStepExpr(Expr *E) { 4396 E = E->IgnoreParens(); 4397 4398 // Cannot know anything else if the expression is dependent. 4399 if (E->isTypeDependent()) 4400 return false; 4401 4402 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4403 } 4404 4405 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4406 CapturingScopeInfo *CSI) { 4407 assert(T->isVariablyModifiedType()); 4408 assert(CSI != nullptr); 4409 4410 // We're going to walk down into the type and look for VLA expressions. 4411 do { 4412 const Type *Ty = T.getTypePtr(); 4413 switch (Ty->getTypeClass()) { 4414 #define TYPE(Class, Base) 4415 #define ABSTRACT_TYPE(Class, Base) 4416 #define NON_CANONICAL_TYPE(Class, Base) 4417 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4418 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4419 #include "clang/AST/TypeNodes.inc" 4420 T = QualType(); 4421 break; 4422 // These types are never variably-modified. 4423 case Type::Builtin: 4424 case Type::Complex: 4425 case Type::Vector: 4426 case Type::ExtVector: 4427 case Type::ConstantMatrix: 4428 case Type::Record: 4429 case Type::Enum: 4430 case Type::Elaborated: 4431 case Type::TemplateSpecialization: 4432 case Type::ObjCObject: 4433 case Type::ObjCInterface: 4434 case Type::ObjCObjectPointer: 4435 case Type::ObjCTypeParam: 4436 case Type::Pipe: 4437 case Type::ExtInt: 4438 llvm_unreachable("type class is never variably-modified!"); 4439 case Type::Adjusted: 4440 T = cast<AdjustedType>(Ty)->getOriginalType(); 4441 break; 4442 case Type::Decayed: 4443 T = cast<DecayedType>(Ty)->getPointeeType(); 4444 break; 4445 case Type::Pointer: 4446 T = cast<PointerType>(Ty)->getPointeeType(); 4447 break; 4448 case Type::BlockPointer: 4449 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4450 break; 4451 case Type::LValueReference: 4452 case Type::RValueReference: 4453 T = cast<ReferenceType>(Ty)->getPointeeType(); 4454 break; 4455 case Type::MemberPointer: 4456 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4457 break; 4458 case Type::ConstantArray: 4459 case Type::IncompleteArray: 4460 // Losing element qualification here is fine. 4461 T = cast<ArrayType>(Ty)->getElementType(); 4462 break; 4463 case Type::VariableArray: { 4464 // Losing element qualification here is fine. 4465 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4466 4467 // Unknown size indication requires no size computation. 4468 // Otherwise, evaluate and record it. 4469 auto Size = VAT->getSizeExpr(); 4470 if (Size && !CSI->isVLATypeCaptured(VAT) && 4471 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4472 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4473 4474 T = VAT->getElementType(); 4475 break; 4476 } 4477 case Type::FunctionProto: 4478 case Type::FunctionNoProto: 4479 T = cast<FunctionType>(Ty)->getReturnType(); 4480 break; 4481 case Type::Paren: 4482 case Type::TypeOf: 4483 case Type::UnaryTransform: 4484 case Type::Attributed: 4485 case Type::SubstTemplateTypeParm: 4486 case Type::MacroQualified: 4487 // Keep walking after single level desugaring. 4488 T = T.getSingleStepDesugaredType(Context); 4489 break; 4490 case Type::Typedef: 4491 T = cast<TypedefType>(Ty)->desugar(); 4492 break; 4493 case Type::Decltype: 4494 T = cast<DecltypeType>(Ty)->desugar(); 4495 break; 4496 case Type::Auto: 4497 case Type::DeducedTemplateSpecialization: 4498 T = cast<DeducedType>(Ty)->getDeducedType(); 4499 break; 4500 case Type::TypeOfExpr: 4501 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4502 break; 4503 case Type::Atomic: 4504 T = cast<AtomicType>(Ty)->getValueType(); 4505 break; 4506 } 4507 } while (!T.isNull() && T->isVariablyModifiedType()); 4508 } 4509 4510 /// Build a sizeof or alignof expression given a type operand. 4511 ExprResult 4512 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4513 SourceLocation OpLoc, 4514 UnaryExprOrTypeTrait ExprKind, 4515 SourceRange R) { 4516 if (!TInfo) 4517 return ExprError(); 4518 4519 QualType T = TInfo->getType(); 4520 4521 if (!T->isDependentType() && 4522 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4523 return ExprError(); 4524 4525 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4526 if (auto *TT = T->getAs<TypedefType>()) { 4527 for (auto I = FunctionScopes.rbegin(), 4528 E = std::prev(FunctionScopes.rend()); 4529 I != E; ++I) { 4530 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4531 if (CSI == nullptr) 4532 break; 4533 DeclContext *DC = nullptr; 4534 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4535 DC = LSI->CallOperator; 4536 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4537 DC = CRSI->TheCapturedDecl; 4538 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4539 DC = BSI->TheDecl; 4540 if (DC) { 4541 if (DC->containsDecl(TT->getDecl())) 4542 break; 4543 captureVariablyModifiedType(Context, T, CSI); 4544 } 4545 } 4546 } 4547 } 4548 4549 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4550 return new (Context) UnaryExprOrTypeTraitExpr( 4551 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4552 } 4553 4554 /// Build a sizeof or alignof expression given an expression 4555 /// operand. 4556 ExprResult 4557 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4558 UnaryExprOrTypeTrait ExprKind) { 4559 ExprResult PE = CheckPlaceholderExpr(E); 4560 if (PE.isInvalid()) 4561 return ExprError(); 4562 4563 E = PE.get(); 4564 4565 // Verify that the operand is valid. 4566 bool isInvalid = false; 4567 if (E->isTypeDependent()) { 4568 // Delay type-checking for type-dependent expressions. 4569 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4570 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4571 } else if (ExprKind == UETT_VecStep) { 4572 isInvalid = CheckVecStepExpr(E); 4573 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4574 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4575 isInvalid = true; 4576 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4577 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4578 isInvalid = true; 4579 } else { 4580 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4581 } 4582 4583 if (isInvalid) 4584 return ExprError(); 4585 4586 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4587 PE = TransformToPotentiallyEvaluated(E); 4588 if (PE.isInvalid()) return ExprError(); 4589 E = PE.get(); 4590 } 4591 4592 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4593 return new (Context) UnaryExprOrTypeTraitExpr( 4594 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4595 } 4596 4597 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4598 /// expr and the same for @c alignof and @c __alignof 4599 /// Note that the ArgRange is invalid if isType is false. 4600 ExprResult 4601 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4602 UnaryExprOrTypeTrait ExprKind, bool IsType, 4603 void *TyOrEx, SourceRange ArgRange) { 4604 // If error parsing type, ignore. 4605 if (!TyOrEx) return ExprError(); 4606 4607 if (IsType) { 4608 TypeSourceInfo *TInfo; 4609 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4610 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4611 } 4612 4613 Expr *ArgEx = (Expr *)TyOrEx; 4614 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4615 return Result; 4616 } 4617 4618 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4619 bool IsReal) { 4620 if (V.get()->isTypeDependent()) 4621 return S.Context.DependentTy; 4622 4623 // _Real and _Imag are only l-values for normal l-values. 4624 if (V.get()->getObjectKind() != OK_Ordinary) { 4625 V = S.DefaultLvalueConversion(V.get()); 4626 if (V.isInvalid()) 4627 return QualType(); 4628 } 4629 4630 // These operators return the element type of a complex type. 4631 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4632 return CT->getElementType(); 4633 4634 // Otherwise they pass through real integer and floating point types here. 4635 if (V.get()->getType()->isArithmeticType()) 4636 return V.get()->getType(); 4637 4638 // Test for placeholders. 4639 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4640 if (PR.isInvalid()) return QualType(); 4641 if (PR.get() != V.get()) { 4642 V = PR; 4643 return CheckRealImagOperand(S, V, Loc, IsReal); 4644 } 4645 4646 // Reject anything else. 4647 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4648 << (IsReal ? "__real" : "__imag"); 4649 return QualType(); 4650 } 4651 4652 4653 4654 ExprResult 4655 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4656 tok::TokenKind Kind, Expr *Input) { 4657 UnaryOperatorKind Opc; 4658 switch (Kind) { 4659 default: llvm_unreachable("Unknown unary op!"); 4660 case tok::plusplus: Opc = UO_PostInc; break; 4661 case tok::minusminus: Opc = UO_PostDec; break; 4662 } 4663 4664 // Since this might is a postfix expression, get rid of ParenListExprs. 4665 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4666 if (Result.isInvalid()) return ExprError(); 4667 Input = Result.get(); 4668 4669 return BuildUnaryOp(S, OpLoc, Opc, Input); 4670 } 4671 4672 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4673 /// 4674 /// \return true on error 4675 static bool checkArithmeticOnObjCPointer(Sema &S, 4676 SourceLocation opLoc, 4677 Expr *op) { 4678 assert(op->getType()->isObjCObjectPointerType()); 4679 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4680 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4681 return false; 4682 4683 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4684 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4685 << op->getSourceRange(); 4686 return true; 4687 } 4688 4689 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4690 auto *BaseNoParens = Base->IgnoreParens(); 4691 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4692 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4693 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4694 } 4695 4696 ExprResult 4697 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4698 Expr *idx, SourceLocation rbLoc) { 4699 if (base && !base->getType().isNull() && 4700 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4701 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4702 SourceLocation(), /*Length*/ nullptr, 4703 /*Stride=*/nullptr, rbLoc); 4704 4705 // Since this might be a postfix expression, get rid of ParenListExprs. 4706 if (isa<ParenListExpr>(base)) { 4707 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4708 if (result.isInvalid()) return ExprError(); 4709 base = result.get(); 4710 } 4711 4712 // Check if base and idx form a MatrixSubscriptExpr. 4713 // 4714 // Helper to check for comma expressions, which are not allowed as indices for 4715 // matrix subscript expressions. 4716 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4717 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4718 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4719 << SourceRange(base->getBeginLoc(), rbLoc); 4720 return true; 4721 } 4722 return false; 4723 }; 4724 // The matrix subscript operator ([][])is considered a single operator. 4725 // Separating the index expressions by parenthesis is not allowed. 4726 if (base->getType()->isSpecificPlaceholderType( 4727 BuiltinType::IncompleteMatrixIdx) && 4728 !isa<MatrixSubscriptExpr>(base)) { 4729 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4730 << SourceRange(base->getBeginLoc(), rbLoc); 4731 return ExprError(); 4732 } 4733 // If the base is a MatrixSubscriptExpr, try to create a new 4734 // MatrixSubscriptExpr. 4735 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4736 if (matSubscriptE) { 4737 if (CheckAndReportCommaError(idx)) 4738 return ExprError(); 4739 4740 assert(matSubscriptE->isIncomplete() && 4741 "base has to be an incomplete matrix subscript"); 4742 return CreateBuiltinMatrixSubscriptExpr( 4743 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4744 } 4745 4746 // Handle any non-overload placeholder types in the base and index 4747 // expressions. We can't handle overloads here because the other 4748 // operand might be an overloadable type, in which case the overload 4749 // resolution for the operator overload should get the first crack 4750 // at the overload. 4751 bool IsMSPropertySubscript = false; 4752 if (base->getType()->isNonOverloadPlaceholderType()) { 4753 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4754 if (!IsMSPropertySubscript) { 4755 ExprResult result = CheckPlaceholderExpr(base); 4756 if (result.isInvalid()) 4757 return ExprError(); 4758 base = result.get(); 4759 } 4760 } 4761 4762 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4763 if (base->getType()->isMatrixType()) { 4764 if (CheckAndReportCommaError(idx)) 4765 return ExprError(); 4766 4767 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4768 } 4769 4770 // A comma-expression as the index is deprecated in C++2a onwards. 4771 if (getLangOpts().CPlusPlus20 && 4772 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4773 (isa<CXXOperatorCallExpr>(idx) && 4774 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4775 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4776 << SourceRange(base->getBeginLoc(), rbLoc); 4777 } 4778 4779 if (idx->getType()->isNonOverloadPlaceholderType()) { 4780 ExprResult result = CheckPlaceholderExpr(idx); 4781 if (result.isInvalid()) return ExprError(); 4782 idx = result.get(); 4783 } 4784 4785 // Build an unanalyzed expression if either operand is type-dependent. 4786 if (getLangOpts().CPlusPlus && 4787 (base->isTypeDependent() || idx->isTypeDependent())) { 4788 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4789 VK_LValue, OK_Ordinary, rbLoc); 4790 } 4791 4792 // MSDN, property (C++) 4793 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4794 // This attribute can also be used in the declaration of an empty array in a 4795 // class or structure definition. For example: 4796 // __declspec(property(get=GetX, put=PutX)) int x[]; 4797 // The above statement indicates that x[] can be used with one or more array 4798 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4799 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4800 if (IsMSPropertySubscript) { 4801 // Build MS property subscript expression if base is MS property reference 4802 // or MS property subscript. 4803 return new (Context) MSPropertySubscriptExpr( 4804 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4805 } 4806 4807 // Use C++ overloaded-operator rules if either operand has record 4808 // type. The spec says to do this if either type is *overloadable*, 4809 // but enum types can't declare subscript operators or conversion 4810 // operators, so there's nothing interesting for overload resolution 4811 // to do if there aren't any record types involved. 4812 // 4813 // ObjC pointers have their own subscripting logic that is not tied 4814 // to overload resolution and so should not take this path. 4815 if (getLangOpts().CPlusPlus && 4816 (base->getType()->isRecordType() || 4817 (!base->getType()->isObjCObjectPointerType() && 4818 idx->getType()->isRecordType()))) { 4819 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4820 } 4821 4822 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4823 4824 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4825 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4826 4827 return Res; 4828 } 4829 4830 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4831 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4832 InitializationKind Kind = 4833 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4834 InitializationSequence InitSeq(*this, Entity, Kind, E); 4835 return InitSeq.Perform(*this, Entity, Kind, E); 4836 } 4837 4838 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4839 Expr *ColumnIdx, 4840 SourceLocation RBLoc) { 4841 ExprResult BaseR = CheckPlaceholderExpr(Base); 4842 if (BaseR.isInvalid()) 4843 return BaseR; 4844 Base = BaseR.get(); 4845 4846 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4847 if (RowR.isInvalid()) 4848 return RowR; 4849 RowIdx = RowR.get(); 4850 4851 if (!ColumnIdx) 4852 return new (Context) MatrixSubscriptExpr( 4853 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4854 4855 // Build an unanalyzed expression if any of the operands is type-dependent. 4856 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4857 ColumnIdx->isTypeDependent()) 4858 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4859 Context.DependentTy, RBLoc); 4860 4861 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4862 if (ColumnR.isInvalid()) 4863 return ColumnR; 4864 ColumnIdx = ColumnR.get(); 4865 4866 // Check that IndexExpr is an integer expression. If it is a constant 4867 // expression, check that it is less than Dim (= the number of elements in the 4868 // corresponding dimension). 4869 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4870 bool IsColumnIdx) -> Expr * { 4871 if (!IndexExpr->getType()->isIntegerType() && 4872 !IndexExpr->isTypeDependent()) { 4873 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4874 << IsColumnIdx; 4875 return nullptr; 4876 } 4877 4878 if (Optional<llvm::APSInt> Idx = 4879 IndexExpr->getIntegerConstantExpr(Context)) { 4880 if ((*Idx < 0 || *Idx >= Dim)) { 4881 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4882 << IsColumnIdx << Dim; 4883 return nullptr; 4884 } 4885 } 4886 4887 ExprResult ConvExpr = 4888 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4889 assert(!ConvExpr.isInvalid() && 4890 "should be able to convert any integer type to size type"); 4891 return ConvExpr.get(); 4892 }; 4893 4894 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4895 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4896 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4897 if (!RowIdx || !ColumnIdx) 4898 return ExprError(); 4899 4900 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4901 MTy->getElementType(), RBLoc); 4902 } 4903 4904 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4905 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4906 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4907 4908 // For expressions like `&(*s).b`, the base is recorded and what should be 4909 // checked. 4910 const MemberExpr *Member = nullptr; 4911 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4912 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4913 4914 LastRecord.PossibleDerefs.erase(StrippedExpr); 4915 } 4916 4917 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4918 if (isUnevaluatedContext()) 4919 return; 4920 4921 QualType ResultTy = E->getType(); 4922 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4923 4924 // Bail if the element is an array since it is not memory access. 4925 if (isa<ArrayType>(ResultTy)) 4926 return; 4927 4928 if (ResultTy->hasAttr(attr::NoDeref)) { 4929 LastRecord.PossibleDerefs.insert(E); 4930 return; 4931 } 4932 4933 // Check if the base type is a pointer to a member access of a struct 4934 // marked with noderef. 4935 const Expr *Base = E->getBase(); 4936 QualType BaseTy = Base->getType(); 4937 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4938 // Not a pointer access 4939 return; 4940 4941 const MemberExpr *Member = nullptr; 4942 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4943 Member->isArrow()) 4944 Base = Member->getBase(); 4945 4946 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4947 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4948 LastRecord.PossibleDerefs.insert(E); 4949 } 4950 } 4951 4952 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4953 Expr *LowerBound, 4954 SourceLocation ColonLocFirst, 4955 SourceLocation ColonLocSecond, 4956 Expr *Length, Expr *Stride, 4957 SourceLocation RBLoc) { 4958 if (Base->getType()->isPlaceholderType() && 4959 !Base->getType()->isSpecificPlaceholderType( 4960 BuiltinType::OMPArraySection)) { 4961 ExprResult Result = CheckPlaceholderExpr(Base); 4962 if (Result.isInvalid()) 4963 return ExprError(); 4964 Base = Result.get(); 4965 } 4966 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4967 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4968 if (Result.isInvalid()) 4969 return ExprError(); 4970 Result = DefaultLvalueConversion(Result.get()); 4971 if (Result.isInvalid()) 4972 return ExprError(); 4973 LowerBound = Result.get(); 4974 } 4975 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4976 ExprResult Result = CheckPlaceholderExpr(Length); 4977 if (Result.isInvalid()) 4978 return ExprError(); 4979 Result = DefaultLvalueConversion(Result.get()); 4980 if (Result.isInvalid()) 4981 return ExprError(); 4982 Length = Result.get(); 4983 } 4984 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4985 ExprResult Result = CheckPlaceholderExpr(Stride); 4986 if (Result.isInvalid()) 4987 return ExprError(); 4988 Result = DefaultLvalueConversion(Result.get()); 4989 if (Result.isInvalid()) 4990 return ExprError(); 4991 Stride = Result.get(); 4992 } 4993 4994 // Build an unanalyzed expression if either operand is type-dependent. 4995 if (Base->isTypeDependent() || 4996 (LowerBound && 4997 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4998 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4999 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5000 return new (Context) OMPArraySectionExpr( 5001 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5002 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5003 } 5004 5005 // Perform default conversions. 5006 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5007 QualType ResultTy; 5008 if (OriginalTy->isAnyPointerType()) { 5009 ResultTy = OriginalTy->getPointeeType(); 5010 } else if (OriginalTy->isArrayType()) { 5011 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5012 } else { 5013 return ExprError( 5014 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5015 << Base->getSourceRange()); 5016 } 5017 // C99 6.5.2.1p1 5018 if (LowerBound) { 5019 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5020 LowerBound); 5021 if (Res.isInvalid()) 5022 return ExprError(Diag(LowerBound->getExprLoc(), 5023 diag::err_omp_typecheck_section_not_integer) 5024 << 0 << LowerBound->getSourceRange()); 5025 LowerBound = Res.get(); 5026 5027 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5028 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5029 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5030 << 0 << LowerBound->getSourceRange(); 5031 } 5032 if (Length) { 5033 auto Res = 5034 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5035 if (Res.isInvalid()) 5036 return ExprError(Diag(Length->getExprLoc(), 5037 diag::err_omp_typecheck_section_not_integer) 5038 << 1 << Length->getSourceRange()); 5039 Length = Res.get(); 5040 5041 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5042 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5043 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5044 << 1 << Length->getSourceRange(); 5045 } 5046 if (Stride) { 5047 ExprResult Res = 5048 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5049 if (Res.isInvalid()) 5050 return ExprError(Diag(Stride->getExprLoc(), 5051 diag::err_omp_typecheck_section_not_integer) 5052 << 1 << Stride->getSourceRange()); 5053 Stride = Res.get(); 5054 5055 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5056 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5057 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5058 << 1 << Stride->getSourceRange(); 5059 } 5060 5061 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5062 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5063 // type. Note that functions are not objects, and that (in C99 parlance) 5064 // incomplete types are not object types. 5065 if (ResultTy->isFunctionType()) { 5066 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5067 << ResultTy << Base->getSourceRange(); 5068 return ExprError(); 5069 } 5070 5071 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5072 diag::err_omp_section_incomplete_type, Base)) 5073 return ExprError(); 5074 5075 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5076 Expr::EvalResult Result; 5077 if (LowerBound->EvaluateAsInt(Result, Context)) { 5078 // OpenMP 5.0, [2.1.5 Array Sections] 5079 // The array section must be a subset of the original array. 5080 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5081 if (LowerBoundValue.isNegative()) { 5082 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5083 << LowerBound->getSourceRange(); 5084 return ExprError(); 5085 } 5086 } 5087 } 5088 5089 if (Length) { 5090 Expr::EvalResult Result; 5091 if (Length->EvaluateAsInt(Result, Context)) { 5092 // OpenMP 5.0, [2.1.5 Array Sections] 5093 // The length must evaluate to non-negative integers. 5094 llvm::APSInt LengthValue = Result.Val.getInt(); 5095 if (LengthValue.isNegative()) { 5096 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5097 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5098 << Length->getSourceRange(); 5099 return ExprError(); 5100 } 5101 } 5102 } else if (ColonLocFirst.isValid() && 5103 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5104 !OriginalTy->isVariableArrayType()))) { 5105 // OpenMP 5.0, [2.1.5 Array Sections] 5106 // When the size of the array dimension is not known, the length must be 5107 // specified explicitly. 5108 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5109 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5110 return ExprError(); 5111 } 5112 5113 if (Stride) { 5114 Expr::EvalResult Result; 5115 if (Stride->EvaluateAsInt(Result, Context)) { 5116 // OpenMP 5.0, [2.1.5 Array Sections] 5117 // The stride must evaluate to a positive integer. 5118 llvm::APSInt StrideValue = Result.Val.getInt(); 5119 if (!StrideValue.isStrictlyPositive()) { 5120 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5121 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5122 << Stride->getSourceRange(); 5123 return ExprError(); 5124 } 5125 } 5126 } 5127 5128 if (!Base->getType()->isSpecificPlaceholderType( 5129 BuiltinType::OMPArraySection)) { 5130 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5131 if (Result.isInvalid()) 5132 return ExprError(); 5133 Base = Result.get(); 5134 } 5135 return new (Context) OMPArraySectionExpr( 5136 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5137 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5138 } 5139 5140 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5141 SourceLocation RParenLoc, 5142 ArrayRef<Expr *> Dims, 5143 ArrayRef<SourceRange> Brackets) { 5144 if (Base->getType()->isPlaceholderType()) { 5145 ExprResult Result = CheckPlaceholderExpr(Base); 5146 if (Result.isInvalid()) 5147 return ExprError(); 5148 Result = DefaultLvalueConversion(Result.get()); 5149 if (Result.isInvalid()) 5150 return ExprError(); 5151 Base = Result.get(); 5152 } 5153 QualType BaseTy = Base->getType(); 5154 // Delay analysis of the types/expressions if instantiation/specialization is 5155 // required. 5156 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5157 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5158 LParenLoc, RParenLoc, Dims, Brackets); 5159 if (!BaseTy->isPointerType() || 5160 (!Base->isTypeDependent() && 5161 BaseTy->getPointeeType()->isIncompleteType())) 5162 return ExprError(Diag(Base->getExprLoc(), 5163 diag::err_omp_non_pointer_type_array_shaping_base) 5164 << Base->getSourceRange()); 5165 5166 SmallVector<Expr *, 4> NewDims; 5167 bool ErrorFound = false; 5168 for (Expr *Dim : Dims) { 5169 if (Dim->getType()->isPlaceholderType()) { 5170 ExprResult Result = CheckPlaceholderExpr(Dim); 5171 if (Result.isInvalid()) { 5172 ErrorFound = true; 5173 continue; 5174 } 5175 Result = DefaultLvalueConversion(Result.get()); 5176 if (Result.isInvalid()) { 5177 ErrorFound = true; 5178 continue; 5179 } 5180 Dim = Result.get(); 5181 } 5182 if (!Dim->isTypeDependent()) { 5183 ExprResult Result = 5184 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5185 if (Result.isInvalid()) { 5186 ErrorFound = true; 5187 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5188 << Dim->getSourceRange(); 5189 continue; 5190 } 5191 Dim = Result.get(); 5192 Expr::EvalResult EvResult; 5193 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5194 // OpenMP 5.0, [2.1.4 Array Shaping] 5195 // Each si is an integral type expression that must evaluate to a 5196 // positive integer. 5197 llvm::APSInt Value = EvResult.Val.getInt(); 5198 if (!Value.isStrictlyPositive()) { 5199 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5200 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5201 << Dim->getSourceRange(); 5202 ErrorFound = true; 5203 continue; 5204 } 5205 } 5206 } 5207 NewDims.push_back(Dim); 5208 } 5209 if (ErrorFound) 5210 return ExprError(); 5211 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5212 LParenLoc, RParenLoc, NewDims, Brackets); 5213 } 5214 5215 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5216 SourceLocation LLoc, SourceLocation RLoc, 5217 ArrayRef<OMPIteratorData> Data) { 5218 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5219 bool IsCorrect = true; 5220 for (const OMPIteratorData &D : Data) { 5221 TypeSourceInfo *TInfo = nullptr; 5222 SourceLocation StartLoc; 5223 QualType DeclTy; 5224 if (!D.Type.getAsOpaquePtr()) { 5225 // OpenMP 5.0, 2.1.6 Iterators 5226 // In an iterator-specifier, if the iterator-type is not specified then 5227 // the type of that iterator is of int type. 5228 DeclTy = Context.IntTy; 5229 StartLoc = D.DeclIdentLoc; 5230 } else { 5231 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5232 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5233 } 5234 5235 bool IsDeclTyDependent = DeclTy->isDependentType() || 5236 DeclTy->containsUnexpandedParameterPack() || 5237 DeclTy->isInstantiationDependentType(); 5238 if (!IsDeclTyDependent) { 5239 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5240 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5241 // The iterator-type must be an integral or pointer type. 5242 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5243 << DeclTy; 5244 IsCorrect = false; 5245 continue; 5246 } 5247 if (DeclTy.isConstant(Context)) { 5248 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5249 // The iterator-type must not be const qualified. 5250 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5251 << DeclTy; 5252 IsCorrect = false; 5253 continue; 5254 } 5255 } 5256 5257 // Iterator declaration. 5258 assert(D.DeclIdent && "Identifier expected."); 5259 // Always try to create iterator declarator to avoid extra error messages 5260 // about unknown declarations use. 5261 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5262 D.DeclIdent, DeclTy, TInfo, SC_None); 5263 VD->setImplicit(); 5264 if (S) { 5265 // Check for conflicting previous declaration. 5266 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5267 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5268 ForVisibleRedeclaration); 5269 Previous.suppressDiagnostics(); 5270 LookupName(Previous, S); 5271 5272 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5273 /*AllowInlineNamespace=*/false); 5274 if (!Previous.empty()) { 5275 NamedDecl *Old = Previous.getRepresentativeDecl(); 5276 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5277 Diag(Old->getLocation(), diag::note_previous_definition); 5278 } else { 5279 PushOnScopeChains(VD, S); 5280 } 5281 } else { 5282 CurContext->addDecl(VD); 5283 } 5284 Expr *Begin = D.Range.Begin; 5285 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5286 ExprResult BeginRes = 5287 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5288 Begin = BeginRes.get(); 5289 } 5290 Expr *End = D.Range.End; 5291 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5292 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5293 End = EndRes.get(); 5294 } 5295 Expr *Step = D.Range.Step; 5296 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5297 if (!Step->getType()->isIntegralType(Context)) { 5298 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5299 << Step << Step->getSourceRange(); 5300 IsCorrect = false; 5301 continue; 5302 } 5303 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5304 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5305 // If the step expression of a range-specification equals zero, the 5306 // behavior is unspecified. 5307 if (Result && Result->isNullValue()) { 5308 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5309 << Step << Step->getSourceRange(); 5310 IsCorrect = false; 5311 continue; 5312 } 5313 } 5314 if (!Begin || !End || !IsCorrect) { 5315 IsCorrect = false; 5316 continue; 5317 } 5318 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5319 IDElem.IteratorDecl = VD; 5320 IDElem.AssignmentLoc = D.AssignLoc; 5321 IDElem.Range.Begin = Begin; 5322 IDElem.Range.End = End; 5323 IDElem.Range.Step = Step; 5324 IDElem.ColonLoc = D.ColonLoc; 5325 IDElem.SecondColonLoc = D.SecColonLoc; 5326 } 5327 if (!IsCorrect) { 5328 // Invalidate all created iterator declarations if error is found. 5329 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5330 if (Decl *ID = D.IteratorDecl) 5331 ID->setInvalidDecl(); 5332 } 5333 return ExprError(); 5334 } 5335 SmallVector<OMPIteratorHelperData, 4> Helpers; 5336 if (!CurContext->isDependentContext()) { 5337 // Build number of ityeration for each iteration range. 5338 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5339 // ((Begini-Stepi-1-Endi) / -Stepi); 5340 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5341 // (Endi - Begini) 5342 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5343 D.Range.Begin); 5344 if(!Res.isUsable()) { 5345 IsCorrect = false; 5346 continue; 5347 } 5348 ExprResult St, St1; 5349 if (D.Range.Step) { 5350 St = D.Range.Step; 5351 // (Endi - Begini) + Stepi 5352 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5353 if (!Res.isUsable()) { 5354 IsCorrect = false; 5355 continue; 5356 } 5357 // (Endi - Begini) + Stepi - 1 5358 Res = 5359 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5360 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5361 if (!Res.isUsable()) { 5362 IsCorrect = false; 5363 continue; 5364 } 5365 // ((Endi - Begini) + Stepi - 1) / Stepi 5366 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5367 if (!Res.isUsable()) { 5368 IsCorrect = false; 5369 continue; 5370 } 5371 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5372 // (Begini - Endi) 5373 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5374 D.Range.Begin, D.Range.End); 5375 if (!Res1.isUsable()) { 5376 IsCorrect = false; 5377 continue; 5378 } 5379 // (Begini - Endi) - Stepi 5380 Res1 = 5381 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5382 if (!Res1.isUsable()) { 5383 IsCorrect = false; 5384 continue; 5385 } 5386 // (Begini - Endi) - Stepi - 1 5387 Res1 = 5388 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5389 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5390 if (!Res1.isUsable()) { 5391 IsCorrect = false; 5392 continue; 5393 } 5394 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5395 Res1 = 5396 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5397 if (!Res1.isUsable()) { 5398 IsCorrect = false; 5399 continue; 5400 } 5401 // Stepi > 0. 5402 ExprResult CmpRes = 5403 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5404 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5405 if (!CmpRes.isUsable()) { 5406 IsCorrect = false; 5407 continue; 5408 } 5409 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5410 Res.get(), Res1.get()); 5411 if (!Res.isUsable()) { 5412 IsCorrect = false; 5413 continue; 5414 } 5415 } 5416 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5417 if (!Res.isUsable()) { 5418 IsCorrect = false; 5419 continue; 5420 } 5421 5422 // Build counter update. 5423 // Build counter. 5424 auto *CounterVD = 5425 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5426 D.IteratorDecl->getBeginLoc(), nullptr, 5427 Res.get()->getType(), nullptr, SC_None); 5428 CounterVD->setImplicit(); 5429 ExprResult RefRes = 5430 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5431 D.IteratorDecl->getBeginLoc()); 5432 // Build counter update. 5433 // I = Begini + counter * Stepi; 5434 ExprResult UpdateRes; 5435 if (D.Range.Step) { 5436 UpdateRes = CreateBuiltinBinOp( 5437 D.AssignmentLoc, BO_Mul, 5438 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5439 } else { 5440 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5441 } 5442 if (!UpdateRes.isUsable()) { 5443 IsCorrect = false; 5444 continue; 5445 } 5446 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5447 UpdateRes.get()); 5448 if (!UpdateRes.isUsable()) { 5449 IsCorrect = false; 5450 continue; 5451 } 5452 ExprResult VDRes = 5453 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5454 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5455 D.IteratorDecl->getBeginLoc()); 5456 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5457 UpdateRes.get()); 5458 if (!UpdateRes.isUsable()) { 5459 IsCorrect = false; 5460 continue; 5461 } 5462 UpdateRes = 5463 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5464 if (!UpdateRes.isUsable()) { 5465 IsCorrect = false; 5466 continue; 5467 } 5468 ExprResult CounterUpdateRes = 5469 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5470 if (!CounterUpdateRes.isUsable()) { 5471 IsCorrect = false; 5472 continue; 5473 } 5474 CounterUpdateRes = 5475 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5476 if (!CounterUpdateRes.isUsable()) { 5477 IsCorrect = false; 5478 continue; 5479 } 5480 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5481 HD.CounterVD = CounterVD; 5482 HD.Upper = Res.get(); 5483 HD.Update = UpdateRes.get(); 5484 HD.CounterUpdate = CounterUpdateRes.get(); 5485 } 5486 } else { 5487 Helpers.assign(ID.size(), {}); 5488 } 5489 if (!IsCorrect) { 5490 // Invalidate all created iterator declarations if error is found. 5491 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5492 if (Decl *ID = D.IteratorDecl) 5493 ID->setInvalidDecl(); 5494 } 5495 return ExprError(); 5496 } 5497 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5498 LLoc, RLoc, ID, Helpers); 5499 } 5500 5501 ExprResult 5502 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5503 Expr *Idx, SourceLocation RLoc) { 5504 Expr *LHSExp = Base; 5505 Expr *RHSExp = Idx; 5506 5507 ExprValueKind VK = VK_LValue; 5508 ExprObjectKind OK = OK_Ordinary; 5509 5510 // Per C++ core issue 1213, the result is an xvalue if either operand is 5511 // a non-lvalue array, and an lvalue otherwise. 5512 if (getLangOpts().CPlusPlus11) { 5513 for (auto *Op : {LHSExp, RHSExp}) { 5514 Op = Op->IgnoreImplicit(); 5515 if (Op->getType()->isArrayType() && !Op->isLValue()) 5516 VK = VK_XValue; 5517 } 5518 } 5519 5520 // Perform default conversions. 5521 if (!LHSExp->getType()->getAs<VectorType>()) { 5522 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5523 if (Result.isInvalid()) 5524 return ExprError(); 5525 LHSExp = Result.get(); 5526 } 5527 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5528 if (Result.isInvalid()) 5529 return ExprError(); 5530 RHSExp = Result.get(); 5531 5532 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5533 5534 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5535 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5536 // in the subscript position. As a result, we need to derive the array base 5537 // and index from the expression types. 5538 Expr *BaseExpr, *IndexExpr; 5539 QualType ResultType; 5540 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5541 BaseExpr = LHSExp; 5542 IndexExpr = RHSExp; 5543 ResultType = Context.DependentTy; 5544 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5545 BaseExpr = LHSExp; 5546 IndexExpr = RHSExp; 5547 ResultType = PTy->getPointeeType(); 5548 } else if (const ObjCObjectPointerType *PTy = 5549 LHSTy->getAs<ObjCObjectPointerType>()) { 5550 BaseExpr = LHSExp; 5551 IndexExpr = RHSExp; 5552 5553 // Use custom logic if this should be the pseudo-object subscript 5554 // expression. 5555 if (!LangOpts.isSubscriptPointerArithmetic()) 5556 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5557 nullptr); 5558 5559 ResultType = PTy->getPointeeType(); 5560 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5561 // Handle the uncommon case of "123[Ptr]". 5562 BaseExpr = RHSExp; 5563 IndexExpr = LHSExp; 5564 ResultType = PTy->getPointeeType(); 5565 } else if (const ObjCObjectPointerType *PTy = 5566 RHSTy->getAs<ObjCObjectPointerType>()) { 5567 // Handle the uncommon case of "123[Ptr]". 5568 BaseExpr = RHSExp; 5569 IndexExpr = LHSExp; 5570 ResultType = PTy->getPointeeType(); 5571 if (!LangOpts.isSubscriptPointerArithmetic()) { 5572 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5573 << ResultType << BaseExpr->getSourceRange(); 5574 return ExprError(); 5575 } 5576 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5577 BaseExpr = LHSExp; // vectors: V[123] 5578 IndexExpr = RHSExp; 5579 // We apply C++ DR1213 to vector subscripting too. 5580 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5581 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5582 if (Materialized.isInvalid()) 5583 return ExprError(); 5584 LHSExp = Materialized.get(); 5585 } 5586 VK = LHSExp->getValueKind(); 5587 if (VK != VK_PRValue) 5588 OK = OK_VectorComponent; 5589 5590 ResultType = VTy->getElementType(); 5591 QualType BaseType = BaseExpr->getType(); 5592 Qualifiers BaseQuals = BaseType.getQualifiers(); 5593 Qualifiers MemberQuals = ResultType.getQualifiers(); 5594 Qualifiers Combined = BaseQuals + MemberQuals; 5595 if (Combined != MemberQuals) 5596 ResultType = Context.getQualifiedType(ResultType, Combined); 5597 } else if (LHSTy->isArrayType()) { 5598 // If we see an array that wasn't promoted by 5599 // DefaultFunctionArrayLvalueConversion, it must be an array that 5600 // wasn't promoted because of the C90 rule that doesn't 5601 // allow promoting non-lvalue arrays. Warn, then 5602 // force the promotion here. 5603 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5604 << LHSExp->getSourceRange(); 5605 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5606 CK_ArrayToPointerDecay).get(); 5607 LHSTy = LHSExp->getType(); 5608 5609 BaseExpr = LHSExp; 5610 IndexExpr = RHSExp; 5611 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5612 } else if (RHSTy->isArrayType()) { 5613 // Same as previous, except for 123[f().a] case 5614 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5615 << RHSExp->getSourceRange(); 5616 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5617 CK_ArrayToPointerDecay).get(); 5618 RHSTy = RHSExp->getType(); 5619 5620 BaseExpr = RHSExp; 5621 IndexExpr = LHSExp; 5622 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5623 } else { 5624 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5625 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5626 } 5627 // C99 6.5.2.1p1 5628 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5629 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5630 << IndexExpr->getSourceRange()); 5631 5632 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5633 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5634 && !IndexExpr->isTypeDependent()) 5635 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5636 5637 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5638 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5639 // type. Note that Functions are not objects, and that (in C99 parlance) 5640 // incomplete types are not object types. 5641 if (ResultType->isFunctionType()) { 5642 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5643 << ResultType << BaseExpr->getSourceRange(); 5644 return ExprError(); 5645 } 5646 5647 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5648 // GNU extension: subscripting on pointer to void 5649 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5650 << BaseExpr->getSourceRange(); 5651 5652 // C forbids expressions of unqualified void type from being l-values. 5653 // See IsCForbiddenLValueType. 5654 if (!ResultType.hasQualifiers()) 5655 VK = VK_PRValue; 5656 } else if (!ResultType->isDependentType() && 5657 RequireCompleteSizedType( 5658 LLoc, ResultType, 5659 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5660 return ExprError(); 5661 5662 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5663 !ResultType.isCForbiddenLValueType()); 5664 5665 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5666 FunctionScopes.size() > 1) { 5667 if (auto *TT = 5668 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5669 for (auto I = FunctionScopes.rbegin(), 5670 E = std::prev(FunctionScopes.rend()); 5671 I != E; ++I) { 5672 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5673 if (CSI == nullptr) 5674 break; 5675 DeclContext *DC = nullptr; 5676 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5677 DC = LSI->CallOperator; 5678 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5679 DC = CRSI->TheCapturedDecl; 5680 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5681 DC = BSI->TheDecl; 5682 if (DC) { 5683 if (DC->containsDecl(TT->getDecl())) 5684 break; 5685 captureVariablyModifiedType( 5686 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5687 } 5688 } 5689 } 5690 } 5691 5692 return new (Context) 5693 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5694 } 5695 5696 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5697 ParmVarDecl *Param) { 5698 if (Param->hasUnparsedDefaultArg()) { 5699 // If we've already cleared out the location for the default argument, 5700 // that means we're parsing it right now. 5701 if (!UnparsedDefaultArgLocs.count(Param)) { 5702 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5703 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5704 Param->setInvalidDecl(); 5705 return true; 5706 } 5707 5708 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5709 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5710 Diag(UnparsedDefaultArgLocs[Param], 5711 diag::note_default_argument_declared_here); 5712 return true; 5713 } 5714 5715 if (Param->hasUninstantiatedDefaultArg() && 5716 InstantiateDefaultArgument(CallLoc, FD, Param)) 5717 return true; 5718 5719 assert(Param->hasInit() && "default argument but no initializer?"); 5720 5721 // If the default expression creates temporaries, we need to 5722 // push them to the current stack of expression temporaries so they'll 5723 // be properly destroyed. 5724 // FIXME: We should really be rebuilding the default argument with new 5725 // bound temporaries; see the comment in PR5810. 5726 // We don't need to do that with block decls, though, because 5727 // blocks in default argument expression can never capture anything. 5728 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5729 // Set the "needs cleanups" bit regardless of whether there are 5730 // any explicit objects. 5731 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5732 5733 // Append all the objects to the cleanup list. Right now, this 5734 // should always be a no-op, because blocks in default argument 5735 // expressions should never be able to capture anything. 5736 assert(!Init->getNumObjects() && 5737 "default argument expression has capturing blocks?"); 5738 } 5739 5740 // We already type-checked the argument, so we know it works. 5741 // Just mark all of the declarations in this potentially-evaluated expression 5742 // as being "referenced". 5743 EnterExpressionEvaluationContext EvalContext( 5744 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5745 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5746 /*SkipLocalVariables=*/true); 5747 return false; 5748 } 5749 5750 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5751 FunctionDecl *FD, ParmVarDecl *Param) { 5752 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5753 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5754 return ExprError(); 5755 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5756 } 5757 5758 Sema::VariadicCallType 5759 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5760 Expr *Fn) { 5761 if (Proto && Proto->isVariadic()) { 5762 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5763 return VariadicConstructor; 5764 else if (Fn && Fn->getType()->isBlockPointerType()) 5765 return VariadicBlock; 5766 else if (FDecl) { 5767 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5768 if (Method->isInstance()) 5769 return VariadicMethod; 5770 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5771 return VariadicMethod; 5772 return VariadicFunction; 5773 } 5774 return VariadicDoesNotApply; 5775 } 5776 5777 namespace { 5778 class FunctionCallCCC final : public FunctionCallFilterCCC { 5779 public: 5780 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5781 unsigned NumArgs, MemberExpr *ME) 5782 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5783 FunctionName(FuncName) {} 5784 5785 bool ValidateCandidate(const TypoCorrection &candidate) override { 5786 if (!candidate.getCorrectionSpecifier() || 5787 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5788 return false; 5789 } 5790 5791 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5792 } 5793 5794 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5795 return std::make_unique<FunctionCallCCC>(*this); 5796 } 5797 5798 private: 5799 const IdentifierInfo *const FunctionName; 5800 }; 5801 } 5802 5803 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5804 FunctionDecl *FDecl, 5805 ArrayRef<Expr *> Args) { 5806 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5807 DeclarationName FuncName = FDecl->getDeclName(); 5808 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5809 5810 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5811 if (TypoCorrection Corrected = S.CorrectTypo( 5812 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5813 S.getScopeForContext(S.CurContext), nullptr, CCC, 5814 Sema::CTK_ErrorRecovery)) { 5815 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5816 if (Corrected.isOverloaded()) { 5817 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5818 OverloadCandidateSet::iterator Best; 5819 for (NamedDecl *CD : Corrected) { 5820 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5821 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5822 OCS); 5823 } 5824 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5825 case OR_Success: 5826 ND = Best->FoundDecl; 5827 Corrected.setCorrectionDecl(ND); 5828 break; 5829 default: 5830 break; 5831 } 5832 } 5833 ND = ND->getUnderlyingDecl(); 5834 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5835 return Corrected; 5836 } 5837 } 5838 return TypoCorrection(); 5839 } 5840 5841 /// ConvertArgumentsForCall - Converts the arguments specified in 5842 /// Args/NumArgs to the parameter types of the function FDecl with 5843 /// function prototype Proto. Call is the call expression itself, and 5844 /// Fn is the function expression. For a C++ member function, this 5845 /// routine does not attempt to convert the object argument. Returns 5846 /// true if the call is ill-formed. 5847 bool 5848 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5849 FunctionDecl *FDecl, 5850 const FunctionProtoType *Proto, 5851 ArrayRef<Expr *> Args, 5852 SourceLocation RParenLoc, 5853 bool IsExecConfig) { 5854 // Bail out early if calling a builtin with custom typechecking. 5855 if (FDecl) 5856 if (unsigned ID = FDecl->getBuiltinID()) 5857 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5858 return false; 5859 5860 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5861 // assignment, to the types of the corresponding parameter, ... 5862 unsigned NumParams = Proto->getNumParams(); 5863 bool Invalid = false; 5864 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5865 unsigned FnKind = Fn->getType()->isBlockPointerType() 5866 ? 1 /* block */ 5867 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5868 : 0 /* function */); 5869 5870 // If too few arguments are available (and we don't have default 5871 // arguments for the remaining parameters), don't make the call. 5872 if (Args.size() < NumParams) { 5873 if (Args.size() < MinArgs) { 5874 TypoCorrection TC; 5875 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5876 unsigned diag_id = 5877 MinArgs == NumParams && !Proto->isVariadic() 5878 ? diag::err_typecheck_call_too_few_args_suggest 5879 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5880 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5881 << static_cast<unsigned>(Args.size()) 5882 << TC.getCorrectionRange()); 5883 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5884 Diag(RParenLoc, 5885 MinArgs == NumParams && !Proto->isVariadic() 5886 ? diag::err_typecheck_call_too_few_args_one 5887 : diag::err_typecheck_call_too_few_args_at_least_one) 5888 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5889 else 5890 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5891 ? diag::err_typecheck_call_too_few_args 5892 : diag::err_typecheck_call_too_few_args_at_least) 5893 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5894 << Fn->getSourceRange(); 5895 5896 // Emit the location of the prototype. 5897 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5898 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5899 5900 return true; 5901 } 5902 // We reserve space for the default arguments when we create 5903 // the call expression, before calling ConvertArgumentsForCall. 5904 assert((Call->getNumArgs() == NumParams) && 5905 "We should have reserved space for the default arguments before!"); 5906 } 5907 5908 // If too many are passed and not variadic, error on the extras and drop 5909 // them. 5910 if (Args.size() > NumParams) { 5911 if (!Proto->isVariadic()) { 5912 TypoCorrection TC; 5913 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5914 unsigned diag_id = 5915 MinArgs == NumParams && !Proto->isVariadic() 5916 ? diag::err_typecheck_call_too_many_args_suggest 5917 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5918 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5919 << static_cast<unsigned>(Args.size()) 5920 << TC.getCorrectionRange()); 5921 } else if (NumParams == 1 && FDecl && 5922 FDecl->getParamDecl(0)->getDeclName()) 5923 Diag(Args[NumParams]->getBeginLoc(), 5924 MinArgs == NumParams 5925 ? diag::err_typecheck_call_too_many_args_one 5926 : diag::err_typecheck_call_too_many_args_at_most_one) 5927 << FnKind << FDecl->getParamDecl(0) 5928 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5929 << SourceRange(Args[NumParams]->getBeginLoc(), 5930 Args.back()->getEndLoc()); 5931 else 5932 Diag(Args[NumParams]->getBeginLoc(), 5933 MinArgs == NumParams 5934 ? diag::err_typecheck_call_too_many_args 5935 : diag::err_typecheck_call_too_many_args_at_most) 5936 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5937 << Fn->getSourceRange() 5938 << SourceRange(Args[NumParams]->getBeginLoc(), 5939 Args.back()->getEndLoc()); 5940 5941 // Emit the location of the prototype. 5942 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5943 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5944 5945 // This deletes the extra arguments. 5946 Call->shrinkNumArgs(NumParams); 5947 return true; 5948 } 5949 } 5950 SmallVector<Expr *, 8> AllArgs; 5951 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5952 5953 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5954 AllArgs, CallType); 5955 if (Invalid) 5956 return true; 5957 unsigned TotalNumArgs = AllArgs.size(); 5958 for (unsigned i = 0; i < TotalNumArgs; ++i) 5959 Call->setArg(i, AllArgs[i]); 5960 5961 Call->computeDependence(); 5962 return false; 5963 } 5964 5965 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5966 const FunctionProtoType *Proto, 5967 unsigned FirstParam, ArrayRef<Expr *> Args, 5968 SmallVectorImpl<Expr *> &AllArgs, 5969 VariadicCallType CallType, bool AllowExplicit, 5970 bool IsListInitialization) { 5971 unsigned NumParams = Proto->getNumParams(); 5972 bool Invalid = false; 5973 size_t ArgIx = 0; 5974 // Continue to check argument types (even if we have too few/many args). 5975 for (unsigned i = FirstParam; i < NumParams; i++) { 5976 QualType ProtoArgType = Proto->getParamType(i); 5977 5978 Expr *Arg; 5979 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5980 if (ArgIx < Args.size()) { 5981 Arg = Args[ArgIx++]; 5982 5983 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5984 diag::err_call_incomplete_argument, Arg)) 5985 return true; 5986 5987 // Strip the unbridged-cast placeholder expression off, if applicable. 5988 bool CFAudited = false; 5989 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5990 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5991 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5992 Arg = stripARCUnbridgedCast(Arg); 5993 else if (getLangOpts().ObjCAutoRefCount && 5994 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5995 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5996 CFAudited = true; 5997 5998 if (Proto->getExtParameterInfo(i).isNoEscape() && 5999 ProtoArgType->isBlockPointerType()) 6000 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6001 BE->getBlockDecl()->setDoesNotEscape(); 6002 6003 InitializedEntity Entity = 6004 Param ? InitializedEntity::InitializeParameter(Context, Param, 6005 ProtoArgType) 6006 : InitializedEntity::InitializeParameter( 6007 Context, ProtoArgType, Proto->isParamConsumed(i)); 6008 6009 // Remember that parameter belongs to a CF audited API. 6010 if (CFAudited) 6011 Entity.setParameterCFAudited(); 6012 6013 ExprResult ArgE = PerformCopyInitialization( 6014 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6015 if (ArgE.isInvalid()) 6016 return true; 6017 6018 Arg = ArgE.getAs<Expr>(); 6019 } else { 6020 assert(Param && "can't use default arguments without a known callee"); 6021 6022 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6023 if (ArgExpr.isInvalid()) 6024 return true; 6025 6026 Arg = ArgExpr.getAs<Expr>(); 6027 } 6028 6029 // Check for array bounds violations for each argument to the call. This 6030 // check only triggers warnings when the argument isn't a more complex Expr 6031 // with its own checking, such as a BinaryOperator. 6032 CheckArrayAccess(Arg); 6033 6034 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6035 CheckStaticArrayArgument(CallLoc, Param, Arg); 6036 6037 AllArgs.push_back(Arg); 6038 } 6039 6040 // If this is a variadic call, handle args passed through "...". 6041 if (CallType != VariadicDoesNotApply) { 6042 // Assume that extern "C" functions with variadic arguments that 6043 // return __unknown_anytype aren't *really* variadic. 6044 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6045 FDecl->isExternC()) { 6046 for (Expr *A : Args.slice(ArgIx)) { 6047 QualType paramType; // ignored 6048 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6049 Invalid |= arg.isInvalid(); 6050 AllArgs.push_back(arg.get()); 6051 } 6052 6053 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6054 } else { 6055 for (Expr *A : Args.slice(ArgIx)) { 6056 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6057 Invalid |= Arg.isInvalid(); 6058 AllArgs.push_back(Arg.get()); 6059 } 6060 } 6061 6062 // Check for array bounds violations. 6063 for (Expr *A : Args.slice(ArgIx)) 6064 CheckArrayAccess(A); 6065 } 6066 return Invalid; 6067 } 6068 6069 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6070 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6071 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6072 TL = DTL.getOriginalLoc(); 6073 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6074 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6075 << ATL.getLocalSourceRange(); 6076 } 6077 6078 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6079 /// array parameter, check that it is non-null, and that if it is formed by 6080 /// array-to-pointer decay, the underlying array is sufficiently large. 6081 /// 6082 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6083 /// array type derivation, then for each call to the function, the value of the 6084 /// corresponding actual argument shall provide access to the first element of 6085 /// an array with at least as many elements as specified by the size expression. 6086 void 6087 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6088 ParmVarDecl *Param, 6089 const Expr *ArgExpr) { 6090 // Static array parameters are not supported in C++. 6091 if (!Param || getLangOpts().CPlusPlus) 6092 return; 6093 6094 QualType OrigTy = Param->getOriginalType(); 6095 6096 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6097 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6098 return; 6099 6100 if (ArgExpr->isNullPointerConstant(Context, 6101 Expr::NPC_NeverValueDependent)) { 6102 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6103 DiagnoseCalleeStaticArrayParam(*this, Param); 6104 return; 6105 } 6106 6107 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6108 if (!CAT) 6109 return; 6110 6111 const ConstantArrayType *ArgCAT = 6112 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6113 if (!ArgCAT) 6114 return; 6115 6116 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6117 ArgCAT->getElementType())) { 6118 if (ArgCAT->getSize().ult(CAT->getSize())) { 6119 Diag(CallLoc, diag::warn_static_array_too_small) 6120 << ArgExpr->getSourceRange() 6121 << (unsigned)ArgCAT->getSize().getZExtValue() 6122 << (unsigned)CAT->getSize().getZExtValue() << 0; 6123 DiagnoseCalleeStaticArrayParam(*this, Param); 6124 } 6125 return; 6126 } 6127 6128 Optional<CharUnits> ArgSize = 6129 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6130 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6131 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6132 Diag(CallLoc, diag::warn_static_array_too_small) 6133 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6134 << (unsigned)ParmSize->getQuantity() << 1; 6135 DiagnoseCalleeStaticArrayParam(*this, Param); 6136 } 6137 } 6138 6139 /// Given a function expression of unknown-any type, try to rebuild it 6140 /// to have a function type. 6141 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6142 6143 /// Is the given type a placeholder that we need to lower out 6144 /// immediately during argument processing? 6145 static bool isPlaceholderToRemoveAsArg(QualType type) { 6146 // Placeholders are never sugared. 6147 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6148 if (!placeholder) return false; 6149 6150 switch (placeholder->getKind()) { 6151 // Ignore all the non-placeholder types. 6152 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6153 case BuiltinType::Id: 6154 #include "clang/Basic/OpenCLImageTypes.def" 6155 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6156 case BuiltinType::Id: 6157 #include "clang/Basic/OpenCLExtensionTypes.def" 6158 // In practice we'll never use this, since all SVE types are sugared 6159 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6160 #define SVE_TYPE(Name, Id, SingletonId) \ 6161 case BuiltinType::Id: 6162 #include "clang/Basic/AArch64SVEACLETypes.def" 6163 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6164 case BuiltinType::Id: 6165 #include "clang/Basic/PPCTypes.def" 6166 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6167 #include "clang/Basic/RISCVVTypes.def" 6168 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6169 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6170 #include "clang/AST/BuiltinTypes.def" 6171 return false; 6172 6173 // We cannot lower out overload sets; they might validly be resolved 6174 // by the call machinery. 6175 case BuiltinType::Overload: 6176 return false; 6177 6178 // Unbridged casts in ARC can be handled in some call positions and 6179 // should be left in place. 6180 case BuiltinType::ARCUnbridgedCast: 6181 return false; 6182 6183 // Pseudo-objects should be converted as soon as possible. 6184 case BuiltinType::PseudoObject: 6185 return true; 6186 6187 // The debugger mode could theoretically but currently does not try 6188 // to resolve unknown-typed arguments based on known parameter types. 6189 case BuiltinType::UnknownAny: 6190 return true; 6191 6192 // These are always invalid as call arguments and should be reported. 6193 case BuiltinType::BoundMember: 6194 case BuiltinType::BuiltinFn: 6195 case BuiltinType::IncompleteMatrixIdx: 6196 case BuiltinType::OMPArraySection: 6197 case BuiltinType::OMPArrayShaping: 6198 case BuiltinType::OMPIterator: 6199 return true; 6200 6201 } 6202 llvm_unreachable("bad builtin type kind"); 6203 } 6204 6205 /// Check an argument list for placeholders that we won't try to 6206 /// handle later. 6207 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6208 // Apply this processing to all the arguments at once instead of 6209 // dying at the first failure. 6210 bool hasInvalid = false; 6211 for (size_t i = 0, e = args.size(); i != e; i++) { 6212 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6213 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6214 if (result.isInvalid()) hasInvalid = true; 6215 else args[i] = result.get(); 6216 } 6217 } 6218 return hasInvalid; 6219 } 6220 6221 /// If a builtin function has a pointer argument with no explicit address 6222 /// space, then it should be able to accept a pointer to any address 6223 /// space as input. In order to do this, we need to replace the 6224 /// standard builtin declaration with one that uses the same address space 6225 /// as the call. 6226 /// 6227 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6228 /// it does not contain any pointer arguments without 6229 /// an address space qualifer. Otherwise the rewritten 6230 /// FunctionDecl is returned. 6231 /// TODO: Handle pointer return types. 6232 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6233 FunctionDecl *FDecl, 6234 MultiExprArg ArgExprs) { 6235 6236 QualType DeclType = FDecl->getType(); 6237 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6238 6239 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6240 ArgExprs.size() < FT->getNumParams()) 6241 return nullptr; 6242 6243 bool NeedsNewDecl = false; 6244 unsigned i = 0; 6245 SmallVector<QualType, 8> OverloadParams; 6246 6247 for (QualType ParamType : FT->param_types()) { 6248 6249 // Convert array arguments to pointer to simplify type lookup. 6250 ExprResult ArgRes = 6251 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6252 if (ArgRes.isInvalid()) 6253 return nullptr; 6254 Expr *Arg = ArgRes.get(); 6255 QualType ArgType = Arg->getType(); 6256 if (!ParamType->isPointerType() || 6257 ParamType.hasAddressSpace() || 6258 !ArgType->isPointerType() || 6259 !ArgType->getPointeeType().hasAddressSpace()) { 6260 OverloadParams.push_back(ParamType); 6261 continue; 6262 } 6263 6264 QualType PointeeType = ParamType->getPointeeType(); 6265 if (PointeeType.hasAddressSpace()) 6266 continue; 6267 6268 NeedsNewDecl = true; 6269 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6270 6271 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6272 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6273 } 6274 6275 if (!NeedsNewDecl) 6276 return nullptr; 6277 6278 FunctionProtoType::ExtProtoInfo EPI; 6279 EPI.Variadic = FT->isVariadic(); 6280 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6281 OverloadParams, EPI); 6282 DeclContext *Parent = FDecl->getParent(); 6283 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6284 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6285 FDecl->getIdentifier(), OverloadTy, 6286 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6287 false, 6288 /*hasPrototype=*/true); 6289 SmallVector<ParmVarDecl*, 16> Params; 6290 FT = cast<FunctionProtoType>(OverloadTy); 6291 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6292 QualType ParamType = FT->getParamType(i); 6293 ParmVarDecl *Parm = 6294 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6295 SourceLocation(), nullptr, ParamType, 6296 /*TInfo=*/nullptr, SC_None, nullptr); 6297 Parm->setScopeInfo(0, i); 6298 Params.push_back(Parm); 6299 } 6300 OverloadDecl->setParams(Params); 6301 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6302 return OverloadDecl; 6303 } 6304 6305 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6306 FunctionDecl *Callee, 6307 MultiExprArg ArgExprs) { 6308 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6309 // similar attributes) really don't like it when functions are called with an 6310 // invalid number of args. 6311 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6312 /*PartialOverloading=*/false) && 6313 !Callee->isVariadic()) 6314 return; 6315 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6316 return; 6317 6318 if (const EnableIfAttr *Attr = 6319 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6320 S.Diag(Fn->getBeginLoc(), 6321 isa<CXXMethodDecl>(Callee) 6322 ? diag::err_ovl_no_viable_member_function_in_call 6323 : diag::err_ovl_no_viable_function_in_call) 6324 << Callee << Callee->getSourceRange(); 6325 S.Diag(Callee->getLocation(), 6326 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6327 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6328 return; 6329 } 6330 } 6331 6332 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6333 const UnresolvedMemberExpr *const UME, Sema &S) { 6334 6335 const auto GetFunctionLevelDCIfCXXClass = 6336 [](Sema &S) -> const CXXRecordDecl * { 6337 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6338 if (!DC || !DC->getParent()) 6339 return nullptr; 6340 6341 // If the call to some member function was made from within a member 6342 // function body 'M' return return 'M's parent. 6343 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6344 return MD->getParent()->getCanonicalDecl(); 6345 // else the call was made from within a default member initializer of a 6346 // class, so return the class. 6347 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6348 return RD->getCanonicalDecl(); 6349 return nullptr; 6350 }; 6351 // If our DeclContext is neither a member function nor a class (in the 6352 // case of a lambda in a default member initializer), we can't have an 6353 // enclosing 'this'. 6354 6355 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6356 if (!CurParentClass) 6357 return false; 6358 6359 // The naming class for implicit member functions call is the class in which 6360 // name lookup starts. 6361 const CXXRecordDecl *const NamingClass = 6362 UME->getNamingClass()->getCanonicalDecl(); 6363 assert(NamingClass && "Must have naming class even for implicit access"); 6364 6365 // If the unresolved member functions were found in a 'naming class' that is 6366 // related (either the same or derived from) to the class that contains the 6367 // member function that itself contained the implicit member access. 6368 6369 return CurParentClass == NamingClass || 6370 CurParentClass->isDerivedFrom(NamingClass); 6371 } 6372 6373 static void 6374 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6375 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6376 6377 if (!UME) 6378 return; 6379 6380 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6381 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6382 // already been captured, or if this is an implicit member function call (if 6383 // it isn't, an attempt to capture 'this' should already have been made). 6384 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6385 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6386 return; 6387 6388 // Check if the naming class in which the unresolved members were found is 6389 // related (same as or is a base of) to the enclosing class. 6390 6391 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6392 return; 6393 6394 6395 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6396 // If the enclosing function is not dependent, then this lambda is 6397 // capture ready, so if we can capture this, do so. 6398 if (!EnclosingFunctionCtx->isDependentContext()) { 6399 // If the current lambda and all enclosing lambdas can capture 'this' - 6400 // then go ahead and capture 'this' (since our unresolved overload set 6401 // contains at least one non-static member function). 6402 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6403 S.CheckCXXThisCapture(CallLoc); 6404 } else if (S.CurContext->isDependentContext()) { 6405 // ... since this is an implicit member reference, that might potentially 6406 // involve a 'this' capture, mark 'this' for potential capture in 6407 // enclosing lambdas. 6408 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6409 CurLSI->addPotentialThisCapture(CallLoc); 6410 } 6411 } 6412 6413 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6414 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6415 Expr *ExecConfig) { 6416 ExprResult Call = 6417 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6418 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6419 if (Call.isInvalid()) 6420 return Call; 6421 6422 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6423 // language modes. 6424 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6425 if (ULE->hasExplicitTemplateArgs() && 6426 ULE->decls_begin() == ULE->decls_end()) { 6427 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6428 ? diag::warn_cxx17_compat_adl_only_template_id 6429 : diag::ext_adl_only_template_id) 6430 << ULE->getName(); 6431 } 6432 } 6433 6434 if (LangOpts.OpenMP) 6435 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6436 ExecConfig); 6437 6438 return Call; 6439 } 6440 6441 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6442 /// This provides the location of the left/right parens and a list of comma 6443 /// locations. 6444 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6445 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6446 Expr *ExecConfig, bool IsExecConfig, 6447 bool AllowRecovery) { 6448 // Since this might be a postfix expression, get rid of ParenListExprs. 6449 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6450 if (Result.isInvalid()) return ExprError(); 6451 Fn = Result.get(); 6452 6453 if (checkArgsForPlaceholders(*this, ArgExprs)) 6454 return ExprError(); 6455 6456 if (getLangOpts().CPlusPlus) { 6457 // If this is a pseudo-destructor expression, build the call immediately. 6458 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6459 if (!ArgExprs.empty()) { 6460 // Pseudo-destructor calls should not have any arguments. 6461 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6462 << FixItHint::CreateRemoval( 6463 SourceRange(ArgExprs.front()->getBeginLoc(), 6464 ArgExprs.back()->getEndLoc())); 6465 } 6466 6467 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6468 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6469 } 6470 if (Fn->getType() == Context.PseudoObjectTy) { 6471 ExprResult result = CheckPlaceholderExpr(Fn); 6472 if (result.isInvalid()) return ExprError(); 6473 Fn = result.get(); 6474 } 6475 6476 // Determine whether this is a dependent call inside a C++ template, 6477 // in which case we won't do any semantic analysis now. 6478 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6479 if (ExecConfig) { 6480 return CUDAKernelCallExpr::Create(Context, Fn, 6481 cast<CallExpr>(ExecConfig), ArgExprs, 6482 Context.DependentTy, VK_PRValue, 6483 RParenLoc, CurFPFeatureOverrides()); 6484 } else { 6485 6486 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6487 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6488 Fn->getBeginLoc()); 6489 6490 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6491 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6492 } 6493 } 6494 6495 // Determine whether this is a call to an object (C++ [over.call.object]). 6496 if (Fn->getType()->isRecordType()) 6497 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6498 RParenLoc); 6499 6500 if (Fn->getType() == Context.UnknownAnyTy) { 6501 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6502 if (result.isInvalid()) return ExprError(); 6503 Fn = result.get(); 6504 } 6505 6506 if (Fn->getType() == Context.BoundMemberTy) { 6507 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6508 RParenLoc, AllowRecovery); 6509 } 6510 } 6511 6512 // Check for overloaded calls. This can happen even in C due to extensions. 6513 if (Fn->getType() == Context.OverloadTy) { 6514 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6515 6516 // We aren't supposed to apply this logic if there's an '&' involved. 6517 if (!find.HasFormOfMemberPointer) { 6518 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6519 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6520 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6521 OverloadExpr *ovl = find.Expression; 6522 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6523 return BuildOverloadedCallExpr( 6524 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6525 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6526 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6527 RParenLoc, AllowRecovery); 6528 } 6529 } 6530 6531 // If we're directly calling a function, get the appropriate declaration. 6532 if (Fn->getType() == Context.UnknownAnyTy) { 6533 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6534 if (result.isInvalid()) return ExprError(); 6535 Fn = result.get(); 6536 } 6537 6538 Expr *NakedFn = Fn->IgnoreParens(); 6539 6540 bool CallingNDeclIndirectly = false; 6541 NamedDecl *NDecl = nullptr; 6542 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6543 if (UnOp->getOpcode() == UO_AddrOf) { 6544 CallingNDeclIndirectly = true; 6545 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6546 } 6547 } 6548 6549 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6550 NDecl = DRE->getDecl(); 6551 6552 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6553 if (FDecl && FDecl->getBuiltinID()) { 6554 // Rewrite the function decl for this builtin by replacing parameters 6555 // with no explicit address space with the address space of the arguments 6556 // in ArgExprs. 6557 if ((FDecl = 6558 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6559 NDecl = FDecl; 6560 Fn = DeclRefExpr::Create( 6561 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6562 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6563 nullptr, DRE->isNonOdrUse()); 6564 } 6565 } 6566 } else if (isa<MemberExpr>(NakedFn)) 6567 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6568 6569 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6570 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6571 FD, /*Complain=*/true, Fn->getBeginLoc())) 6572 return ExprError(); 6573 6574 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6575 6576 // If this expression is a call to a builtin function in HIP device 6577 // compilation, allow a pointer-type argument to default address space to be 6578 // passed as a pointer-type parameter to a non-default address space. 6579 // If Arg is declared in the default address space and Param is declared 6580 // in a non-default address space, perform an implicit address space cast to 6581 // the parameter type. 6582 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 6583 FD->getBuiltinID()) { 6584 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 6585 ParmVarDecl *Param = FD->getParamDecl(Idx); 6586 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 6587 !ArgExprs[Idx]->getType()->isPointerType()) 6588 continue; 6589 6590 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 6591 auto ArgTy = ArgExprs[Idx]->getType(); 6592 auto ArgPtTy = ArgTy->getPointeeType(); 6593 auto ArgAS = ArgPtTy.getAddressSpace(); 6594 6595 // Only allow implicit casting from a non-default address space pointee 6596 // type to a default address space pointee type 6597 if (ArgAS != LangAS::Default || ParamAS == LangAS::Default) 6598 continue; 6599 6600 // First, ensure that the Arg is an RValue. 6601 if (ArgExprs[Idx]->isGLValue()) { 6602 ArgExprs[Idx] = ImplicitCastExpr::Create( 6603 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 6604 nullptr, VK_PRValue, FPOptionsOverride()); 6605 } 6606 6607 // Construct a new arg type with address space of Param 6608 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 6609 ArgPtQuals.setAddressSpace(ParamAS); 6610 auto NewArgPtTy = 6611 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 6612 auto NewArgTy = 6613 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 6614 ArgTy.getQualifiers()); 6615 6616 // Finally perform an implicit address space cast 6617 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 6618 CK_AddressSpaceConversion) 6619 .get(); 6620 } 6621 } 6622 } 6623 6624 if (Context.isDependenceAllowed() && 6625 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6626 assert(!getLangOpts().CPlusPlus); 6627 assert((Fn->containsErrors() || 6628 llvm::any_of(ArgExprs, 6629 [](clang::Expr *E) { return E->containsErrors(); })) && 6630 "should only occur in error-recovery path."); 6631 QualType ReturnType = 6632 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6633 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6634 : Context.DependentTy; 6635 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6636 Expr::getValueKindForType(ReturnType), RParenLoc, 6637 CurFPFeatureOverrides()); 6638 } 6639 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6640 ExecConfig, IsExecConfig); 6641 } 6642 6643 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6644 // with the specified CallArgs 6645 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6646 MultiExprArg CallArgs) { 6647 StringRef Name = Context.BuiltinInfo.getName(Id); 6648 LookupResult R(*this, &Context.Idents.get(Name), Loc, 6649 Sema::LookupOrdinaryName); 6650 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 6651 6652 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 6653 assert(BuiltInDecl && "failed to find builtin declaration"); 6654 6655 ExprResult DeclRef = 6656 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 6657 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 6658 6659 ExprResult Call = 6660 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 6661 6662 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 6663 return Call.get(); 6664 } 6665 6666 /// Parse a __builtin_astype expression. 6667 /// 6668 /// __builtin_astype( value, dst type ) 6669 /// 6670 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6671 SourceLocation BuiltinLoc, 6672 SourceLocation RParenLoc) { 6673 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6674 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6675 } 6676 6677 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6678 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6679 SourceLocation BuiltinLoc, 6680 SourceLocation RParenLoc) { 6681 ExprValueKind VK = VK_PRValue; 6682 ExprObjectKind OK = OK_Ordinary; 6683 QualType SrcTy = E->getType(); 6684 if (!SrcTy->isDependentType() && 6685 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6686 return ExprError( 6687 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6688 << DestTy << SrcTy << E->getSourceRange()); 6689 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6690 } 6691 6692 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6693 /// provided arguments. 6694 /// 6695 /// __builtin_convertvector( value, dst type ) 6696 /// 6697 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6698 SourceLocation BuiltinLoc, 6699 SourceLocation RParenLoc) { 6700 TypeSourceInfo *TInfo; 6701 GetTypeFromParser(ParsedDestTy, &TInfo); 6702 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6703 } 6704 6705 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6706 /// i.e. an expression not of \p OverloadTy. The expression should 6707 /// unary-convert to an expression of function-pointer or 6708 /// block-pointer type. 6709 /// 6710 /// \param NDecl the declaration being called, if available 6711 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6712 SourceLocation LParenLoc, 6713 ArrayRef<Expr *> Args, 6714 SourceLocation RParenLoc, Expr *Config, 6715 bool IsExecConfig, ADLCallKind UsesADL) { 6716 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6717 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6718 6719 // Functions with 'interrupt' attribute cannot be called directly. 6720 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6721 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6722 return ExprError(); 6723 } 6724 6725 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6726 // so there's some risk when calling out to non-interrupt handler functions 6727 // that the callee might not preserve them. This is easy to diagnose here, 6728 // but can be very challenging to debug. 6729 // Likewise, X86 interrupt handlers may only call routines with attribute 6730 // no_caller_saved_registers since there is no efficient way to 6731 // save and restore the non-GPR state. 6732 if (auto *Caller = getCurFunctionDecl()) { 6733 if (Caller->hasAttr<ARMInterruptAttr>()) { 6734 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6735 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6736 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6737 if (FDecl) 6738 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6739 } 6740 } 6741 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6742 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6743 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6744 if (FDecl) 6745 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6746 } 6747 } 6748 6749 // Promote the function operand. 6750 // We special-case function promotion here because we only allow promoting 6751 // builtin functions to function pointers in the callee of a call. 6752 ExprResult Result; 6753 QualType ResultTy; 6754 if (BuiltinID && 6755 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6756 // Extract the return type from the (builtin) function pointer type. 6757 // FIXME Several builtins still have setType in 6758 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6759 // Builtins.def to ensure they are correct before removing setType calls. 6760 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6761 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6762 ResultTy = FDecl->getCallResultType(); 6763 } else { 6764 Result = CallExprUnaryConversions(Fn); 6765 ResultTy = Context.BoolTy; 6766 } 6767 if (Result.isInvalid()) 6768 return ExprError(); 6769 Fn = Result.get(); 6770 6771 // Check for a valid function type, but only if it is not a builtin which 6772 // requires custom type checking. These will be handled by 6773 // CheckBuiltinFunctionCall below just after creation of the call expression. 6774 const FunctionType *FuncT = nullptr; 6775 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6776 retry: 6777 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6778 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6779 // have type pointer to function". 6780 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6781 if (!FuncT) 6782 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6783 << Fn->getType() << Fn->getSourceRange()); 6784 } else if (const BlockPointerType *BPT = 6785 Fn->getType()->getAs<BlockPointerType>()) { 6786 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6787 } else { 6788 // Handle calls to expressions of unknown-any type. 6789 if (Fn->getType() == Context.UnknownAnyTy) { 6790 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6791 if (rewrite.isInvalid()) 6792 return ExprError(); 6793 Fn = rewrite.get(); 6794 goto retry; 6795 } 6796 6797 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6798 << Fn->getType() << Fn->getSourceRange()); 6799 } 6800 } 6801 6802 // Get the number of parameters in the function prototype, if any. 6803 // We will allocate space for max(Args.size(), NumParams) arguments 6804 // in the call expression. 6805 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6806 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6807 6808 CallExpr *TheCall; 6809 if (Config) { 6810 assert(UsesADL == ADLCallKind::NotADL && 6811 "CUDAKernelCallExpr should not use ADL"); 6812 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6813 Args, ResultTy, VK_PRValue, RParenLoc, 6814 CurFPFeatureOverrides(), NumParams); 6815 } else { 6816 TheCall = 6817 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6818 CurFPFeatureOverrides(), NumParams, UsesADL); 6819 } 6820 6821 if (!Context.isDependenceAllowed()) { 6822 // Forget about the nulled arguments since typo correction 6823 // do not handle them well. 6824 TheCall->shrinkNumArgs(Args.size()); 6825 // C cannot always handle TypoExpr nodes in builtin calls and direct 6826 // function calls as their argument checking don't necessarily handle 6827 // dependent types properly, so make sure any TypoExprs have been 6828 // dealt with. 6829 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6830 if (!Result.isUsable()) return ExprError(); 6831 CallExpr *TheOldCall = TheCall; 6832 TheCall = dyn_cast<CallExpr>(Result.get()); 6833 bool CorrectedTypos = TheCall != TheOldCall; 6834 if (!TheCall) return Result; 6835 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6836 6837 // A new call expression node was created if some typos were corrected. 6838 // However it may not have been constructed with enough storage. In this 6839 // case, rebuild the node with enough storage. The waste of space is 6840 // immaterial since this only happens when some typos were corrected. 6841 if (CorrectedTypos && Args.size() < NumParams) { 6842 if (Config) 6843 TheCall = CUDAKernelCallExpr::Create( 6844 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 6845 RParenLoc, CurFPFeatureOverrides(), NumParams); 6846 else 6847 TheCall = 6848 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 6849 CurFPFeatureOverrides(), NumParams, UsesADL); 6850 } 6851 // We can now handle the nulled arguments for the default arguments. 6852 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6853 } 6854 6855 // Bail out early if calling a builtin with custom type checking. 6856 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6857 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6858 6859 if (getLangOpts().CUDA) { 6860 if (Config) { 6861 // CUDA: Kernel calls must be to global functions 6862 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6863 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6864 << FDecl << Fn->getSourceRange()); 6865 6866 // CUDA: Kernel function must have 'void' return type 6867 if (!FuncT->getReturnType()->isVoidType() && 6868 !FuncT->getReturnType()->getAs<AutoType>() && 6869 !FuncT->getReturnType()->isInstantiationDependentType()) 6870 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6871 << Fn->getType() << Fn->getSourceRange()); 6872 } else { 6873 // CUDA: Calls to global functions must be configured 6874 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6875 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6876 << FDecl << Fn->getSourceRange()); 6877 } 6878 } 6879 6880 // Check for a valid return type 6881 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6882 FDecl)) 6883 return ExprError(); 6884 6885 // We know the result type of the call, set it. 6886 TheCall->setType(FuncT->getCallResultType(Context)); 6887 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6888 6889 if (Proto) { 6890 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6891 IsExecConfig)) 6892 return ExprError(); 6893 } else { 6894 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6895 6896 if (FDecl) { 6897 // Check if we have too few/too many template arguments, based 6898 // on our knowledge of the function definition. 6899 const FunctionDecl *Def = nullptr; 6900 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6901 Proto = Def->getType()->getAs<FunctionProtoType>(); 6902 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6903 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6904 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6905 } 6906 6907 // If the function we're calling isn't a function prototype, but we have 6908 // a function prototype from a prior declaratiom, use that prototype. 6909 if (!FDecl->hasPrototype()) 6910 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6911 } 6912 6913 // Promote the arguments (C99 6.5.2.2p6). 6914 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6915 Expr *Arg = Args[i]; 6916 6917 if (Proto && i < Proto->getNumParams()) { 6918 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6919 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6920 ExprResult ArgE = 6921 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6922 if (ArgE.isInvalid()) 6923 return true; 6924 6925 Arg = ArgE.getAs<Expr>(); 6926 6927 } else { 6928 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6929 6930 if (ArgE.isInvalid()) 6931 return true; 6932 6933 Arg = ArgE.getAs<Expr>(); 6934 } 6935 6936 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6937 diag::err_call_incomplete_argument, Arg)) 6938 return ExprError(); 6939 6940 TheCall->setArg(i, Arg); 6941 } 6942 TheCall->computeDependence(); 6943 } 6944 6945 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6946 if (!Method->isStatic()) 6947 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6948 << Fn->getSourceRange()); 6949 6950 // Check for sentinels 6951 if (NDecl) 6952 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6953 6954 // Warn for unions passing across security boundary (CMSE). 6955 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6956 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6957 if (const auto *RT = 6958 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6959 if (RT->getDecl()->isOrContainsUnion()) 6960 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6961 << 0 << i; 6962 } 6963 } 6964 } 6965 6966 // Do special checking on direct calls to functions. 6967 if (FDecl) { 6968 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6969 return ExprError(); 6970 6971 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6972 6973 if (BuiltinID) 6974 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6975 } else if (NDecl) { 6976 if (CheckPointerCall(NDecl, TheCall, Proto)) 6977 return ExprError(); 6978 } else { 6979 if (CheckOtherCall(TheCall, Proto)) 6980 return ExprError(); 6981 } 6982 6983 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6984 } 6985 6986 ExprResult 6987 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6988 SourceLocation RParenLoc, Expr *InitExpr) { 6989 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6990 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6991 6992 TypeSourceInfo *TInfo; 6993 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6994 if (!TInfo) 6995 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6996 6997 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6998 } 6999 7000 ExprResult 7001 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7002 SourceLocation RParenLoc, Expr *LiteralExpr) { 7003 QualType literalType = TInfo->getType(); 7004 7005 if (literalType->isArrayType()) { 7006 if (RequireCompleteSizedType( 7007 LParenLoc, Context.getBaseElementType(literalType), 7008 diag::err_array_incomplete_or_sizeless_type, 7009 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7010 return ExprError(); 7011 if (literalType->isVariableArrayType()) { 7012 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7013 diag::err_variable_object_no_init)) { 7014 return ExprError(); 7015 } 7016 } 7017 } else if (!literalType->isDependentType() && 7018 RequireCompleteType(LParenLoc, literalType, 7019 diag::err_typecheck_decl_incomplete_type, 7020 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7021 return ExprError(); 7022 7023 InitializedEntity Entity 7024 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7025 InitializationKind Kind 7026 = InitializationKind::CreateCStyleCast(LParenLoc, 7027 SourceRange(LParenLoc, RParenLoc), 7028 /*InitList=*/true); 7029 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7030 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7031 &literalType); 7032 if (Result.isInvalid()) 7033 return ExprError(); 7034 LiteralExpr = Result.get(); 7035 7036 bool isFileScope = !CurContext->isFunctionOrMethod(); 7037 7038 // In C, compound literals are l-values for some reason. 7039 // For GCC compatibility, in C++, file-scope array compound literals with 7040 // constant initializers are also l-values, and compound literals are 7041 // otherwise prvalues. 7042 // 7043 // (GCC also treats C++ list-initialized file-scope array prvalues with 7044 // constant initializers as l-values, but that's non-conforming, so we don't 7045 // follow it there.) 7046 // 7047 // FIXME: It would be better to handle the lvalue cases as materializing and 7048 // lifetime-extending a temporary object, but our materialized temporaries 7049 // representation only supports lifetime extension from a variable, not "out 7050 // of thin air". 7051 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7052 // is bound to the result of applying array-to-pointer decay to the compound 7053 // literal. 7054 // FIXME: GCC supports compound literals of reference type, which should 7055 // obviously have a value kind derived from the kind of reference involved. 7056 ExprValueKind VK = 7057 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7058 ? VK_PRValue 7059 : VK_LValue; 7060 7061 if (isFileScope) 7062 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7063 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7064 Expr *Init = ILE->getInit(i); 7065 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7066 } 7067 7068 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7069 VK, LiteralExpr, isFileScope); 7070 if (isFileScope) { 7071 if (!LiteralExpr->isTypeDependent() && 7072 !LiteralExpr->isValueDependent() && 7073 !literalType->isDependentType()) // C99 6.5.2.5p3 7074 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7075 return ExprError(); 7076 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7077 literalType.getAddressSpace() != LangAS::Default) { 7078 // Embedded-C extensions to C99 6.5.2.5: 7079 // "If the compound literal occurs inside the body of a function, the 7080 // type name shall not be qualified by an address-space qualifier." 7081 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7082 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7083 return ExprError(); 7084 } 7085 7086 if (!isFileScope && !getLangOpts().CPlusPlus) { 7087 // Compound literals that have automatic storage duration are destroyed at 7088 // the end of the scope in C; in C++, they're just temporaries. 7089 7090 // Emit diagnostics if it is or contains a C union type that is non-trivial 7091 // to destruct. 7092 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7093 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7094 NTCUC_CompoundLiteral, NTCUK_Destruct); 7095 7096 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7097 if (literalType.isDestructedType()) { 7098 Cleanup.setExprNeedsCleanups(true); 7099 ExprCleanupObjects.push_back(E); 7100 getCurFunction()->setHasBranchProtectedScope(); 7101 } 7102 } 7103 7104 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7105 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7106 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7107 E->getInitializer()->getExprLoc()); 7108 7109 return MaybeBindToTemporary(E); 7110 } 7111 7112 ExprResult 7113 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7114 SourceLocation RBraceLoc) { 7115 // Only produce each kind of designated initialization diagnostic once. 7116 SourceLocation FirstDesignator; 7117 bool DiagnosedArrayDesignator = false; 7118 bool DiagnosedNestedDesignator = false; 7119 bool DiagnosedMixedDesignator = false; 7120 7121 // Check that any designated initializers are syntactically valid in the 7122 // current language mode. 7123 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7124 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7125 if (FirstDesignator.isInvalid()) 7126 FirstDesignator = DIE->getBeginLoc(); 7127 7128 if (!getLangOpts().CPlusPlus) 7129 break; 7130 7131 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7132 DiagnosedNestedDesignator = true; 7133 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7134 << DIE->getDesignatorsSourceRange(); 7135 } 7136 7137 for (auto &Desig : DIE->designators()) { 7138 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7139 DiagnosedArrayDesignator = true; 7140 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7141 << Desig.getSourceRange(); 7142 } 7143 } 7144 7145 if (!DiagnosedMixedDesignator && 7146 !isa<DesignatedInitExpr>(InitArgList[0])) { 7147 DiagnosedMixedDesignator = true; 7148 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7149 << DIE->getSourceRange(); 7150 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7151 << InitArgList[0]->getSourceRange(); 7152 } 7153 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7154 isa<DesignatedInitExpr>(InitArgList[0])) { 7155 DiagnosedMixedDesignator = true; 7156 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7157 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7158 << DIE->getSourceRange(); 7159 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7160 << InitArgList[I]->getSourceRange(); 7161 } 7162 } 7163 7164 if (FirstDesignator.isValid()) { 7165 // Only diagnose designated initiaization as a C++20 extension if we didn't 7166 // already diagnose use of (non-C++20) C99 designator syntax. 7167 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7168 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7169 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7170 ? diag::warn_cxx17_compat_designated_init 7171 : diag::ext_cxx_designated_init); 7172 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7173 Diag(FirstDesignator, diag::ext_designated_init); 7174 } 7175 } 7176 7177 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7178 } 7179 7180 ExprResult 7181 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7182 SourceLocation RBraceLoc) { 7183 // Semantic analysis for initializers is done by ActOnDeclarator() and 7184 // CheckInitializer() - it requires knowledge of the object being initialized. 7185 7186 // Immediately handle non-overload placeholders. Overloads can be 7187 // resolved contextually, but everything else here can't. 7188 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7189 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7190 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7191 7192 // Ignore failures; dropping the entire initializer list because 7193 // of one failure would be terrible for indexing/etc. 7194 if (result.isInvalid()) continue; 7195 7196 InitArgList[I] = result.get(); 7197 } 7198 } 7199 7200 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7201 RBraceLoc); 7202 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7203 return E; 7204 } 7205 7206 /// Do an explicit extend of the given block pointer if we're in ARC. 7207 void Sema::maybeExtendBlockObject(ExprResult &E) { 7208 assert(E.get()->getType()->isBlockPointerType()); 7209 assert(E.get()->isPRValue()); 7210 7211 // Only do this in an r-value context. 7212 if (!getLangOpts().ObjCAutoRefCount) return; 7213 7214 E = ImplicitCastExpr::Create( 7215 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7216 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7217 Cleanup.setExprNeedsCleanups(true); 7218 } 7219 7220 /// Prepare a conversion of the given expression to an ObjC object 7221 /// pointer type. 7222 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7223 QualType type = E.get()->getType(); 7224 if (type->isObjCObjectPointerType()) { 7225 return CK_BitCast; 7226 } else if (type->isBlockPointerType()) { 7227 maybeExtendBlockObject(E); 7228 return CK_BlockPointerToObjCPointerCast; 7229 } else { 7230 assert(type->isPointerType()); 7231 return CK_CPointerToObjCPointerCast; 7232 } 7233 } 7234 7235 /// Prepares for a scalar cast, performing all the necessary stages 7236 /// except the final cast and returning the kind required. 7237 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7238 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7239 // Also, callers should have filtered out the invalid cases with 7240 // pointers. Everything else should be possible. 7241 7242 QualType SrcTy = Src.get()->getType(); 7243 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7244 return CK_NoOp; 7245 7246 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7247 case Type::STK_MemberPointer: 7248 llvm_unreachable("member pointer type in C"); 7249 7250 case Type::STK_CPointer: 7251 case Type::STK_BlockPointer: 7252 case Type::STK_ObjCObjectPointer: 7253 switch (DestTy->getScalarTypeKind()) { 7254 case Type::STK_CPointer: { 7255 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7256 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7257 if (SrcAS != DestAS) 7258 return CK_AddressSpaceConversion; 7259 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7260 return CK_NoOp; 7261 return CK_BitCast; 7262 } 7263 case Type::STK_BlockPointer: 7264 return (SrcKind == Type::STK_BlockPointer 7265 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7266 case Type::STK_ObjCObjectPointer: 7267 if (SrcKind == Type::STK_ObjCObjectPointer) 7268 return CK_BitCast; 7269 if (SrcKind == Type::STK_CPointer) 7270 return CK_CPointerToObjCPointerCast; 7271 maybeExtendBlockObject(Src); 7272 return CK_BlockPointerToObjCPointerCast; 7273 case Type::STK_Bool: 7274 return CK_PointerToBoolean; 7275 case Type::STK_Integral: 7276 return CK_PointerToIntegral; 7277 case Type::STK_Floating: 7278 case Type::STK_FloatingComplex: 7279 case Type::STK_IntegralComplex: 7280 case Type::STK_MemberPointer: 7281 case Type::STK_FixedPoint: 7282 llvm_unreachable("illegal cast from pointer"); 7283 } 7284 llvm_unreachable("Should have returned before this"); 7285 7286 case Type::STK_FixedPoint: 7287 switch (DestTy->getScalarTypeKind()) { 7288 case Type::STK_FixedPoint: 7289 return CK_FixedPointCast; 7290 case Type::STK_Bool: 7291 return CK_FixedPointToBoolean; 7292 case Type::STK_Integral: 7293 return CK_FixedPointToIntegral; 7294 case Type::STK_Floating: 7295 return CK_FixedPointToFloating; 7296 case Type::STK_IntegralComplex: 7297 case Type::STK_FloatingComplex: 7298 Diag(Src.get()->getExprLoc(), 7299 diag::err_unimplemented_conversion_with_fixed_point_type) 7300 << DestTy; 7301 return CK_IntegralCast; 7302 case Type::STK_CPointer: 7303 case Type::STK_ObjCObjectPointer: 7304 case Type::STK_BlockPointer: 7305 case Type::STK_MemberPointer: 7306 llvm_unreachable("illegal cast to pointer type"); 7307 } 7308 llvm_unreachable("Should have returned before this"); 7309 7310 case Type::STK_Bool: // casting from bool is like casting from an integer 7311 case Type::STK_Integral: 7312 switch (DestTy->getScalarTypeKind()) { 7313 case Type::STK_CPointer: 7314 case Type::STK_ObjCObjectPointer: 7315 case Type::STK_BlockPointer: 7316 if (Src.get()->isNullPointerConstant(Context, 7317 Expr::NPC_ValueDependentIsNull)) 7318 return CK_NullToPointer; 7319 return CK_IntegralToPointer; 7320 case Type::STK_Bool: 7321 return CK_IntegralToBoolean; 7322 case Type::STK_Integral: 7323 return CK_IntegralCast; 7324 case Type::STK_Floating: 7325 return CK_IntegralToFloating; 7326 case Type::STK_IntegralComplex: 7327 Src = ImpCastExprToType(Src.get(), 7328 DestTy->castAs<ComplexType>()->getElementType(), 7329 CK_IntegralCast); 7330 return CK_IntegralRealToComplex; 7331 case Type::STK_FloatingComplex: 7332 Src = ImpCastExprToType(Src.get(), 7333 DestTy->castAs<ComplexType>()->getElementType(), 7334 CK_IntegralToFloating); 7335 return CK_FloatingRealToComplex; 7336 case Type::STK_MemberPointer: 7337 llvm_unreachable("member pointer type in C"); 7338 case Type::STK_FixedPoint: 7339 return CK_IntegralToFixedPoint; 7340 } 7341 llvm_unreachable("Should have returned before this"); 7342 7343 case Type::STK_Floating: 7344 switch (DestTy->getScalarTypeKind()) { 7345 case Type::STK_Floating: 7346 return CK_FloatingCast; 7347 case Type::STK_Bool: 7348 return CK_FloatingToBoolean; 7349 case Type::STK_Integral: 7350 return CK_FloatingToIntegral; 7351 case Type::STK_FloatingComplex: 7352 Src = ImpCastExprToType(Src.get(), 7353 DestTy->castAs<ComplexType>()->getElementType(), 7354 CK_FloatingCast); 7355 return CK_FloatingRealToComplex; 7356 case Type::STK_IntegralComplex: 7357 Src = ImpCastExprToType(Src.get(), 7358 DestTy->castAs<ComplexType>()->getElementType(), 7359 CK_FloatingToIntegral); 7360 return CK_IntegralRealToComplex; 7361 case Type::STK_CPointer: 7362 case Type::STK_ObjCObjectPointer: 7363 case Type::STK_BlockPointer: 7364 llvm_unreachable("valid float->pointer cast?"); 7365 case Type::STK_MemberPointer: 7366 llvm_unreachable("member pointer type in C"); 7367 case Type::STK_FixedPoint: 7368 return CK_FloatingToFixedPoint; 7369 } 7370 llvm_unreachable("Should have returned before this"); 7371 7372 case Type::STK_FloatingComplex: 7373 switch (DestTy->getScalarTypeKind()) { 7374 case Type::STK_FloatingComplex: 7375 return CK_FloatingComplexCast; 7376 case Type::STK_IntegralComplex: 7377 return CK_FloatingComplexToIntegralComplex; 7378 case Type::STK_Floating: { 7379 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7380 if (Context.hasSameType(ET, DestTy)) 7381 return CK_FloatingComplexToReal; 7382 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7383 return CK_FloatingCast; 7384 } 7385 case Type::STK_Bool: 7386 return CK_FloatingComplexToBoolean; 7387 case Type::STK_Integral: 7388 Src = ImpCastExprToType(Src.get(), 7389 SrcTy->castAs<ComplexType>()->getElementType(), 7390 CK_FloatingComplexToReal); 7391 return CK_FloatingToIntegral; 7392 case Type::STK_CPointer: 7393 case Type::STK_ObjCObjectPointer: 7394 case Type::STK_BlockPointer: 7395 llvm_unreachable("valid complex float->pointer cast?"); 7396 case Type::STK_MemberPointer: 7397 llvm_unreachable("member pointer type in C"); 7398 case Type::STK_FixedPoint: 7399 Diag(Src.get()->getExprLoc(), 7400 diag::err_unimplemented_conversion_with_fixed_point_type) 7401 << SrcTy; 7402 return CK_IntegralCast; 7403 } 7404 llvm_unreachable("Should have returned before this"); 7405 7406 case Type::STK_IntegralComplex: 7407 switch (DestTy->getScalarTypeKind()) { 7408 case Type::STK_FloatingComplex: 7409 return CK_IntegralComplexToFloatingComplex; 7410 case Type::STK_IntegralComplex: 7411 return CK_IntegralComplexCast; 7412 case Type::STK_Integral: { 7413 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7414 if (Context.hasSameType(ET, DestTy)) 7415 return CK_IntegralComplexToReal; 7416 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7417 return CK_IntegralCast; 7418 } 7419 case Type::STK_Bool: 7420 return CK_IntegralComplexToBoolean; 7421 case Type::STK_Floating: 7422 Src = ImpCastExprToType(Src.get(), 7423 SrcTy->castAs<ComplexType>()->getElementType(), 7424 CK_IntegralComplexToReal); 7425 return CK_IntegralToFloating; 7426 case Type::STK_CPointer: 7427 case Type::STK_ObjCObjectPointer: 7428 case Type::STK_BlockPointer: 7429 llvm_unreachable("valid complex int->pointer cast?"); 7430 case Type::STK_MemberPointer: 7431 llvm_unreachable("member pointer type in C"); 7432 case Type::STK_FixedPoint: 7433 Diag(Src.get()->getExprLoc(), 7434 diag::err_unimplemented_conversion_with_fixed_point_type) 7435 << SrcTy; 7436 return CK_IntegralCast; 7437 } 7438 llvm_unreachable("Should have returned before this"); 7439 } 7440 7441 llvm_unreachable("Unhandled scalar cast"); 7442 } 7443 7444 static bool breakDownVectorType(QualType type, uint64_t &len, 7445 QualType &eltType) { 7446 // Vectors are simple. 7447 if (const VectorType *vecType = type->getAs<VectorType>()) { 7448 len = vecType->getNumElements(); 7449 eltType = vecType->getElementType(); 7450 assert(eltType->isScalarType()); 7451 return true; 7452 } 7453 7454 // We allow lax conversion to and from non-vector types, but only if 7455 // they're real types (i.e. non-complex, non-pointer scalar types). 7456 if (!type->isRealType()) return false; 7457 7458 len = 1; 7459 eltType = type; 7460 return true; 7461 } 7462 7463 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7464 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7465 /// allowed? 7466 /// 7467 /// This will also return false if the two given types do not make sense from 7468 /// the perspective of SVE bitcasts. 7469 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7470 assert(srcTy->isVectorType() || destTy->isVectorType()); 7471 7472 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7473 if (!FirstType->isSizelessBuiltinType()) 7474 return false; 7475 7476 const auto *VecTy = SecondType->getAs<VectorType>(); 7477 return VecTy && 7478 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7479 }; 7480 7481 return ValidScalableConversion(srcTy, destTy) || 7482 ValidScalableConversion(destTy, srcTy); 7483 } 7484 7485 /// Are the two types matrix types and do they have the same dimensions i.e. 7486 /// do they have the same number of rows and the same number of columns? 7487 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7488 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7489 return false; 7490 7491 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7492 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7493 7494 return matSrcType->getNumRows() == matDestType->getNumRows() && 7495 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7496 } 7497 7498 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7499 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7500 7501 uint64_t SrcLen, DestLen; 7502 QualType SrcEltTy, DestEltTy; 7503 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7504 return false; 7505 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7506 return false; 7507 7508 // ASTContext::getTypeSize will return the size rounded up to a 7509 // power of 2, so instead of using that, we need to use the raw 7510 // element size multiplied by the element count. 7511 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7512 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7513 7514 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7515 } 7516 7517 /// Are the two types lax-compatible vector types? That is, given 7518 /// that one of them is a vector, do they have equal storage sizes, 7519 /// where the storage size is the number of elements times the element 7520 /// size? 7521 /// 7522 /// This will also return false if either of the types is neither a 7523 /// vector nor a real type. 7524 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7525 assert(destTy->isVectorType() || srcTy->isVectorType()); 7526 7527 // Disallow lax conversions between scalars and ExtVectors (these 7528 // conversions are allowed for other vector types because common headers 7529 // depend on them). Most scalar OP ExtVector cases are handled by the 7530 // splat path anyway, which does what we want (convert, not bitcast). 7531 // What this rules out for ExtVectors is crazy things like char4*float. 7532 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7533 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7534 7535 return areVectorTypesSameSize(srcTy, destTy); 7536 } 7537 7538 /// Is this a legal conversion between two types, one of which is 7539 /// known to be a vector type? 7540 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7541 assert(destTy->isVectorType() || srcTy->isVectorType()); 7542 7543 switch (Context.getLangOpts().getLaxVectorConversions()) { 7544 case LangOptions::LaxVectorConversionKind::None: 7545 return false; 7546 7547 case LangOptions::LaxVectorConversionKind::Integer: 7548 if (!srcTy->isIntegralOrEnumerationType()) { 7549 auto *Vec = srcTy->getAs<VectorType>(); 7550 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7551 return false; 7552 } 7553 if (!destTy->isIntegralOrEnumerationType()) { 7554 auto *Vec = destTy->getAs<VectorType>(); 7555 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7556 return false; 7557 } 7558 // OK, integer (vector) -> integer (vector) bitcast. 7559 break; 7560 7561 case LangOptions::LaxVectorConversionKind::All: 7562 break; 7563 } 7564 7565 return areLaxCompatibleVectorTypes(srcTy, destTy); 7566 } 7567 7568 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7569 CastKind &Kind) { 7570 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7571 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7572 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7573 << DestTy << SrcTy << R; 7574 } 7575 } else if (SrcTy->isMatrixType()) { 7576 return Diag(R.getBegin(), 7577 diag::err_invalid_conversion_between_matrix_and_type) 7578 << SrcTy << DestTy << R; 7579 } else if (DestTy->isMatrixType()) { 7580 return Diag(R.getBegin(), 7581 diag::err_invalid_conversion_between_matrix_and_type) 7582 << DestTy << SrcTy << R; 7583 } 7584 7585 Kind = CK_MatrixCast; 7586 return false; 7587 } 7588 7589 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7590 CastKind &Kind) { 7591 assert(VectorTy->isVectorType() && "Not a vector type!"); 7592 7593 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7594 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7595 return Diag(R.getBegin(), 7596 Ty->isVectorType() ? 7597 diag::err_invalid_conversion_between_vectors : 7598 diag::err_invalid_conversion_between_vector_and_integer) 7599 << VectorTy << Ty << R; 7600 } else 7601 return Diag(R.getBegin(), 7602 diag::err_invalid_conversion_between_vector_and_scalar) 7603 << VectorTy << Ty << R; 7604 7605 Kind = CK_BitCast; 7606 return false; 7607 } 7608 7609 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7610 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7611 7612 if (DestElemTy == SplattedExpr->getType()) 7613 return SplattedExpr; 7614 7615 assert(DestElemTy->isFloatingType() || 7616 DestElemTy->isIntegralOrEnumerationType()); 7617 7618 CastKind CK; 7619 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7620 // OpenCL requires that we convert `true` boolean expressions to -1, but 7621 // only when splatting vectors. 7622 if (DestElemTy->isFloatingType()) { 7623 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7624 // in two steps: boolean to signed integral, then to floating. 7625 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7626 CK_BooleanToSignedIntegral); 7627 SplattedExpr = CastExprRes.get(); 7628 CK = CK_IntegralToFloating; 7629 } else { 7630 CK = CK_BooleanToSignedIntegral; 7631 } 7632 } else { 7633 ExprResult CastExprRes = SplattedExpr; 7634 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7635 if (CastExprRes.isInvalid()) 7636 return ExprError(); 7637 SplattedExpr = CastExprRes.get(); 7638 } 7639 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7640 } 7641 7642 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7643 Expr *CastExpr, CastKind &Kind) { 7644 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7645 7646 QualType SrcTy = CastExpr->getType(); 7647 7648 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7649 // an ExtVectorType. 7650 // In OpenCL, casts between vectors of different types are not allowed. 7651 // (See OpenCL 6.2). 7652 if (SrcTy->isVectorType()) { 7653 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7654 (getLangOpts().OpenCL && 7655 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7656 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7657 << DestTy << SrcTy << R; 7658 return ExprError(); 7659 } 7660 Kind = CK_BitCast; 7661 return CastExpr; 7662 } 7663 7664 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7665 // conversion will take place first from scalar to elt type, and then 7666 // splat from elt type to vector. 7667 if (SrcTy->isPointerType()) 7668 return Diag(R.getBegin(), 7669 diag::err_invalid_conversion_between_vector_and_scalar) 7670 << DestTy << SrcTy << R; 7671 7672 Kind = CK_VectorSplat; 7673 return prepareVectorSplat(DestTy, CastExpr); 7674 } 7675 7676 ExprResult 7677 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7678 Declarator &D, ParsedType &Ty, 7679 SourceLocation RParenLoc, Expr *CastExpr) { 7680 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7681 "ActOnCastExpr(): missing type or expr"); 7682 7683 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7684 if (D.isInvalidType()) 7685 return ExprError(); 7686 7687 if (getLangOpts().CPlusPlus) { 7688 // Check that there are no default arguments (C++ only). 7689 CheckExtraCXXDefaultArguments(D); 7690 } else { 7691 // Make sure any TypoExprs have been dealt with. 7692 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7693 if (!Res.isUsable()) 7694 return ExprError(); 7695 CastExpr = Res.get(); 7696 } 7697 7698 checkUnusedDeclAttributes(D); 7699 7700 QualType castType = castTInfo->getType(); 7701 Ty = CreateParsedType(castType, castTInfo); 7702 7703 bool isVectorLiteral = false; 7704 7705 // Check for an altivec or OpenCL literal, 7706 // i.e. all the elements are integer constants. 7707 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7708 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7709 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7710 && castType->isVectorType() && (PE || PLE)) { 7711 if (PLE && PLE->getNumExprs() == 0) { 7712 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7713 return ExprError(); 7714 } 7715 if (PE || PLE->getNumExprs() == 1) { 7716 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7717 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7718 isVectorLiteral = true; 7719 } 7720 else 7721 isVectorLiteral = true; 7722 } 7723 7724 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7725 // then handle it as such. 7726 if (isVectorLiteral) 7727 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7728 7729 // If the Expr being casted is a ParenListExpr, handle it specially. 7730 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7731 // sequence of BinOp comma operators. 7732 if (isa<ParenListExpr>(CastExpr)) { 7733 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7734 if (Result.isInvalid()) return ExprError(); 7735 CastExpr = Result.get(); 7736 } 7737 7738 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7739 !getSourceManager().isInSystemMacro(LParenLoc)) 7740 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7741 7742 CheckTollFreeBridgeCast(castType, CastExpr); 7743 7744 CheckObjCBridgeRelatedCast(castType, CastExpr); 7745 7746 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7747 7748 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7749 } 7750 7751 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7752 SourceLocation RParenLoc, Expr *E, 7753 TypeSourceInfo *TInfo) { 7754 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7755 "Expected paren or paren list expression"); 7756 7757 Expr **exprs; 7758 unsigned numExprs; 7759 Expr *subExpr; 7760 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7761 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7762 LiteralLParenLoc = PE->getLParenLoc(); 7763 LiteralRParenLoc = PE->getRParenLoc(); 7764 exprs = PE->getExprs(); 7765 numExprs = PE->getNumExprs(); 7766 } else { // isa<ParenExpr> by assertion at function entrance 7767 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7768 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7769 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7770 exprs = &subExpr; 7771 numExprs = 1; 7772 } 7773 7774 QualType Ty = TInfo->getType(); 7775 assert(Ty->isVectorType() && "Expected vector type"); 7776 7777 SmallVector<Expr *, 8> initExprs; 7778 const VectorType *VTy = Ty->castAs<VectorType>(); 7779 unsigned numElems = VTy->getNumElements(); 7780 7781 // '(...)' form of vector initialization in AltiVec: the number of 7782 // initializers must be one or must match the size of the vector. 7783 // If a single value is specified in the initializer then it will be 7784 // replicated to all the components of the vector 7785 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 7786 VTy->getElementType())) 7787 return ExprError(); 7788 if (ShouldSplatAltivecScalarInCast(VTy)) { 7789 // The number of initializers must be one or must match the size of the 7790 // vector. If a single value is specified in the initializer then it will 7791 // be replicated to all the components of the vector 7792 if (numExprs == 1) { 7793 QualType ElemTy = VTy->getElementType(); 7794 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7795 if (Literal.isInvalid()) 7796 return ExprError(); 7797 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7798 PrepareScalarCast(Literal, ElemTy)); 7799 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7800 } 7801 else if (numExprs < numElems) { 7802 Diag(E->getExprLoc(), 7803 diag::err_incorrect_number_of_vector_initializers); 7804 return ExprError(); 7805 } 7806 else 7807 initExprs.append(exprs, exprs + numExprs); 7808 } 7809 else { 7810 // For OpenCL, when the number of initializers is a single value, 7811 // it will be replicated to all components of the vector. 7812 if (getLangOpts().OpenCL && 7813 VTy->getVectorKind() == VectorType::GenericVector && 7814 numExprs == 1) { 7815 QualType ElemTy = VTy->getElementType(); 7816 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7817 if (Literal.isInvalid()) 7818 return ExprError(); 7819 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7820 PrepareScalarCast(Literal, ElemTy)); 7821 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7822 } 7823 7824 initExprs.append(exprs, exprs + numExprs); 7825 } 7826 // FIXME: This means that pretty-printing the final AST will produce curly 7827 // braces instead of the original commas. 7828 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7829 initExprs, LiteralRParenLoc); 7830 initE->setType(Ty); 7831 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7832 } 7833 7834 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7835 /// the ParenListExpr into a sequence of comma binary operators. 7836 ExprResult 7837 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7838 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7839 if (!E) 7840 return OrigExpr; 7841 7842 ExprResult Result(E->getExpr(0)); 7843 7844 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7845 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7846 E->getExpr(i)); 7847 7848 if (Result.isInvalid()) return ExprError(); 7849 7850 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7851 } 7852 7853 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7854 SourceLocation R, 7855 MultiExprArg Val) { 7856 return ParenListExpr::Create(Context, L, Val, R); 7857 } 7858 7859 /// Emit a specialized diagnostic when one expression is a null pointer 7860 /// constant and the other is not a pointer. Returns true if a diagnostic is 7861 /// emitted. 7862 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7863 SourceLocation QuestionLoc) { 7864 Expr *NullExpr = LHSExpr; 7865 Expr *NonPointerExpr = RHSExpr; 7866 Expr::NullPointerConstantKind NullKind = 7867 NullExpr->isNullPointerConstant(Context, 7868 Expr::NPC_ValueDependentIsNotNull); 7869 7870 if (NullKind == Expr::NPCK_NotNull) { 7871 NullExpr = RHSExpr; 7872 NonPointerExpr = LHSExpr; 7873 NullKind = 7874 NullExpr->isNullPointerConstant(Context, 7875 Expr::NPC_ValueDependentIsNotNull); 7876 } 7877 7878 if (NullKind == Expr::NPCK_NotNull) 7879 return false; 7880 7881 if (NullKind == Expr::NPCK_ZeroExpression) 7882 return false; 7883 7884 if (NullKind == Expr::NPCK_ZeroLiteral) { 7885 // In this case, check to make sure that we got here from a "NULL" 7886 // string in the source code. 7887 NullExpr = NullExpr->IgnoreParenImpCasts(); 7888 SourceLocation loc = NullExpr->getExprLoc(); 7889 if (!findMacroSpelling(loc, "NULL")) 7890 return false; 7891 } 7892 7893 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7894 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7895 << NonPointerExpr->getType() << DiagType 7896 << NonPointerExpr->getSourceRange(); 7897 return true; 7898 } 7899 7900 /// Return false if the condition expression is valid, true otherwise. 7901 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7902 QualType CondTy = Cond->getType(); 7903 7904 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7905 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7906 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7907 << CondTy << Cond->getSourceRange(); 7908 return true; 7909 } 7910 7911 // C99 6.5.15p2 7912 if (CondTy->isScalarType()) return false; 7913 7914 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7915 << CondTy << Cond->getSourceRange(); 7916 return true; 7917 } 7918 7919 /// Handle when one or both operands are void type. 7920 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7921 ExprResult &RHS) { 7922 Expr *LHSExpr = LHS.get(); 7923 Expr *RHSExpr = RHS.get(); 7924 7925 if (!LHSExpr->getType()->isVoidType()) 7926 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7927 << RHSExpr->getSourceRange(); 7928 if (!RHSExpr->getType()->isVoidType()) 7929 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7930 << LHSExpr->getSourceRange(); 7931 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7932 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7933 return S.Context.VoidTy; 7934 } 7935 7936 /// Return false if the NullExpr can be promoted to PointerTy, 7937 /// true otherwise. 7938 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7939 QualType PointerTy) { 7940 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7941 !NullExpr.get()->isNullPointerConstant(S.Context, 7942 Expr::NPC_ValueDependentIsNull)) 7943 return true; 7944 7945 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7946 return false; 7947 } 7948 7949 /// Checks compatibility between two pointers and return the resulting 7950 /// type. 7951 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7952 ExprResult &RHS, 7953 SourceLocation Loc) { 7954 QualType LHSTy = LHS.get()->getType(); 7955 QualType RHSTy = RHS.get()->getType(); 7956 7957 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7958 // Two identical pointers types are always compatible. 7959 return LHSTy; 7960 } 7961 7962 QualType lhptee, rhptee; 7963 7964 // Get the pointee types. 7965 bool IsBlockPointer = false; 7966 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7967 lhptee = LHSBTy->getPointeeType(); 7968 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7969 IsBlockPointer = true; 7970 } else { 7971 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7972 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7973 } 7974 7975 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7976 // differently qualified versions of compatible types, the result type is 7977 // a pointer to an appropriately qualified version of the composite 7978 // type. 7979 7980 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7981 // clause doesn't make sense for our extensions. E.g. address space 2 should 7982 // be incompatible with address space 3: they may live on different devices or 7983 // anything. 7984 Qualifiers lhQual = lhptee.getQualifiers(); 7985 Qualifiers rhQual = rhptee.getQualifiers(); 7986 7987 LangAS ResultAddrSpace = LangAS::Default; 7988 LangAS LAddrSpace = lhQual.getAddressSpace(); 7989 LangAS RAddrSpace = rhQual.getAddressSpace(); 7990 7991 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7992 // spaces is disallowed. 7993 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7994 ResultAddrSpace = LAddrSpace; 7995 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7996 ResultAddrSpace = RAddrSpace; 7997 else { 7998 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7999 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8000 << RHS.get()->getSourceRange(); 8001 return QualType(); 8002 } 8003 8004 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8005 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8006 lhQual.removeCVRQualifiers(); 8007 rhQual.removeCVRQualifiers(); 8008 8009 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8010 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8011 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8012 // qual types are compatible iff 8013 // * corresponded types are compatible 8014 // * CVR qualifiers are equal 8015 // * address spaces are equal 8016 // Thus for conditional operator we merge CVR and address space unqualified 8017 // pointees and if there is a composite type we return a pointer to it with 8018 // merged qualifiers. 8019 LHSCastKind = 8020 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8021 RHSCastKind = 8022 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8023 lhQual.removeAddressSpace(); 8024 rhQual.removeAddressSpace(); 8025 8026 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8027 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8028 8029 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 8030 8031 if (CompositeTy.isNull()) { 8032 // In this situation, we assume void* type. No especially good 8033 // reason, but this is what gcc does, and we do have to pick 8034 // to get a consistent AST. 8035 QualType incompatTy; 8036 incompatTy = S.Context.getPointerType( 8037 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8038 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8039 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8040 8041 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8042 // for casts between types with incompatible address space qualifiers. 8043 // For the following code the compiler produces casts between global and 8044 // local address spaces of the corresponded innermost pointees: 8045 // local int *global *a; 8046 // global int *global *b; 8047 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8048 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8049 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8050 << RHS.get()->getSourceRange(); 8051 8052 return incompatTy; 8053 } 8054 8055 // The pointer types are compatible. 8056 // In case of OpenCL ResultTy should have the address space qualifier 8057 // which is a superset of address spaces of both the 2nd and the 3rd 8058 // operands of the conditional operator. 8059 QualType ResultTy = [&, ResultAddrSpace]() { 8060 if (S.getLangOpts().OpenCL) { 8061 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8062 CompositeQuals.setAddressSpace(ResultAddrSpace); 8063 return S.Context 8064 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8065 .withCVRQualifiers(MergedCVRQual); 8066 } 8067 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8068 }(); 8069 if (IsBlockPointer) 8070 ResultTy = S.Context.getBlockPointerType(ResultTy); 8071 else 8072 ResultTy = S.Context.getPointerType(ResultTy); 8073 8074 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8075 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8076 return ResultTy; 8077 } 8078 8079 /// Return the resulting type when the operands are both block pointers. 8080 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8081 ExprResult &LHS, 8082 ExprResult &RHS, 8083 SourceLocation Loc) { 8084 QualType LHSTy = LHS.get()->getType(); 8085 QualType RHSTy = RHS.get()->getType(); 8086 8087 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8088 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8089 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8090 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8091 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8092 return destType; 8093 } 8094 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8095 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8096 << RHS.get()->getSourceRange(); 8097 return QualType(); 8098 } 8099 8100 // We have 2 block pointer types. 8101 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8102 } 8103 8104 /// Return the resulting type when the operands are both pointers. 8105 static QualType 8106 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8107 ExprResult &RHS, 8108 SourceLocation Loc) { 8109 // get the pointer types 8110 QualType LHSTy = LHS.get()->getType(); 8111 QualType RHSTy = RHS.get()->getType(); 8112 8113 // get the "pointed to" types 8114 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8115 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8116 8117 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8118 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8119 // Figure out necessary qualifiers (C99 6.5.15p6) 8120 QualType destPointee 8121 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8122 QualType destType = S.Context.getPointerType(destPointee); 8123 // Add qualifiers if necessary. 8124 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8125 // Promote to void*. 8126 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8127 return destType; 8128 } 8129 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8130 QualType destPointee 8131 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8132 QualType destType = S.Context.getPointerType(destPointee); 8133 // Add qualifiers if necessary. 8134 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8135 // Promote to void*. 8136 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8137 return destType; 8138 } 8139 8140 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8141 } 8142 8143 /// Return false if the first expression is not an integer and the second 8144 /// expression is not a pointer, true otherwise. 8145 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8146 Expr* PointerExpr, SourceLocation Loc, 8147 bool IsIntFirstExpr) { 8148 if (!PointerExpr->getType()->isPointerType() || 8149 !Int.get()->getType()->isIntegerType()) 8150 return false; 8151 8152 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8153 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8154 8155 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8156 << Expr1->getType() << Expr2->getType() 8157 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8158 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8159 CK_IntegralToPointer); 8160 return true; 8161 } 8162 8163 /// Simple conversion between integer and floating point types. 8164 /// 8165 /// Used when handling the OpenCL conditional operator where the 8166 /// condition is a vector while the other operands are scalar. 8167 /// 8168 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8169 /// types are either integer or floating type. Between the two 8170 /// operands, the type with the higher rank is defined as the "result 8171 /// type". The other operand needs to be promoted to the same type. No 8172 /// other type promotion is allowed. We cannot use 8173 /// UsualArithmeticConversions() for this purpose, since it always 8174 /// promotes promotable types. 8175 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8176 ExprResult &RHS, 8177 SourceLocation QuestionLoc) { 8178 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8179 if (LHS.isInvalid()) 8180 return QualType(); 8181 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8182 if (RHS.isInvalid()) 8183 return QualType(); 8184 8185 // For conversion purposes, we ignore any qualifiers. 8186 // For example, "const float" and "float" are equivalent. 8187 QualType LHSType = 8188 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8189 QualType RHSType = 8190 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8191 8192 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8193 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8194 << LHSType << LHS.get()->getSourceRange(); 8195 return QualType(); 8196 } 8197 8198 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8199 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8200 << RHSType << RHS.get()->getSourceRange(); 8201 return QualType(); 8202 } 8203 8204 // If both types are identical, no conversion is needed. 8205 if (LHSType == RHSType) 8206 return LHSType; 8207 8208 // Now handle "real" floating types (i.e. float, double, long double). 8209 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8210 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8211 /*IsCompAssign = */ false); 8212 8213 // Finally, we have two differing integer types. 8214 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8215 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8216 } 8217 8218 /// Convert scalar operands to a vector that matches the 8219 /// condition in length. 8220 /// 8221 /// Used when handling the OpenCL conditional operator where the 8222 /// condition is a vector while the other operands are scalar. 8223 /// 8224 /// We first compute the "result type" for the scalar operands 8225 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8226 /// into a vector of that type where the length matches the condition 8227 /// vector type. s6.11.6 requires that the element types of the result 8228 /// and the condition must have the same number of bits. 8229 static QualType 8230 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8231 QualType CondTy, SourceLocation QuestionLoc) { 8232 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8233 if (ResTy.isNull()) return QualType(); 8234 8235 const VectorType *CV = CondTy->getAs<VectorType>(); 8236 assert(CV); 8237 8238 // Determine the vector result type 8239 unsigned NumElements = CV->getNumElements(); 8240 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8241 8242 // Ensure that all types have the same number of bits 8243 if (S.Context.getTypeSize(CV->getElementType()) 8244 != S.Context.getTypeSize(ResTy)) { 8245 // Since VectorTy is created internally, it does not pretty print 8246 // with an OpenCL name. Instead, we just print a description. 8247 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8248 SmallString<64> Str; 8249 llvm::raw_svector_ostream OS(Str); 8250 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8251 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8252 << CondTy << OS.str(); 8253 return QualType(); 8254 } 8255 8256 // Convert operands to the vector result type 8257 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8258 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8259 8260 return VectorTy; 8261 } 8262 8263 /// Return false if this is a valid OpenCL condition vector 8264 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8265 SourceLocation QuestionLoc) { 8266 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8267 // integral type. 8268 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8269 assert(CondTy); 8270 QualType EleTy = CondTy->getElementType(); 8271 if (EleTy->isIntegerType()) return false; 8272 8273 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8274 << Cond->getType() << Cond->getSourceRange(); 8275 return true; 8276 } 8277 8278 /// Return false if the vector condition type and the vector 8279 /// result type are compatible. 8280 /// 8281 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8282 /// number of elements, and their element types have the same number 8283 /// of bits. 8284 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8285 SourceLocation QuestionLoc) { 8286 const VectorType *CV = CondTy->getAs<VectorType>(); 8287 const VectorType *RV = VecResTy->getAs<VectorType>(); 8288 assert(CV && RV); 8289 8290 if (CV->getNumElements() != RV->getNumElements()) { 8291 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8292 << CondTy << VecResTy; 8293 return true; 8294 } 8295 8296 QualType CVE = CV->getElementType(); 8297 QualType RVE = RV->getElementType(); 8298 8299 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8300 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8301 << CondTy << VecResTy; 8302 return true; 8303 } 8304 8305 return false; 8306 } 8307 8308 /// Return the resulting type for the conditional operator in 8309 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8310 /// s6.3.i) when the condition is a vector type. 8311 static QualType 8312 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8313 ExprResult &LHS, ExprResult &RHS, 8314 SourceLocation QuestionLoc) { 8315 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8316 if (Cond.isInvalid()) 8317 return QualType(); 8318 QualType CondTy = Cond.get()->getType(); 8319 8320 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8321 return QualType(); 8322 8323 // If either operand is a vector then find the vector type of the 8324 // result as specified in OpenCL v1.1 s6.3.i. 8325 if (LHS.get()->getType()->isVectorType() || 8326 RHS.get()->getType()->isVectorType()) { 8327 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8328 /*isCompAssign*/false, 8329 /*AllowBothBool*/true, 8330 /*AllowBoolConversions*/false); 8331 if (VecResTy.isNull()) return QualType(); 8332 // The result type must match the condition type as specified in 8333 // OpenCL v1.1 s6.11.6. 8334 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8335 return QualType(); 8336 return VecResTy; 8337 } 8338 8339 // Both operands are scalar. 8340 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8341 } 8342 8343 /// Return true if the Expr is block type 8344 static bool checkBlockType(Sema &S, const Expr *E) { 8345 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8346 QualType Ty = CE->getCallee()->getType(); 8347 if (Ty->isBlockPointerType()) { 8348 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8349 return true; 8350 } 8351 } 8352 return false; 8353 } 8354 8355 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8356 /// In that case, LHS = cond. 8357 /// C99 6.5.15 8358 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8359 ExprResult &RHS, ExprValueKind &VK, 8360 ExprObjectKind &OK, 8361 SourceLocation QuestionLoc) { 8362 8363 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8364 if (!LHSResult.isUsable()) return QualType(); 8365 LHS = LHSResult; 8366 8367 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8368 if (!RHSResult.isUsable()) return QualType(); 8369 RHS = RHSResult; 8370 8371 // C++ is sufficiently different to merit its own checker. 8372 if (getLangOpts().CPlusPlus) 8373 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8374 8375 VK = VK_PRValue; 8376 OK = OK_Ordinary; 8377 8378 if (Context.isDependenceAllowed() && 8379 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8380 RHS.get()->isTypeDependent())) { 8381 assert(!getLangOpts().CPlusPlus); 8382 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8383 RHS.get()->containsErrors()) && 8384 "should only occur in error-recovery path."); 8385 return Context.DependentTy; 8386 } 8387 8388 // The OpenCL operator with a vector condition is sufficiently 8389 // different to merit its own checker. 8390 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8391 Cond.get()->getType()->isExtVectorType()) 8392 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8393 8394 // First, check the condition. 8395 Cond = UsualUnaryConversions(Cond.get()); 8396 if (Cond.isInvalid()) 8397 return QualType(); 8398 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8399 return QualType(); 8400 8401 // Now check the two expressions. 8402 if (LHS.get()->getType()->isVectorType() || 8403 RHS.get()->getType()->isVectorType()) 8404 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8405 /*AllowBothBool*/true, 8406 /*AllowBoolConversions*/false); 8407 8408 QualType ResTy = 8409 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8410 if (LHS.isInvalid() || RHS.isInvalid()) 8411 return QualType(); 8412 8413 QualType LHSTy = LHS.get()->getType(); 8414 QualType RHSTy = RHS.get()->getType(); 8415 8416 // Diagnose attempts to convert between __float128 and long double where 8417 // such conversions currently can't be handled. 8418 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8419 Diag(QuestionLoc, 8420 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8421 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8422 return QualType(); 8423 } 8424 8425 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8426 // selection operator (?:). 8427 if (getLangOpts().OpenCL && 8428 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8429 return QualType(); 8430 } 8431 8432 // If both operands have arithmetic type, do the usual arithmetic conversions 8433 // to find a common type: C99 6.5.15p3,5. 8434 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8435 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8436 // different sizes, or between ExtInts and other types. 8437 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8438 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8439 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8440 << RHS.get()->getSourceRange(); 8441 return QualType(); 8442 } 8443 8444 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8445 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8446 8447 return ResTy; 8448 } 8449 8450 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8451 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8452 return LHSTy; 8453 } 8454 8455 // If both operands are the same structure or union type, the result is that 8456 // type. 8457 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8458 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8459 if (LHSRT->getDecl() == RHSRT->getDecl()) 8460 // "If both the operands have structure or union type, the result has 8461 // that type." This implies that CV qualifiers are dropped. 8462 return LHSTy.getUnqualifiedType(); 8463 // FIXME: Type of conditional expression must be complete in C mode. 8464 } 8465 8466 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8467 // The following || allows only one side to be void (a GCC-ism). 8468 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8469 return checkConditionalVoidType(*this, LHS, RHS); 8470 } 8471 8472 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8473 // the type of the other operand." 8474 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8475 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8476 8477 // All objective-c pointer type analysis is done here. 8478 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8479 QuestionLoc); 8480 if (LHS.isInvalid() || RHS.isInvalid()) 8481 return QualType(); 8482 if (!compositeType.isNull()) 8483 return compositeType; 8484 8485 8486 // Handle block pointer types. 8487 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8488 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8489 QuestionLoc); 8490 8491 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8492 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8493 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8494 QuestionLoc); 8495 8496 // GCC compatibility: soften pointer/integer mismatch. Note that 8497 // null pointers have been filtered out by this point. 8498 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8499 /*IsIntFirstExpr=*/true)) 8500 return RHSTy; 8501 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8502 /*IsIntFirstExpr=*/false)) 8503 return LHSTy; 8504 8505 // Allow ?: operations in which both operands have the same 8506 // built-in sizeless type. 8507 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 8508 return LHSTy; 8509 8510 // Emit a better diagnostic if one of the expressions is a null pointer 8511 // constant and the other is not a pointer type. In this case, the user most 8512 // likely forgot to take the address of the other expression. 8513 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8514 return QualType(); 8515 8516 // Otherwise, the operands are not compatible. 8517 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8518 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8519 << RHS.get()->getSourceRange(); 8520 return QualType(); 8521 } 8522 8523 /// FindCompositeObjCPointerType - Helper method to find composite type of 8524 /// two objective-c pointer types of the two input expressions. 8525 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8526 SourceLocation QuestionLoc) { 8527 QualType LHSTy = LHS.get()->getType(); 8528 QualType RHSTy = RHS.get()->getType(); 8529 8530 // Handle things like Class and struct objc_class*. Here we case the result 8531 // to the pseudo-builtin, because that will be implicitly cast back to the 8532 // redefinition type if an attempt is made to access its fields. 8533 if (LHSTy->isObjCClassType() && 8534 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8535 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8536 return LHSTy; 8537 } 8538 if (RHSTy->isObjCClassType() && 8539 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8540 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8541 return RHSTy; 8542 } 8543 // And the same for struct objc_object* / id 8544 if (LHSTy->isObjCIdType() && 8545 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8546 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8547 return LHSTy; 8548 } 8549 if (RHSTy->isObjCIdType() && 8550 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8551 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8552 return RHSTy; 8553 } 8554 // And the same for struct objc_selector* / SEL 8555 if (Context.isObjCSelType(LHSTy) && 8556 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8557 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8558 return LHSTy; 8559 } 8560 if (Context.isObjCSelType(RHSTy) && 8561 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8562 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8563 return RHSTy; 8564 } 8565 // Check constraints for Objective-C object pointers types. 8566 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8567 8568 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8569 // Two identical object pointer types are always compatible. 8570 return LHSTy; 8571 } 8572 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8573 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8574 QualType compositeType = LHSTy; 8575 8576 // If both operands are interfaces and either operand can be 8577 // assigned to the other, use that type as the composite 8578 // type. This allows 8579 // xxx ? (A*) a : (B*) b 8580 // where B is a subclass of A. 8581 // 8582 // Additionally, as for assignment, if either type is 'id' 8583 // allow silent coercion. Finally, if the types are 8584 // incompatible then make sure to use 'id' as the composite 8585 // type so the result is acceptable for sending messages to. 8586 8587 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8588 // It could return the composite type. 8589 if (!(compositeType = 8590 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8591 // Nothing more to do. 8592 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8593 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8594 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8595 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8596 } else if ((LHSOPT->isObjCQualifiedIdType() || 8597 RHSOPT->isObjCQualifiedIdType()) && 8598 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8599 true)) { 8600 // Need to handle "id<xx>" explicitly. 8601 // GCC allows qualified id and any Objective-C type to devolve to 8602 // id. Currently localizing to here until clear this should be 8603 // part of ObjCQualifiedIdTypesAreCompatible. 8604 compositeType = Context.getObjCIdType(); 8605 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8606 compositeType = Context.getObjCIdType(); 8607 } else { 8608 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8609 << LHSTy << RHSTy 8610 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8611 QualType incompatTy = Context.getObjCIdType(); 8612 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8613 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8614 return incompatTy; 8615 } 8616 // The object pointer types are compatible. 8617 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8618 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8619 return compositeType; 8620 } 8621 // Check Objective-C object pointer types and 'void *' 8622 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8623 if (getLangOpts().ObjCAutoRefCount) { 8624 // ARC forbids the implicit conversion of object pointers to 'void *', 8625 // so these types are not compatible. 8626 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8627 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8628 LHS = RHS = true; 8629 return QualType(); 8630 } 8631 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8632 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8633 QualType destPointee 8634 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8635 QualType destType = Context.getPointerType(destPointee); 8636 // Add qualifiers if necessary. 8637 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8638 // Promote to void*. 8639 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8640 return destType; 8641 } 8642 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8643 if (getLangOpts().ObjCAutoRefCount) { 8644 // ARC forbids the implicit conversion of object pointers to 'void *', 8645 // so these types are not compatible. 8646 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8647 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8648 LHS = RHS = true; 8649 return QualType(); 8650 } 8651 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8652 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8653 QualType destPointee 8654 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8655 QualType destType = Context.getPointerType(destPointee); 8656 // Add qualifiers if necessary. 8657 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8658 // Promote to void*. 8659 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8660 return destType; 8661 } 8662 return QualType(); 8663 } 8664 8665 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8666 /// ParenRange in parentheses. 8667 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8668 const PartialDiagnostic &Note, 8669 SourceRange ParenRange) { 8670 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8671 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8672 EndLoc.isValid()) { 8673 Self.Diag(Loc, Note) 8674 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8675 << FixItHint::CreateInsertion(EndLoc, ")"); 8676 } else { 8677 // We can't display the parentheses, so just show the bare note. 8678 Self.Diag(Loc, Note) << ParenRange; 8679 } 8680 } 8681 8682 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8683 return BinaryOperator::isAdditiveOp(Opc) || 8684 BinaryOperator::isMultiplicativeOp(Opc) || 8685 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8686 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8687 // not any of the logical operators. Bitwise-xor is commonly used as a 8688 // logical-xor because there is no logical-xor operator. The logical 8689 // operators, including uses of xor, have a high false positive rate for 8690 // precedence warnings. 8691 } 8692 8693 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8694 /// expression, either using a built-in or overloaded operator, 8695 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8696 /// expression. 8697 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8698 Expr **RHSExprs) { 8699 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8700 E = E->IgnoreImpCasts(); 8701 E = E->IgnoreConversionOperatorSingleStep(); 8702 E = E->IgnoreImpCasts(); 8703 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8704 E = MTE->getSubExpr(); 8705 E = E->IgnoreImpCasts(); 8706 } 8707 8708 // Built-in binary operator. 8709 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8710 if (IsArithmeticOp(OP->getOpcode())) { 8711 *Opcode = OP->getOpcode(); 8712 *RHSExprs = OP->getRHS(); 8713 return true; 8714 } 8715 } 8716 8717 // Overloaded operator. 8718 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8719 if (Call->getNumArgs() != 2) 8720 return false; 8721 8722 // Make sure this is really a binary operator that is safe to pass into 8723 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8724 OverloadedOperatorKind OO = Call->getOperator(); 8725 if (OO < OO_Plus || OO > OO_Arrow || 8726 OO == OO_PlusPlus || OO == OO_MinusMinus) 8727 return false; 8728 8729 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8730 if (IsArithmeticOp(OpKind)) { 8731 *Opcode = OpKind; 8732 *RHSExprs = Call->getArg(1); 8733 return true; 8734 } 8735 } 8736 8737 return false; 8738 } 8739 8740 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8741 /// or is a logical expression such as (x==y) which has int type, but is 8742 /// commonly interpreted as boolean. 8743 static bool ExprLooksBoolean(Expr *E) { 8744 E = E->IgnoreParenImpCasts(); 8745 8746 if (E->getType()->isBooleanType()) 8747 return true; 8748 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8749 return OP->isComparisonOp() || OP->isLogicalOp(); 8750 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8751 return OP->getOpcode() == UO_LNot; 8752 if (E->getType()->isPointerType()) 8753 return true; 8754 // FIXME: What about overloaded operator calls returning "unspecified boolean 8755 // type"s (commonly pointer-to-members)? 8756 8757 return false; 8758 } 8759 8760 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8761 /// and binary operator are mixed in a way that suggests the programmer assumed 8762 /// the conditional operator has higher precedence, for example: 8763 /// "int x = a + someBinaryCondition ? 1 : 2". 8764 static void DiagnoseConditionalPrecedence(Sema &Self, 8765 SourceLocation OpLoc, 8766 Expr *Condition, 8767 Expr *LHSExpr, 8768 Expr *RHSExpr) { 8769 BinaryOperatorKind CondOpcode; 8770 Expr *CondRHS; 8771 8772 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8773 return; 8774 if (!ExprLooksBoolean(CondRHS)) 8775 return; 8776 8777 // The condition is an arithmetic binary expression, with a right- 8778 // hand side that looks boolean, so warn. 8779 8780 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8781 ? diag::warn_precedence_bitwise_conditional 8782 : diag::warn_precedence_conditional; 8783 8784 Self.Diag(OpLoc, DiagID) 8785 << Condition->getSourceRange() 8786 << BinaryOperator::getOpcodeStr(CondOpcode); 8787 8788 SuggestParentheses( 8789 Self, OpLoc, 8790 Self.PDiag(diag::note_precedence_silence) 8791 << BinaryOperator::getOpcodeStr(CondOpcode), 8792 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8793 8794 SuggestParentheses(Self, OpLoc, 8795 Self.PDiag(diag::note_precedence_conditional_first), 8796 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8797 } 8798 8799 /// Compute the nullability of a conditional expression. 8800 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8801 QualType LHSTy, QualType RHSTy, 8802 ASTContext &Ctx) { 8803 if (!ResTy->isAnyPointerType()) 8804 return ResTy; 8805 8806 auto GetNullability = [&Ctx](QualType Ty) { 8807 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8808 if (Kind) { 8809 // For our purposes, treat _Nullable_result as _Nullable. 8810 if (*Kind == NullabilityKind::NullableResult) 8811 return NullabilityKind::Nullable; 8812 return *Kind; 8813 } 8814 return NullabilityKind::Unspecified; 8815 }; 8816 8817 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8818 NullabilityKind MergedKind; 8819 8820 // Compute nullability of a binary conditional expression. 8821 if (IsBin) { 8822 if (LHSKind == NullabilityKind::NonNull) 8823 MergedKind = NullabilityKind::NonNull; 8824 else 8825 MergedKind = RHSKind; 8826 // Compute nullability of a normal conditional expression. 8827 } else { 8828 if (LHSKind == NullabilityKind::Nullable || 8829 RHSKind == NullabilityKind::Nullable) 8830 MergedKind = NullabilityKind::Nullable; 8831 else if (LHSKind == NullabilityKind::NonNull) 8832 MergedKind = RHSKind; 8833 else if (RHSKind == NullabilityKind::NonNull) 8834 MergedKind = LHSKind; 8835 else 8836 MergedKind = NullabilityKind::Unspecified; 8837 } 8838 8839 // Return if ResTy already has the correct nullability. 8840 if (GetNullability(ResTy) == MergedKind) 8841 return ResTy; 8842 8843 // Strip all nullability from ResTy. 8844 while (ResTy->getNullability(Ctx)) 8845 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8846 8847 // Create a new AttributedType with the new nullability kind. 8848 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8849 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8850 } 8851 8852 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8853 /// in the case of a the GNU conditional expr extension. 8854 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8855 SourceLocation ColonLoc, 8856 Expr *CondExpr, Expr *LHSExpr, 8857 Expr *RHSExpr) { 8858 if (!Context.isDependenceAllowed()) { 8859 // C cannot handle TypoExpr nodes in the condition because it 8860 // doesn't handle dependent types properly, so make sure any TypoExprs have 8861 // been dealt with before checking the operands. 8862 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8863 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8864 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8865 8866 if (!CondResult.isUsable()) 8867 return ExprError(); 8868 8869 if (LHSExpr) { 8870 if (!LHSResult.isUsable()) 8871 return ExprError(); 8872 } 8873 8874 if (!RHSResult.isUsable()) 8875 return ExprError(); 8876 8877 CondExpr = CondResult.get(); 8878 LHSExpr = LHSResult.get(); 8879 RHSExpr = RHSResult.get(); 8880 } 8881 8882 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8883 // was the condition. 8884 OpaqueValueExpr *opaqueValue = nullptr; 8885 Expr *commonExpr = nullptr; 8886 if (!LHSExpr) { 8887 commonExpr = CondExpr; 8888 // Lower out placeholder types first. This is important so that we don't 8889 // try to capture a placeholder. This happens in few cases in C++; such 8890 // as Objective-C++'s dictionary subscripting syntax. 8891 if (commonExpr->hasPlaceholderType()) { 8892 ExprResult result = CheckPlaceholderExpr(commonExpr); 8893 if (!result.isUsable()) return ExprError(); 8894 commonExpr = result.get(); 8895 } 8896 // We usually want to apply unary conversions *before* saving, except 8897 // in the special case of a C++ l-value conditional. 8898 if (!(getLangOpts().CPlusPlus 8899 && !commonExpr->isTypeDependent() 8900 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8901 && commonExpr->isGLValue() 8902 && commonExpr->isOrdinaryOrBitFieldObject() 8903 && RHSExpr->isOrdinaryOrBitFieldObject() 8904 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8905 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8906 if (commonRes.isInvalid()) 8907 return ExprError(); 8908 commonExpr = commonRes.get(); 8909 } 8910 8911 // If the common expression is a class or array prvalue, materialize it 8912 // so that we can safely refer to it multiple times. 8913 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 8914 commonExpr->getType()->isArrayType())) { 8915 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8916 if (MatExpr.isInvalid()) 8917 return ExprError(); 8918 commonExpr = MatExpr.get(); 8919 } 8920 8921 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8922 commonExpr->getType(), 8923 commonExpr->getValueKind(), 8924 commonExpr->getObjectKind(), 8925 commonExpr); 8926 LHSExpr = CondExpr = opaqueValue; 8927 } 8928 8929 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8930 ExprValueKind VK = VK_PRValue; 8931 ExprObjectKind OK = OK_Ordinary; 8932 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8933 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8934 VK, OK, QuestionLoc); 8935 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8936 RHS.isInvalid()) 8937 return ExprError(); 8938 8939 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8940 RHS.get()); 8941 8942 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8943 8944 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8945 Context); 8946 8947 if (!commonExpr) 8948 return new (Context) 8949 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8950 RHS.get(), result, VK, OK); 8951 8952 return new (Context) BinaryConditionalOperator( 8953 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8954 ColonLoc, result, VK, OK); 8955 } 8956 8957 // Check if we have a conversion between incompatible cmse function pointer 8958 // types, that is, a conversion between a function pointer with the 8959 // cmse_nonsecure_call attribute and one without. 8960 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8961 QualType ToType) { 8962 if (const auto *ToFn = 8963 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8964 if (const auto *FromFn = 8965 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8966 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8967 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8968 8969 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8970 } 8971 } 8972 return false; 8973 } 8974 8975 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8976 // being closely modeled after the C99 spec:-). The odd characteristic of this 8977 // routine is it effectively iqnores the qualifiers on the top level pointee. 8978 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8979 // FIXME: add a couple examples in this comment. 8980 static Sema::AssignConvertType 8981 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8982 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8983 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8984 8985 // get the "pointed to" type (ignoring qualifiers at the top level) 8986 const Type *lhptee, *rhptee; 8987 Qualifiers lhq, rhq; 8988 std::tie(lhptee, lhq) = 8989 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8990 std::tie(rhptee, rhq) = 8991 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8992 8993 Sema::AssignConvertType ConvTy = Sema::Compatible; 8994 8995 // C99 6.5.16.1p1: This following citation is common to constraints 8996 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8997 // qualifiers of the type *pointed to* by the right; 8998 8999 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9000 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9001 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9002 // Ignore lifetime for further calculation. 9003 lhq.removeObjCLifetime(); 9004 rhq.removeObjCLifetime(); 9005 } 9006 9007 if (!lhq.compatiblyIncludes(rhq)) { 9008 // Treat address-space mismatches as fatal. 9009 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9010 return Sema::IncompatiblePointerDiscardsQualifiers; 9011 9012 // It's okay to add or remove GC or lifetime qualifiers when converting to 9013 // and from void*. 9014 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9015 .compatiblyIncludes( 9016 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9017 && (lhptee->isVoidType() || rhptee->isVoidType())) 9018 ; // keep old 9019 9020 // Treat lifetime mismatches as fatal. 9021 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9022 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9023 9024 // For GCC/MS compatibility, other qualifier mismatches are treated 9025 // as still compatible in C. 9026 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9027 } 9028 9029 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9030 // incomplete type and the other is a pointer to a qualified or unqualified 9031 // version of void... 9032 if (lhptee->isVoidType()) { 9033 if (rhptee->isIncompleteOrObjectType()) 9034 return ConvTy; 9035 9036 // As an extension, we allow cast to/from void* to function pointer. 9037 assert(rhptee->isFunctionType()); 9038 return Sema::FunctionVoidPointer; 9039 } 9040 9041 if (rhptee->isVoidType()) { 9042 if (lhptee->isIncompleteOrObjectType()) 9043 return ConvTy; 9044 9045 // As an extension, we allow cast to/from void* to function pointer. 9046 assert(lhptee->isFunctionType()); 9047 return Sema::FunctionVoidPointer; 9048 } 9049 9050 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9051 // unqualified versions of compatible types, ... 9052 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9053 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9054 // Check if the pointee types are compatible ignoring the sign. 9055 // We explicitly check for char so that we catch "char" vs 9056 // "unsigned char" on systems where "char" is unsigned. 9057 if (lhptee->isCharType()) 9058 ltrans = S.Context.UnsignedCharTy; 9059 else if (lhptee->hasSignedIntegerRepresentation()) 9060 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9061 9062 if (rhptee->isCharType()) 9063 rtrans = S.Context.UnsignedCharTy; 9064 else if (rhptee->hasSignedIntegerRepresentation()) 9065 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9066 9067 if (ltrans == rtrans) { 9068 // Types are compatible ignoring the sign. Qualifier incompatibility 9069 // takes priority over sign incompatibility because the sign 9070 // warning can be disabled. 9071 if (ConvTy != Sema::Compatible) 9072 return ConvTy; 9073 9074 return Sema::IncompatiblePointerSign; 9075 } 9076 9077 // If we are a multi-level pointer, it's possible that our issue is simply 9078 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9079 // the eventual target type is the same and the pointers have the same 9080 // level of indirection, this must be the issue. 9081 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9082 do { 9083 std::tie(lhptee, lhq) = 9084 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9085 std::tie(rhptee, rhq) = 9086 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9087 9088 // Inconsistent address spaces at this point is invalid, even if the 9089 // address spaces would be compatible. 9090 // FIXME: This doesn't catch address space mismatches for pointers of 9091 // different nesting levels, like: 9092 // __local int *** a; 9093 // int ** b = a; 9094 // It's not clear how to actually determine when such pointers are 9095 // invalidly incompatible. 9096 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9097 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9098 9099 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9100 9101 if (lhptee == rhptee) 9102 return Sema::IncompatibleNestedPointerQualifiers; 9103 } 9104 9105 // General pointer incompatibility takes priority over qualifiers. 9106 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9107 return Sema::IncompatibleFunctionPointer; 9108 return Sema::IncompatiblePointer; 9109 } 9110 if (!S.getLangOpts().CPlusPlus && 9111 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9112 return Sema::IncompatibleFunctionPointer; 9113 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9114 return Sema::IncompatibleFunctionPointer; 9115 return ConvTy; 9116 } 9117 9118 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9119 /// block pointer types are compatible or whether a block and normal pointer 9120 /// are compatible. It is more restrict than comparing two function pointer 9121 // types. 9122 static Sema::AssignConvertType 9123 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9124 QualType RHSType) { 9125 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9126 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9127 9128 QualType lhptee, rhptee; 9129 9130 // get the "pointed to" type (ignoring qualifiers at the top level) 9131 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9132 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9133 9134 // In C++, the types have to match exactly. 9135 if (S.getLangOpts().CPlusPlus) 9136 return Sema::IncompatibleBlockPointer; 9137 9138 Sema::AssignConvertType ConvTy = Sema::Compatible; 9139 9140 // For blocks we enforce that qualifiers are identical. 9141 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9142 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9143 if (S.getLangOpts().OpenCL) { 9144 LQuals.removeAddressSpace(); 9145 RQuals.removeAddressSpace(); 9146 } 9147 if (LQuals != RQuals) 9148 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9149 9150 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9151 // assignment. 9152 // The current behavior is similar to C++ lambdas. A block might be 9153 // assigned to a variable iff its return type and parameters are compatible 9154 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9155 // an assignment. Presumably it should behave in way that a function pointer 9156 // assignment does in C, so for each parameter and return type: 9157 // * CVR and address space of LHS should be a superset of CVR and address 9158 // space of RHS. 9159 // * unqualified types should be compatible. 9160 if (S.getLangOpts().OpenCL) { 9161 if (!S.Context.typesAreBlockPointerCompatible( 9162 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9163 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9164 return Sema::IncompatibleBlockPointer; 9165 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9166 return Sema::IncompatibleBlockPointer; 9167 9168 return ConvTy; 9169 } 9170 9171 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9172 /// for assignment compatibility. 9173 static Sema::AssignConvertType 9174 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9175 QualType RHSType) { 9176 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9177 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9178 9179 if (LHSType->isObjCBuiltinType()) { 9180 // Class is not compatible with ObjC object pointers. 9181 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9182 !RHSType->isObjCQualifiedClassType()) 9183 return Sema::IncompatiblePointer; 9184 return Sema::Compatible; 9185 } 9186 if (RHSType->isObjCBuiltinType()) { 9187 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9188 !LHSType->isObjCQualifiedClassType()) 9189 return Sema::IncompatiblePointer; 9190 return Sema::Compatible; 9191 } 9192 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9193 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9194 9195 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9196 // make an exception for id<P> 9197 !LHSType->isObjCQualifiedIdType()) 9198 return Sema::CompatiblePointerDiscardsQualifiers; 9199 9200 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9201 return Sema::Compatible; 9202 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9203 return Sema::IncompatibleObjCQualifiedId; 9204 return Sema::IncompatiblePointer; 9205 } 9206 9207 Sema::AssignConvertType 9208 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9209 QualType LHSType, QualType RHSType) { 9210 // Fake up an opaque expression. We don't actually care about what 9211 // cast operations are required, so if CheckAssignmentConstraints 9212 // adds casts to this they'll be wasted, but fortunately that doesn't 9213 // usually happen on valid code. 9214 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9215 ExprResult RHSPtr = &RHSExpr; 9216 CastKind K; 9217 9218 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9219 } 9220 9221 /// This helper function returns true if QT is a vector type that has element 9222 /// type ElementType. 9223 static bool isVector(QualType QT, QualType ElementType) { 9224 if (const VectorType *VT = QT->getAs<VectorType>()) 9225 return VT->getElementType().getCanonicalType() == ElementType; 9226 return false; 9227 } 9228 9229 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9230 /// has code to accommodate several GCC extensions when type checking 9231 /// pointers. Here are some objectionable examples that GCC considers warnings: 9232 /// 9233 /// int a, *pint; 9234 /// short *pshort; 9235 /// struct foo *pfoo; 9236 /// 9237 /// pint = pshort; // warning: assignment from incompatible pointer type 9238 /// a = pint; // warning: assignment makes integer from pointer without a cast 9239 /// pint = a; // warning: assignment makes pointer from integer without a cast 9240 /// pint = pfoo; // warning: assignment from incompatible pointer type 9241 /// 9242 /// As a result, the code for dealing with pointers is more complex than the 9243 /// C99 spec dictates. 9244 /// 9245 /// Sets 'Kind' for any result kind except Incompatible. 9246 Sema::AssignConvertType 9247 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9248 CastKind &Kind, bool ConvertRHS) { 9249 QualType RHSType = RHS.get()->getType(); 9250 QualType OrigLHSType = LHSType; 9251 9252 // Get canonical types. We're not formatting these types, just comparing 9253 // them. 9254 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9255 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9256 9257 // Common case: no conversion required. 9258 if (LHSType == RHSType) { 9259 Kind = CK_NoOp; 9260 return Compatible; 9261 } 9262 9263 // If we have an atomic type, try a non-atomic assignment, then just add an 9264 // atomic qualification step. 9265 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9266 Sema::AssignConvertType result = 9267 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9268 if (result != Compatible) 9269 return result; 9270 if (Kind != CK_NoOp && ConvertRHS) 9271 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9272 Kind = CK_NonAtomicToAtomic; 9273 return Compatible; 9274 } 9275 9276 // If the left-hand side is a reference type, then we are in a 9277 // (rare!) case where we've allowed the use of references in C, 9278 // e.g., as a parameter type in a built-in function. In this case, 9279 // just make sure that the type referenced is compatible with the 9280 // right-hand side type. The caller is responsible for adjusting 9281 // LHSType so that the resulting expression does not have reference 9282 // type. 9283 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9284 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9285 Kind = CK_LValueBitCast; 9286 return Compatible; 9287 } 9288 return Incompatible; 9289 } 9290 9291 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9292 // to the same ExtVector type. 9293 if (LHSType->isExtVectorType()) { 9294 if (RHSType->isExtVectorType()) 9295 return Incompatible; 9296 if (RHSType->isArithmeticType()) { 9297 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9298 if (ConvertRHS) 9299 RHS = prepareVectorSplat(LHSType, RHS.get()); 9300 Kind = CK_VectorSplat; 9301 return Compatible; 9302 } 9303 } 9304 9305 // Conversions to or from vector type. 9306 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9307 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9308 // Allow assignments of an AltiVec vector type to an equivalent GCC 9309 // vector type and vice versa 9310 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9311 Kind = CK_BitCast; 9312 return Compatible; 9313 } 9314 9315 // If we are allowing lax vector conversions, and LHS and RHS are both 9316 // vectors, the total size only needs to be the same. This is a bitcast; 9317 // no bits are changed but the result type is different. 9318 if (isLaxVectorConversion(RHSType, LHSType)) { 9319 Kind = CK_BitCast; 9320 return IncompatibleVectors; 9321 } 9322 } 9323 9324 // When the RHS comes from another lax conversion (e.g. binops between 9325 // scalars and vectors) the result is canonicalized as a vector. When the 9326 // LHS is also a vector, the lax is allowed by the condition above. Handle 9327 // the case where LHS is a scalar. 9328 if (LHSType->isScalarType()) { 9329 const VectorType *VecType = RHSType->getAs<VectorType>(); 9330 if (VecType && VecType->getNumElements() == 1 && 9331 isLaxVectorConversion(RHSType, LHSType)) { 9332 ExprResult *VecExpr = &RHS; 9333 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9334 Kind = CK_BitCast; 9335 return Compatible; 9336 } 9337 } 9338 9339 // Allow assignments between fixed-length and sizeless SVE vectors. 9340 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9341 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9342 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9343 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9344 Kind = CK_BitCast; 9345 return Compatible; 9346 } 9347 9348 return Incompatible; 9349 } 9350 9351 // Diagnose attempts to convert between __float128 and long double where 9352 // such conversions currently can't be handled. 9353 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9354 return Incompatible; 9355 9356 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9357 // discards the imaginary part. 9358 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9359 !LHSType->getAs<ComplexType>()) 9360 return Incompatible; 9361 9362 // Arithmetic conversions. 9363 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9364 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9365 if (ConvertRHS) 9366 Kind = PrepareScalarCast(RHS, LHSType); 9367 return Compatible; 9368 } 9369 9370 // Conversions to normal pointers. 9371 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9372 // U* -> T* 9373 if (isa<PointerType>(RHSType)) { 9374 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9375 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9376 if (AddrSpaceL != AddrSpaceR) 9377 Kind = CK_AddressSpaceConversion; 9378 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9379 Kind = CK_NoOp; 9380 else 9381 Kind = CK_BitCast; 9382 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9383 } 9384 9385 // int -> T* 9386 if (RHSType->isIntegerType()) { 9387 Kind = CK_IntegralToPointer; // FIXME: null? 9388 return IntToPointer; 9389 } 9390 9391 // C pointers are not compatible with ObjC object pointers, 9392 // with two exceptions: 9393 if (isa<ObjCObjectPointerType>(RHSType)) { 9394 // - conversions to void* 9395 if (LHSPointer->getPointeeType()->isVoidType()) { 9396 Kind = CK_BitCast; 9397 return Compatible; 9398 } 9399 9400 // - conversions from 'Class' to the redefinition type 9401 if (RHSType->isObjCClassType() && 9402 Context.hasSameType(LHSType, 9403 Context.getObjCClassRedefinitionType())) { 9404 Kind = CK_BitCast; 9405 return Compatible; 9406 } 9407 9408 Kind = CK_BitCast; 9409 return IncompatiblePointer; 9410 } 9411 9412 // U^ -> void* 9413 if (RHSType->getAs<BlockPointerType>()) { 9414 if (LHSPointer->getPointeeType()->isVoidType()) { 9415 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9416 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9417 ->getPointeeType() 9418 .getAddressSpace(); 9419 Kind = 9420 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9421 return Compatible; 9422 } 9423 } 9424 9425 return Incompatible; 9426 } 9427 9428 // Conversions to block pointers. 9429 if (isa<BlockPointerType>(LHSType)) { 9430 // U^ -> T^ 9431 if (RHSType->isBlockPointerType()) { 9432 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9433 ->getPointeeType() 9434 .getAddressSpace(); 9435 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9436 ->getPointeeType() 9437 .getAddressSpace(); 9438 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9439 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9440 } 9441 9442 // int or null -> T^ 9443 if (RHSType->isIntegerType()) { 9444 Kind = CK_IntegralToPointer; // FIXME: null 9445 return IntToBlockPointer; 9446 } 9447 9448 // id -> T^ 9449 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9450 Kind = CK_AnyPointerToBlockPointerCast; 9451 return Compatible; 9452 } 9453 9454 // void* -> T^ 9455 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9456 if (RHSPT->getPointeeType()->isVoidType()) { 9457 Kind = CK_AnyPointerToBlockPointerCast; 9458 return Compatible; 9459 } 9460 9461 return Incompatible; 9462 } 9463 9464 // Conversions to Objective-C pointers. 9465 if (isa<ObjCObjectPointerType>(LHSType)) { 9466 // A* -> B* 9467 if (RHSType->isObjCObjectPointerType()) { 9468 Kind = CK_BitCast; 9469 Sema::AssignConvertType result = 9470 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9471 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9472 result == Compatible && 9473 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9474 result = IncompatibleObjCWeakRef; 9475 return result; 9476 } 9477 9478 // int or null -> A* 9479 if (RHSType->isIntegerType()) { 9480 Kind = CK_IntegralToPointer; // FIXME: null 9481 return IntToPointer; 9482 } 9483 9484 // In general, C pointers are not compatible with ObjC object pointers, 9485 // with two exceptions: 9486 if (isa<PointerType>(RHSType)) { 9487 Kind = CK_CPointerToObjCPointerCast; 9488 9489 // - conversions from 'void*' 9490 if (RHSType->isVoidPointerType()) { 9491 return Compatible; 9492 } 9493 9494 // - conversions to 'Class' from its redefinition type 9495 if (LHSType->isObjCClassType() && 9496 Context.hasSameType(RHSType, 9497 Context.getObjCClassRedefinitionType())) { 9498 return Compatible; 9499 } 9500 9501 return IncompatiblePointer; 9502 } 9503 9504 // Only under strict condition T^ is compatible with an Objective-C pointer. 9505 if (RHSType->isBlockPointerType() && 9506 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9507 if (ConvertRHS) 9508 maybeExtendBlockObject(RHS); 9509 Kind = CK_BlockPointerToObjCPointerCast; 9510 return Compatible; 9511 } 9512 9513 return Incompatible; 9514 } 9515 9516 // Conversions from pointers that are not covered by the above. 9517 if (isa<PointerType>(RHSType)) { 9518 // T* -> _Bool 9519 if (LHSType == Context.BoolTy) { 9520 Kind = CK_PointerToBoolean; 9521 return Compatible; 9522 } 9523 9524 // T* -> int 9525 if (LHSType->isIntegerType()) { 9526 Kind = CK_PointerToIntegral; 9527 return PointerToInt; 9528 } 9529 9530 return Incompatible; 9531 } 9532 9533 // Conversions from Objective-C pointers that are not covered by the above. 9534 if (isa<ObjCObjectPointerType>(RHSType)) { 9535 // T* -> _Bool 9536 if (LHSType == Context.BoolTy) { 9537 Kind = CK_PointerToBoolean; 9538 return Compatible; 9539 } 9540 9541 // T* -> int 9542 if (LHSType->isIntegerType()) { 9543 Kind = CK_PointerToIntegral; 9544 return PointerToInt; 9545 } 9546 9547 return Incompatible; 9548 } 9549 9550 // struct A -> struct B 9551 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9552 if (Context.typesAreCompatible(LHSType, RHSType)) { 9553 Kind = CK_NoOp; 9554 return Compatible; 9555 } 9556 } 9557 9558 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9559 Kind = CK_IntToOCLSampler; 9560 return Compatible; 9561 } 9562 9563 return Incompatible; 9564 } 9565 9566 /// Constructs a transparent union from an expression that is 9567 /// used to initialize the transparent union. 9568 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9569 ExprResult &EResult, QualType UnionType, 9570 FieldDecl *Field) { 9571 // Build an initializer list that designates the appropriate member 9572 // of the transparent union. 9573 Expr *E = EResult.get(); 9574 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9575 E, SourceLocation()); 9576 Initializer->setType(UnionType); 9577 Initializer->setInitializedFieldInUnion(Field); 9578 9579 // Build a compound literal constructing a value of the transparent 9580 // union type from this initializer list. 9581 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9582 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9583 VK_PRValue, Initializer, false); 9584 } 9585 9586 Sema::AssignConvertType 9587 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9588 ExprResult &RHS) { 9589 QualType RHSType = RHS.get()->getType(); 9590 9591 // If the ArgType is a Union type, we want to handle a potential 9592 // transparent_union GCC extension. 9593 const RecordType *UT = ArgType->getAsUnionType(); 9594 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9595 return Incompatible; 9596 9597 // The field to initialize within the transparent union. 9598 RecordDecl *UD = UT->getDecl(); 9599 FieldDecl *InitField = nullptr; 9600 // It's compatible if the expression matches any of the fields. 9601 for (auto *it : UD->fields()) { 9602 if (it->getType()->isPointerType()) { 9603 // If the transparent union contains a pointer type, we allow: 9604 // 1) void pointer 9605 // 2) null pointer constant 9606 if (RHSType->isPointerType()) 9607 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9608 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9609 InitField = it; 9610 break; 9611 } 9612 9613 if (RHS.get()->isNullPointerConstant(Context, 9614 Expr::NPC_ValueDependentIsNull)) { 9615 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9616 CK_NullToPointer); 9617 InitField = it; 9618 break; 9619 } 9620 } 9621 9622 CastKind Kind; 9623 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9624 == Compatible) { 9625 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9626 InitField = it; 9627 break; 9628 } 9629 } 9630 9631 if (!InitField) 9632 return Incompatible; 9633 9634 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9635 return Compatible; 9636 } 9637 9638 Sema::AssignConvertType 9639 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9640 bool Diagnose, 9641 bool DiagnoseCFAudited, 9642 bool ConvertRHS) { 9643 // We need to be able to tell the caller whether we diagnosed a problem, if 9644 // they ask us to issue diagnostics. 9645 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9646 9647 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9648 // we can't avoid *all* modifications at the moment, so we need some somewhere 9649 // to put the updated value. 9650 ExprResult LocalRHS = CallerRHS; 9651 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9652 9653 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9654 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9655 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9656 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9657 Diag(RHS.get()->getExprLoc(), 9658 diag::warn_noderef_to_dereferenceable_pointer) 9659 << RHS.get()->getSourceRange(); 9660 } 9661 } 9662 } 9663 9664 if (getLangOpts().CPlusPlus) { 9665 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9666 // C++ 5.17p3: If the left operand is not of class type, the 9667 // expression is implicitly converted (C++ 4) to the 9668 // cv-unqualified type of the left operand. 9669 QualType RHSType = RHS.get()->getType(); 9670 if (Diagnose) { 9671 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9672 AA_Assigning); 9673 } else { 9674 ImplicitConversionSequence ICS = 9675 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9676 /*SuppressUserConversions=*/false, 9677 AllowedExplicit::None, 9678 /*InOverloadResolution=*/false, 9679 /*CStyle=*/false, 9680 /*AllowObjCWritebackConversion=*/false); 9681 if (ICS.isFailure()) 9682 return Incompatible; 9683 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9684 ICS, AA_Assigning); 9685 } 9686 if (RHS.isInvalid()) 9687 return Incompatible; 9688 Sema::AssignConvertType result = Compatible; 9689 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9690 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9691 result = IncompatibleObjCWeakRef; 9692 return result; 9693 } 9694 9695 // FIXME: Currently, we fall through and treat C++ classes like C 9696 // structures. 9697 // FIXME: We also fall through for atomics; not sure what should 9698 // happen there, though. 9699 } else if (RHS.get()->getType() == Context.OverloadTy) { 9700 // As a set of extensions to C, we support overloading on functions. These 9701 // functions need to be resolved here. 9702 DeclAccessPair DAP; 9703 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9704 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9705 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9706 else 9707 return Incompatible; 9708 } 9709 9710 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9711 // a null pointer constant. 9712 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9713 LHSType->isBlockPointerType()) && 9714 RHS.get()->isNullPointerConstant(Context, 9715 Expr::NPC_ValueDependentIsNull)) { 9716 if (Diagnose || ConvertRHS) { 9717 CastKind Kind; 9718 CXXCastPath Path; 9719 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9720 /*IgnoreBaseAccess=*/false, Diagnose); 9721 if (ConvertRHS) 9722 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 9723 } 9724 return Compatible; 9725 } 9726 9727 // OpenCL queue_t type assignment. 9728 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9729 Context, Expr::NPC_ValueDependentIsNull)) { 9730 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9731 return Compatible; 9732 } 9733 9734 // This check seems unnatural, however it is necessary to ensure the proper 9735 // conversion of functions/arrays. If the conversion were done for all 9736 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9737 // expressions that suppress this implicit conversion (&, sizeof). 9738 // 9739 // Suppress this for references: C++ 8.5.3p5. 9740 if (!LHSType->isReferenceType()) { 9741 // FIXME: We potentially allocate here even if ConvertRHS is false. 9742 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9743 if (RHS.isInvalid()) 9744 return Incompatible; 9745 } 9746 CastKind Kind; 9747 Sema::AssignConvertType result = 9748 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9749 9750 // C99 6.5.16.1p2: The value of the right operand is converted to the 9751 // type of the assignment expression. 9752 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9753 // so that we can use references in built-in functions even in C. 9754 // The getNonReferenceType() call makes sure that the resulting expression 9755 // does not have reference type. 9756 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9757 QualType Ty = LHSType.getNonLValueExprType(Context); 9758 Expr *E = RHS.get(); 9759 9760 // Check for various Objective-C errors. If we are not reporting 9761 // diagnostics and just checking for errors, e.g., during overload 9762 // resolution, return Incompatible to indicate the failure. 9763 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9764 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9765 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9766 if (!Diagnose) 9767 return Incompatible; 9768 } 9769 if (getLangOpts().ObjC && 9770 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9771 E->getType(), E, Diagnose) || 9772 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9773 if (!Diagnose) 9774 return Incompatible; 9775 // Replace the expression with a corrected version and continue so we 9776 // can find further errors. 9777 RHS = E; 9778 return Compatible; 9779 } 9780 9781 if (ConvertRHS) 9782 RHS = ImpCastExprToType(E, Ty, Kind); 9783 } 9784 9785 return result; 9786 } 9787 9788 namespace { 9789 /// The original operand to an operator, prior to the application of the usual 9790 /// arithmetic conversions and converting the arguments of a builtin operator 9791 /// candidate. 9792 struct OriginalOperand { 9793 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9794 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9795 Op = MTE->getSubExpr(); 9796 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9797 Op = BTE->getSubExpr(); 9798 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9799 Orig = ICE->getSubExprAsWritten(); 9800 Conversion = ICE->getConversionFunction(); 9801 } 9802 } 9803 9804 QualType getType() const { return Orig->getType(); } 9805 9806 Expr *Orig; 9807 NamedDecl *Conversion; 9808 }; 9809 } 9810 9811 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9812 ExprResult &RHS) { 9813 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9814 9815 Diag(Loc, diag::err_typecheck_invalid_operands) 9816 << OrigLHS.getType() << OrigRHS.getType() 9817 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9818 9819 // If a user-defined conversion was applied to either of the operands prior 9820 // to applying the built-in operator rules, tell the user about it. 9821 if (OrigLHS.Conversion) { 9822 Diag(OrigLHS.Conversion->getLocation(), 9823 diag::note_typecheck_invalid_operands_converted) 9824 << 0 << LHS.get()->getType(); 9825 } 9826 if (OrigRHS.Conversion) { 9827 Diag(OrigRHS.Conversion->getLocation(), 9828 diag::note_typecheck_invalid_operands_converted) 9829 << 1 << RHS.get()->getType(); 9830 } 9831 9832 return QualType(); 9833 } 9834 9835 // Diagnose cases where a scalar was implicitly converted to a vector and 9836 // diagnose the underlying types. Otherwise, diagnose the error 9837 // as invalid vector logical operands for non-C++ cases. 9838 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9839 ExprResult &RHS) { 9840 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9841 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9842 9843 bool LHSNatVec = LHSType->isVectorType(); 9844 bool RHSNatVec = RHSType->isVectorType(); 9845 9846 if (!(LHSNatVec && RHSNatVec)) { 9847 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9848 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9849 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9850 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9851 << Vector->getSourceRange(); 9852 return QualType(); 9853 } 9854 9855 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9856 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9857 << RHS.get()->getSourceRange(); 9858 9859 return QualType(); 9860 } 9861 9862 /// Try to convert a value of non-vector type to a vector type by converting 9863 /// the type to the element type of the vector and then performing a splat. 9864 /// If the language is OpenCL, we only use conversions that promote scalar 9865 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9866 /// for float->int. 9867 /// 9868 /// OpenCL V2.0 6.2.6.p2: 9869 /// An error shall occur if any scalar operand type has greater rank 9870 /// than the type of the vector element. 9871 /// 9872 /// \param scalar - if non-null, actually perform the conversions 9873 /// \return true if the operation fails (but without diagnosing the failure) 9874 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9875 QualType scalarTy, 9876 QualType vectorEltTy, 9877 QualType vectorTy, 9878 unsigned &DiagID) { 9879 // The conversion to apply to the scalar before splatting it, 9880 // if necessary. 9881 CastKind scalarCast = CK_NoOp; 9882 9883 if (vectorEltTy->isIntegralType(S.Context)) { 9884 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9885 (scalarTy->isIntegerType() && 9886 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9887 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9888 return true; 9889 } 9890 if (!scalarTy->isIntegralType(S.Context)) 9891 return true; 9892 scalarCast = CK_IntegralCast; 9893 } else if (vectorEltTy->isRealFloatingType()) { 9894 if (scalarTy->isRealFloatingType()) { 9895 if (S.getLangOpts().OpenCL && 9896 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9897 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9898 return true; 9899 } 9900 scalarCast = CK_FloatingCast; 9901 } 9902 else if (scalarTy->isIntegralType(S.Context)) 9903 scalarCast = CK_IntegralToFloating; 9904 else 9905 return true; 9906 } else { 9907 return true; 9908 } 9909 9910 // Adjust scalar if desired. 9911 if (scalar) { 9912 if (scalarCast != CK_NoOp) 9913 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9914 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9915 } 9916 return false; 9917 } 9918 9919 /// Convert vector E to a vector with the same number of elements but different 9920 /// element type. 9921 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9922 const auto *VecTy = E->getType()->getAs<VectorType>(); 9923 assert(VecTy && "Expression E must be a vector"); 9924 QualType NewVecTy = S.Context.getVectorType(ElementType, 9925 VecTy->getNumElements(), 9926 VecTy->getVectorKind()); 9927 9928 // Look through the implicit cast. Return the subexpression if its type is 9929 // NewVecTy. 9930 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9931 if (ICE->getSubExpr()->getType() == NewVecTy) 9932 return ICE->getSubExpr(); 9933 9934 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9935 return S.ImpCastExprToType(E, NewVecTy, Cast); 9936 } 9937 9938 /// Test if a (constant) integer Int can be casted to another integer type 9939 /// IntTy without losing precision. 9940 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9941 QualType OtherIntTy) { 9942 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9943 9944 // Reject cases where the value of the Int is unknown as that would 9945 // possibly cause truncation, but accept cases where the scalar can be 9946 // demoted without loss of precision. 9947 Expr::EvalResult EVResult; 9948 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9949 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9950 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9951 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9952 9953 if (CstInt) { 9954 // If the scalar is constant and is of a higher order and has more active 9955 // bits that the vector element type, reject it. 9956 llvm::APSInt Result = EVResult.Val.getInt(); 9957 unsigned NumBits = IntSigned 9958 ? (Result.isNegative() ? Result.getMinSignedBits() 9959 : Result.getActiveBits()) 9960 : Result.getActiveBits(); 9961 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9962 return true; 9963 9964 // If the signedness of the scalar type and the vector element type 9965 // differs and the number of bits is greater than that of the vector 9966 // element reject it. 9967 return (IntSigned != OtherIntSigned && 9968 NumBits > S.Context.getIntWidth(OtherIntTy)); 9969 } 9970 9971 // Reject cases where the value of the scalar is not constant and it's 9972 // order is greater than that of the vector element type. 9973 return (Order < 0); 9974 } 9975 9976 /// Test if a (constant) integer Int can be casted to floating point type 9977 /// FloatTy without losing precision. 9978 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9979 QualType FloatTy) { 9980 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9981 9982 // Determine if the integer constant can be expressed as a floating point 9983 // number of the appropriate type. 9984 Expr::EvalResult EVResult; 9985 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9986 9987 uint64_t Bits = 0; 9988 if (CstInt) { 9989 // Reject constants that would be truncated if they were converted to 9990 // the floating point type. Test by simple to/from conversion. 9991 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9992 // could be avoided if there was a convertFromAPInt method 9993 // which could signal back if implicit truncation occurred. 9994 llvm::APSInt Result = EVResult.Val.getInt(); 9995 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9996 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9997 llvm::APFloat::rmTowardZero); 9998 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9999 !IntTy->hasSignedIntegerRepresentation()); 10000 bool Ignored = false; 10001 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10002 &Ignored); 10003 if (Result != ConvertBack) 10004 return true; 10005 } else { 10006 // Reject types that cannot be fully encoded into the mantissa of 10007 // the float. 10008 Bits = S.Context.getTypeSize(IntTy); 10009 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10010 S.Context.getFloatTypeSemantics(FloatTy)); 10011 if (Bits > FloatPrec) 10012 return true; 10013 } 10014 10015 return false; 10016 } 10017 10018 /// Attempt to convert and splat Scalar into a vector whose types matches 10019 /// Vector following GCC conversion rules. The rule is that implicit 10020 /// conversion can occur when Scalar can be casted to match Vector's element 10021 /// type without causing truncation of Scalar. 10022 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10023 ExprResult *Vector) { 10024 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10025 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10026 const VectorType *VT = VectorTy->getAs<VectorType>(); 10027 10028 assert(!isa<ExtVectorType>(VT) && 10029 "ExtVectorTypes should not be handled here!"); 10030 10031 QualType VectorEltTy = VT->getElementType(); 10032 10033 // Reject cases where the vector element type or the scalar element type are 10034 // not integral or floating point types. 10035 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10036 return true; 10037 10038 // The conversion to apply to the scalar before splatting it, 10039 // if necessary. 10040 CastKind ScalarCast = CK_NoOp; 10041 10042 // Accept cases where the vector elements are integers and the scalar is 10043 // an integer. 10044 // FIXME: Notionally if the scalar was a floating point value with a precise 10045 // integral representation, we could cast it to an appropriate integer 10046 // type and then perform the rest of the checks here. GCC will perform 10047 // this conversion in some cases as determined by the input language. 10048 // We should accept it on a language independent basis. 10049 if (VectorEltTy->isIntegralType(S.Context) && 10050 ScalarTy->isIntegralType(S.Context) && 10051 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10052 10053 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10054 return true; 10055 10056 ScalarCast = CK_IntegralCast; 10057 } else if (VectorEltTy->isIntegralType(S.Context) && 10058 ScalarTy->isRealFloatingType()) { 10059 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10060 ScalarCast = CK_FloatingToIntegral; 10061 else 10062 return true; 10063 } else if (VectorEltTy->isRealFloatingType()) { 10064 if (ScalarTy->isRealFloatingType()) { 10065 10066 // Reject cases where the scalar type is not a constant and has a higher 10067 // Order than the vector element type. 10068 llvm::APFloat Result(0.0); 10069 10070 // Determine whether this is a constant scalar. In the event that the 10071 // value is dependent (and thus cannot be evaluated by the constant 10072 // evaluator), skip the evaluation. This will then diagnose once the 10073 // expression is instantiated. 10074 bool CstScalar = Scalar->get()->isValueDependent() || 10075 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10076 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10077 if (!CstScalar && Order < 0) 10078 return true; 10079 10080 // If the scalar cannot be safely casted to the vector element type, 10081 // reject it. 10082 if (CstScalar) { 10083 bool Truncated = false; 10084 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10085 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10086 if (Truncated) 10087 return true; 10088 } 10089 10090 ScalarCast = CK_FloatingCast; 10091 } else if (ScalarTy->isIntegralType(S.Context)) { 10092 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10093 return true; 10094 10095 ScalarCast = CK_IntegralToFloating; 10096 } else 10097 return true; 10098 } else if (ScalarTy->isEnumeralType()) 10099 return true; 10100 10101 // Adjust scalar if desired. 10102 if (Scalar) { 10103 if (ScalarCast != CK_NoOp) 10104 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10105 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10106 } 10107 return false; 10108 } 10109 10110 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10111 SourceLocation Loc, bool IsCompAssign, 10112 bool AllowBothBool, 10113 bool AllowBoolConversions) { 10114 if (!IsCompAssign) { 10115 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10116 if (LHS.isInvalid()) 10117 return QualType(); 10118 } 10119 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10120 if (RHS.isInvalid()) 10121 return QualType(); 10122 10123 // For conversion purposes, we ignore any qualifiers. 10124 // For example, "const float" and "float" are equivalent. 10125 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10126 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10127 10128 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10129 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10130 assert(LHSVecType || RHSVecType); 10131 10132 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10133 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10134 return InvalidOperands(Loc, LHS, RHS); 10135 10136 // AltiVec-style "vector bool op vector bool" combinations are allowed 10137 // for some operators but not others. 10138 if (!AllowBothBool && 10139 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10140 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10141 return InvalidOperands(Loc, LHS, RHS); 10142 10143 // If the vector types are identical, return. 10144 if (Context.hasSameType(LHSType, RHSType)) 10145 return LHSType; 10146 10147 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10148 if (LHSVecType && RHSVecType && 10149 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10150 if (isa<ExtVectorType>(LHSVecType)) { 10151 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10152 return LHSType; 10153 } 10154 10155 if (!IsCompAssign) 10156 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10157 return RHSType; 10158 } 10159 10160 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10161 // can be mixed, with the result being the non-bool type. The non-bool 10162 // operand must have integer element type. 10163 if (AllowBoolConversions && LHSVecType && RHSVecType && 10164 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10165 (Context.getTypeSize(LHSVecType->getElementType()) == 10166 Context.getTypeSize(RHSVecType->getElementType()))) { 10167 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10168 LHSVecType->getElementType()->isIntegerType() && 10169 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10170 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10171 return LHSType; 10172 } 10173 if (!IsCompAssign && 10174 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10175 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10176 RHSVecType->getElementType()->isIntegerType()) { 10177 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10178 return RHSType; 10179 } 10180 } 10181 10182 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10183 // since the ambiguity can affect the ABI. 10184 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10185 const VectorType *VecType = SecondType->getAs<VectorType>(); 10186 return FirstType->isSizelessBuiltinType() && VecType && 10187 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10188 VecType->getVectorKind() == 10189 VectorType::SveFixedLengthPredicateVector); 10190 }; 10191 10192 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10193 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10194 return QualType(); 10195 } 10196 10197 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10198 // since the ambiguity can affect the ABI. 10199 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10200 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10201 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10202 10203 if (FirstVecType && SecondVecType) 10204 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10205 (SecondVecType->getVectorKind() == 10206 VectorType::SveFixedLengthDataVector || 10207 SecondVecType->getVectorKind() == 10208 VectorType::SveFixedLengthPredicateVector); 10209 10210 return FirstType->isSizelessBuiltinType() && SecondVecType && 10211 SecondVecType->getVectorKind() == VectorType::GenericVector; 10212 }; 10213 10214 if (IsSveGnuConversion(LHSType, RHSType) || 10215 IsSveGnuConversion(RHSType, LHSType)) { 10216 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10217 return QualType(); 10218 } 10219 10220 // If there's a vector type and a scalar, try to convert the scalar to 10221 // the vector element type and splat. 10222 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10223 if (!RHSVecType) { 10224 if (isa<ExtVectorType>(LHSVecType)) { 10225 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10226 LHSVecType->getElementType(), LHSType, 10227 DiagID)) 10228 return LHSType; 10229 } else { 10230 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10231 return LHSType; 10232 } 10233 } 10234 if (!LHSVecType) { 10235 if (isa<ExtVectorType>(RHSVecType)) { 10236 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10237 LHSType, RHSVecType->getElementType(), 10238 RHSType, DiagID)) 10239 return RHSType; 10240 } else { 10241 if (LHS.get()->isLValue() || 10242 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10243 return RHSType; 10244 } 10245 } 10246 10247 // FIXME: The code below also handles conversion between vectors and 10248 // non-scalars, we should break this down into fine grained specific checks 10249 // and emit proper diagnostics. 10250 QualType VecType = LHSVecType ? LHSType : RHSType; 10251 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10252 QualType OtherType = LHSVecType ? RHSType : LHSType; 10253 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10254 if (isLaxVectorConversion(OtherType, VecType)) { 10255 // If we're allowing lax vector conversions, only the total (data) size 10256 // needs to be the same. For non compound assignment, if one of the types is 10257 // scalar, the result is always the vector type. 10258 if (!IsCompAssign) { 10259 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10260 return VecType; 10261 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10262 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10263 // type. Note that this is already done by non-compound assignments in 10264 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10265 // <1 x T> -> T. The result is also a vector type. 10266 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10267 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10268 ExprResult *RHSExpr = &RHS; 10269 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10270 return VecType; 10271 } 10272 } 10273 10274 // Okay, the expression is invalid. 10275 10276 // If there's a non-vector, non-real operand, diagnose that. 10277 if ((!RHSVecType && !RHSType->isRealType()) || 10278 (!LHSVecType && !LHSType->isRealType())) { 10279 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10280 << LHSType << RHSType 10281 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10282 return QualType(); 10283 } 10284 10285 // OpenCL V1.1 6.2.6.p1: 10286 // If the operands are of more than one vector type, then an error shall 10287 // occur. Implicit conversions between vector types are not permitted, per 10288 // section 6.2.1. 10289 if (getLangOpts().OpenCL && 10290 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10291 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10292 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10293 << RHSType; 10294 return QualType(); 10295 } 10296 10297 10298 // If there is a vector type that is not a ExtVector and a scalar, we reach 10299 // this point if scalar could not be converted to the vector's element type 10300 // without truncation. 10301 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10302 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10303 QualType Scalar = LHSVecType ? RHSType : LHSType; 10304 QualType Vector = LHSVecType ? LHSType : RHSType; 10305 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10306 Diag(Loc, 10307 diag::err_typecheck_vector_not_convertable_implict_truncation) 10308 << ScalarOrVector << Scalar << Vector; 10309 10310 return QualType(); 10311 } 10312 10313 // Otherwise, use the generic diagnostic. 10314 Diag(Loc, DiagID) 10315 << LHSType << RHSType 10316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10317 return QualType(); 10318 } 10319 10320 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10321 // expression. These are mainly cases where the null pointer is used as an 10322 // integer instead of a pointer. 10323 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10324 SourceLocation Loc, bool IsCompare) { 10325 // The canonical way to check for a GNU null is with isNullPointerConstant, 10326 // but we use a bit of a hack here for speed; this is a relatively 10327 // hot path, and isNullPointerConstant is slow. 10328 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10329 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10330 10331 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10332 10333 // Avoid analyzing cases where the result will either be invalid (and 10334 // diagnosed as such) or entirely valid and not something to warn about. 10335 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10336 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10337 return; 10338 10339 // Comparison operations would not make sense with a null pointer no matter 10340 // what the other expression is. 10341 if (!IsCompare) { 10342 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10343 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10344 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10345 return; 10346 } 10347 10348 // The rest of the operations only make sense with a null pointer 10349 // if the other expression is a pointer. 10350 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10351 NonNullType->canDecayToPointerType()) 10352 return; 10353 10354 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10355 << LHSNull /* LHS is NULL */ << NonNullType 10356 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10357 } 10358 10359 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10360 SourceLocation Loc) { 10361 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10362 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10363 if (!LUE || !RUE) 10364 return; 10365 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10366 RUE->getKind() != UETT_SizeOf) 10367 return; 10368 10369 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10370 QualType LHSTy = LHSArg->getType(); 10371 QualType RHSTy; 10372 10373 if (RUE->isArgumentType()) 10374 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10375 else 10376 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10377 10378 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10379 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10380 return; 10381 10382 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10383 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10384 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10385 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10386 << LHSArgDecl; 10387 } 10388 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10389 QualType ArrayElemTy = ArrayTy->getElementType(); 10390 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10391 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10392 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10393 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10394 return; 10395 S.Diag(Loc, diag::warn_division_sizeof_array) 10396 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10397 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10398 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10399 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10400 << LHSArgDecl; 10401 } 10402 10403 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10404 } 10405 } 10406 10407 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10408 ExprResult &RHS, 10409 SourceLocation Loc, bool IsDiv) { 10410 // Check for division/remainder by zero. 10411 Expr::EvalResult RHSValue; 10412 if (!RHS.get()->isValueDependent() && 10413 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10414 RHSValue.Val.getInt() == 0) 10415 S.DiagRuntimeBehavior(Loc, RHS.get(), 10416 S.PDiag(diag::warn_remainder_division_by_zero) 10417 << IsDiv << RHS.get()->getSourceRange()); 10418 } 10419 10420 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10421 SourceLocation Loc, 10422 bool IsCompAssign, bool IsDiv) { 10423 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10424 10425 QualType LHSTy = LHS.get()->getType(); 10426 QualType RHSTy = RHS.get()->getType(); 10427 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10428 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10429 /*AllowBothBool*/getLangOpts().AltiVec, 10430 /*AllowBoolConversions*/false); 10431 if (!IsDiv && 10432 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10433 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10434 // For division, only matrix-by-scalar is supported. Other combinations with 10435 // matrix types are invalid. 10436 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10437 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10438 10439 QualType compType = UsualArithmeticConversions( 10440 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10441 if (LHS.isInvalid() || RHS.isInvalid()) 10442 return QualType(); 10443 10444 10445 if (compType.isNull() || !compType->isArithmeticType()) 10446 return InvalidOperands(Loc, LHS, RHS); 10447 if (IsDiv) { 10448 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10449 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10450 } 10451 return compType; 10452 } 10453 10454 QualType Sema::CheckRemainderOperands( 10455 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10456 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10457 10458 if (LHS.get()->getType()->isVectorType() || 10459 RHS.get()->getType()->isVectorType()) { 10460 if (LHS.get()->getType()->hasIntegerRepresentation() && 10461 RHS.get()->getType()->hasIntegerRepresentation()) 10462 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10463 /*AllowBothBool*/getLangOpts().AltiVec, 10464 /*AllowBoolConversions*/false); 10465 return InvalidOperands(Loc, LHS, RHS); 10466 } 10467 10468 QualType compType = UsualArithmeticConversions( 10469 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10470 if (LHS.isInvalid() || RHS.isInvalid()) 10471 return QualType(); 10472 10473 if (compType.isNull() || !compType->isIntegerType()) 10474 return InvalidOperands(Loc, LHS, RHS); 10475 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10476 return compType; 10477 } 10478 10479 /// Diagnose invalid arithmetic on two void pointers. 10480 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10481 Expr *LHSExpr, Expr *RHSExpr) { 10482 S.Diag(Loc, S.getLangOpts().CPlusPlus 10483 ? diag::err_typecheck_pointer_arith_void_type 10484 : diag::ext_gnu_void_ptr) 10485 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10486 << RHSExpr->getSourceRange(); 10487 } 10488 10489 /// Diagnose invalid arithmetic on a void pointer. 10490 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10491 Expr *Pointer) { 10492 S.Diag(Loc, S.getLangOpts().CPlusPlus 10493 ? diag::err_typecheck_pointer_arith_void_type 10494 : diag::ext_gnu_void_ptr) 10495 << 0 /* one pointer */ << Pointer->getSourceRange(); 10496 } 10497 10498 /// Diagnose invalid arithmetic on a null pointer. 10499 /// 10500 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10501 /// idiom, which we recognize as a GNU extension. 10502 /// 10503 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10504 Expr *Pointer, bool IsGNUIdiom) { 10505 if (IsGNUIdiom) 10506 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10507 << Pointer->getSourceRange(); 10508 else 10509 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10510 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10511 } 10512 10513 /// Diagnose invalid subraction on a null pointer. 10514 /// 10515 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 10516 Expr *Pointer, bool BothNull) { 10517 // Null - null is valid in C++ [expr.add]p7 10518 if (BothNull && S.getLangOpts().CPlusPlus) 10519 return; 10520 10521 // Is this s a macro from a system header? 10522 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 10523 return; 10524 10525 S.Diag(Loc, diag::warn_pointer_sub_null_ptr) 10526 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10527 } 10528 10529 /// Diagnose invalid arithmetic on two function pointers. 10530 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10531 Expr *LHS, Expr *RHS) { 10532 assert(LHS->getType()->isAnyPointerType()); 10533 assert(RHS->getType()->isAnyPointerType()); 10534 S.Diag(Loc, S.getLangOpts().CPlusPlus 10535 ? diag::err_typecheck_pointer_arith_function_type 10536 : diag::ext_gnu_ptr_func_arith) 10537 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10538 // We only show the second type if it differs from the first. 10539 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10540 RHS->getType()) 10541 << RHS->getType()->getPointeeType() 10542 << LHS->getSourceRange() << RHS->getSourceRange(); 10543 } 10544 10545 /// Diagnose invalid arithmetic on a function pointer. 10546 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10547 Expr *Pointer) { 10548 assert(Pointer->getType()->isAnyPointerType()); 10549 S.Diag(Loc, S.getLangOpts().CPlusPlus 10550 ? diag::err_typecheck_pointer_arith_function_type 10551 : diag::ext_gnu_ptr_func_arith) 10552 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10553 << 0 /* one pointer, so only one type */ 10554 << Pointer->getSourceRange(); 10555 } 10556 10557 /// Emit error if Operand is incomplete pointer type 10558 /// 10559 /// \returns True if pointer has incomplete type 10560 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10561 Expr *Operand) { 10562 QualType ResType = Operand->getType(); 10563 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10564 ResType = ResAtomicType->getValueType(); 10565 10566 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10567 QualType PointeeTy = ResType->getPointeeType(); 10568 return S.RequireCompleteSizedType( 10569 Loc, PointeeTy, 10570 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10571 Operand->getSourceRange()); 10572 } 10573 10574 /// Check the validity of an arithmetic pointer operand. 10575 /// 10576 /// If the operand has pointer type, this code will check for pointer types 10577 /// which are invalid in arithmetic operations. These will be diagnosed 10578 /// appropriately, including whether or not the use is supported as an 10579 /// extension. 10580 /// 10581 /// \returns True when the operand is valid to use (even if as an extension). 10582 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10583 Expr *Operand) { 10584 QualType ResType = Operand->getType(); 10585 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10586 ResType = ResAtomicType->getValueType(); 10587 10588 if (!ResType->isAnyPointerType()) return true; 10589 10590 QualType PointeeTy = ResType->getPointeeType(); 10591 if (PointeeTy->isVoidType()) { 10592 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10593 return !S.getLangOpts().CPlusPlus; 10594 } 10595 if (PointeeTy->isFunctionType()) { 10596 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10597 return !S.getLangOpts().CPlusPlus; 10598 } 10599 10600 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10601 10602 return true; 10603 } 10604 10605 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10606 /// operands. 10607 /// 10608 /// This routine will diagnose any invalid arithmetic on pointer operands much 10609 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10610 /// for emitting a single diagnostic even for operations where both LHS and RHS 10611 /// are (potentially problematic) pointers. 10612 /// 10613 /// \returns True when the operand is valid to use (even if as an extension). 10614 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10615 Expr *LHSExpr, Expr *RHSExpr) { 10616 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10617 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10618 if (!isLHSPointer && !isRHSPointer) return true; 10619 10620 QualType LHSPointeeTy, RHSPointeeTy; 10621 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10622 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10623 10624 // if both are pointers check if operation is valid wrt address spaces 10625 if (isLHSPointer && isRHSPointer) { 10626 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10627 S.Diag(Loc, 10628 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10629 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10630 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10631 return false; 10632 } 10633 } 10634 10635 // Check for arithmetic on pointers to incomplete types. 10636 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10637 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10638 if (isLHSVoidPtr || isRHSVoidPtr) { 10639 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10640 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10641 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10642 10643 return !S.getLangOpts().CPlusPlus; 10644 } 10645 10646 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10647 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10648 if (isLHSFuncPtr || isRHSFuncPtr) { 10649 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10650 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10651 RHSExpr); 10652 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10653 10654 return !S.getLangOpts().CPlusPlus; 10655 } 10656 10657 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10658 return false; 10659 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10660 return false; 10661 10662 return true; 10663 } 10664 10665 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10666 /// literal. 10667 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10668 Expr *LHSExpr, Expr *RHSExpr) { 10669 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10670 Expr* IndexExpr = RHSExpr; 10671 if (!StrExpr) { 10672 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10673 IndexExpr = LHSExpr; 10674 } 10675 10676 bool IsStringPlusInt = StrExpr && 10677 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10678 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10679 return; 10680 10681 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10682 Self.Diag(OpLoc, diag::warn_string_plus_int) 10683 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10684 10685 // Only print a fixit for "str" + int, not for int + "str". 10686 if (IndexExpr == RHSExpr) { 10687 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10688 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10689 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10690 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10691 << FixItHint::CreateInsertion(EndLoc, "]"); 10692 } else 10693 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10694 } 10695 10696 /// Emit a warning when adding a char literal to a string. 10697 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10698 Expr *LHSExpr, Expr *RHSExpr) { 10699 const Expr *StringRefExpr = LHSExpr; 10700 const CharacterLiteral *CharExpr = 10701 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10702 10703 if (!CharExpr) { 10704 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10705 StringRefExpr = RHSExpr; 10706 } 10707 10708 if (!CharExpr || !StringRefExpr) 10709 return; 10710 10711 const QualType StringType = StringRefExpr->getType(); 10712 10713 // Return if not a PointerType. 10714 if (!StringType->isAnyPointerType()) 10715 return; 10716 10717 // Return if not a CharacterType. 10718 if (!StringType->getPointeeType()->isAnyCharacterType()) 10719 return; 10720 10721 ASTContext &Ctx = Self.getASTContext(); 10722 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10723 10724 const QualType CharType = CharExpr->getType(); 10725 if (!CharType->isAnyCharacterType() && 10726 CharType->isIntegerType() && 10727 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10728 Self.Diag(OpLoc, diag::warn_string_plus_char) 10729 << DiagRange << Ctx.CharTy; 10730 } else { 10731 Self.Diag(OpLoc, diag::warn_string_plus_char) 10732 << DiagRange << CharExpr->getType(); 10733 } 10734 10735 // Only print a fixit for str + char, not for char + str. 10736 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10737 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10738 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10739 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10740 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10741 << FixItHint::CreateInsertion(EndLoc, "]"); 10742 } else { 10743 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10744 } 10745 } 10746 10747 /// Emit error when two pointers are incompatible. 10748 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10749 Expr *LHSExpr, Expr *RHSExpr) { 10750 assert(LHSExpr->getType()->isAnyPointerType()); 10751 assert(RHSExpr->getType()->isAnyPointerType()); 10752 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10753 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10754 << RHSExpr->getSourceRange(); 10755 } 10756 10757 // C99 6.5.6 10758 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10759 SourceLocation Loc, BinaryOperatorKind Opc, 10760 QualType* CompLHSTy) { 10761 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10762 10763 if (LHS.get()->getType()->isVectorType() || 10764 RHS.get()->getType()->isVectorType()) { 10765 QualType compType = CheckVectorOperands( 10766 LHS, RHS, Loc, CompLHSTy, 10767 /*AllowBothBool*/getLangOpts().AltiVec, 10768 /*AllowBoolConversions*/getLangOpts().ZVector); 10769 if (CompLHSTy) *CompLHSTy = compType; 10770 return compType; 10771 } 10772 10773 if (LHS.get()->getType()->isConstantMatrixType() || 10774 RHS.get()->getType()->isConstantMatrixType()) { 10775 QualType compType = 10776 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10777 if (CompLHSTy) 10778 *CompLHSTy = compType; 10779 return compType; 10780 } 10781 10782 QualType compType = UsualArithmeticConversions( 10783 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10784 if (LHS.isInvalid() || RHS.isInvalid()) 10785 return QualType(); 10786 10787 // Diagnose "string literal" '+' int and string '+' "char literal". 10788 if (Opc == BO_Add) { 10789 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10790 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10791 } 10792 10793 // handle the common case first (both operands are arithmetic). 10794 if (!compType.isNull() && compType->isArithmeticType()) { 10795 if (CompLHSTy) *CompLHSTy = compType; 10796 return compType; 10797 } 10798 10799 // Type-checking. Ultimately the pointer's going to be in PExp; 10800 // note that we bias towards the LHS being the pointer. 10801 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10802 10803 bool isObjCPointer; 10804 if (PExp->getType()->isPointerType()) { 10805 isObjCPointer = false; 10806 } else if (PExp->getType()->isObjCObjectPointerType()) { 10807 isObjCPointer = true; 10808 } else { 10809 std::swap(PExp, IExp); 10810 if (PExp->getType()->isPointerType()) { 10811 isObjCPointer = false; 10812 } else if (PExp->getType()->isObjCObjectPointerType()) { 10813 isObjCPointer = true; 10814 } else { 10815 return InvalidOperands(Loc, LHS, RHS); 10816 } 10817 } 10818 assert(PExp->getType()->isAnyPointerType()); 10819 10820 if (!IExp->getType()->isIntegerType()) 10821 return InvalidOperands(Loc, LHS, RHS); 10822 10823 // Adding to a null pointer results in undefined behavior. 10824 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10825 Context, Expr::NPC_ValueDependentIsNotNull)) { 10826 // In C++ adding zero to a null pointer is defined. 10827 Expr::EvalResult KnownVal; 10828 if (!getLangOpts().CPlusPlus || 10829 (!IExp->isValueDependent() && 10830 (!IExp->EvaluateAsInt(KnownVal, Context) || 10831 KnownVal.Val.getInt() != 0))) { 10832 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10833 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10834 Context, BO_Add, PExp, IExp); 10835 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10836 } 10837 } 10838 10839 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10840 return QualType(); 10841 10842 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10843 return QualType(); 10844 10845 // Check array bounds for pointer arithemtic 10846 CheckArrayAccess(PExp, IExp); 10847 10848 if (CompLHSTy) { 10849 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10850 if (LHSTy.isNull()) { 10851 LHSTy = LHS.get()->getType(); 10852 if (LHSTy->isPromotableIntegerType()) 10853 LHSTy = Context.getPromotedIntegerType(LHSTy); 10854 } 10855 *CompLHSTy = LHSTy; 10856 } 10857 10858 return PExp->getType(); 10859 } 10860 10861 // C99 6.5.6 10862 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10863 SourceLocation Loc, 10864 QualType* CompLHSTy) { 10865 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10866 10867 if (LHS.get()->getType()->isVectorType() || 10868 RHS.get()->getType()->isVectorType()) { 10869 QualType compType = CheckVectorOperands( 10870 LHS, RHS, Loc, CompLHSTy, 10871 /*AllowBothBool*/getLangOpts().AltiVec, 10872 /*AllowBoolConversions*/getLangOpts().ZVector); 10873 if (CompLHSTy) *CompLHSTy = compType; 10874 return compType; 10875 } 10876 10877 if (LHS.get()->getType()->isConstantMatrixType() || 10878 RHS.get()->getType()->isConstantMatrixType()) { 10879 QualType compType = 10880 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10881 if (CompLHSTy) 10882 *CompLHSTy = compType; 10883 return compType; 10884 } 10885 10886 QualType compType = UsualArithmeticConversions( 10887 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10888 if (LHS.isInvalid() || RHS.isInvalid()) 10889 return QualType(); 10890 10891 // Enforce type constraints: C99 6.5.6p3. 10892 10893 // Handle the common case first (both operands are arithmetic). 10894 if (!compType.isNull() && compType->isArithmeticType()) { 10895 if (CompLHSTy) *CompLHSTy = compType; 10896 return compType; 10897 } 10898 10899 // Either ptr - int or ptr - ptr. 10900 if (LHS.get()->getType()->isAnyPointerType()) { 10901 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10902 10903 // Diagnose bad cases where we step over interface counts. 10904 if (LHS.get()->getType()->isObjCObjectPointerType() && 10905 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10906 return QualType(); 10907 10908 // The result type of a pointer-int computation is the pointer type. 10909 if (RHS.get()->getType()->isIntegerType()) { 10910 // Subtracting from a null pointer should produce a warning. 10911 // The last argument to the diagnose call says this doesn't match the 10912 // GNU int-to-pointer idiom. 10913 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10914 Expr::NPC_ValueDependentIsNotNull)) { 10915 // In C++ adding zero to a null pointer is defined. 10916 Expr::EvalResult KnownVal; 10917 if (!getLangOpts().CPlusPlus || 10918 (!RHS.get()->isValueDependent() && 10919 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10920 KnownVal.Val.getInt() != 0))) { 10921 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10922 } 10923 } 10924 10925 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10926 return QualType(); 10927 10928 // Check array bounds for pointer arithemtic 10929 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10930 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10931 10932 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10933 return LHS.get()->getType(); 10934 } 10935 10936 // Handle pointer-pointer subtractions. 10937 if (const PointerType *RHSPTy 10938 = RHS.get()->getType()->getAs<PointerType>()) { 10939 QualType rpointee = RHSPTy->getPointeeType(); 10940 10941 if (getLangOpts().CPlusPlus) { 10942 // Pointee types must be the same: C++ [expr.add] 10943 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10944 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10945 } 10946 } else { 10947 // Pointee types must be compatible C99 6.5.6p3 10948 if (!Context.typesAreCompatible( 10949 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10950 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10951 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10952 return QualType(); 10953 } 10954 } 10955 10956 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10957 LHS.get(), RHS.get())) 10958 return QualType(); 10959 10960 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10961 Context, Expr::NPC_ValueDependentIsNotNull); 10962 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 10963 Context, Expr::NPC_ValueDependentIsNotNull); 10964 10965 // Subtracting nullptr or from nullptr is suspect 10966 if (LHSIsNullPtr) 10967 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 10968 if (RHSIsNullPtr) 10969 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 10970 10971 // The pointee type may have zero size. As an extension, a structure or 10972 // union may have zero size or an array may have zero length. In this 10973 // case subtraction does not make sense. 10974 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10975 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10976 if (ElementSize.isZero()) { 10977 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10978 << rpointee.getUnqualifiedType() 10979 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10980 } 10981 } 10982 10983 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10984 return Context.getPointerDiffType(); 10985 } 10986 } 10987 10988 return InvalidOperands(Loc, LHS, RHS); 10989 } 10990 10991 static bool isScopedEnumerationType(QualType T) { 10992 if (const EnumType *ET = T->getAs<EnumType>()) 10993 return ET->getDecl()->isScoped(); 10994 return false; 10995 } 10996 10997 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10998 SourceLocation Loc, BinaryOperatorKind Opc, 10999 QualType LHSType) { 11000 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11001 // so skip remaining warnings as we don't want to modify values within Sema. 11002 if (S.getLangOpts().OpenCL) 11003 return; 11004 11005 // Check right/shifter operand 11006 Expr::EvalResult RHSResult; 11007 if (RHS.get()->isValueDependent() || 11008 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11009 return; 11010 llvm::APSInt Right = RHSResult.Val.getInt(); 11011 11012 if (Right.isNegative()) { 11013 S.DiagRuntimeBehavior(Loc, RHS.get(), 11014 S.PDiag(diag::warn_shift_negative) 11015 << RHS.get()->getSourceRange()); 11016 return; 11017 } 11018 11019 QualType LHSExprType = LHS.get()->getType(); 11020 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11021 if (LHSExprType->isExtIntType()) 11022 LeftSize = S.Context.getIntWidth(LHSExprType); 11023 else if (LHSExprType->isFixedPointType()) { 11024 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11025 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11026 } 11027 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11028 if (Right.uge(LeftBits)) { 11029 S.DiagRuntimeBehavior(Loc, RHS.get(), 11030 S.PDiag(diag::warn_shift_gt_typewidth) 11031 << RHS.get()->getSourceRange()); 11032 return; 11033 } 11034 11035 // FIXME: We probably need to handle fixed point types specially here. 11036 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11037 return; 11038 11039 // When left shifting an ICE which is signed, we can check for overflow which 11040 // according to C++ standards prior to C++2a has undefined behavior 11041 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11042 // more than the maximum value representable in the result type, so never 11043 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11044 // expression is still probably a bug.) 11045 Expr::EvalResult LHSResult; 11046 if (LHS.get()->isValueDependent() || 11047 LHSType->hasUnsignedIntegerRepresentation() || 11048 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11049 return; 11050 llvm::APSInt Left = LHSResult.Val.getInt(); 11051 11052 // If LHS does not have a signed type and non-negative value 11053 // then, the behavior is undefined before C++2a. Warn about it. 11054 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 11055 !S.getLangOpts().CPlusPlus20) { 11056 S.DiagRuntimeBehavior(Loc, LHS.get(), 11057 S.PDiag(diag::warn_shift_lhs_negative) 11058 << LHS.get()->getSourceRange()); 11059 return; 11060 } 11061 11062 llvm::APInt ResultBits = 11063 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11064 if (LeftBits.uge(ResultBits)) 11065 return; 11066 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11067 Result = Result.shl(Right); 11068 11069 // Print the bit representation of the signed integer as an unsigned 11070 // hexadecimal number. 11071 SmallString<40> HexResult; 11072 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11073 11074 // If we are only missing a sign bit, this is less likely to result in actual 11075 // bugs -- if the result is cast back to an unsigned type, it will have the 11076 // expected value. Thus we place this behind a different warning that can be 11077 // turned off separately if needed. 11078 if (LeftBits == ResultBits - 1) { 11079 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11080 << HexResult << LHSType 11081 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11082 return; 11083 } 11084 11085 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11086 << HexResult.str() << Result.getMinSignedBits() << LHSType 11087 << Left.getBitWidth() << LHS.get()->getSourceRange() 11088 << RHS.get()->getSourceRange(); 11089 } 11090 11091 /// Return the resulting type when a vector is shifted 11092 /// by a scalar or vector shift amount. 11093 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11094 SourceLocation Loc, bool IsCompAssign) { 11095 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11096 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11097 !LHS.get()->getType()->isVectorType()) { 11098 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11099 << RHS.get()->getType() << LHS.get()->getType() 11100 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11101 return QualType(); 11102 } 11103 11104 if (!IsCompAssign) { 11105 LHS = S.UsualUnaryConversions(LHS.get()); 11106 if (LHS.isInvalid()) return QualType(); 11107 } 11108 11109 RHS = S.UsualUnaryConversions(RHS.get()); 11110 if (RHS.isInvalid()) return QualType(); 11111 11112 QualType LHSType = LHS.get()->getType(); 11113 // Note that LHS might be a scalar because the routine calls not only in 11114 // OpenCL case. 11115 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11116 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11117 11118 // Note that RHS might not be a vector. 11119 QualType RHSType = RHS.get()->getType(); 11120 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11121 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11122 11123 // The operands need to be integers. 11124 if (!LHSEleType->isIntegerType()) { 11125 S.Diag(Loc, diag::err_typecheck_expect_int) 11126 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11127 return QualType(); 11128 } 11129 11130 if (!RHSEleType->isIntegerType()) { 11131 S.Diag(Loc, diag::err_typecheck_expect_int) 11132 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11133 return QualType(); 11134 } 11135 11136 if (!LHSVecTy) { 11137 assert(RHSVecTy); 11138 if (IsCompAssign) 11139 return RHSType; 11140 if (LHSEleType != RHSEleType) { 11141 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11142 LHSEleType = RHSEleType; 11143 } 11144 QualType VecTy = 11145 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11146 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11147 LHSType = VecTy; 11148 } else if (RHSVecTy) { 11149 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11150 // are applied component-wise. So if RHS is a vector, then ensure 11151 // that the number of elements is the same as LHS... 11152 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11153 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11154 << LHS.get()->getType() << RHS.get()->getType() 11155 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11156 return QualType(); 11157 } 11158 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11159 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11160 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11161 if (LHSBT != RHSBT && 11162 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11163 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11164 << LHS.get()->getType() << RHS.get()->getType() 11165 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11166 } 11167 } 11168 } else { 11169 // ...else expand RHS to match the number of elements in LHS. 11170 QualType VecTy = 11171 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11172 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11173 } 11174 11175 return LHSType; 11176 } 11177 11178 // C99 6.5.7 11179 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11180 SourceLocation Loc, BinaryOperatorKind Opc, 11181 bool IsCompAssign) { 11182 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11183 11184 // Vector shifts promote their scalar inputs to vector type. 11185 if (LHS.get()->getType()->isVectorType() || 11186 RHS.get()->getType()->isVectorType()) { 11187 if (LangOpts.ZVector) { 11188 // The shift operators for the z vector extensions work basically 11189 // like general shifts, except that neither the LHS nor the RHS is 11190 // allowed to be a "vector bool". 11191 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11192 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11193 return InvalidOperands(Loc, LHS, RHS); 11194 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11195 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11196 return InvalidOperands(Loc, LHS, RHS); 11197 } 11198 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11199 } 11200 11201 // Shifts don't perform usual arithmetic conversions, they just do integer 11202 // promotions on each operand. C99 6.5.7p3 11203 11204 // For the LHS, do usual unary conversions, but then reset them away 11205 // if this is a compound assignment. 11206 ExprResult OldLHS = LHS; 11207 LHS = UsualUnaryConversions(LHS.get()); 11208 if (LHS.isInvalid()) 11209 return QualType(); 11210 QualType LHSType = LHS.get()->getType(); 11211 if (IsCompAssign) LHS = OldLHS; 11212 11213 // The RHS is simpler. 11214 RHS = UsualUnaryConversions(RHS.get()); 11215 if (RHS.isInvalid()) 11216 return QualType(); 11217 QualType RHSType = RHS.get()->getType(); 11218 11219 // C99 6.5.7p2: Each of the operands shall have integer type. 11220 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11221 if ((!LHSType->isFixedPointOrIntegerType() && 11222 !LHSType->hasIntegerRepresentation()) || 11223 !RHSType->hasIntegerRepresentation()) 11224 return InvalidOperands(Loc, LHS, RHS); 11225 11226 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11227 // hasIntegerRepresentation() above instead of this. 11228 if (isScopedEnumerationType(LHSType) || 11229 isScopedEnumerationType(RHSType)) { 11230 return InvalidOperands(Loc, LHS, RHS); 11231 } 11232 // Sanity-check shift operands 11233 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11234 11235 // "The type of the result is that of the promoted left operand." 11236 return LHSType; 11237 } 11238 11239 /// Diagnose bad pointer comparisons. 11240 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11241 ExprResult &LHS, ExprResult &RHS, 11242 bool IsError) { 11243 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11244 : diag::ext_typecheck_comparison_of_distinct_pointers) 11245 << LHS.get()->getType() << RHS.get()->getType() 11246 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11247 } 11248 11249 /// Returns false if the pointers are converted to a composite type, 11250 /// true otherwise. 11251 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11252 ExprResult &LHS, ExprResult &RHS) { 11253 // C++ [expr.rel]p2: 11254 // [...] Pointer conversions (4.10) and qualification 11255 // conversions (4.4) are performed on pointer operands (or on 11256 // a pointer operand and a null pointer constant) to bring 11257 // them to their composite pointer type. [...] 11258 // 11259 // C++ [expr.eq]p1 uses the same notion for (in)equality 11260 // comparisons of pointers. 11261 11262 QualType LHSType = LHS.get()->getType(); 11263 QualType RHSType = RHS.get()->getType(); 11264 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11265 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11266 11267 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11268 if (T.isNull()) { 11269 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11270 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11271 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11272 else 11273 S.InvalidOperands(Loc, LHS, RHS); 11274 return true; 11275 } 11276 11277 return false; 11278 } 11279 11280 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11281 ExprResult &LHS, 11282 ExprResult &RHS, 11283 bool IsError) { 11284 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11285 : diag::ext_typecheck_comparison_of_fptr_to_void) 11286 << LHS.get()->getType() << RHS.get()->getType() 11287 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11288 } 11289 11290 static bool isObjCObjectLiteral(ExprResult &E) { 11291 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11292 case Stmt::ObjCArrayLiteralClass: 11293 case Stmt::ObjCDictionaryLiteralClass: 11294 case Stmt::ObjCStringLiteralClass: 11295 case Stmt::ObjCBoxedExprClass: 11296 return true; 11297 default: 11298 // Note that ObjCBoolLiteral is NOT an object literal! 11299 return false; 11300 } 11301 } 11302 11303 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11304 const ObjCObjectPointerType *Type = 11305 LHS->getType()->getAs<ObjCObjectPointerType>(); 11306 11307 // If this is not actually an Objective-C object, bail out. 11308 if (!Type) 11309 return false; 11310 11311 // Get the LHS object's interface type. 11312 QualType InterfaceType = Type->getPointeeType(); 11313 11314 // If the RHS isn't an Objective-C object, bail out. 11315 if (!RHS->getType()->isObjCObjectPointerType()) 11316 return false; 11317 11318 // Try to find the -isEqual: method. 11319 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11320 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11321 InterfaceType, 11322 /*IsInstance=*/true); 11323 if (!Method) { 11324 if (Type->isObjCIdType()) { 11325 // For 'id', just check the global pool. 11326 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11327 /*receiverId=*/true); 11328 } else { 11329 // Check protocols. 11330 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11331 /*IsInstance=*/true); 11332 } 11333 } 11334 11335 if (!Method) 11336 return false; 11337 11338 QualType T = Method->parameters()[0]->getType(); 11339 if (!T->isObjCObjectPointerType()) 11340 return false; 11341 11342 QualType R = Method->getReturnType(); 11343 if (!R->isScalarType()) 11344 return false; 11345 11346 return true; 11347 } 11348 11349 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11350 FromE = FromE->IgnoreParenImpCasts(); 11351 switch (FromE->getStmtClass()) { 11352 default: 11353 break; 11354 case Stmt::ObjCStringLiteralClass: 11355 // "string literal" 11356 return LK_String; 11357 case Stmt::ObjCArrayLiteralClass: 11358 // "array literal" 11359 return LK_Array; 11360 case Stmt::ObjCDictionaryLiteralClass: 11361 // "dictionary literal" 11362 return LK_Dictionary; 11363 case Stmt::BlockExprClass: 11364 return LK_Block; 11365 case Stmt::ObjCBoxedExprClass: { 11366 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11367 switch (Inner->getStmtClass()) { 11368 case Stmt::IntegerLiteralClass: 11369 case Stmt::FloatingLiteralClass: 11370 case Stmt::CharacterLiteralClass: 11371 case Stmt::ObjCBoolLiteralExprClass: 11372 case Stmt::CXXBoolLiteralExprClass: 11373 // "numeric literal" 11374 return LK_Numeric; 11375 case Stmt::ImplicitCastExprClass: { 11376 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11377 // Boolean literals can be represented by implicit casts. 11378 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11379 return LK_Numeric; 11380 break; 11381 } 11382 default: 11383 break; 11384 } 11385 return LK_Boxed; 11386 } 11387 } 11388 return LK_None; 11389 } 11390 11391 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11392 ExprResult &LHS, ExprResult &RHS, 11393 BinaryOperator::Opcode Opc){ 11394 Expr *Literal; 11395 Expr *Other; 11396 if (isObjCObjectLiteral(LHS)) { 11397 Literal = LHS.get(); 11398 Other = RHS.get(); 11399 } else { 11400 Literal = RHS.get(); 11401 Other = LHS.get(); 11402 } 11403 11404 // Don't warn on comparisons against nil. 11405 Other = Other->IgnoreParenCasts(); 11406 if (Other->isNullPointerConstant(S.getASTContext(), 11407 Expr::NPC_ValueDependentIsNotNull)) 11408 return; 11409 11410 // This should be kept in sync with warn_objc_literal_comparison. 11411 // LK_String should always be after the other literals, since it has its own 11412 // warning flag. 11413 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11414 assert(LiteralKind != Sema::LK_Block); 11415 if (LiteralKind == Sema::LK_None) { 11416 llvm_unreachable("Unknown Objective-C object literal kind"); 11417 } 11418 11419 if (LiteralKind == Sema::LK_String) 11420 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11421 << Literal->getSourceRange(); 11422 else 11423 S.Diag(Loc, diag::warn_objc_literal_comparison) 11424 << LiteralKind << Literal->getSourceRange(); 11425 11426 if (BinaryOperator::isEqualityOp(Opc) && 11427 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11428 SourceLocation Start = LHS.get()->getBeginLoc(); 11429 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11430 CharSourceRange OpRange = 11431 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11432 11433 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11434 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11435 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11436 << FixItHint::CreateInsertion(End, "]"); 11437 } 11438 } 11439 11440 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11441 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11442 ExprResult &RHS, SourceLocation Loc, 11443 BinaryOperatorKind Opc) { 11444 // Check that left hand side is !something. 11445 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11446 if (!UO || UO->getOpcode() != UO_LNot) return; 11447 11448 // Only check if the right hand side is non-bool arithmetic type. 11449 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11450 11451 // Make sure that the something in !something is not bool. 11452 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11453 if (SubExpr->isKnownToHaveBooleanValue()) return; 11454 11455 // Emit warning. 11456 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11457 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11458 << Loc << IsBitwiseOp; 11459 11460 // First note suggest !(x < y) 11461 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11462 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11463 FirstClose = S.getLocForEndOfToken(FirstClose); 11464 if (FirstClose.isInvalid()) 11465 FirstOpen = SourceLocation(); 11466 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11467 << IsBitwiseOp 11468 << FixItHint::CreateInsertion(FirstOpen, "(") 11469 << FixItHint::CreateInsertion(FirstClose, ")"); 11470 11471 // Second note suggests (!x) < y 11472 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11473 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11474 SecondClose = S.getLocForEndOfToken(SecondClose); 11475 if (SecondClose.isInvalid()) 11476 SecondOpen = SourceLocation(); 11477 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11478 << FixItHint::CreateInsertion(SecondOpen, "(") 11479 << FixItHint::CreateInsertion(SecondClose, ")"); 11480 } 11481 11482 // Returns true if E refers to a non-weak array. 11483 static bool checkForArray(const Expr *E) { 11484 const ValueDecl *D = nullptr; 11485 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11486 D = DR->getDecl(); 11487 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11488 if (Mem->isImplicitAccess()) 11489 D = Mem->getMemberDecl(); 11490 } 11491 if (!D) 11492 return false; 11493 return D->getType()->isArrayType() && !D->isWeak(); 11494 } 11495 11496 /// Diagnose some forms of syntactically-obvious tautological comparison. 11497 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11498 Expr *LHS, Expr *RHS, 11499 BinaryOperatorKind Opc) { 11500 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11501 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11502 11503 QualType LHSType = LHS->getType(); 11504 QualType RHSType = RHS->getType(); 11505 if (LHSType->hasFloatingRepresentation() || 11506 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11507 S.inTemplateInstantiation()) 11508 return; 11509 11510 // Comparisons between two array types are ill-formed for operator<=>, so 11511 // we shouldn't emit any additional warnings about it. 11512 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11513 return; 11514 11515 // For non-floating point types, check for self-comparisons of the form 11516 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11517 // often indicate logic errors in the program. 11518 // 11519 // NOTE: Don't warn about comparison expressions resulting from macro 11520 // expansion. Also don't warn about comparisons which are only self 11521 // comparisons within a template instantiation. The warnings should catch 11522 // obvious cases in the definition of the template anyways. The idea is to 11523 // warn when the typed comparison operator will always evaluate to the same 11524 // result. 11525 11526 // Used for indexing into %select in warn_comparison_always 11527 enum { 11528 AlwaysConstant, 11529 AlwaysTrue, 11530 AlwaysFalse, 11531 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11532 }; 11533 11534 // C++2a [depr.array.comp]: 11535 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11536 // operands of array type are deprecated. 11537 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11538 RHSStripped->getType()->isArrayType()) { 11539 S.Diag(Loc, diag::warn_depr_array_comparison) 11540 << LHS->getSourceRange() << RHS->getSourceRange() 11541 << LHSStripped->getType() << RHSStripped->getType(); 11542 // Carry on to produce the tautological comparison warning, if this 11543 // expression is potentially-evaluated, we can resolve the array to a 11544 // non-weak declaration, and so on. 11545 } 11546 11547 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11548 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11549 unsigned Result; 11550 switch (Opc) { 11551 case BO_EQ: 11552 case BO_LE: 11553 case BO_GE: 11554 Result = AlwaysTrue; 11555 break; 11556 case BO_NE: 11557 case BO_LT: 11558 case BO_GT: 11559 Result = AlwaysFalse; 11560 break; 11561 case BO_Cmp: 11562 Result = AlwaysEqual; 11563 break; 11564 default: 11565 Result = AlwaysConstant; 11566 break; 11567 } 11568 S.DiagRuntimeBehavior(Loc, nullptr, 11569 S.PDiag(diag::warn_comparison_always) 11570 << 0 /*self-comparison*/ 11571 << Result); 11572 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11573 // What is it always going to evaluate to? 11574 unsigned Result; 11575 switch (Opc) { 11576 case BO_EQ: // e.g. array1 == array2 11577 Result = AlwaysFalse; 11578 break; 11579 case BO_NE: // e.g. array1 != array2 11580 Result = AlwaysTrue; 11581 break; 11582 default: // e.g. array1 <= array2 11583 // The best we can say is 'a constant' 11584 Result = AlwaysConstant; 11585 break; 11586 } 11587 S.DiagRuntimeBehavior(Loc, nullptr, 11588 S.PDiag(diag::warn_comparison_always) 11589 << 1 /*array comparison*/ 11590 << Result); 11591 } 11592 } 11593 11594 if (isa<CastExpr>(LHSStripped)) 11595 LHSStripped = LHSStripped->IgnoreParenCasts(); 11596 if (isa<CastExpr>(RHSStripped)) 11597 RHSStripped = RHSStripped->IgnoreParenCasts(); 11598 11599 // Warn about comparisons against a string constant (unless the other 11600 // operand is null); the user probably wants string comparison function. 11601 Expr *LiteralString = nullptr; 11602 Expr *LiteralStringStripped = nullptr; 11603 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11604 !RHSStripped->isNullPointerConstant(S.Context, 11605 Expr::NPC_ValueDependentIsNull)) { 11606 LiteralString = LHS; 11607 LiteralStringStripped = LHSStripped; 11608 } else if ((isa<StringLiteral>(RHSStripped) || 11609 isa<ObjCEncodeExpr>(RHSStripped)) && 11610 !LHSStripped->isNullPointerConstant(S.Context, 11611 Expr::NPC_ValueDependentIsNull)) { 11612 LiteralString = RHS; 11613 LiteralStringStripped = RHSStripped; 11614 } 11615 11616 if (LiteralString) { 11617 S.DiagRuntimeBehavior(Loc, nullptr, 11618 S.PDiag(diag::warn_stringcompare) 11619 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11620 << LiteralString->getSourceRange()); 11621 } 11622 } 11623 11624 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11625 switch (CK) { 11626 default: { 11627 #ifndef NDEBUG 11628 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11629 << "\n"; 11630 #endif 11631 llvm_unreachable("unhandled cast kind"); 11632 } 11633 case CK_UserDefinedConversion: 11634 return ICK_Identity; 11635 case CK_LValueToRValue: 11636 return ICK_Lvalue_To_Rvalue; 11637 case CK_ArrayToPointerDecay: 11638 return ICK_Array_To_Pointer; 11639 case CK_FunctionToPointerDecay: 11640 return ICK_Function_To_Pointer; 11641 case CK_IntegralCast: 11642 return ICK_Integral_Conversion; 11643 case CK_FloatingCast: 11644 return ICK_Floating_Conversion; 11645 case CK_IntegralToFloating: 11646 case CK_FloatingToIntegral: 11647 return ICK_Floating_Integral; 11648 case CK_IntegralComplexCast: 11649 case CK_FloatingComplexCast: 11650 case CK_FloatingComplexToIntegralComplex: 11651 case CK_IntegralComplexToFloatingComplex: 11652 return ICK_Complex_Conversion; 11653 case CK_FloatingComplexToReal: 11654 case CK_FloatingRealToComplex: 11655 case CK_IntegralComplexToReal: 11656 case CK_IntegralRealToComplex: 11657 return ICK_Complex_Real; 11658 } 11659 } 11660 11661 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11662 QualType FromType, 11663 SourceLocation Loc) { 11664 // Check for a narrowing implicit conversion. 11665 StandardConversionSequence SCS; 11666 SCS.setAsIdentityConversion(); 11667 SCS.setToType(0, FromType); 11668 SCS.setToType(1, ToType); 11669 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11670 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11671 11672 APValue PreNarrowingValue; 11673 QualType PreNarrowingType; 11674 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11675 PreNarrowingType, 11676 /*IgnoreFloatToIntegralConversion*/ true)) { 11677 case NK_Dependent_Narrowing: 11678 // Implicit conversion to a narrower type, but the expression is 11679 // value-dependent so we can't tell whether it's actually narrowing. 11680 case NK_Not_Narrowing: 11681 return false; 11682 11683 case NK_Constant_Narrowing: 11684 // Implicit conversion to a narrower type, and the value is not a constant 11685 // expression. 11686 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11687 << /*Constant*/ 1 11688 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11689 return true; 11690 11691 case NK_Variable_Narrowing: 11692 // Implicit conversion to a narrower type, and the value is not a constant 11693 // expression. 11694 case NK_Type_Narrowing: 11695 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11696 << /*Constant*/ 0 << FromType << ToType; 11697 // TODO: It's not a constant expression, but what if the user intended it 11698 // to be? Can we produce notes to help them figure out why it isn't? 11699 return true; 11700 } 11701 llvm_unreachable("unhandled case in switch"); 11702 } 11703 11704 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11705 ExprResult &LHS, 11706 ExprResult &RHS, 11707 SourceLocation Loc) { 11708 QualType LHSType = LHS.get()->getType(); 11709 QualType RHSType = RHS.get()->getType(); 11710 // Dig out the original argument type and expression before implicit casts 11711 // were applied. These are the types/expressions we need to check the 11712 // [expr.spaceship] requirements against. 11713 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11714 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11715 QualType LHSStrippedType = LHSStripped.get()->getType(); 11716 QualType RHSStrippedType = RHSStripped.get()->getType(); 11717 11718 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11719 // other is not, the program is ill-formed. 11720 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11721 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11722 return QualType(); 11723 } 11724 11725 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11726 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11727 RHSStrippedType->isEnumeralType(); 11728 if (NumEnumArgs == 1) { 11729 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11730 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11731 if (OtherTy->hasFloatingRepresentation()) { 11732 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11733 return QualType(); 11734 } 11735 } 11736 if (NumEnumArgs == 2) { 11737 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11738 // type E, the operator yields the result of converting the operands 11739 // to the underlying type of E and applying <=> to the converted operands. 11740 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11741 S.InvalidOperands(Loc, LHS, RHS); 11742 return QualType(); 11743 } 11744 QualType IntType = 11745 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11746 assert(IntType->isArithmeticType()); 11747 11748 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11749 // promote the boolean type, and all other promotable integer types, to 11750 // avoid this. 11751 if (IntType->isPromotableIntegerType()) 11752 IntType = S.Context.getPromotedIntegerType(IntType); 11753 11754 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11755 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11756 LHSType = RHSType = IntType; 11757 } 11758 11759 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11760 // usual arithmetic conversions are applied to the operands. 11761 QualType Type = 11762 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11763 if (LHS.isInvalid() || RHS.isInvalid()) 11764 return QualType(); 11765 if (Type.isNull()) 11766 return S.InvalidOperands(Loc, LHS, RHS); 11767 11768 Optional<ComparisonCategoryType> CCT = 11769 getComparisonCategoryForBuiltinCmp(Type); 11770 if (!CCT) 11771 return S.InvalidOperands(Loc, LHS, RHS); 11772 11773 bool HasNarrowing = checkThreeWayNarrowingConversion( 11774 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11775 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11776 RHS.get()->getBeginLoc()); 11777 if (HasNarrowing) 11778 return QualType(); 11779 11780 assert(!Type.isNull() && "composite type for <=> has not been set"); 11781 11782 return S.CheckComparisonCategoryType( 11783 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11784 } 11785 11786 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11787 ExprResult &RHS, 11788 SourceLocation Loc, 11789 BinaryOperatorKind Opc) { 11790 if (Opc == BO_Cmp) 11791 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11792 11793 // C99 6.5.8p3 / C99 6.5.9p4 11794 QualType Type = 11795 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11796 if (LHS.isInvalid() || RHS.isInvalid()) 11797 return QualType(); 11798 if (Type.isNull()) 11799 return S.InvalidOperands(Loc, LHS, RHS); 11800 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11801 11802 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11803 return S.InvalidOperands(Loc, LHS, RHS); 11804 11805 // Check for comparisons of floating point operands using != and ==. 11806 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11807 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11808 11809 // The result of comparisons is 'bool' in C++, 'int' in C. 11810 return S.Context.getLogicalOperationType(); 11811 } 11812 11813 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11814 if (!NullE.get()->getType()->isAnyPointerType()) 11815 return; 11816 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11817 if (!E.get()->getType()->isAnyPointerType() && 11818 E.get()->isNullPointerConstant(Context, 11819 Expr::NPC_ValueDependentIsNotNull) == 11820 Expr::NPCK_ZeroExpression) { 11821 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11822 if (CL->getValue() == 0) 11823 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11824 << NullValue 11825 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11826 NullValue ? "NULL" : "(void *)0"); 11827 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11828 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11829 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11830 if (T == Context.CharTy) 11831 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11832 << NullValue 11833 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11834 NullValue ? "NULL" : "(void *)0"); 11835 } 11836 } 11837 } 11838 11839 // C99 6.5.8, C++ [expr.rel] 11840 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11841 SourceLocation Loc, 11842 BinaryOperatorKind Opc) { 11843 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11844 bool IsThreeWay = Opc == BO_Cmp; 11845 bool IsOrdered = IsRelational || IsThreeWay; 11846 auto IsAnyPointerType = [](ExprResult E) { 11847 QualType Ty = E.get()->getType(); 11848 return Ty->isPointerType() || Ty->isMemberPointerType(); 11849 }; 11850 11851 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11852 // type, array-to-pointer, ..., conversions are performed on both operands to 11853 // bring them to their composite type. 11854 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11855 // any type-related checks. 11856 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11857 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11858 if (LHS.isInvalid()) 11859 return QualType(); 11860 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11861 if (RHS.isInvalid()) 11862 return QualType(); 11863 } else { 11864 LHS = DefaultLvalueConversion(LHS.get()); 11865 if (LHS.isInvalid()) 11866 return QualType(); 11867 RHS = DefaultLvalueConversion(RHS.get()); 11868 if (RHS.isInvalid()) 11869 return QualType(); 11870 } 11871 11872 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11873 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11874 CheckPtrComparisonWithNullChar(LHS, RHS); 11875 CheckPtrComparisonWithNullChar(RHS, LHS); 11876 } 11877 11878 // Handle vector comparisons separately. 11879 if (LHS.get()->getType()->isVectorType() || 11880 RHS.get()->getType()->isVectorType()) 11881 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11882 11883 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11884 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11885 11886 QualType LHSType = LHS.get()->getType(); 11887 QualType RHSType = RHS.get()->getType(); 11888 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11889 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11890 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11891 11892 const Expr::NullPointerConstantKind LHSNullKind = 11893 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11894 const Expr::NullPointerConstantKind RHSNullKind = 11895 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11896 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11897 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11898 11899 auto computeResultTy = [&]() { 11900 if (Opc != BO_Cmp) 11901 return Context.getLogicalOperationType(); 11902 assert(getLangOpts().CPlusPlus); 11903 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11904 11905 QualType CompositeTy = LHS.get()->getType(); 11906 assert(!CompositeTy->isReferenceType()); 11907 11908 Optional<ComparisonCategoryType> CCT = 11909 getComparisonCategoryForBuiltinCmp(CompositeTy); 11910 if (!CCT) 11911 return InvalidOperands(Loc, LHS, RHS); 11912 11913 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11914 // P0946R0: Comparisons between a null pointer constant and an object 11915 // pointer result in std::strong_equality, which is ill-formed under 11916 // P1959R0. 11917 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11918 << (LHSIsNull ? LHS.get()->getSourceRange() 11919 : RHS.get()->getSourceRange()); 11920 return QualType(); 11921 } 11922 11923 return CheckComparisonCategoryType( 11924 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11925 }; 11926 11927 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11928 bool IsEquality = Opc == BO_EQ; 11929 if (RHSIsNull) 11930 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11931 RHS.get()->getSourceRange()); 11932 else 11933 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11934 LHS.get()->getSourceRange()); 11935 } 11936 11937 if (IsOrdered && LHSType->isFunctionPointerType() && 11938 RHSType->isFunctionPointerType()) { 11939 // Valid unless a relational comparison of function pointers 11940 bool IsError = Opc == BO_Cmp; 11941 auto DiagID = 11942 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 11943 : getLangOpts().CPlusPlus 11944 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 11945 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 11946 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 11947 << RHS.get()->getSourceRange(); 11948 if (IsError) 11949 return QualType(); 11950 } 11951 11952 if ((LHSType->isIntegerType() && !LHSIsNull) || 11953 (RHSType->isIntegerType() && !RHSIsNull)) { 11954 // Skip normal pointer conversion checks in this case; we have better 11955 // diagnostics for this below. 11956 } else if (getLangOpts().CPlusPlus) { 11957 // Equality comparison of a function pointer to a void pointer is invalid, 11958 // but we allow it as an extension. 11959 // FIXME: If we really want to allow this, should it be part of composite 11960 // pointer type computation so it works in conditionals too? 11961 if (!IsOrdered && 11962 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11963 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11964 // This is a gcc extension compatibility comparison. 11965 // In a SFINAE context, we treat this as a hard error to maintain 11966 // conformance with the C++ standard. 11967 diagnoseFunctionPointerToVoidComparison( 11968 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11969 11970 if (isSFINAEContext()) 11971 return QualType(); 11972 11973 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11974 return computeResultTy(); 11975 } 11976 11977 // C++ [expr.eq]p2: 11978 // If at least one operand is a pointer [...] bring them to their 11979 // composite pointer type. 11980 // C++ [expr.spaceship]p6 11981 // If at least one of the operands is of pointer type, [...] bring them 11982 // to their composite pointer type. 11983 // C++ [expr.rel]p2: 11984 // If both operands are pointers, [...] bring them to their composite 11985 // pointer type. 11986 // For <=>, the only valid non-pointer types are arrays and functions, and 11987 // we already decayed those, so this is really the same as the relational 11988 // comparison rule. 11989 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11990 (IsOrdered ? 2 : 1) && 11991 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11992 RHSType->isObjCObjectPointerType()))) { 11993 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11994 return QualType(); 11995 return computeResultTy(); 11996 } 11997 } else if (LHSType->isPointerType() && 11998 RHSType->isPointerType()) { // C99 6.5.8p2 11999 // All of the following pointer-related warnings are GCC extensions, except 12000 // when handling null pointer constants. 12001 QualType LCanPointeeTy = 12002 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12003 QualType RCanPointeeTy = 12004 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12005 12006 // C99 6.5.9p2 and C99 6.5.8p2 12007 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12008 RCanPointeeTy.getUnqualifiedType())) { 12009 if (IsRelational) { 12010 // Pointers both need to point to complete or incomplete types 12011 if ((LCanPointeeTy->isIncompleteType() != 12012 RCanPointeeTy->isIncompleteType()) && 12013 !getLangOpts().C11) { 12014 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12015 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12016 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12017 << RCanPointeeTy->isIncompleteType(); 12018 } 12019 } 12020 } else if (!IsRelational && 12021 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12022 // Valid unless comparison between non-null pointer and function pointer 12023 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12024 && !LHSIsNull && !RHSIsNull) 12025 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12026 /*isError*/false); 12027 } else { 12028 // Invalid 12029 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12030 } 12031 if (LCanPointeeTy != RCanPointeeTy) { 12032 // Treat NULL constant as a special case in OpenCL. 12033 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12034 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12035 Diag(Loc, 12036 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12037 << LHSType << RHSType << 0 /* comparison */ 12038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12039 } 12040 } 12041 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12042 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12043 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12044 : CK_BitCast; 12045 if (LHSIsNull && !RHSIsNull) 12046 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12047 else 12048 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12049 } 12050 return computeResultTy(); 12051 } 12052 12053 if (getLangOpts().CPlusPlus) { 12054 // C++ [expr.eq]p4: 12055 // Two operands of type std::nullptr_t or one operand of type 12056 // std::nullptr_t and the other a null pointer constant compare equal. 12057 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12058 if (LHSType->isNullPtrType()) { 12059 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12060 return computeResultTy(); 12061 } 12062 if (RHSType->isNullPtrType()) { 12063 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12064 return computeResultTy(); 12065 } 12066 } 12067 12068 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12069 // These aren't covered by the composite pointer type rules. 12070 if (!IsOrdered && RHSType->isNullPtrType() && 12071 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12073 return computeResultTy(); 12074 } 12075 if (!IsOrdered && LHSType->isNullPtrType() && 12076 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12077 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12078 return computeResultTy(); 12079 } 12080 12081 if (IsRelational && 12082 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12083 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12084 // HACK: Relational comparison of nullptr_t against a pointer type is 12085 // invalid per DR583, but we allow it within std::less<> and friends, 12086 // since otherwise common uses of it break. 12087 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12088 // friends to have std::nullptr_t overload candidates. 12089 DeclContext *DC = CurContext; 12090 if (isa<FunctionDecl>(DC)) 12091 DC = DC->getParent(); 12092 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12093 if (CTSD->isInStdNamespace() && 12094 llvm::StringSwitch<bool>(CTSD->getName()) 12095 .Cases("less", "less_equal", "greater", "greater_equal", true) 12096 .Default(false)) { 12097 if (RHSType->isNullPtrType()) 12098 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12099 else 12100 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12101 return computeResultTy(); 12102 } 12103 } 12104 } 12105 12106 // C++ [expr.eq]p2: 12107 // If at least one operand is a pointer to member, [...] bring them to 12108 // their composite pointer type. 12109 if (!IsOrdered && 12110 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12111 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12112 return QualType(); 12113 else 12114 return computeResultTy(); 12115 } 12116 } 12117 12118 // Handle block pointer types. 12119 if (!IsOrdered && LHSType->isBlockPointerType() && 12120 RHSType->isBlockPointerType()) { 12121 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12122 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12123 12124 if (!LHSIsNull && !RHSIsNull && 12125 !Context.typesAreCompatible(lpointee, rpointee)) { 12126 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12127 << LHSType << RHSType << LHS.get()->getSourceRange() 12128 << RHS.get()->getSourceRange(); 12129 } 12130 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12131 return computeResultTy(); 12132 } 12133 12134 // Allow block pointers to be compared with null pointer constants. 12135 if (!IsOrdered 12136 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12137 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12138 if (!LHSIsNull && !RHSIsNull) { 12139 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12140 ->getPointeeType()->isVoidType()) 12141 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12142 ->getPointeeType()->isVoidType()))) 12143 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12144 << LHSType << RHSType << LHS.get()->getSourceRange() 12145 << RHS.get()->getSourceRange(); 12146 } 12147 if (LHSIsNull && !RHSIsNull) 12148 LHS = ImpCastExprToType(LHS.get(), RHSType, 12149 RHSType->isPointerType() ? CK_BitCast 12150 : CK_AnyPointerToBlockPointerCast); 12151 else 12152 RHS = ImpCastExprToType(RHS.get(), LHSType, 12153 LHSType->isPointerType() ? CK_BitCast 12154 : CK_AnyPointerToBlockPointerCast); 12155 return computeResultTy(); 12156 } 12157 12158 if (LHSType->isObjCObjectPointerType() || 12159 RHSType->isObjCObjectPointerType()) { 12160 const PointerType *LPT = LHSType->getAs<PointerType>(); 12161 const PointerType *RPT = RHSType->getAs<PointerType>(); 12162 if (LPT || RPT) { 12163 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12164 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12165 12166 if (!LPtrToVoid && !RPtrToVoid && 12167 !Context.typesAreCompatible(LHSType, RHSType)) { 12168 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12169 /*isError*/false); 12170 } 12171 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12172 // the RHS, but we have test coverage for this behavior. 12173 // FIXME: Consider using convertPointersToCompositeType in C++. 12174 if (LHSIsNull && !RHSIsNull) { 12175 Expr *E = LHS.get(); 12176 if (getLangOpts().ObjCAutoRefCount) 12177 CheckObjCConversion(SourceRange(), RHSType, E, 12178 CCK_ImplicitConversion); 12179 LHS = ImpCastExprToType(E, RHSType, 12180 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12181 } 12182 else { 12183 Expr *E = RHS.get(); 12184 if (getLangOpts().ObjCAutoRefCount) 12185 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12186 /*Diagnose=*/true, 12187 /*DiagnoseCFAudited=*/false, Opc); 12188 RHS = ImpCastExprToType(E, LHSType, 12189 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12190 } 12191 return computeResultTy(); 12192 } 12193 if (LHSType->isObjCObjectPointerType() && 12194 RHSType->isObjCObjectPointerType()) { 12195 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 12196 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12197 /*isError*/false); 12198 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12199 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12200 12201 if (LHSIsNull && !RHSIsNull) 12202 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12203 else 12204 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12205 return computeResultTy(); 12206 } 12207 12208 if (!IsOrdered && LHSType->isBlockPointerType() && 12209 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12210 LHS = ImpCastExprToType(LHS.get(), RHSType, 12211 CK_BlockPointerToObjCPointerCast); 12212 return computeResultTy(); 12213 } else if (!IsOrdered && 12214 LHSType->isBlockCompatibleObjCPointerType(Context) && 12215 RHSType->isBlockPointerType()) { 12216 RHS = ImpCastExprToType(RHS.get(), LHSType, 12217 CK_BlockPointerToObjCPointerCast); 12218 return computeResultTy(); 12219 } 12220 } 12221 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12222 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12223 unsigned DiagID = 0; 12224 bool isError = false; 12225 if (LangOpts.DebuggerSupport) { 12226 // Under a debugger, allow the comparison of pointers to integers, 12227 // since users tend to want to compare addresses. 12228 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12229 (RHSIsNull && RHSType->isIntegerType())) { 12230 if (IsOrdered) { 12231 isError = getLangOpts().CPlusPlus; 12232 DiagID = 12233 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12234 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12235 } 12236 } else if (getLangOpts().CPlusPlus) { 12237 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12238 isError = true; 12239 } else if (IsOrdered) 12240 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12241 else 12242 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12243 12244 if (DiagID) { 12245 Diag(Loc, DiagID) 12246 << LHSType << RHSType << LHS.get()->getSourceRange() 12247 << RHS.get()->getSourceRange(); 12248 if (isError) 12249 return QualType(); 12250 } 12251 12252 if (LHSType->isIntegerType()) 12253 LHS = ImpCastExprToType(LHS.get(), RHSType, 12254 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12255 else 12256 RHS = ImpCastExprToType(RHS.get(), LHSType, 12257 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12258 return computeResultTy(); 12259 } 12260 12261 // Handle block pointers. 12262 if (!IsOrdered && RHSIsNull 12263 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12264 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12265 return computeResultTy(); 12266 } 12267 if (!IsOrdered && LHSIsNull 12268 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12269 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12270 return computeResultTy(); 12271 } 12272 12273 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12274 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12275 return computeResultTy(); 12276 } 12277 12278 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12279 return computeResultTy(); 12280 } 12281 12282 if (LHSIsNull && RHSType->isQueueT()) { 12283 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12284 return computeResultTy(); 12285 } 12286 12287 if (LHSType->isQueueT() && RHSIsNull) { 12288 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12289 return computeResultTy(); 12290 } 12291 } 12292 12293 return InvalidOperands(Loc, LHS, RHS); 12294 } 12295 12296 // Return a signed ext_vector_type that is of identical size and number of 12297 // elements. For floating point vectors, return an integer type of identical 12298 // size and number of elements. In the non ext_vector_type case, search from 12299 // the largest type to the smallest type to avoid cases where long long == long, 12300 // where long gets picked over long long. 12301 QualType Sema::GetSignedVectorType(QualType V) { 12302 const VectorType *VTy = V->castAs<VectorType>(); 12303 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12304 12305 if (isa<ExtVectorType>(VTy)) { 12306 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12307 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12308 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12309 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12310 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12311 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12312 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12313 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12314 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12315 "Unhandled vector element size in vector compare"); 12316 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12317 } 12318 12319 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12320 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12321 VectorType::GenericVector); 12322 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12323 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12324 VectorType::GenericVector); 12325 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12326 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12327 VectorType::GenericVector); 12328 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12329 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12330 VectorType::GenericVector); 12331 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12332 "Unhandled vector element size in vector compare"); 12333 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12334 VectorType::GenericVector); 12335 } 12336 12337 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12338 /// operates on extended vector types. Instead of producing an IntTy result, 12339 /// like a scalar comparison, a vector comparison produces a vector of integer 12340 /// types. 12341 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12342 SourceLocation Loc, 12343 BinaryOperatorKind Opc) { 12344 if (Opc == BO_Cmp) { 12345 Diag(Loc, diag::err_three_way_vector_comparison); 12346 return QualType(); 12347 } 12348 12349 // Check to make sure we're operating on vectors of the same type and width, 12350 // Allowing one side to be a scalar of element type. 12351 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12352 /*AllowBothBool*/true, 12353 /*AllowBoolConversions*/getLangOpts().ZVector); 12354 if (vType.isNull()) 12355 return vType; 12356 12357 QualType LHSType = LHS.get()->getType(); 12358 12359 // Determine the return type of a vector compare. By default clang will return 12360 // a scalar for all vector compares except vector bool and vector pixel. 12361 // With the gcc compiler we will always return a vector type and with the xl 12362 // compiler we will always return a scalar type. This switch allows choosing 12363 // which behavior is prefered. 12364 if (getLangOpts().AltiVec) { 12365 switch (getLangOpts().getAltivecSrcCompat()) { 12366 case LangOptions::AltivecSrcCompatKind::Mixed: 12367 // If AltiVec, the comparison results in a numeric type, i.e. 12368 // bool for C++, int for C 12369 if (vType->castAs<VectorType>()->getVectorKind() == 12370 VectorType::AltiVecVector) 12371 return Context.getLogicalOperationType(); 12372 else 12373 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 12374 break; 12375 case LangOptions::AltivecSrcCompatKind::GCC: 12376 // For GCC we always return the vector type. 12377 break; 12378 case LangOptions::AltivecSrcCompatKind::XL: 12379 return Context.getLogicalOperationType(); 12380 break; 12381 } 12382 } 12383 12384 // For non-floating point types, check for self-comparisons of the form 12385 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12386 // often indicate logic errors in the program. 12387 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12388 12389 // Check for comparisons of floating point operands using != and ==. 12390 if (BinaryOperator::isEqualityOp(Opc) && 12391 LHSType->hasFloatingRepresentation()) { 12392 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12393 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12394 } 12395 12396 // Return a signed type for the vector. 12397 return GetSignedVectorType(vType); 12398 } 12399 12400 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12401 const ExprResult &XorRHS, 12402 const SourceLocation Loc) { 12403 // Do not diagnose macros. 12404 if (Loc.isMacroID()) 12405 return; 12406 12407 // Do not diagnose if both LHS and RHS are macros. 12408 if (XorLHS.get()->getExprLoc().isMacroID() && 12409 XorRHS.get()->getExprLoc().isMacroID()) 12410 return; 12411 12412 bool Negative = false; 12413 bool ExplicitPlus = false; 12414 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12415 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12416 12417 if (!LHSInt) 12418 return; 12419 if (!RHSInt) { 12420 // Check negative literals. 12421 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12422 UnaryOperatorKind Opc = UO->getOpcode(); 12423 if (Opc != UO_Minus && Opc != UO_Plus) 12424 return; 12425 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12426 if (!RHSInt) 12427 return; 12428 Negative = (Opc == UO_Minus); 12429 ExplicitPlus = !Negative; 12430 } else { 12431 return; 12432 } 12433 } 12434 12435 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12436 llvm::APInt RightSideValue = RHSInt->getValue(); 12437 if (LeftSideValue != 2 && LeftSideValue != 10) 12438 return; 12439 12440 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12441 return; 12442 12443 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12444 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12445 llvm::StringRef ExprStr = 12446 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12447 12448 CharSourceRange XorRange = 12449 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12450 llvm::StringRef XorStr = 12451 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12452 // Do not diagnose if xor keyword/macro is used. 12453 if (XorStr == "xor") 12454 return; 12455 12456 std::string LHSStr = std::string(Lexer::getSourceText( 12457 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12458 S.getSourceManager(), S.getLangOpts())); 12459 std::string RHSStr = std::string(Lexer::getSourceText( 12460 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12461 S.getSourceManager(), S.getLangOpts())); 12462 12463 if (Negative) { 12464 RightSideValue = -RightSideValue; 12465 RHSStr = "-" + RHSStr; 12466 } else if (ExplicitPlus) { 12467 RHSStr = "+" + RHSStr; 12468 } 12469 12470 StringRef LHSStrRef = LHSStr; 12471 StringRef RHSStrRef = RHSStr; 12472 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12473 // literals. 12474 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12475 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12476 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12477 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12478 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12479 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12480 LHSStrRef.find('\'') != StringRef::npos || 12481 RHSStrRef.find('\'') != StringRef::npos) 12482 return; 12483 12484 bool SuggestXor = 12485 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12486 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12487 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12488 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12489 std::string SuggestedExpr = "1 << " + RHSStr; 12490 bool Overflow = false; 12491 llvm::APInt One = (LeftSideValue - 1); 12492 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12493 if (Overflow) { 12494 if (RightSideIntValue < 64) 12495 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12496 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 12497 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12498 else if (RightSideIntValue == 64) 12499 S.Diag(Loc, diag::warn_xor_used_as_pow) 12500 << ExprStr << toString(XorValue, 10, true); 12501 else 12502 return; 12503 } else { 12504 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12505 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 12506 << toString(PowValue, 10, true) 12507 << FixItHint::CreateReplacement( 12508 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12509 } 12510 12511 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12512 << ("0x2 ^ " + RHSStr) << SuggestXor; 12513 } else if (LeftSideValue == 10) { 12514 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12515 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12516 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 12517 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12518 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 12519 << ("0xA ^ " + RHSStr) << SuggestXor; 12520 } 12521 } 12522 12523 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12524 SourceLocation Loc) { 12525 // Ensure that either both operands are of the same vector type, or 12526 // one operand is of a vector type and the other is of its element type. 12527 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12528 /*AllowBothBool*/true, 12529 /*AllowBoolConversions*/false); 12530 if (vType.isNull()) 12531 return InvalidOperands(Loc, LHS, RHS); 12532 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12533 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12534 return InvalidOperands(Loc, LHS, RHS); 12535 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12536 // usage of the logical operators && and || with vectors in C. This 12537 // check could be notionally dropped. 12538 if (!getLangOpts().CPlusPlus && 12539 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12540 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12541 12542 return GetSignedVectorType(LHS.get()->getType()); 12543 } 12544 12545 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12546 SourceLocation Loc, 12547 bool IsCompAssign) { 12548 if (!IsCompAssign) { 12549 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12550 if (LHS.isInvalid()) 12551 return QualType(); 12552 } 12553 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12554 if (RHS.isInvalid()) 12555 return QualType(); 12556 12557 // For conversion purposes, we ignore any qualifiers. 12558 // For example, "const float" and "float" are equivalent. 12559 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12560 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12561 12562 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12563 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12564 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12565 12566 if (Context.hasSameType(LHSType, RHSType)) 12567 return LHSType; 12568 12569 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12570 // case we have to return InvalidOperands. 12571 ExprResult OriginalLHS = LHS; 12572 ExprResult OriginalRHS = RHS; 12573 if (LHSMatType && !RHSMatType) { 12574 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12575 if (!RHS.isInvalid()) 12576 return LHSType; 12577 12578 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12579 } 12580 12581 if (!LHSMatType && RHSMatType) { 12582 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12583 if (!LHS.isInvalid()) 12584 return RHSType; 12585 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12586 } 12587 12588 return InvalidOperands(Loc, LHS, RHS); 12589 } 12590 12591 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12592 SourceLocation Loc, 12593 bool IsCompAssign) { 12594 if (!IsCompAssign) { 12595 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12596 if (LHS.isInvalid()) 12597 return QualType(); 12598 } 12599 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12600 if (RHS.isInvalid()) 12601 return QualType(); 12602 12603 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12604 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12605 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12606 12607 if (LHSMatType && RHSMatType) { 12608 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12609 return InvalidOperands(Loc, LHS, RHS); 12610 12611 if (!Context.hasSameType(LHSMatType->getElementType(), 12612 RHSMatType->getElementType())) 12613 return InvalidOperands(Loc, LHS, RHS); 12614 12615 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12616 LHSMatType->getNumRows(), 12617 RHSMatType->getNumColumns()); 12618 } 12619 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12620 } 12621 12622 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12623 SourceLocation Loc, 12624 BinaryOperatorKind Opc) { 12625 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12626 12627 bool IsCompAssign = 12628 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12629 12630 if (LHS.get()->getType()->isVectorType() || 12631 RHS.get()->getType()->isVectorType()) { 12632 if (LHS.get()->getType()->hasIntegerRepresentation() && 12633 RHS.get()->getType()->hasIntegerRepresentation()) 12634 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12635 /*AllowBothBool*/true, 12636 /*AllowBoolConversions*/getLangOpts().ZVector); 12637 return InvalidOperands(Loc, LHS, RHS); 12638 } 12639 12640 if (Opc == BO_And) 12641 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12642 12643 if (LHS.get()->getType()->hasFloatingRepresentation() || 12644 RHS.get()->getType()->hasFloatingRepresentation()) 12645 return InvalidOperands(Loc, LHS, RHS); 12646 12647 ExprResult LHSResult = LHS, RHSResult = RHS; 12648 QualType compType = UsualArithmeticConversions( 12649 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12650 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12651 return QualType(); 12652 LHS = LHSResult.get(); 12653 RHS = RHSResult.get(); 12654 12655 if (Opc == BO_Xor) 12656 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12657 12658 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12659 return compType; 12660 return InvalidOperands(Loc, LHS, RHS); 12661 } 12662 12663 // C99 6.5.[13,14] 12664 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12665 SourceLocation Loc, 12666 BinaryOperatorKind Opc) { 12667 // Check vector operands differently. 12668 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12669 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12670 12671 bool EnumConstantInBoolContext = false; 12672 for (const ExprResult &HS : {LHS, RHS}) { 12673 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12674 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12675 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12676 EnumConstantInBoolContext = true; 12677 } 12678 } 12679 12680 if (EnumConstantInBoolContext) 12681 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12682 12683 // Diagnose cases where the user write a logical and/or but probably meant a 12684 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12685 // is a constant. 12686 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12687 !LHS.get()->getType()->isBooleanType() && 12688 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12689 // Don't warn in macros or template instantiations. 12690 !Loc.isMacroID() && !inTemplateInstantiation()) { 12691 // If the RHS can be constant folded, and if it constant folds to something 12692 // that isn't 0 or 1 (which indicate a potential logical operation that 12693 // happened to fold to true/false) then warn. 12694 // Parens on the RHS are ignored. 12695 Expr::EvalResult EVResult; 12696 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12697 llvm::APSInt Result = EVResult.Val.getInt(); 12698 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12699 !RHS.get()->getExprLoc().isMacroID()) || 12700 (Result != 0 && Result != 1)) { 12701 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12702 << RHS.get()->getSourceRange() 12703 << (Opc == BO_LAnd ? "&&" : "||"); 12704 // Suggest replacing the logical operator with the bitwise version 12705 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12706 << (Opc == BO_LAnd ? "&" : "|") 12707 << FixItHint::CreateReplacement(SourceRange( 12708 Loc, getLocForEndOfToken(Loc)), 12709 Opc == BO_LAnd ? "&" : "|"); 12710 if (Opc == BO_LAnd) 12711 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12712 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12713 << FixItHint::CreateRemoval( 12714 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12715 RHS.get()->getEndLoc())); 12716 } 12717 } 12718 } 12719 12720 if (!Context.getLangOpts().CPlusPlus) { 12721 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12722 // not operate on the built-in scalar and vector float types. 12723 if (Context.getLangOpts().OpenCL && 12724 Context.getLangOpts().OpenCLVersion < 120) { 12725 if (LHS.get()->getType()->isFloatingType() || 12726 RHS.get()->getType()->isFloatingType()) 12727 return InvalidOperands(Loc, LHS, RHS); 12728 } 12729 12730 LHS = UsualUnaryConversions(LHS.get()); 12731 if (LHS.isInvalid()) 12732 return QualType(); 12733 12734 RHS = UsualUnaryConversions(RHS.get()); 12735 if (RHS.isInvalid()) 12736 return QualType(); 12737 12738 if (!LHS.get()->getType()->isScalarType() || 12739 !RHS.get()->getType()->isScalarType()) 12740 return InvalidOperands(Loc, LHS, RHS); 12741 12742 return Context.IntTy; 12743 } 12744 12745 // The following is safe because we only use this method for 12746 // non-overloadable operands. 12747 12748 // C++ [expr.log.and]p1 12749 // C++ [expr.log.or]p1 12750 // The operands are both contextually converted to type bool. 12751 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12752 if (LHSRes.isInvalid()) 12753 return InvalidOperands(Loc, LHS, RHS); 12754 LHS = LHSRes; 12755 12756 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12757 if (RHSRes.isInvalid()) 12758 return InvalidOperands(Loc, LHS, RHS); 12759 RHS = RHSRes; 12760 12761 // C++ [expr.log.and]p2 12762 // C++ [expr.log.or]p2 12763 // The result is a bool. 12764 return Context.BoolTy; 12765 } 12766 12767 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12768 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12769 if (!ME) return false; 12770 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12771 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12772 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12773 if (!Base) return false; 12774 return Base->getMethodDecl() != nullptr; 12775 } 12776 12777 /// Is the given expression (which must be 'const') a reference to a 12778 /// variable which was originally non-const, but which has become 12779 /// 'const' due to being captured within a block? 12780 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12781 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12782 assert(E->isLValue() && E->getType().isConstQualified()); 12783 E = E->IgnoreParens(); 12784 12785 // Must be a reference to a declaration from an enclosing scope. 12786 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12787 if (!DRE) return NCCK_None; 12788 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12789 12790 // The declaration must be a variable which is not declared 'const'. 12791 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12792 if (!var) return NCCK_None; 12793 if (var->getType().isConstQualified()) return NCCK_None; 12794 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12795 12796 // Decide whether the first capture was for a block or a lambda. 12797 DeclContext *DC = S.CurContext, *Prev = nullptr; 12798 // Decide whether the first capture was for a block or a lambda. 12799 while (DC) { 12800 // For init-capture, it is possible that the variable belongs to the 12801 // template pattern of the current context. 12802 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12803 if (var->isInitCapture() && 12804 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12805 break; 12806 if (DC == var->getDeclContext()) 12807 break; 12808 Prev = DC; 12809 DC = DC->getParent(); 12810 } 12811 // Unless we have an init-capture, we've gone one step too far. 12812 if (!var->isInitCapture()) 12813 DC = Prev; 12814 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12815 } 12816 12817 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12818 Ty = Ty.getNonReferenceType(); 12819 if (IsDereference && Ty->isPointerType()) 12820 Ty = Ty->getPointeeType(); 12821 return !Ty.isConstQualified(); 12822 } 12823 12824 // Update err_typecheck_assign_const and note_typecheck_assign_const 12825 // when this enum is changed. 12826 enum { 12827 ConstFunction, 12828 ConstVariable, 12829 ConstMember, 12830 ConstMethod, 12831 NestedConstMember, 12832 ConstUnknown, // Keep as last element 12833 }; 12834 12835 /// Emit the "read-only variable not assignable" error and print notes to give 12836 /// more information about why the variable is not assignable, such as pointing 12837 /// to the declaration of a const variable, showing that a method is const, or 12838 /// that the function is returning a const reference. 12839 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12840 SourceLocation Loc) { 12841 SourceRange ExprRange = E->getSourceRange(); 12842 12843 // Only emit one error on the first const found. All other consts will emit 12844 // a note to the error. 12845 bool DiagnosticEmitted = false; 12846 12847 // Track if the current expression is the result of a dereference, and if the 12848 // next checked expression is the result of a dereference. 12849 bool IsDereference = false; 12850 bool NextIsDereference = false; 12851 12852 // Loop to process MemberExpr chains. 12853 while (true) { 12854 IsDereference = NextIsDereference; 12855 12856 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12857 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12858 NextIsDereference = ME->isArrow(); 12859 const ValueDecl *VD = ME->getMemberDecl(); 12860 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12861 // Mutable fields can be modified even if the class is const. 12862 if (Field->isMutable()) { 12863 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12864 break; 12865 } 12866 12867 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12868 if (!DiagnosticEmitted) { 12869 S.Diag(Loc, diag::err_typecheck_assign_const) 12870 << ExprRange << ConstMember << false /*static*/ << Field 12871 << Field->getType(); 12872 DiagnosticEmitted = true; 12873 } 12874 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12875 << ConstMember << false /*static*/ << Field << Field->getType() 12876 << Field->getSourceRange(); 12877 } 12878 E = ME->getBase(); 12879 continue; 12880 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12881 if (VDecl->getType().isConstQualified()) { 12882 if (!DiagnosticEmitted) { 12883 S.Diag(Loc, diag::err_typecheck_assign_const) 12884 << ExprRange << ConstMember << true /*static*/ << VDecl 12885 << VDecl->getType(); 12886 DiagnosticEmitted = true; 12887 } 12888 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12889 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12890 << VDecl->getSourceRange(); 12891 } 12892 // Static fields do not inherit constness from parents. 12893 break; 12894 } 12895 break; // End MemberExpr 12896 } else if (const ArraySubscriptExpr *ASE = 12897 dyn_cast<ArraySubscriptExpr>(E)) { 12898 E = ASE->getBase()->IgnoreParenImpCasts(); 12899 continue; 12900 } else if (const ExtVectorElementExpr *EVE = 12901 dyn_cast<ExtVectorElementExpr>(E)) { 12902 E = EVE->getBase()->IgnoreParenImpCasts(); 12903 continue; 12904 } 12905 break; 12906 } 12907 12908 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12909 // Function calls 12910 const FunctionDecl *FD = CE->getDirectCallee(); 12911 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12912 if (!DiagnosticEmitted) { 12913 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12914 << ConstFunction << FD; 12915 DiagnosticEmitted = true; 12916 } 12917 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12918 diag::note_typecheck_assign_const) 12919 << ConstFunction << FD << FD->getReturnType() 12920 << FD->getReturnTypeSourceRange(); 12921 } 12922 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12923 // Point to variable declaration. 12924 if (const ValueDecl *VD = DRE->getDecl()) { 12925 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12926 if (!DiagnosticEmitted) { 12927 S.Diag(Loc, diag::err_typecheck_assign_const) 12928 << ExprRange << ConstVariable << VD << VD->getType(); 12929 DiagnosticEmitted = true; 12930 } 12931 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12932 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12933 } 12934 } 12935 } else if (isa<CXXThisExpr>(E)) { 12936 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12937 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12938 if (MD->isConst()) { 12939 if (!DiagnosticEmitted) { 12940 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12941 << ConstMethod << MD; 12942 DiagnosticEmitted = true; 12943 } 12944 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12945 << ConstMethod << MD << MD->getSourceRange(); 12946 } 12947 } 12948 } 12949 } 12950 12951 if (DiagnosticEmitted) 12952 return; 12953 12954 // Can't determine a more specific message, so display the generic error. 12955 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12956 } 12957 12958 enum OriginalExprKind { 12959 OEK_Variable, 12960 OEK_Member, 12961 OEK_LValue 12962 }; 12963 12964 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12965 const RecordType *Ty, 12966 SourceLocation Loc, SourceRange Range, 12967 OriginalExprKind OEK, 12968 bool &DiagnosticEmitted) { 12969 std::vector<const RecordType *> RecordTypeList; 12970 RecordTypeList.push_back(Ty); 12971 unsigned NextToCheckIndex = 0; 12972 // We walk the record hierarchy breadth-first to ensure that we print 12973 // diagnostics in field nesting order. 12974 while (RecordTypeList.size() > NextToCheckIndex) { 12975 bool IsNested = NextToCheckIndex > 0; 12976 for (const FieldDecl *Field : 12977 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12978 // First, check every field for constness. 12979 QualType FieldTy = Field->getType(); 12980 if (FieldTy.isConstQualified()) { 12981 if (!DiagnosticEmitted) { 12982 S.Diag(Loc, diag::err_typecheck_assign_const) 12983 << Range << NestedConstMember << OEK << VD 12984 << IsNested << Field; 12985 DiagnosticEmitted = true; 12986 } 12987 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12988 << NestedConstMember << IsNested << Field 12989 << FieldTy << Field->getSourceRange(); 12990 } 12991 12992 // Then we append it to the list to check next in order. 12993 FieldTy = FieldTy.getCanonicalType(); 12994 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12995 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12996 RecordTypeList.push_back(FieldRecTy); 12997 } 12998 } 12999 ++NextToCheckIndex; 13000 } 13001 } 13002 13003 /// Emit an error for the case where a record we are trying to assign to has a 13004 /// const-qualified field somewhere in its hierarchy. 13005 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13006 SourceLocation Loc) { 13007 QualType Ty = E->getType(); 13008 assert(Ty->isRecordType() && "lvalue was not record?"); 13009 SourceRange Range = E->getSourceRange(); 13010 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13011 bool DiagEmitted = false; 13012 13013 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13014 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13015 Range, OEK_Member, DiagEmitted); 13016 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13017 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13018 Range, OEK_Variable, DiagEmitted); 13019 else 13020 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13021 Range, OEK_LValue, DiagEmitted); 13022 if (!DiagEmitted) 13023 DiagnoseConstAssignment(S, E, Loc); 13024 } 13025 13026 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13027 /// emit an error and return true. If so, return false. 13028 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13029 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13030 13031 S.CheckShadowingDeclModification(E, Loc); 13032 13033 SourceLocation OrigLoc = Loc; 13034 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13035 &Loc); 13036 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13037 IsLV = Expr::MLV_InvalidMessageExpression; 13038 if (IsLV == Expr::MLV_Valid) 13039 return false; 13040 13041 unsigned DiagID = 0; 13042 bool NeedType = false; 13043 switch (IsLV) { // C99 6.5.16p2 13044 case Expr::MLV_ConstQualified: 13045 // Use a specialized diagnostic when we're assigning to an object 13046 // from an enclosing function or block. 13047 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13048 if (NCCK == NCCK_Block) 13049 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13050 else 13051 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13052 break; 13053 } 13054 13055 // In ARC, use some specialized diagnostics for occasions where we 13056 // infer 'const'. These are always pseudo-strong variables. 13057 if (S.getLangOpts().ObjCAutoRefCount) { 13058 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13059 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13060 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13061 13062 // Use the normal diagnostic if it's pseudo-__strong but the 13063 // user actually wrote 'const'. 13064 if (var->isARCPseudoStrong() && 13065 (!var->getTypeSourceInfo() || 13066 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13067 // There are three pseudo-strong cases: 13068 // - self 13069 ObjCMethodDecl *method = S.getCurMethodDecl(); 13070 if (method && var == method->getSelfDecl()) { 13071 DiagID = method->isClassMethod() 13072 ? diag::err_typecheck_arc_assign_self_class_method 13073 : diag::err_typecheck_arc_assign_self; 13074 13075 // - Objective-C externally_retained attribute. 13076 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13077 isa<ParmVarDecl>(var)) { 13078 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13079 13080 // - fast enumeration variables 13081 } else { 13082 DiagID = diag::err_typecheck_arr_assign_enumeration; 13083 } 13084 13085 SourceRange Assign; 13086 if (Loc != OrigLoc) 13087 Assign = SourceRange(OrigLoc, OrigLoc); 13088 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13089 // We need to preserve the AST regardless, so migration tool 13090 // can do its job. 13091 return false; 13092 } 13093 } 13094 } 13095 13096 // If none of the special cases above are triggered, then this is a 13097 // simple const assignment. 13098 if (DiagID == 0) { 13099 DiagnoseConstAssignment(S, E, Loc); 13100 return true; 13101 } 13102 13103 break; 13104 case Expr::MLV_ConstAddrSpace: 13105 DiagnoseConstAssignment(S, E, Loc); 13106 return true; 13107 case Expr::MLV_ConstQualifiedField: 13108 DiagnoseRecursiveConstFields(S, E, Loc); 13109 return true; 13110 case Expr::MLV_ArrayType: 13111 case Expr::MLV_ArrayTemporary: 13112 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 13113 NeedType = true; 13114 break; 13115 case Expr::MLV_NotObjectType: 13116 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 13117 NeedType = true; 13118 break; 13119 case Expr::MLV_LValueCast: 13120 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 13121 break; 13122 case Expr::MLV_Valid: 13123 llvm_unreachable("did not take early return for MLV_Valid"); 13124 case Expr::MLV_InvalidExpression: 13125 case Expr::MLV_MemberFunction: 13126 case Expr::MLV_ClassTemporary: 13127 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 13128 break; 13129 case Expr::MLV_IncompleteType: 13130 case Expr::MLV_IncompleteVoidType: 13131 return S.RequireCompleteType(Loc, E->getType(), 13132 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 13133 case Expr::MLV_DuplicateVectorComponents: 13134 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 13135 break; 13136 case Expr::MLV_NoSetterProperty: 13137 llvm_unreachable("readonly properties should be processed differently"); 13138 case Expr::MLV_InvalidMessageExpression: 13139 DiagID = diag::err_readonly_message_assignment; 13140 break; 13141 case Expr::MLV_SubObjCPropertySetting: 13142 DiagID = diag::err_no_subobject_property_setting; 13143 break; 13144 } 13145 13146 SourceRange Assign; 13147 if (Loc != OrigLoc) 13148 Assign = SourceRange(OrigLoc, OrigLoc); 13149 if (NeedType) 13150 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 13151 else 13152 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 13153 return true; 13154 } 13155 13156 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 13157 SourceLocation Loc, 13158 Sema &Sema) { 13159 if (Sema.inTemplateInstantiation()) 13160 return; 13161 if (Sema.isUnevaluatedContext()) 13162 return; 13163 if (Loc.isInvalid() || Loc.isMacroID()) 13164 return; 13165 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 13166 return; 13167 13168 // C / C++ fields 13169 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 13170 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 13171 if (ML && MR) { 13172 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 13173 return; 13174 const ValueDecl *LHSDecl = 13175 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 13176 const ValueDecl *RHSDecl = 13177 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 13178 if (LHSDecl != RHSDecl) 13179 return; 13180 if (LHSDecl->getType().isVolatileQualified()) 13181 return; 13182 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13183 if (RefTy->getPointeeType().isVolatileQualified()) 13184 return; 13185 13186 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 13187 } 13188 13189 // Objective-C instance variables 13190 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 13191 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 13192 if (OL && OR && OL->getDecl() == OR->getDecl()) { 13193 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 13194 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 13195 if (RL && RR && RL->getDecl() == RR->getDecl()) 13196 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 13197 } 13198 } 13199 13200 // C99 6.5.16.1 13201 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 13202 SourceLocation Loc, 13203 QualType CompoundType) { 13204 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 13205 13206 // Verify that LHS is a modifiable lvalue, and emit error if not. 13207 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 13208 return QualType(); 13209 13210 QualType LHSType = LHSExpr->getType(); 13211 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 13212 CompoundType; 13213 // OpenCL v1.2 s6.1.1.1 p2: 13214 // The half data type can only be used to declare a pointer to a buffer that 13215 // contains half values 13216 if (getLangOpts().OpenCL && 13217 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 13218 LHSType->isHalfType()) { 13219 Diag(Loc, diag::err_opencl_half_load_store) << 1 13220 << LHSType.getUnqualifiedType(); 13221 return QualType(); 13222 } 13223 13224 AssignConvertType ConvTy; 13225 if (CompoundType.isNull()) { 13226 Expr *RHSCheck = RHS.get(); 13227 13228 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13229 13230 QualType LHSTy(LHSType); 13231 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13232 if (RHS.isInvalid()) 13233 return QualType(); 13234 // Special case of NSObject attributes on c-style pointer types. 13235 if (ConvTy == IncompatiblePointer && 13236 ((Context.isObjCNSObjectType(LHSType) && 13237 RHSType->isObjCObjectPointerType()) || 13238 (Context.isObjCNSObjectType(RHSType) && 13239 LHSType->isObjCObjectPointerType()))) 13240 ConvTy = Compatible; 13241 13242 if (ConvTy == Compatible && 13243 LHSType->isObjCObjectType()) 13244 Diag(Loc, diag::err_objc_object_assignment) 13245 << LHSType; 13246 13247 // If the RHS is a unary plus or minus, check to see if they = and + are 13248 // right next to each other. If so, the user may have typo'd "x =+ 4" 13249 // instead of "x += 4". 13250 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13251 RHSCheck = ICE->getSubExpr(); 13252 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13253 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13254 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13255 // Only if the two operators are exactly adjacent. 13256 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13257 // And there is a space or other character before the subexpr of the 13258 // unary +/-. We don't want to warn on "x=-1". 13259 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13260 UO->getSubExpr()->getBeginLoc().isFileID()) { 13261 Diag(Loc, diag::warn_not_compound_assign) 13262 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13263 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13264 } 13265 } 13266 13267 if (ConvTy == Compatible) { 13268 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13269 // Warn about retain cycles where a block captures the LHS, but 13270 // not if the LHS is a simple variable into which the block is 13271 // being stored...unless that variable can be captured by reference! 13272 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13273 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13274 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13275 checkRetainCycles(LHSExpr, RHS.get()); 13276 } 13277 13278 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13279 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13280 // It is safe to assign a weak reference into a strong variable. 13281 // Although this code can still have problems: 13282 // id x = self.weakProp; 13283 // id y = self.weakProp; 13284 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13285 // paths through the function. This should be revisited if 13286 // -Wrepeated-use-of-weak is made flow-sensitive. 13287 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13288 // variable, which will be valid for the current autorelease scope. 13289 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13290 RHS.get()->getBeginLoc())) 13291 getCurFunction()->markSafeWeakUse(RHS.get()); 13292 13293 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13294 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13295 } 13296 } 13297 } else { 13298 // Compound assignment "x += y" 13299 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13300 } 13301 13302 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13303 RHS.get(), AA_Assigning)) 13304 return QualType(); 13305 13306 CheckForNullPointerDereference(*this, LHSExpr); 13307 13308 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13309 if (CompoundType.isNull()) { 13310 // C++2a [expr.ass]p5: 13311 // A simple-assignment whose left operand is of a volatile-qualified 13312 // type is deprecated unless the assignment is either a discarded-value 13313 // expression or an unevaluated operand 13314 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13315 } else { 13316 // C++2a [expr.ass]p6: 13317 // [Compound-assignment] expressions are deprecated if E1 has 13318 // volatile-qualified type 13319 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13320 } 13321 } 13322 13323 // C99 6.5.16p3: The type of an assignment expression is the type of the 13324 // left operand unless the left operand has qualified type, in which case 13325 // it is the unqualified version of the type of the left operand. 13326 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13327 // is converted to the type of the assignment expression (above). 13328 // C++ 5.17p1: the type of the assignment expression is that of its left 13329 // operand. 13330 return (getLangOpts().CPlusPlus 13331 ? LHSType : LHSType.getUnqualifiedType()); 13332 } 13333 13334 // Only ignore explicit casts to void. 13335 static bool IgnoreCommaOperand(const Expr *E) { 13336 E = E->IgnoreParens(); 13337 13338 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13339 if (CE->getCastKind() == CK_ToVoid) { 13340 return true; 13341 } 13342 13343 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13344 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13345 CE->getSubExpr()->getType()->isDependentType()) { 13346 return true; 13347 } 13348 } 13349 13350 return false; 13351 } 13352 13353 // Look for instances where it is likely the comma operator is confused with 13354 // another operator. There is an explicit list of acceptable expressions for 13355 // the left hand side of the comma operator, otherwise emit a warning. 13356 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13357 // No warnings in macros 13358 if (Loc.isMacroID()) 13359 return; 13360 13361 // Don't warn in template instantiations. 13362 if (inTemplateInstantiation()) 13363 return; 13364 13365 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13366 // instead, skip more than needed, then call back into here with the 13367 // CommaVisitor in SemaStmt.cpp. 13368 // The listed locations are the initialization and increment portions 13369 // of a for loop. The additional checks are on the condition of 13370 // if statements, do/while loops, and for loops. 13371 // Differences in scope flags for C89 mode requires the extra logic. 13372 const unsigned ForIncrementFlags = 13373 getLangOpts().C99 || getLangOpts().CPlusPlus 13374 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13375 : Scope::ContinueScope | Scope::BreakScope; 13376 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13377 const unsigned ScopeFlags = getCurScope()->getFlags(); 13378 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13379 (ScopeFlags & ForInitFlags) == ForInitFlags) 13380 return; 13381 13382 // If there are multiple comma operators used together, get the RHS of the 13383 // of the comma operator as the LHS. 13384 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13385 if (BO->getOpcode() != BO_Comma) 13386 break; 13387 LHS = BO->getRHS(); 13388 } 13389 13390 // Only allow some expressions on LHS to not warn. 13391 if (IgnoreCommaOperand(LHS)) 13392 return; 13393 13394 Diag(Loc, diag::warn_comma_operator); 13395 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13396 << LHS->getSourceRange() 13397 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13398 LangOpts.CPlusPlus ? "static_cast<void>(" 13399 : "(void)(") 13400 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13401 ")"); 13402 } 13403 13404 // C99 6.5.17 13405 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13406 SourceLocation Loc) { 13407 LHS = S.CheckPlaceholderExpr(LHS.get()); 13408 RHS = S.CheckPlaceholderExpr(RHS.get()); 13409 if (LHS.isInvalid() || RHS.isInvalid()) 13410 return QualType(); 13411 13412 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13413 // operands, but not unary promotions. 13414 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13415 13416 // So we treat the LHS as a ignored value, and in C++ we allow the 13417 // containing site to determine what should be done with the RHS. 13418 LHS = S.IgnoredValueConversions(LHS.get()); 13419 if (LHS.isInvalid()) 13420 return QualType(); 13421 13422 S.DiagnoseUnusedExprResult(LHS.get()); 13423 13424 if (!S.getLangOpts().CPlusPlus) { 13425 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13426 if (RHS.isInvalid()) 13427 return QualType(); 13428 if (!RHS.get()->getType()->isVoidType()) 13429 S.RequireCompleteType(Loc, RHS.get()->getType(), 13430 diag::err_incomplete_type); 13431 } 13432 13433 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13434 S.DiagnoseCommaOperator(LHS.get(), Loc); 13435 13436 return RHS.get()->getType(); 13437 } 13438 13439 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13440 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13441 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13442 ExprValueKind &VK, 13443 ExprObjectKind &OK, 13444 SourceLocation OpLoc, 13445 bool IsInc, bool IsPrefix) { 13446 if (Op->isTypeDependent()) 13447 return S.Context.DependentTy; 13448 13449 QualType ResType = Op->getType(); 13450 // Atomic types can be used for increment / decrement where the non-atomic 13451 // versions can, so ignore the _Atomic() specifier for the purpose of 13452 // checking. 13453 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13454 ResType = ResAtomicType->getValueType(); 13455 13456 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13457 13458 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13459 // Decrement of bool is not allowed. 13460 if (!IsInc) { 13461 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13462 return QualType(); 13463 } 13464 // Increment of bool sets it to true, but is deprecated. 13465 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13466 : diag::warn_increment_bool) 13467 << Op->getSourceRange(); 13468 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13469 // Error on enum increments and decrements in C++ mode 13470 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13471 return QualType(); 13472 } else if (ResType->isRealType()) { 13473 // OK! 13474 } else if (ResType->isPointerType()) { 13475 // C99 6.5.2.4p2, 6.5.6p2 13476 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13477 return QualType(); 13478 } else if (ResType->isObjCObjectPointerType()) { 13479 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13480 // Otherwise, we just need a complete type. 13481 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13482 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13483 return QualType(); 13484 } else if (ResType->isAnyComplexType()) { 13485 // C99 does not support ++/-- on complex types, we allow as an extension. 13486 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13487 << ResType << Op->getSourceRange(); 13488 } else if (ResType->isPlaceholderType()) { 13489 ExprResult PR = S.CheckPlaceholderExpr(Op); 13490 if (PR.isInvalid()) return QualType(); 13491 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13492 IsInc, IsPrefix); 13493 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13494 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13495 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13496 (ResType->castAs<VectorType>()->getVectorKind() != 13497 VectorType::AltiVecBool)) { 13498 // The z vector extensions allow ++ and -- for non-bool vectors. 13499 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13500 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13501 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13502 } else { 13503 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13504 << ResType << int(IsInc) << Op->getSourceRange(); 13505 return QualType(); 13506 } 13507 // At this point, we know we have a real, complex or pointer type. 13508 // Now make sure the operand is a modifiable lvalue. 13509 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13510 return QualType(); 13511 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13512 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13513 // An operand with volatile-qualified type is deprecated 13514 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13515 << IsInc << ResType; 13516 } 13517 // In C++, a prefix increment is the same type as the operand. Otherwise 13518 // (in C or with postfix), the increment is the unqualified type of the 13519 // operand. 13520 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13521 VK = VK_LValue; 13522 OK = Op->getObjectKind(); 13523 return ResType; 13524 } else { 13525 VK = VK_PRValue; 13526 return ResType.getUnqualifiedType(); 13527 } 13528 } 13529 13530 13531 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13532 /// This routine allows us to typecheck complex/recursive expressions 13533 /// where the declaration is needed for type checking. We only need to 13534 /// handle cases when the expression references a function designator 13535 /// or is an lvalue. Here are some examples: 13536 /// - &(x) => x 13537 /// - &*****f => f for f a function designator. 13538 /// - &s.xx => s 13539 /// - &s.zz[1].yy -> s, if zz is an array 13540 /// - *(x + 1) -> x, if x is an array 13541 /// - &"123"[2] -> 0 13542 /// - & __real__ x -> x 13543 /// 13544 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13545 /// members. 13546 static ValueDecl *getPrimaryDecl(Expr *E) { 13547 switch (E->getStmtClass()) { 13548 case Stmt::DeclRefExprClass: 13549 return cast<DeclRefExpr>(E)->getDecl(); 13550 case Stmt::MemberExprClass: 13551 // If this is an arrow operator, the address is an offset from 13552 // the base's value, so the object the base refers to is 13553 // irrelevant. 13554 if (cast<MemberExpr>(E)->isArrow()) 13555 return nullptr; 13556 // Otherwise, the expression refers to a part of the base 13557 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13558 case Stmt::ArraySubscriptExprClass: { 13559 // FIXME: This code shouldn't be necessary! We should catch the implicit 13560 // promotion of register arrays earlier. 13561 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13562 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13563 if (ICE->getSubExpr()->getType()->isArrayType()) 13564 return getPrimaryDecl(ICE->getSubExpr()); 13565 } 13566 return nullptr; 13567 } 13568 case Stmt::UnaryOperatorClass: { 13569 UnaryOperator *UO = cast<UnaryOperator>(E); 13570 13571 switch(UO->getOpcode()) { 13572 case UO_Real: 13573 case UO_Imag: 13574 case UO_Extension: 13575 return getPrimaryDecl(UO->getSubExpr()); 13576 default: 13577 return nullptr; 13578 } 13579 } 13580 case Stmt::ParenExprClass: 13581 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13582 case Stmt::ImplicitCastExprClass: 13583 // If the result of an implicit cast is an l-value, we care about 13584 // the sub-expression; otherwise, the result here doesn't matter. 13585 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13586 case Stmt::CXXUuidofExprClass: 13587 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13588 default: 13589 return nullptr; 13590 } 13591 } 13592 13593 namespace { 13594 enum { 13595 AO_Bit_Field = 0, 13596 AO_Vector_Element = 1, 13597 AO_Property_Expansion = 2, 13598 AO_Register_Variable = 3, 13599 AO_Matrix_Element = 4, 13600 AO_No_Error = 5 13601 }; 13602 } 13603 /// Diagnose invalid operand for address of operations. 13604 /// 13605 /// \param Type The type of operand which cannot have its address taken. 13606 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13607 Expr *E, unsigned Type) { 13608 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13609 } 13610 13611 /// CheckAddressOfOperand - The operand of & must be either a function 13612 /// designator or an lvalue designating an object. If it is an lvalue, the 13613 /// object cannot be declared with storage class register or be a bit field. 13614 /// Note: The usual conversions are *not* applied to the operand of the & 13615 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13616 /// In C++, the operand might be an overloaded function name, in which case 13617 /// we allow the '&' but retain the overloaded-function type. 13618 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13619 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13620 if (PTy->getKind() == BuiltinType::Overload) { 13621 Expr *E = OrigOp.get()->IgnoreParens(); 13622 if (!isa<OverloadExpr>(E)) { 13623 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13624 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13625 << OrigOp.get()->getSourceRange(); 13626 return QualType(); 13627 } 13628 13629 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13630 if (isa<UnresolvedMemberExpr>(Ovl)) 13631 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13632 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13633 << OrigOp.get()->getSourceRange(); 13634 return QualType(); 13635 } 13636 13637 return Context.OverloadTy; 13638 } 13639 13640 if (PTy->getKind() == BuiltinType::UnknownAny) 13641 return Context.UnknownAnyTy; 13642 13643 if (PTy->getKind() == BuiltinType::BoundMember) { 13644 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13645 << OrigOp.get()->getSourceRange(); 13646 return QualType(); 13647 } 13648 13649 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13650 if (OrigOp.isInvalid()) return QualType(); 13651 } 13652 13653 if (OrigOp.get()->isTypeDependent()) 13654 return Context.DependentTy; 13655 13656 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13657 13658 // Make sure to ignore parentheses in subsequent checks 13659 Expr *op = OrigOp.get()->IgnoreParens(); 13660 13661 // In OpenCL captures for blocks called as lambda functions 13662 // are located in the private address space. Blocks used in 13663 // enqueue_kernel can be located in a different address space 13664 // depending on a vendor implementation. Thus preventing 13665 // taking an address of the capture to avoid invalid AS casts. 13666 if (LangOpts.OpenCL) { 13667 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13668 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13669 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13670 return QualType(); 13671 } 13672 } 13673 13674 if (getLangOpts().C99) { 13675 // Implement C99-only parts of addressof rules. 13676 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13677 if (uOp->getOpcode() == UO_Deref) 13678 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13679 // (assuming the deref expression is valid). 13680 return uOp->getSubExpr()->getType(); 13681 } 13682 // Technically, there should be a check for array subscript 13683 // expressions here, but the result of one is always an lvalue anyway. 13684 } 13685 ValueDecl *dcl = getPrimaryDecl(op); 13686 13687 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13688 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13689 op->getBeginLoc())) 13690 return QualType(); 13691 13692 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13693 unsigned AddressOfError = AO_No_Error; 13694 13695 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13696 bool sfinae = (bool)isSFINAEContext(); 13697 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13698 : diag::ext_typecheck_addrof_temporary) 13699 << op->getType() << op->getSourceRange(); 13700 if (sfinae) 13701 return QualType(); 13702 // Materialize the temporary as an lvalue so that we can take its address. 13703 OrigOp = op = 13704 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13705 } else if (isa<ObjCSelectorExpr>(op)) { 13706 return Context.getPointerType(op->getType()); 13707 } else if (lval == Expr::LV_MemberFunction) { 13708 // If it's an instance method, make a member pointer. 13709 // The expression must have exactly the form &A::foo. 13710 13711 // If the underlying expression isn't a decl ref, give up. 13712 if (!isa<DeclRefExpr>(op)) { 13713 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13714 << OrigOp.get()->getSourceRange(); 13715 return QualType(); 13716 } 13717 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13718 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13719 13720 // The id-expression was parenthesized. 13721 if (OrigOp.get() != DRE) { 13722 Diag(OpLoc, diag::err_parens_pointer_member_function) 13723 << OrigOp.get()->getSourceRange(); 13724 13725 // The method was named without a qualifier. 13726 } else if (!DRE->getQualifier()) { 13727 if (MD->getParent()->getName().empty()) 13728 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13729 << op->getSourceRange(); 13730 else { 13731 SmallString<32> Str; 13732 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13733 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13734 << op->getSourceRange() 13735 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13736 } 13737 } 13738 13739 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13740 if (isa<CXXDestructorDecl>(MD)) 13741 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13742 13743 QualType MPTy = Context.getMemberPointerType( 13744 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13745 // Under the MS ABI, lock down the inheritance model now. 13746 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13747 (void)isCompleteType(OpLoc, MPTy); 13748 return MPTy; 13749 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13750 // C99 6.5.3.2p1 13751 // The operand must be either an l-value or a function designator 13752 if (!op->getType()->isFunctionType()) { 13753 // Use a special diagnostic for loads from property references. 13754 if (isa<PseudoObjectExpr>(op)) { 13755 AddressOfError = AO_Property_Expansion; 13756 } else { 13757 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13758 << op->getType() << op->getSourceRange(); 13759 return QualType(); 13760 } 13761 } 13762 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13763 // The operand cannot be a bit-field 13764 AddressOfError = AO_Bit_Field; 13765 } else if (op->getObjectKind() == OK_VectorComponent) { 13766 // The operand cannot be an element of a vector 13767 AddressOfError = AO_Vector_Element; 13768 } else if (op->getObjectKind() == OK_MatrixComponent) { 13769 // The operand cannot be an element of a matrix. 13770 AddressOfError = AO_Matrix_Element; 13771 } else if (dcl) { // C99 6.5.3.2p1 13772 // We have an lvalue with a decl. Make sure the decl is not declared 13773 // with the register storage-class specifier. 13774 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13775 // in C++ it is not error to take address of a register 13776 // variable (c++03 7.1.1P3) 13777 if (vd->getStorageClass() == SC_Register && 13778 !getLangOpts().CPlusPlus) { 13779 AddressOfError = AO_Register_Variable; 13780 } 13781 } else if (isa<MSPropertyDecl>(dcl)) { 13782 AddressOfError = AO_Property_Expansion; 13783 } else if (isa<FunctionTemplateDecl>(dcl)) { 13784 return Context.OverloadTy; 13785 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13786 // Okay: we can take the address of a field. 13787 // Could be a pointer to member, though, if there is an explicit 13788 // scope qualifier for the class. 13789 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13790 DeclContext *Ctx = dcl->getDeclContext(); 13791 if (Ctx && Ctx->isRecord()) { 13792 if (dcl->getType()->isReferenceType()) { 13793 Diag(OpLoc, 13794 diag::err_cannot_form_pointer_to_member_of_reference_type) 13795 << dcl->getDeclName() << dcl->getType(); 13796 return QualType(); 13797 } 13798 13799 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13800 Ctx = Ctx->getParent(); 13801 13802 QualType MPTy = Context.getMemberPointerType( 13803 op->getType(), 13804 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13805 // Under the MS ABI, lock down the inheritance model now. 13806 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13807 (void)isCompleteType(OpLoc, MPTy); 13808 return MPTy; 13809 } 13810 } 13811 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13812 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13813 llvm_unreachable("Unknown/unexpected decl type"); 13814 } 13815 13816 if (AddressOfError != AO_No_Error) { 13817 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13818 return QualType(); 13819 } 13820 13821 if (lval == Expr::LV_IncompleteVoidType) { 13822 // Taking the address of a void variable is technically illegal, but we 13823 // allow it in cases which are otherwise valid. 13824 // Example: "extern void x; void* y = &x;". 13825 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13826 } 13827 13828 // If the operand has type "type", the result has type "pointer to type". 13829 if (op->getType()->isObjCObjectType()) 13830 return Context.getObjCObjectPointerType(op->getType()); 13831 13832 CheckAddressOfPackedMember(op); 13833 13834 return Context.getPointerType(op->getType()); 13835 } 13836 13837 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13838 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13839 if (!DRE) 13840 return; 13841 const Decl *D = DRE->getDecl(); 13842 if (!D) 13843 return; 13844 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13845 if (!Param) 13846 return; 13847 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13848 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13849 return; 13850 if (FunctionScopeInfo *FD = S.getCurFunction()) 13851 if (!FD->ModifiedNonNullParams.count(Param)) 13852 FD->ModifiedNonNullParams.insert(Param); 13853 } 13854 13855 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13856 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13857 SourceLocation OpLoc) { 13858 if (Op->isTypeDependent()) 13859 return S.Context.DependentTy; 13860 13861 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13862 if (ConvResult.isInvalid()) 13863 return QualType(); 13864 Op = ConvResult.get(); 13865 QualType OpTy = Op->getType(); 13866 QualType Result; 13867 13868 if (isa<CXXReinterpretCastExpr>(Op)) { 13869 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13870 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13871 Op->getSourceRange()); 13872 } 13873 13874 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13875 { 13876 Result = PT->getPointeeType(); 13877 } 13878 else if (const ObjCObjectPointerType *OPT = 13879 OpTy->getAs<ObjCObjectPointerType>()) 13880 Result = OPT->getPointeeType(); 13881 else { 13882 ExprResult PR = S.CheckPlaceholderExpr(Op); 13883 if (PR.isInvalid()) return QualType(); 13884 if (PR.get() != Op) 13885 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13886 } 13887 13888 if (Result.isNull()) { 13889 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13890 << OpTy << Op->getSourceRange(); 13891 return QualType(); 13892 } 13893 13894 // Note that per both C89 and C99, indirection is always legal, even if Result 13895 // is an incomplete type or void. It would be possible to warn about 13896 // dereferencing a void pointer, but it's completely well-defined, and such a 13897 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13898 // for pointers to 'void' but is fine for any other pointer type: 13899 // 13900 // C++ [expr.unary.op]p1: 13901 // [...] the expression to which [the unary * operator] is applied shall 13902 // be a pointer to an object type, or a pointer to a function type 13903 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13904 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13905 << OpTy << Op->getSourceRange(); 13906 13907 // Dereferences are usually l-values... 13908 VK = VK_LValue; 13909 13910 // ...except that certain expressions are never l-values in C. 13911 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13912 VK = VK_PRValue; 13913 13914 return Result; 13915 } 13916 13917 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13918 BinaryOperatorKind Opc; 13919 switch (Kind) { 13920 default: llvm_unreachable("Unknown binop!"); 13921 case tok::periodstar: Opc = BO_PtrMemD; break; 13922 case tok::arrowstar: Opc = BO_PtrMemI; break; 13923 case tok::star: Opc = BO_Mul; break; 13924 case tok::slash: Opc = BO_Div; break; 13925 case tok::percent: Opc = BO_Rem; break; 13926 case tok::plus: Opc = BO_Add; break; 13927 case tok::minus: Opc = BO_Sub; break; 13928 case tok::lessless: Opc = BO_Shl; break; 13929 case tok::greatergreater: Opc = BO_Shr; break; 13930 case tok::lessequal: Opc = BO_LE; break; 13931 case tok::less: Opc = BO_LT; break; 13932 case tok::greaterequal: Opc = BO_GE; break; 13933 case tok::greater: Opc = BO_GT; break; 13934 case tok::exclaimequal: Opc = BO_NE; break; 13935 case tok::equalequal: Opc = BO_EQ; break; 13936 case tok::spaceship: Opc = BO_Cmp; break; 13937 case tok::amp: Opc = BO_And; break; 13938 case tok::caret: Opc = BO_Xor; break; 13939 case tok::pipe: Opc = BO_Or; break; 13940 case tok::ampamp: Opc = BO_LAnd; break; 13941 case tok::pipepipe: Opc = BO_LOr; break; 13942 case tok::equal: Opc = BO_Assign; break; 13943 case tok::starequal: Opc = BO_MulAssign; break; 13944 case tok::slashequal: Opc = BO_DivAssign; break; 13945 case tok::percentequal: Opc = BO_RemAssign; break; 13946 case tok::plusequal: Opc = BO_AddAssign; break; 13947 case tok::minusequal: Opc = BO_SubAssign; break; 13948 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13949 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13950 case tok::ampequal: Opc = BO_AndAssign; break; 13951 case tok::caretequal: Opc = BO_XorAssign; break; 13952 case tok::pipeequal: Opc = BO_OrAssign; break; 13953 case tok::comma: Opc = BO_Comma; break; 13954 } 13955 return Opc; 13956 } 13957 13958 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13959 tok::TokenKind Kind) { 13960 UnaryOperatorKind Opc; 13961 switch (Kind) { 13962 default: llvm_unreachable("Unknown unary op!"); 13963 case tok::plusplus: Opc = UO_PreInc; break; 13964 case tok::minusminus: Opc = UO_PreDec; break; 13965 case tok::amp: Opc = UO_AddrOf; break; 13966 case tok::star: Opc = UO_Deref; break; 13967 case tok::plus: Opc = UO_Plus; break; 13968 case tok::minus: Opc = UO_Minus; break; 13969 case tok::tilde: Opc = UO_Not; break; 13970 case tok::exclaim: Opc = UO_LNot; break; 13971 case tok::kw___real: Opc = UO_Real; break; 13972 case tok::kw___imag: Opc = UO_Imag; break; 13973 case tok::kw___extension__: Opc = UO_Extension; break; 13974 } 13975 return Opc; 13976 } 13977 13978 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13979 /// This warning suppressed in the event of macro expansions. 13980 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13981 SourceLocation OpLoc, bool IsBuiltin) { 13982 if (S.inTemplateInstantiation()) 13983 return; 13984 if (S.isUnevaluatedContext()) 13985 return; 13986 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13987 return; 13988 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13989 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13990 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13991 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13992 if (!LHSDeclRef || !RHSDeclRef || 13993 LHSDeclRef->getLocation().isMacroID() || 13994 RHSDeclRef->getLocation().isMacroID()) 13995 return; 13996 const ValueDecl *LHSDecl = 13997 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13998 const ValueDecl *RHSDecl = 13999 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14000 if (LHSDecl != RHSDecl) 14001 return; 14002 if (LHSDecl->getType().isVolatileQualified()) 14003 return; 14004 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14005 if (RefTy->getPointeeType().isVolatileQualified()) 14006 return; 14007 14008 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14009 : diag::warn_self_assignment_overloaded) 14010 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14011 << RHSExpr->getSourceRange(); 14012 } 14013 14014 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14015 /// is usually indicative of introspection within the Objective-C pointer. 14016 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14017 SourceLocation OpLoc) { 14018 if (!S.getLangOpts().ObjC) 14019 return; 14020 14021 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14022 const Expr *LHS = L.get(); 14023 const Expr *RHS = R.get(); 14024 14025 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14026 ObjCPointerExpr = LHS; 14027 OtherExpr = RHS; 14028 } 14029 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14030 ObjCPointerExpr = RHS; 14031 OtherExpr = LHS; 14032 } 14033 14034 // This warning is deliberately made very specific to reduce false 14035 // positives with logic that uses '&' for hashing. This logic mainly 14036 // looks for code trying to introspect into tagged pointers, which 14037 // code should generally never do. 14038 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14039 unsigned Diag = diag::warn_objc_pointer_masking; 14040 // Determine if we are introspecting the result of performSelectorXXX. 14041 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14042 // Special case messages to -performSelector and friends, which 14043 // can return non-pointer values boxed in a pointer value. 14044 // Some clients may wish to silence warnings in this subcase. 14045 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14046 Selector S = ME->getSelector(); 14047 StringRef SelArg0 = S.getNameForSlot(0); 14048 if (SelArg0.startswith("performSelector")) 14049 Diag = diag::warn_objc_pointer_masking_performSelector; 14050 } 14051 14052 S.Diag(OpLoc, Diag) 14053 << ObjCPointerExpr->getSourceRange(); 14054 } 14055 } 14056 14057 static NamedDecl *getDeclFromExpr(Expr *E) { 14058 if (!E) 14059 return nullptr; 14060 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 14061 return DRE->getDecl(); 14062 if (auto *ME = dyn_cast<MemberExpr>(E)) 14063 return ME->getMemberDecl(); 14064 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 14065 return IRE->getDecl(); 14066 return nullptr; 14067 } 14068 14069 // This helper function promotes a binary operator's operands (which are of a 14070 // half vector type) to a vector of floats and then truncates the result to 14071 // a vector of either half or short. 14072 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 14073 BinaryOperatorKind Opc, QualType ResultTy, 14074 ExprValueKind VK, ExprObjectKind OK, 14075 bool IsCompAssign, SourceLocation OpLoc, 14076 FPOptionsOverride FPFeatures) { 14077 auto &Context = S.getASTContext(); 14078 assert((isVector(ResultTy, Context.HalfTy) || 14079 isVector(ResultTy, Context.ShortTy)) && 14080 "Result must be a vector of half or short"); 14081 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 14082 isVector(RHS.get()->getType(), Context.HalfTy) && 14083 "both operands expected to be a half vector"); 14084 14085 RHS = convertVector(RHS.get(), Context.FloatTy, S); 14086 QualType BinOpResTy = RHS.get()->getType(); 14087 14088 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 14089 // change BinOpResTy to a vector of ints. 14090 if (isVector(ResultTy, Context.ShortTy)) 14091 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 14092 14093 if (IsCompAssign) 14094 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14095 ResultTy, VK, OK, OpLoc, FPFeatures, 14096 BinOpResTy, BinOpResTy); 14097 14098 LHS = convertVector(LHS.get(), Context.FloatTy, S); 14099 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 14100 BinOpResTy, VK, OK, OpLoc, FPFeatures); 14101 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 14102 } 14103 14104 static std::pair<ExprResult, ExprResult> 14105 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 14106 Expr *RHSExpr) { 14107 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14108 if (!S.Context.isDependenceAllowed()) { 14109 // C cannot handle TypoExpr nodes on either side of a binop because it 14110 // doesn't handle dependent types properly, so make sure any TypoExprs have 14111 // been dealt with before checking the operands. 14112 LHS = S.CorrectDelayedTyposInExpr(LHS); 14113 RHS = S.CorrectDelayedTyposInExpr( 14114 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 14115 [Opc, LHS](Expr *E) { 14116 if (Opc != BO_Assign) 14117 return ExprResult(E); 14118 // Avoid correcting the RHS to the same Expr as the LHS. 14119 Decl *D = getDeclFromExpr(E); 14120 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 14121 }); 14122 } 14123 return std::make_pair(LHS, RHS); 14124 } 14125 14126 /// Returns true if conversion between vectors of halfs and vectors of floats 14127 /// is needed. 14128 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 14129 Expr *E0, Expr *E1 = nullptr) { 14130 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 14131 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 14132 return false; 14133 14134 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 14135 QualType Ty = E->IgnoreImplicit()->getType(); 14136 14137 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 14138 // to vectors of floats. Although the element type of the vectors is __fp16, 14139 // the vectors shouldn't be treated as storage-only types. See the 14140 // discussion here: https://reviews.llvm.org/rG825235c140e7 14141 if (const VectorType *VT = Ty->getAs<VectorType>()) { 14142 if (VT->getVectorKind() == VectorType::NeonVector) 14143 return false; 14144 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 14145 } 14146 return false; 14147 }; 14148 14149 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 14150 } 14151 14152 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 14153 /// operator @p Opc at location @c TokLoc. This routine only supports 14154 /// built-in operations; ActOnBinOp handles overloaded operators. 14155 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 14156 BinaryOperatorKind Opc, 14157 Expr *LHSExpr, Expr *RHSExpr) { 14158 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 14159 // The syntax only allows initializer lists on the RHS of assignment, 14160 // so we don't need to worry about accepting invalid code for 14161 // non-assignment operators. 14162 // C++11 5.17p9: 14163 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 14164 // of x = {} is x = T(). 14165 InitializationKind Kind = InitializationKind::CreateDirectList( 14166 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14167 InitializedEntity Entity = 14168 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 14169 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 14170 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 14171 if (Init.isInvalid()) 14172 return Init; 14173 RHSExpr = Init.get(); 14174 } 14175 14176 ExprResult LHS = LHSExpr, RHS = RHSExpr; 14177 QualType ResultTy; // Result type of the binary operator. 14178 // The following two variables are used for compound assignment operators 14179 QualType CompLHSTy; // Type of LHS after promotions for computation 14180 QualType CompResultTy; // Type of computation result 14181 ExprValueKind VK = VK_PRValue; 14182 ExprObjectKind OK = OK_Ordinary; 14183 bool ConvertHalfVec = false; 14184 14185 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14186 if (!LHS.isUsable() || !RHS.isUsable()) 14187 return ExprError(); 14188 14189 if (getLangOpts().OpenCL) { 14190 QualType LHSTy = LHSExpr->getType(); 14191 QualType RHSTy = RHSExpr->getType(); 14192 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 14193 // the ATOMIC_VAR_INIT macro. 14194 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 14195 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 14196 if (BO_Assign == Opc) 14197 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 14198 else 14199 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14200 return ExprError(); 14201 } 14202 14203 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14204 // only with a builtin functions and therefore should be disallowed here. 14205 if (LHSTy->isImageType() || RHSTy->isImageType() || 14206 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 14207 LHSTy->isPipeType() || RHSTy->isPipeType() || 14208 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 14209 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 14210 return ExprError(); 14211 } 14212 } 14213 14214 switch (Opc) { 14215 case BO_Assign: 14216 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 14217 if (getLangOpts().CPlusPlus && 14218 LHS.get()->getObjectKind() != OK_ObjCProperty) { 14219 VK = LHS.get()->getValueKind(); 14220 OK = LHS.get()->getObjectKind(); 14221 } 14222 if (!ResultTy.isNull()) { 14223 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14224 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14225 14226 // Avoid copying a block to the heap if the block is assigned to a local 14227 // auto variable that is declared in the same scope as the block. This 14228 // optimization is unsafe if the local variable is declared in an outer 14229 // scope. For example: 14230 // 14231 // BlockTy b; 14232 // { 14233 // b = ^{...}; 14234 // } 14235 // // It is unsafe to invoke the block here if it wasn't copied to the 14236 // // heap. 14237 // b(); 14238 14239 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14240 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14241 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14242 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14243 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14244 14245 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14246 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14247 NTCUC_Assignment, NTCUK_Copy); 14248 } 14249 RecordModifiableNonNullParam(*this, LHS.get()); 14250 break; 14251 case BO_PtrMemD: 14252 case BO_PtrMemI: 14253 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14254 Opc == BO_PtrMemI); 14255 break; 14256 case BO_Mul: 14257 case BO_Div: 14258 ConvertHalfVec = true; 14259 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14260 Opc == BO_Div); 14261 break; 14262 case BO_Rem: 14263 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14264 break; 14265 case BO_Add: 14266 ConvertHalfVec = true; 14267 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14268 break; 14269 case BO_Sub: 14270 ConvertHalfVec = true; 14271 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14272 break; 14273 case BO_Shl: 14274 case BO_Shr: 14275 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14276 break; 14277 case BO_LE: 14278 case BO_LT: 14279 case BO_GE: 14280 case BO_GT: 14281 ConvertHalfVec = true; 14282 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14283 break; 14284 case BO_EQ: 14285 case BO_NE: 14286 ConvertHalfVec = true; 14287 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14288 break; 14289 case BO_Cmp: 14290 ConvertHalfVec = true; 14291 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14292 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14293 break; 14294 case BO_And: 14295 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14296 LLVM_FALLTHROUGH; 14297 case BO_Xor: 14298 case BO_Or: 14299 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14300 break; 14301 case BO_LAnd: 14302 case BO_LOr: 14303 ConvertHalfVec = true; 14304 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14305 break; 14306 case BO_MulAssign: 14307 case BO_DivAssign: 14308 ConvertHalfVec = true; 14309 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14310 Opc == BO_DivAssign); 14311 CompLHSTy = CompResultTy; 14312 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14313 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14314 break; 14315 case BO_RemAssign: 14316 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14317 CompLHSTy = CompResultTy; 14318 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14319 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14320 break; 14321 case BO_AddAssign: 14322 ConvertHalfVec = true; 14323 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14324 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14325 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14326 break; 14327 case BO_SubAssign: 14328 ConvertHalfVec = true; 14329 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14330 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14331 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14332 break; 14333 case BO_ShlAssign: 14334 case BO_ShrAssign: 14335 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14336 CompLHSTy = CompResultTy; 14337 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14339 break; 14340 case BO_AndAssign: 14341 case BO_OrAssign: // fallthrough 14342 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14343 LLVM_FALLTHROUGH; 14344 case BO_XorAssign: 14345 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14346 CompLHSTy = CompResultTy; 14347 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14348 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14349 break; 14350 case BO_Comma: 14351 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14352 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14353 VK = RHS.get()->getValueKind(); 14354 OK = RHS.get()->getObjectKind(); 14355 } 14356 break; 14357 } 14358 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14359 return ExprError(); 14360 14361 // Some of the binary operations require promoting operands of half vector to 14362 // float vectors and truncating the result back to half vector. For now, we do 14363 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14364 // arm64). 14365 assert( 14366 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14367 isVector(LHS.get()->getType(), Context.HalfTy)) && 14368 "both sides are half vectors or neither sides are"); 14369 ConvertHalfVec = 14370 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14371 14372 // Check for array bounds violations for both sides of the BinaryOperator 14373 CheckArrayAccess(LHS.get()); 14374 CheckArrayAccess(RHS.get()); 14375 14376 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14377 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14378 &Context.Idents.get("object_setClass"), 14379 SourceLocation(), LookupOrdinaryName); 14380 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14381 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14382 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14383 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14384 "object_setClass(") 14385 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14386 ",") 14387 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14388 } 14389 else 14390 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14391 } 14392 else if (const ObjCIvarRefExpr *OIRE = 14393 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14394 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14395 14396 // Opc is not a compound assignment if CompResultTy is null. 14397 if (CompResultTy.isNull()) { 14398 if (ConvertHalfVec) 14399 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14400 OpLoc, CurFPFeatureOverrides()); 14401 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14402 VK, OK, OpLoc, CurFPFeatureOverrides()); 14403 } 14404 14405 // Handle compound assignments. 14406 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14407 OK_ObjCProperty) { 14408 VK = VK_LValue; 14409 OK = LHS.get()->getObjectKind(); 14410 } 14411 14412 // The LHS is not converted to the result type for fixed-point compound 14413 // assignment as the common type is computed on demand. Reset the CompLHSTy 14414 // to the LHS type we would have gotten after unary conversions. 14415 if (CompResultTy->isFixedPointType()) 14416 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14417 14418 if (ConvertHalfVec) 14419 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14420 OpLoc, CurFPFeatureOverrides()); 14421 14422 return CompoundAssignOperator::Create( 14423 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14424 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14425 } 14426 14427 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14428 /// operators are mixed in a way that suggests that the programmer forgot that 14429 /// comparison operators have higher precedence. The most typical example of 14430 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14431 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14432 SourceLocation OpLoc, Expr *LHSExpr, 14433 Expr *RHSExpr) { 14434 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14435 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14436 14437 // Check that one of the sides is a comparison operator and the other isn't. 14438 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14439 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14440 if (isLeftComp == isRightComp) 14441 return; 14442 14443 // Bitwise operations are sometimes used as eager logical ops. 14444 // Don't diagnose this. 14445 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14446 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14447 if (isLeftBitwise || isRightBitwise) 14448 return; 14449 14450 SourceRange DiagRange = isLeftComp 14451 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14452 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14453 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14454 SourceRange ParensRange = 14455 isLeftComp 14456 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14457 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14458 14459 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14460 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14461 SuggestParentheses(Self, OpLoc, 14462 Self.PDiag(diag::note_precedence_silence) << OpStr, 14463 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14464 SuggestParentheses(Self, OpLoc, 14465 Self.PDiag(diag::note_precedence_bitwise_first) 14466 << BinaryOperator::getOpcodeStr(Opc), 14467 ParensRange); 14468 } 14469 14470 /// It accepts a '&&' expr that is inside a '||' one. 14471 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14472 /// in parentheses. 14473 static void 14474 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14475 BinaryOperator *Bop) { 14476 assert(Bop->getOpcode() == BO_LAnd); 14477 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14478 << Bop->getSourceRange() << OpLoc; 14479 SuggestParentheses(Self, Bop->getOperatorLoc(), 14480 Self.PDiag(diag::note_precedence_silence) 14481 << Bop->getOpcodeStr(), 14482 Bop->getSourceRange()); 14483 } 14484 14485 /// Returns true if the given expression can be evaluated as a constant 14486 /// 'true'. 14487 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14488 bool Res; 14489 return !E->isValueDependent() && 14490 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14491 } 14492 14493 /// Returns true if the given expression can be evaluated as a constant 14494 /// 'false'. 14495 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14496 bool Res; 14497 return !E->isValueDependent() && 14498 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14499 } 14500 14501 /// Look for '&&' in the left hand of a '||' expr. 14502 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14503 Expr *LHSExpr, Expr *RHSExpr) { 14504 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14505 if (Bop->getOpcode() == BO_LAnd) { 14506 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14507 if (EvaluatesAsFalse(S, RHSExpr)) 14508 return; 14509 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14510 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14511 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14512 } else if (Bop->getOpcode() == BO_LOr) { 14513 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14514 // If it's "a || b && 1 || c" we didn't warn earlier for 14515 // "a || b && 1", but warn now. 14516 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14517 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14518 } 14519 } 14520 } 14521 } 14522 14523 /// Look for '&&' in the right hand of a '||' expr. 14524 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14525 Expr *LHSExpr, Expr *RHSExpr) { 14526 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14527 if (Bop->getOpcode() == BO_LAnd) { 14528 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14529 if (EvaluatesAsFalse(S, LHSExpr)) 14530 return; 14531 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14532 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14533 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14534 } 14535 } 14536 } 14537 14538 /// Look for bitwise op in the left or right hand of a bitwise op with 14539 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14540 /// the '&' expression in parentheses. 14541 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14542 SourceLocation OpLoc, Expr *SubExpr) { 14543 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14544 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14545 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14546 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14547 << Bop->getSourceRange() << OpLoc; 14548 SuggestParentheses(S, Bop->getOperatorLoc(), 14549 S.PDiag(diag::note_precedence_silence) 14550 << Bop->getOpcodeStr(), 14551 Bop->getSourceRange()); 14552 } 14553 } 14554 } 14555 14556 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14557 Expr *SubExpr, StringRef Shift) { 14558 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14559 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14560 StringRef Op = Bop->getOpcodeStr(); 14561 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14562 << Bop->getSourceRange() << OpLoc << Shift << Op; 14563 SuggestParentheses(S, Bop->getOperatorLoc(), 14564 S.PDiag(diag::note_precedence_silence) << Op, 14565 Bop->getSourceRange()); 14566 } 14567 } 14568 } 14569 14570 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14571 Expr *LHSExpr, Expr *RHSExpr) { 14572 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14573 if (!OCE) 14574 return; 14575 14576 FunctionDecl *FD = OCE->getDirectCallee(); 14577 if (!FD || !FD->isOverloadedOperator()) 14578 return; 14579 14580 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14581 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14582 return; 14583 14584 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14585 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14586 << (Kind == OO_LessLess); 14587 SuggestParentheses(S, OCE->getOperatorLoc(), 14588 S.PDiag(diag::note_precedence_silence) 14589 << (Kind == OO_LessLess ? "<<" : ">>"), 14590 OCE->getSourceRange()); 14591 SuggestParentheses( 14592 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14593 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14594 } 14595 14596 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14597 /// precedence. 14598 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14599 SourceLocation OpLoc, Expr *LHSExpr, 14600 Expr *RHSExpr){ 14601 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14602 if (BinaryOperator::isBitwiseOp(Opc)) 14603 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14604 14605 // Diagnose "arg1 & arg2 | arg3" 14606 if ((Opc == BO_Or || Opc == BO_Xor) && 14607 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14608 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14609 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14610 } 14611 14612 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14613 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14614 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14615 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14616 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14617 } 14618 14619 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14620 || Opc == BO_Shr) { 14621 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14622 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14623 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14624 } 14625 14626 // Warn on overloaded shift operators and comparisons, such as: 14627 // cout << 5 == 4; 14628 if (BinaryOperator::isComparisonOp(Opc)) 14629 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14630 } 14631 14632 // Binary Operators. 'Tok' is the token for the operator. 14633 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14634 tok::TokenKind Kind, 14635 Expr *LHSExpr, Expr *RHSExpr) { 14636 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14637 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14638 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14639 14640 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14641 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14642 14643 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14644 } 14645 14646 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14647 UnresolvedSetImpl &Functions) { 14648 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14649 if (OverOp != OO_None && OverOp != OO_Equal) 14650 LookupOverloadedOperatorName(OverOp, S, Functions); 14651 14652 // In C++20 onwards, we may have a second operator to look up. 14653 if (getLangOpts().CPlusPlus20) { 14654 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14655 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14656 } 14657 } 14658 14659 /// Build an overloaded binary operator expression in the given scope. 14660 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14661 BinaryOperatorKind Opc, 14662 Expr *LHS, Expr *RHS) { 14663 switch (Opc) { 14664 case BO_Assign: 14665 case BO_DivAssign: 14666 case BO_RemAssign: 14667 case BO_SubAssign: 14668 case BO_AndAssign: 14669 case BO_OrAssign: 14670 case BO_XorAssign: 14671 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14672 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14673 break; 14674 default: 14675 break; 14676 } 14677 14678 // Find all of the overloaded operators visible from this point. 14679 UnresolvedSet<16> Functions; 14680 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14681 14682 // Build the (potentially-overloaded, potentially-dependent) 14683 // binary operation. 14684 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14685 } 14686 14687 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14688 BinaryOperatorKind Opc, 14689 Expr *LHSExpr, Expr *RHSExpr) { 14690 ExprResult LHS, RHS; 14691 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14692 if (!LHS.isUsable() || !RHS.isUsable()) 14693 return ExprError(); 14694 LHSExpr = LHS.get(); 14695 RHSExpr = RHS.get(); 14696 14697 // We want to end up calling one of checkPseudoObjectAssignment 14698 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14699 // both expressions are overloadable or either is type-dependent), 14700 // or CreateBuiltinBinOp (in any other case). We also want to get 14701 // any placeholder types out of the way. 14702 14703 // Handle pseudo-objects in the LHS. 14704 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14705 // Assignments with a pseudo-object l-value need special analysis. 14706 if (pty->getKind() == BuiltinType::PseudoObject && 14707 BinaryOperator::isAssignmentOp(Opc)) 14708 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14709 14710 // Don't resolve overloads if the other type is overloadable. 14711 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14712 // We can't actually test that if we still have a placeholder, 14713 // though. Fortunately, none of the exceptions we see in that 14714 // code below are valid when the LHS is an overload set. Note 14715 // that an overload set can be dependently-typed, but it never 14716 // instantiates to having an overloadable type. 14717 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14718 if (resolvedRHS.isInvalid()) return ExprError(); 14719 RHSExpr = resolvedRHS.get(); 14720 14721 if (RHSExpr->isTypeDependent() || 14722 RHSExpr->getType()->isOverloadableType()) 14723 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14724 } 14725 14726 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14727 // template, diagnose the missing 'template' keyword instead of diagnosing 14728 // an invalid use of a bound member function. 14729 // 14730 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14731 // to C++1z [over.over]/1.4, but we already checked for that case above. 14732 if (Opc == BO_LT && inTemplateInstantiation() && 14733 (pty->getKind() == BuiltinType::BoundMember || 14734 pty->getKind() == BuiltinType::Overload)) { 14735 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14736 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14737 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14738 return isa<FunctionTemplateDecl>(ND); 14739 })) { 14740 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14741 : OE->getNameLoc(), 14742 diag::err_template_kw_missing) 14743 << OE->getName().getAsString() << ""; 14744 return ExprError(); 14745 } 14746 } 14747 14748 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14749 if (LHS.isInvalid()) return ExprError(); 14750 LHSExpr = LHS.get(); 14751 } 14752 14753 // Handle pseudo-objects in the RHS. 14754 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14755 // An overload in the RHS can potentially be resolved by the type 14756 // being assigned to. 14757 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14758 if (getLangOpts().CPlusPlus && 14759 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14760 LHSExpr->getType()->isOverloadableType())) 14761 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14762 14763 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14764 } 14765 14766 // Don't resolve overloads if the other type is overloadable. 14767 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14768 LHSExpr->getType()->isOverloadableType()) 14769 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14770 14771 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14772 if (!resolvedRHS.isUsable()) return ExprError(); 14773 RHSExpr = resolvedRHS.get(); 14774 } 14775 14776 if (getLangOpts().CPlusPlus) { 14777 // If either expression is type-dependent, always build an 14778 // overloaded op. 14779 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14780 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14781 14782 // Otherwise, build an overloaded op if either expression has an 14783 // overloadable type. 14784 if (LHSExpr->getType()->isOverloadableType() || 14785 RHSExpr->getType()->isOverloadableType()) 14786 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14787 } 14788 14789 if (getLangOpts().RecoveryAST && 14790 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14791 assert(!getLangOpts().CPlusPlus); 14792 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14793 "Should only occur in error-recovery path."); 14794 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14795 // C [6.15.16] p3: 14796 // An assignment expression has the value of the left operand after the 14797 // assignment, but is not an lvalue. 14798 return CompoundAssignOperator::Create( 14799 Context, LHSExpr, RHSExpr, Opc, 14800 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 14801 OpLoc, CurFPFeatureOverrides()); 14802 QualType ResultType; 14803 switch (Opc) { 14804 case BO_Assign: 14805 ResultType = LHSExpr->getType().getUnqualifiedType(); 14806 break; 14807 case BO_LT: 14808 case BO_GT: 14809 case BO_LE: 14810 case BO_GE: 14811 case BO_EQ: 14812 case BO_NE: 14813 case BO_LAnd: 14814 case BO_LOr: 14815 // These operators have a fixed result type regardless of operands. 14816 ResultType = Context.IntTy; 14817 break; 14818 case BO_Comma: 14819 ResultType = RHSExpr->getType(); 14820 break; 14821 default: 14822 ResultType = Context.DependentTy; 14823 break; 14824 } 14825 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14826 VK_PRValue, OK_Ordinary, OpLoc, 14827 CurFPFeatureOverrides()); 14828 } 14829 14830 // Build a built-in binary operation. 14831 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14832 } 14833 14834 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14835 if (T.isNull() || T->isDependentType()) 14836 return false; 14837 14838 if (!T->isPromotableIntegerType()) 14839 return true; 14840 14841 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14842 } 14843 14844 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14845 UnaryOperatorKind Opc, 14846 Expr *InputExpr) { 14847 ExprResult Input = InputExpr; 14848 ExprValueKind VK = VK_PRValue; 14849 ExprObjectKind OK = OK_Ordinary; 14850 QualType resultType; 14851 bool CanOverflow = false; 14852 14853 bool ConvertHalfVec = false; 14854 if (getLangOpts().OpenCL) { 14855 QualType Ty = InputExpr->getType(); 14856 // The only legal unary operation for atomics is '&'. 14857 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14858 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14859 // only with a builtin functions and therefore should be disallowed here. 14860 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14861 || Ty->isBlockPointerType())) { 14862 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14863 << InputExpr->getType() 14864 << Input.get()->getSourceRange()); 14865 } 14866 } 14867 14868 switch (Opc) { 14869 case UO_PreInc: 14870 case UO_PreDec: 14871 case UO_PostInc: 14872 case UO_PostDec: 14873 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14874 OpLoc, 14875 Opc == UO_PreInc || 14876 Opc == UO_PostInc, 14877 Opc == UO_PreInc || 14878 Opc == UO_PreDec); 14879 CanOverflow = isOverflowingIntegerType(Context, resultType); 14880 break; 14881 case UO_AddrOf: 14882 resultType = CheckAddressOfOperand(Input, OpLoc); 14883 CheckAddressOfNoDeref(InputExpr); 14884 RecordModifiableNonNullParam(*this, InputExpr); 14885 break; 14886 case UO_Deref: { 14887 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14888 if (Input.isInvalid()) return ExprError(); 14889 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14890 break; 14891 } 14892 case UO_Plus: 14893 case UO_Minus: 14894 CanOverflow = Opc == UO_Minus && 14895 isOverflowingIntegerType(Context, Input.get()->getType()); 14896 Input = UsualUnaryConversions(Input.get()); 14897 if (Input.isInvalid()) return ExprError(); 14898 // Unary plus and minus require promoting an operand of half vector to a 14899 // float vector and truncating the result back to a half vector. For now, we 14900 // do this only when HalfArgsAndReturns is set (that is, when the target is 14901 // arm or arm64). 14902 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14903 14904 // If the operand is a half vector, promote it to a float vector. 14905 if (ConvertHalfVec) 14906 Input = convertVector(Input.get(), Context.FloatTy, *this); 14907 resultType = Input.get()->getType(); 14908 if (resultType->isDependentType()) 14909 break; 14910 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14911 break; 14912 else if (resultType->isVectorType() && 14913 // The z vector extensions don't allow + or - with bool vectors. 14914 (!Context.getLangOpts().ZVector || 14915 resultType->castAs<VectorType>()->getVectorKind() != 14916 VectorType::AltiVecBool)) 14917 break; 14918 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14919 Opc == UO_Plus && 14920 resultType->isPointerType()) 14921 break; 14922 14923 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14924 << resultType << Input.get()->getSourceRange()); 14925 14926 case UO_Not: // bitwise complement 14927 Input = UsualUnaryConversions(Input.get()); 14928 if (Input.isInvalid()) 14929 return ExprError(); 14930 resultType = Input.get()->getType(); 14931 if (resultType->isDependentType()) 14932 break; 14933 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14934 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14935 // C99 does not support '~' for complex conjugation. 14936 Diag(OpLoc, diag::ext_integer_complement_complex) 14937 << resultType << Input.get()->getSourceRange(); 14938 else if (resultType->hasIntegerRepresentation()) 14939 break; 14940 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14941 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14942 // on vector float types. 14943 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14944 if (!T->isIntegerType()) 14945 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14946 << resultType << Input.get()->getSourceRange()); 14947 } else { 14948 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14949 << resultType << Input.get()->getSourceRange()); 14950 } 14951 break; 14952 14953 case UO_LNot: // logical negation 14954 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14955 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14956 if (Input.isInvalid()) return ExprError(); 14957 resultType = Input.get()->getType(); 14958 14959 // Though we still have to promote half FP to float... 14960 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14961 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14962 resultType = Context.FloatTy; 14963 } 14964 14965 if (resultType->isDependentType()) 14966 break; 14967 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14968 // C99 6.5.3.3p1: ok, fallthrough; 14969 if (Context.getLangOpts().CPlusPlus) { 14970 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14971 // operand contextually converted to bool. 14972 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14973 ScalarTypeToBooleanCastKind(resultType)); 14974 } else if (Context.getLangOpts().OpenCL && 14975 Context.getLangOpts().OpenCLVersion < 120) { 14976 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14977 // operate on scalar float types. 14978 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14979 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14980 << resultType << Input.get()->getSourceRange()); 14981 } 14982 } else if (resultType->isExtVectorType()) { 14983 if (Context.getLangOpts().OpenCL && 14984 Context.getLangOpts().OpenCLVersion < 120 && 14985 !Context.getLangOpts().OpenCLCPlusPlus) { 14986 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14987 // operate on vector float types. 14988 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14989 if (!T->isIntegerType()) 14990 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14991 << resultType << Input.get()->getSourceRange()); 14992 } 14993 // Vector logical not returns the signed variant of the operand type. 14994 resultType = GetSignedVectorType(resultType); 14995 break; 14996 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14997 const VectorType *VTy = resultType->castAs<VectorType>(); 14998 if (VTy->getVectorKind() != VectorType::GenericVector) 14999 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15000 << resultType << Input.get()->getSourceRange()); 15001 15002 // Vector logical not returns the signed variant of the operand type. 15003 resultType = GetSignedVectorType(resultType); 15004 break; 15005 } else { 15006 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15007 << resultType << Input.get()->getSourceRange()); 15008 } 15009 15010 // LNot always has type int. C99 6.5.3.3p5. 15011 // In C++, it's bool. C++ 5.3.1p8 15012 resultType = Context.getLogicalOperationType(); 15013 break; 15014 case UO_Real: 15015 case UO_Imag: 15016 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15017 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15018 // complex l-values to ordinary l-values and all other values to r-values. 15019 if (Input.isInvalid()) return ExprError(); 15020 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15021 if (Input.get()->isGLValue() && 15022 Input.get()->getObjectKind() == OK_Ordinary) 15023 VK = Input.get()->getValueKind(); 15024 } else if (!getLangOpts().CPlusPlus) { 15025 // In C, a volatile scalar is read by __imag. In C++, it is not. 15026 Input = DefaultLvalueConversion(Input.get()); 15027 } 15028 break; 15029 case UO_Extension: 15030 resultType = Input.get()->getType(); 15031 VK = Input.get()->getValueKind(); 15032 OK = Input.get()->getObjectKind(); 15033 break; 15034 case UO_Coawait: 15035 // It's unnecessary to represent the pass-through operator co_await in the 15036 // AST; just return the input expression instead. 15037 assert(!Input.get()->getType()->isDependentType() && 15038 "the co_await expression must be non-dependant before " 15039 "building operator co_await"); 15040 return Input; 15041 } 15042 if (resultType.isNull() || Input.isInvalid()) 15043 return ExprError(); 15044 15045 // Check for array bounds violations in the operand of the UnaryOperator, 15046 // except for the '*' and '&' operators that have to be handled specially 15047 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15048 // that are explicitly defined as valid by the standard). 15049 if (Opc != UO_AddrOf && Opc != UO_Deref) 15050 CheckArrayAccess(Input.get()); 15051 15052 auto *UO = 15053 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 15054 OpLoc, CanOverflow, CurFPFeatureOverrides()); 15055 15056 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 15057 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 15058 !isUnevaluatedContext()) 15059 ExprEvalContexts.back().PossibleDerefs.insert(UO); 15060 15061 // Convert the result back to a half vector. 15062 if (ConvertHalfVec) 15063 return convertVector(UO, Context.HalfTy, *this); 15064 return UO; 15065 } 15066 15067 /// Determine whether the given expression is a qualified member 15068 /// access expression, of a form that could be turned into a pointer to member 15069 /// with the address-of operator. 15070 bool Sema::isQualifiedMemberAccess(Expr *E) { 15071 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15072 if (!DRE->getQualifier()) 15073 return false; 15074 15075 ValueDecl *VD = DRE->getDecl(); 15076 if (!VD->isCXXClassMember()) 15077 return false; 15078 15079 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 15080 return true; 15081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 15082 return Method->isInstance(); 15083 15084 return false; 15085 } 15086 15087 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 15088 if (!ULE->getQualifier()) 15089 return false; 15090 15091 for (NamedDecl *D : ULE->decls()) { 15092 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 15093 if (Method->isInstance()) 15094 return true; 15095 } else { 15096 // Overload set does not contain methods. 15097 break; 15098 } 15099 } 15100 15101 return false; 15102 } 15103 15104 return false; 15105 } 15106 15107 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 15108 UnaryOperatorKind Opc, Expr *Input) { 15109 // First things first: handle placeholders so that the 15110 // overloaded-operator check considers the right type. 15111 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 15112 // Increment and decrement of pseudo-object references. 15113 if (pty->getKind() == BuiltinType::PseudoObject && 15114 UnaryOperator::isIncrementDecrementOp(Opc)) 15115 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 15116 15117 // extension is always a builtin operator. 15118 if (Opc == UO_Extension) 15119 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15120 15121 // & gets special logic for several kinds of placeholder. 15122 // The builtin code knows what to do. 15123 if (Opc == UO_AddrOf && 15124 (pty->getKind() == BuiltinType::Overload || 15125 pty->getKind() == BuiltinType::UnknownAny || 15126 pty->getKind() == BuiltinType::BoundMember)) 15127 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15128 15129 // Anything else needs to be handled now. 15130 ExprResult Result = CheckPlaceholderExpr(Input); 15131 if (Result.isInvalid()) return ExprError(); 15132 Input = Result.get(); 15133 } 15134 15135 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 15136 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 15137 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 15138 // Find all of the overloaded operators visible from this point. 15139 UnresolvedSet<16> Functions; 15140 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 15141 if (S && OverOp != OO_None) 15142 LookupOverloadedOperatorName(OverOp, S, Functions); 15143 15144 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 15145 } 15146 15147 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 15148 } 15149 15150 // Unary Operators. 'Tok' is the token for the operator. 15151 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 15152 tok::TokenKind Op, Expr *Input) { 15153 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 15154 } 15155 15156 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 15157 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 15158 LabelDecl *TheDecl) { 15159 TheDecl->markUsed(Context); 15160 // Create the AST node. The address of a label always has type 'void*'. 15161 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 15162 Context.getPointerType(Context.VoidTy)); 15163 } 15164 15165 void Sema::ActOnStartStmtExpr() { 15166 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15167 } 15168 15169 void Sema::ActOnStmtExprError() { 15170 // Note that function is also called by TreeTransform when leaving a 15171 // StmtExpr scope without rebuilding anything. 15172 15173 DiscardCleanupsInEvaluationContext(); 15174 PopExpressionEvaluationContext(); 15175 } 15176 15177 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 15178 SourceLocation RPLoc) { 15179 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 15180 } 15181 15182 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 15183 SourceLocation RPLoc, unsigned TemplateDepth) { 15184 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 15185 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 15186 15187 if (hasAnyUnrecoverableErrorsInThisFunction()) 15188 DiscardCleanupsInEvaluationContext(); 15189 assert(!Cleanup.exprNeedsCleanups() && 15190 "cleanups within StmtExpr not correctly bound!"); 15191 PopExpressionEvaluationContext(); 15192 15193 // FIXME: there are a variety of strange constraints to enforce here, for 15194 // example, it is not possible to goto into a stmt expression apparently. 15195 // More semantic analysis is needed. 15196 15197 // If there are sub-stmts in the compound stmt, take the type of the last one 15198 // as the type of the stmtexpr. 15199 QualType Ty = Context.VoidTy; 15200 bool StmtExprMayBindToTemp = false; 15201 if (!Compound->body_empty()) { 15202 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 15203 if (const auto *LastStmt = 15204 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 15205 if (const Expr *Value = LastStmt->getExprStmt()) { 15206 StmtExprMayBindToTemp = true; 15207 Ty = Value->getType(); 15208 } 15209 } 15210 } 15211 15212 // FIXME: Check that expression type is complete/non-abstract; statement 15213 // expressions are not lvalues. 15214 Expr *ResStmtExpr = 15215 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 15216 if (StmtExprMayBindToTemp) 15217 return MaybeBindToTemporary(ResStmtExpr); 15218 return ResStmtExpr; 15219 } 15220 15221 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15222 if (ER.isInvalid()) 15223 return ExprError(); 15224 15225 // Do function/array conversion on the last expression, but not 15226 // lvalue-to-rvalue. However, initialize an unqualified type. 15227 ER = DefaultFunctionArrayConversion(ER.get()); 15228 if (ER.isInvalid()) 15229 return ExprError(); 15230 Expr *E = ER.get(); 15231 15232 if (E->isTypeDependent()) 15233 return E; 15234 15235 // In ARC, if the final expression ends in a consume, splice 15236 // the consume out and bind it later. In the alternate case 15237 // (when dealing with a retainable type), the result 15238 // initialization will create a produce. In both cases the 15239 // result will be +1, and we'll need to balance that out with 15240 // a bind. 15241 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15242 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15243 return Cast->getSubExpr(); 15244 15245 // FIXME: Provide a better location for the initialization. 15246 return PerformCopyInitialization( 15247 InitializedEntity::InitializeStmtExprResult( 15248 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15249 SourceLocation(), E); 15250 } 15251 15252 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15253 TypeSourceInfo *TInfo, 15254 ArrayRef<OffsetOfComponent> Components, 15255 SourceLocation RParenLoc) { 15256 QualType ArgTy = TInfo->getType(); 15257 bool Dependent = ArgTy->isDependentType(); 15258 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15259 15260 // We must have at least one component that refers to the type, and the first 15261 // one is known to be a field designator. Verify that the ArgTy represents 15262 // a struct/union/class. 15263 if (!Dependent && !ArgTy->isRecordType()) 15264 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15265 << ArgTy << TypeRange); 15266 15267 // Type must be complete per C99 7.17p3 because a declaring a variable 15268 // with an incomplete type would be ill-formed. 15269 if (!Dependent 15270 && RequireCompleteType(BuiltinLoc, ArgTy, 15271 diag::err_offsetof_incomplete_type, TypeRange)) 15272 return ExprError(); 15273 15274 bool DidWarnAboutNonPOD = false; 15275 QualType CurrentType = ArgTy; 15276 SmallVector<OffsetOfNode, 4> Comps; 15277 SmallVector<Expr*, 4> Exprs; 15278 for (const OffsetOfComponent &OC : Components) { 15279 if (OC.isBrackets) { 15280 // Offset of an array sub-field. TODO: Should we allow vector elements? 15281 if (!CurrentType->isDependentType()) { 15282 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15283 if(!AT) 15284 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15285 << CurrentType); 15286 CurrentType = AT->getElementType(); 15287 } else 15288 CurrentType = Context.DependentTy; 15289 15290 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15291 if (IdxRval.isInvalid()) 15292 return ExprError(); 15293 Expr *Idx = IdxRval.get(); 15294 15295 // The expression must be an integral expression. 15296 // FIXME: An integral constant expression? 15297 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15298 !Idx->getType()->isIntegerType()) 15299 return ExprError( 15300 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15301 << Idx->getSourceRange()); 15302 15303 // Record this array index. 15304 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15305 Exprs.push_back(Idx); 15306 continue; 15307 } 15308 15309 // Offset of a field. 15310 if (CurrentType->isDependentType()) { 15311 // We have the offset of a field, but we can't look into the dependent 15312 // type. Just record the identifier of the field. 15313 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15314 CurrentType = Context.DependentTy; 15315 continue; 15316 } 15317 15318 // We need to have a complete type to look into. 15319 if (RequireCompleteType(OC.LocStart, CurrentType, 15320 diag::err_offsetof_incomplete_type)) 15321 return ExprError(); 15322 15323 // Look for the designated field. 15324 const RecordType *RC = CurrentType->getAs<RecordType>(); 15325 if (!RC) 15326 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15327 << CurrentType); 15328 RecordDecl *RD = RC->getDecl(); 15329 15330 // C++ [lib.support.types]p5: 15331 // The macro offsetof accepts a restricted set of type arguments in this 15332 // International Standard. type shall be a POD structure or a POD union 15333 // (clause 9). 15334 // C++11 [support.types]p4: 15335 // If type is not a standard-layout class (Clause 9), the results are 15336 // undefined. 15337 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15338 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15339 unsigned DiagID = 15340 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15341 : diag::ext_offsetof_non_pod_type; 15342 15343 if (!IsSafe && !DidWarnAboutNonPOD && 15344 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15345 PDiag(DiagID) 15346 << SourceRange(Components[0].LocStart, OC.LocEnd) 15347 << CurrentType)) 15348 DidWarnAboutNonPOD = true; 15349 } 15350 15351 // Look for the field. 15352 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15353 LookupQualifiedName(R, RD); 15354 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15355 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15356 if (!MemberDecl) { 15357 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15358 MemberDecl = IndirectMemberDecl->getAnonField(); 15359 } 15360 15361 if (!MemberDecl) 15362 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15363 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15364 OC.LocEnd)); 15365 15366 // C99 7.17p3: 15367 // (If the specified member is a bit-field, the behavior is undefined.) 15368 // 15369 // We diagnose this as an error. 15370 if (MemberDecl->isBitField()) { 15371 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15372 << MemberDecl->getDeclName() 15373 << SourceRange(BuiltinLoc, RParenLoc); 15374 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15375 return ExprError(); 15376 } 15377 15378 RecordDecl *Parent = MemberDecl->getParent(); 15379 if (IndirectMemberDecl) 15380 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15381 15382 // If the member was found in a base class, introduce OffsetOfNodes for 15383 // the base class indirections. 15384 CXXBasePaths Paths; 15385 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15386 Paths)) { 15387 if (Paths.getDetectedVirtual()) { 15388 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15389 << MemberDecl->getDeclName() 15390 << SourceRange(BuiltinLoc, RParenLoc); 15391 return ExprError(); 15392 } 15393 15394 CXXBasePath &Path = Paths.front(); 15395 for (const CXXBasePathElement &B : Path) 15396 Comps.push_back(OffsetOfNode(B.Base)); 15397 } 15398 15399 if (IndirectMemberDecl) { 15400 for (auto *FI : IndirectMemberDecl->chain()) { 15401 assert(isa<FieldDecl>(FI)); 15402 Comps.push_back(OffsetOfNode(OC.LocStart, 15403 cast<FieldDecl>(FI), OC.LocEnd)); 15404 } 15405 } else 15406 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15407 15408 CurrentType = MemberDecl->getType().getNonReferenceType(); 15409 } 15410 15411 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15412 Comps, Exprs, RParenLoc); 15413 } 15414 15415 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15416 SourceLocation BuiltinLoc, 15417 SourceLocation TypeLoc, 15418 ParsedType ParsedArgTy, 15419 ArrayRef<OffsetOfComponent> Components, 15420 SourceLocation RParenLoc) { 15421 15422 TypeSourceInfo *ArgTInfo; 15423 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15424 if (ArgTy.isNull()) 15425 return ExprError(); 15426 15427 if (!ArgTInfo) 15428 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15429 15430 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15431 } 15432 15433 15434 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15435 Expr *CondExpr, 15436 Expr *LHSExpr, Expr *RHSExpr, 15437 SourceLocation RPLoc) { 15438 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15439 15440 ExprValueKind VK = VK_PRValue; 15441 ExprObjectKind OK = OK_Ordinary; 15442 QualType resType; 15443 bool CondIsTrue = false; 15444 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15445 resType = Context.DependentTy; 15446 } else { 15447 // The conditional expression is required to be a constant expression. 15448 llvm::APSInt condEval(32); 15449 ExprResult CondICE = VerifyIntegerConstantExpression( 15450 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15451 if (CondICE.isInvalid()) 15452 return ExprError(); 15453 CondExpr = CondICE.get(); 15454 CondIsTrue = condEval.getZExtValue(); 15455 15456 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15457 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15458 15459 resType = ActiveExpr->getType(); 15460 VK = ActiveExpr->getValueKind(); 15461 OK = ActiveExpr->getObjectKind(); 15462 } 15463 15464 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15465 resType, VK, OK, RPLoc, CondIsTrue); 15466 } 15467 15468 //===----------------------------------------------------------------------===// 15469 // Clang Extensions. 15470 //===----------------------------------------------------------------------===// 15471 15472 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15473 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15474 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15475 15476 if (LangOpts.CPlusPlus) { 15477 MangleNumberingContext *MCtx; 15478 Decl *ManglingContextDecl; 15479 std::tie(MCtx, ManglingContextDecl) = 15480 getCurrentMangleNumberContext(Block->getDeclContext()); 15481 if (MCtx) { 15482 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15483 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15484 } 15485 } 15486 15487 PushBlockScope(CurScope, Block); 15488 CurContext->addDecl(Block); 15489 if (CurScope) 15490 PushDeclContext(CurScope, Block); 15491 else 15492 CurContext = Block; 15493 15494 getCurBlock()->HasImplicitReturnType = true; 15495 15496 // Enter a new evaluation context to insulate the block from any 15497 // cleanups from the enclosing full-expression. 15498 PushExpressionEvaluationContext( 15499 ExpressionEvaluationContext::PotentiallyEvaluated); 15500 } 15501 15502 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15503 Scope *CurScope) { 15504 assert(ParamInfo.getIdentifier() == nullptr && 15505 "block-id should have no identifier!"); 15506 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15507 BlockScopeInfo *CurBlock = getCurBlock(); 15508 15509 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15510 QualType T = Sig->getType(); 15511 15512 // FIXME: We should allow unexpanded parameter packs here, but that would, 15513 // in turn, make the block expression contain unexpanded parameter packs. 15514 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15515 // Drop the parameters. 15516 FunctionProtoType::ExtProtoInfo EPI; 15517 EPI.HasTrailingReturn = false; 15518 EPI.TypeQuals.addConst(); 15519 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15520 Sig = Context.getTrivialTypeSourceInfo(T); 15521 } 15522 15523 // GetTypeForDeclarator always produces a function type for a block 15524 // literal signature. Furthermore, it is always a FunctionProtoType 15525 // unless the function was written with a typedef. 15526 assert(T->isFunctionType() && 15527 "GetTypeForDeclarator made a non-function block signature"); 15528 15529 // Look for an explicit signature in that function type. 15530 FunctionProtoTypeLoc ExplicitSignature; 15531 15532 if ((ExplicitSignature = Sig->getTypeLoc() 15533 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15534 15535 // Check whether that explicit signature was synthesized by 15536 // GetTypeForDeclarator. If so, don't save that as part of the 15537 // written signature. 15538 if (ExplicitSignature.getLocalRangeBegin() == 15539 ExplicitSignature.getLocalRangeEnd()) { 15540 // This would be much cheaper if we stored TypeLocs instead of 15541 // TypeSourceInfos. 15542 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15543 unsigned Size = Result.getFullDataSize(); 15544 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15545 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15546 15547 ExplicitSignature = FunctionProtoTypeLoc(); 15548 } 15549 } 15550 15551 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15552 CurBlock->FunctionType = T; 15553 15554 const auto *Fn = T->castAs<FunctionType>(); 15555 QualType RetTy = Fn->getReturnType(); 15556 bool isVariadic = 15557 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15558 15559 CurBlock->TheDecl->setIsVariadic(isVariadic); 15560 15561 // Context.DependentTy is used as a placeholder for a missing block 15562 // return type. TODO: what should we do with declarators like: 15563 // ^ * { ... } 15564 // If the answer is "apply template argument deduction".... 15565 if (RetTy != Context.DependentTy) { 15566 CurBlock->ReturnType = RetTy; 15567 CurBlock->TheDecl->setBlockMissingReturnType(false); 15568 CurBlock->HasImplicitReturnType = false; 15569 } 15570 15571 // Push block parameters from the declarator if we had them. 15572 SmallVector<ParmVarDecl*, 8> Params; 15573 if (ExplicitSignature) { 15574 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15575 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15576 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15577 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15578 // Diagnose this as an extension in C17 and earlier. 15579 if (!getLangOpts().C2x) 15580 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15581 } 15582 Params.push_back(Param); 15583 } 15584 15585 // Fake up parameter variables if we have a typedef, like 15586 // ^ fntype { ... } 15587 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15588 for (const auto &I : Fn->param_types()) { 15589 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15590 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15591 Params.push_back(Param); 15592 } 15593 } 15594 15595 // Set the parameters on the block decl. 15596 if (!Params.empty()) { 15597 CurBlock->TheDecl->setParams(Params); 15598 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15599 /*CheckParameterNames=*/false); 15600 } 15601 15602 // Finally we can process decl attributes. 15603 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15604 15605 // Put the parameter variables in scope. 15606 for (auto AI : CurBlock->TheDecl->parameters()) { 15607 AI->setOwningFunction(CurBlock->TheDecl); 15608 15609 // If this has an identifier, add it to the scope stack. 15610 if (AI->getIdentifier()) { 15611 CheckShadow(CurBlock->TheScope, AI); 15612 15613 PushOnScopeChains(AI, CurBlock->TheScope); 15614 } 15615 } 15616 } 15617 15618 /// ActOnBlockError - If there is an error parsing a block, this callback 15619 /// is invoked to pop the information about the block from the action impl. 15620 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15621 // Leave the expression-evaluation context. 15622 DiscardCleanupsInEvaluationContext(); 15623 PopExpressionEvaluationContext(); 15624 15625 // Pop off CurBlock, handle nested blocks. 15626 PopDeclContext(); 15627 PopFunctionScopeInfo(); 15628 } 15629 15630 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15631 /// literal was successfully completed. ^(int x){...} 15632 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15633 Stmt *Body, Scope *CurScope) { 15634 // If blocks are disabled, emit an error. 15635 if (!LangOpts.Blocks) 15636 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15637 15638 // Leave the expression-evaluation context. 15639 if (hasAnyUnrecoverableErrorsInThisFunction()) 15640 DiscardCleanupsInEvaluationContext(); 15641 assert(!Cleanup.exprNeedsCleanups() && 15642 "cleanups within block not correctly bound!"); 15643 PopExpressionEvaluationContext(); 15644 15645 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15646 BlockDecl *BD = BSI->TheDecl; 15647 15648 if (BSI->HasImplicitReturnType) 15649 deduceClosureReturnType(*BSI); 15650 15651 QualType RetTy = Context.VoidTy; 15652 if (!BSI->ReturnType.isNull()) 15653 RetTy = BSI->ReturnType; 15654 15655 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15656 QualType BlockTy; 15657 15658 // If the user wrote a function type in some form, try to use that. 15659 if (!BSI->FunctionType.isNull()) { 15660 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15661 15662 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15663 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15664 15665 // Turn protoless block types into nullary block types. 15666 if (isa<FunctionNoProtoType>(FTy)) { 15667 FunctionProtoType::ExtProtoInfo EPI; 15668 EPI.ExtInfo = Ext; 15669 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15670 15671 // Otherwise, if we don't need to change anything about the function type, 15672 // preserve its sugar structure. 15673 } else if (FTy->getReturnType() == RetTy && 15674 (!NoReturn || FTy->getNoReturnAttr())) { 15675 BlockTy = BSI->FunctionType; 15676 15677 // Otherwise, make the minimal modifications to the function type. 15678 } else { 15679 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15680 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15681 EPI.TypeQuals = Qualifiers(); 15682 EPI.ExtInfo = Ext; 15683 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15684 } 15685 15686 // If we don't have a function type, just build one from nothing. 15687 } else { 15688 FunctionProtoType::ExtProtoInfo EPI; 15689 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15690 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15691 } 15692 15693 DiagnoseUnusedParameters(BD->parameters()); 15694 BlockTy = Context.getBlockPointerType(BlockTy); 15695 15696 // If needed, diagnose invalid gotos and switches in the block. 15697 if (getCurFunction()->NeedsScopeChecking() && 15698 !PP.isCodeCompletionEnabled()) 15699 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15700 15701 BD->setBody(cast<CompoundStmt>(Body)); 15702 15703 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15704 DiagnoseUnguardedAvailabilityViolations(BD); 15705 15706 // Try to apply the named return value optimization. We have to check again 15707 // if we can do this, though, because blocks keep return statements around 15708 // to deduce an implicit return type. 15709 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15710 !BD->isDependentContext()) 15711 computeNRVO(Body, BSI); 15712 15713 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15714 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15715 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15716 NTCUK_Destruct|NTCUK_Copy); 15717 15718 PopDeclContext(); 15719 15720 // Set the captured variables on the block. 15721 SmallVector<BlockDecl::Capture, 4> Captures; 15722 for (Capture &Cap : BSI->Captures) { 15723 if (Cap.isInvalid() || Cap.isThisCapture()) 15724 continue; 15725 15726 VarDecl *Var = Cap.getVariable(); 15727 Expr *CopyExpr = nullptr; 15728 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15729 if (const RecordType *Record = 15730 Cap.getCaptureType()->getAs<RecordType>()) { 15731 // The capture logic needs the destructor, so make sure we mark it. 15732 // Usually this is unnecessary because most local variables have 15733 // their destructors marked at declaration time, but parameters are 15734 // an exception because it's technically only the call site that 15735 // actually requires the destructor. 15736 if (isa<ParmVarDecl>(Var)) 15737 FinalizeVarWithDestructor(Var, Record); 15738 15739 // Enter a separate potentially-evaluated context while building block 15740 // initializers to isolate their cleanups from those of the block 15741 // itself. 15742 // FIXME: Is this appropriate even when the block itself occurs in an 15743 // unevaluated operand? 15744 EnterExpressionEvaluationContext EvalContext( 15745 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15746 15747 SourceLocation Loc = Cap.getLocation(); 15748 15749 ExprResult Result = BuildDeclarationNameExpr( 15750 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15751 15752 // According to the blocks spec, the capture of a variable from 15753 // the stack requires a const copy constructor. This is not true 15754 // of the copy/move done to move a __block variable to the heap. 15755 if (!Result.isInvalid() && 15756 !Result.get()->getType().isConstQualified()) { 15757 Result = ImpCastExprToType(Result.get(), 15758 Result.get()->getType().withConst(), 15759 CK_NoOp, VK_LValue); 15760 } 15761 15762 if (!Result.isInvalid()) { 15763 Result = PerformCopyInitialization( 15764 InitializedEntity::InitializeBlock(Var->getLocation(), 15765 Cap.getCaptureType(), false), 15766 Loc, Result.get()); 15767 } 15768 15769 // Build a full-expression copy expression if initialization 15770 // succeeded and used a non-trivial constructor. Recover from 15771 // errors by pretending that the copy isn't necessary. 15772 if (!Result.isInvalid() && 15773 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15774 ->isTrivial()) { 15775 Result = MaybeCreateExprWithCleanups(Result); 15776 CopyExpr = Result.get(); 15777 } 15778 } 15779 } 15780 15781 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15782 CopyExpr); 15783 Captures.push_back(NewCap); 15784 } 15785 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15786 15787 // Pop the block scope now but keep it alive to the end of this function. 15788 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15789 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15790 15791 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15792 15793 // If the block isn't obviously global, i.e. it captures anything at 15794 // all, then we need to do a few things in the surrounding context: 15795 if (Result->getBlockDecl()->hasCaptures()) { 15796 // First, this expression has a new cleanup object. 15797 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15798 Cleanup.setExprNeedsCleanups(true); 15799 15800 // It also gets a branch-protected scope if any of the captured 15801 // variables needs destruction. 15802 for (const auto &CI : Result->getBlockDecl()->captures()) { 15803 const VarDecl *var = CI.getVariable(); 15804 if (var->getType().isDestructedType() != QualType::DK_none) { 15805 setFunctionHasBranchProtectedScope(); 15806 break; 15807 } 15808 } 15809 } 15810 15811 if (getCurFunction()) 15812 getCurFunction()->addBlock(BD); 15813 15814 return Result; 15815 } 15816 15817 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15818 SourceLocation RPLoc) { 15819 TypeSourceInfo *TInfo; 15820 GetTypeFromParser(Ty, &TInfo); 15821 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15822 } 15823 15824 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15825 Expr *E, TypeSourceInfo *TInfo, 15826 SourceLocation RPLoc) { 15827 Expr *OrigExpr = E; 15828 bool IsMS = false; 15829 15830 // CUDA device code does not support varargs. 15831 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15832 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15833 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15834 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15835 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15836 } 15837 } 15838 15839 // NVPTX does not support va_arg expression. 15840 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15841 Context.getTargetInfo().getTriple().isNVPTX()) 15842 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15843 15844 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15845 // as Microsoft ABI on an actual Microsoft platform, where 15846 // __builtin_ms_va_list and __builtin_va_list are the same.) 15847 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15848 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15849 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15850 if (Context.hasSameType(MSVaListType, E->getType())) { 15851 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15852 return ExprError(); 15853 IsMS = true; 15854 } 15855 } 15856 15857 // Get the va_list type 15858 QualType VaListType = Context.getBuiltinVaListType(); 15859 if (!IsMS) { 15860 if (VaListType->isArrayType()) { 15861 // Deal with implicit array decay; for example, on x86-64, 15862 // va_list is an array, but it's supposed to decay to 15863 // a pointer for va_arg. 15864 VaListType = Context.getArrayDecayedType(VaListType); 15865 // Make sure the input expression also decays appropriately. 15866 ExprResult Result = UsualUnaryConversions(E); 15867 if (Result.isInvalid()) 15868 return ExprError(); 15869 E = Result.get(); 15870 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15871 // If va_list is a record type and we are compiling in C++ mode, 15872 // check the argument using reference binding. 15873 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15874 Context, Context.getLValueReferenceType(VaListType), false); 15875 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15876 if (Init.isInvalid()) 15877 return ExprError(); 15878 E = Init.getAs<Expr>(); 15879 } else { 15880 // Otherwise, the va_list argument must be an l-value because 15881 // it is modified by va_arg. 15882 if (!E->isTypeDependent() && 15883 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15884 return ExprError(); 15885 } 15886 } 15887 15888 if (!IsMS && !E->isTypeDependent() && 15889 !Context.hasSameType(VaListType, E->getType())) 15890 return ExprError( 15891 Diag(E->getBeginLoc(), 15892 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15893 << OrigExpr->getType() << E->getSourceRange()); 15894 15895 if (!TInfo->getType()->isDependentType()) { 15896 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15897 diag::err_second_parameter_to_va_arg_incomplete, 15898 TInfo->getTypeLoc())) 15899 return ExprError(); 15900 15901 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15902 TInfo->getType(), 15903 diag::err_second_parameter_to_va_arg_abstract, 15904 TInfo->getTypeLoc())) 15905 return ExprError(); 15906 15907 if (!TInfo->getType().isPODType(Context)) { 15908 Diag(TInfo->getTypeLoc().getBeginLoc(), 15909 TInfo->getType()->isObjCLifetimeType() 15910 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15911 : diag::warn_second_parameter_to_va_arg_not_pod) 15912 << TInfo->getType() 15913 << TInfo->getTypeLoc().getSourceRange(); 15914 } 15915 15916 // Check for va_arg where arguments of the given type will be promoted 15917 // (i.e. this va_arg is guaranteed to have undefined behavior). 15918 QualType PromoteType; 15919 if (TInfo->getType()->isPromotableIntegerType()) { 15920 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15921 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 15922 // and C2x 7.16.1.1p2 says, in part: 15923 // If type is not compatible with the type of the actual next argument 15924 // (as promoted according to the default argument promotions), the 15925 // behavior is undefined, except for the following cases: 15926 // - both types are pointers to qualified or unqualified versions of 15927 // compatible types; 15928 // - one type is a signed integer type, the other type is the 15929 // corresponding unsigned integer type, and the value is 15930 // representable in both types; 15931 // - one type is pointer to qualified or unqualified void and the 15932 // other is a pointer to a qualified or unqualified character type. 15933 // Given that type compatibility is the primary requirement (ignoring 15934 // qualifications), you would think we could call typesAreCompatible() 15935 // directly to test this. However, in C++, that checks for *same type*, 15936 // which causes false positives when passing an enumeration type to 15937 // va_arg. Instead, get the underlying type of the enumeration and pass 15938 // that. 15939 QualType UnderlyingType = TInfo->getType(); 15940 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 15941 UnderlyingType = ET->getDecl()->getIntegerType(); 15942 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15943 /*CompareUnqualified*/ true)) 15944 PromoteType = QualType(); 15945 15946 // If the types are still not compatible, we need to test whether the 15947 // promoted type and the underlying type are the same except for 15948 // signedness. Ask the AST for the correctly corresponding type and see 15949 // if that's compatible. 15950 if (!PromoteType.isNull() && 15951 PromoteType->isUnsignedIntegerType() != 15952 UnderlyingType->isUnsignedIntegerType()) { 15953 UnderlyingType = 15954 UnderlyingType->isUnsignedIntegerType() 15955 ? Context.getCorrespondingSignedType(UnderlyingType) 15956 : Context.getCorrespondingUnsignedType(UnderlyingType); 15957 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 15958 /*CompareUnqualified*/ true)) 15959 PromoteType = QualType(); 15960 } 15961 } 15962 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15963 PromoteType = Context.DoubleTy; 15964 if (!PromoteType.isNull()) 15965 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15966 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15967 << TInfo->getType() 15968 << PromoteType 15969 << TInfo->getTypeLoc().getSourceRange()); 15970 } 15971 15972 QualType T = TInfo->getType().getNonLValueExprType(Context); 15973 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15974 } 15975 15976 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15977 // The type of __null will be int or long, depending on the size of 15978 // pointers on the target. 15979 QualType Ty; 15980 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15981 if (pw == Context.getTargetInfo().getIntWidth()) 15982 Ty = Context.IntTy; 15983 else if (pw == Context.getTargetInfo().getLongWidth()) 15984 Ty = Context.LongTy; 15985 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15986 Ty = Context.LongLongTy; 15987 else { 15988 llvm_unreachable("I don't know size of pointer!"); 15989 } 15990 15991 return new (Context) GNUNullExpr(Ty, TokenLoc); 15992 } 15993 15994 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15995 SourceLocation BuiltinLoc, 15996 SourceLocation RPLoc) { 15997 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15998 } 15999 16000 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 16001 SourceLocation BuiltinLoc, 16002 SourceLocation RPLoc, 16003 DeclContext *ParentContext) { 16004 return new (Context) 16005 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 16006 } 16007 16008 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 16009 bool Diagnose) { 16010 if (!getLangOpts().ObjC) 16011 return false; 16012 16013 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 16014 if (!PT) 16015 return false; 16016 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 16017 16018 // Ignore any parens, implicit casts (should only be 16019 // array-to-pointer decays), and not-so-opaque values. The last is 16020 // important for making this trigger for property assignments. 16021 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 16022 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 16023 if (OV->getSourceExpr()) 16024 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 16025 16026 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 16027 if (!PT->isObjCIdType() && 16028 !(ID && ID->getIdentifier()->isStr("NSString"))) 16029 return false; 16030 if (!SL->isAscii()) 16031 return false; 16032 16033 if (Diagnose) { 16034 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 16035 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 16036 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 16037 } 16038 return true; 16039 } 16040 16041 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 16042 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 16043 isa<CXXBoolLiteralExpr>(SrcExpr)) && 16044 !SrcExpr->isNullPointerConstant( 16045 getASTContext(), Expr::NPC_NeverValueDependent)) { 16046 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 16047 return false; 16048 if (Diagnose) { 16049 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 16050 << /*number*/1 16051 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 16052 Expr *NumLit = 16053 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 16054 if (NumLit) 16055 Exp = NumLit; 16056 } 16057 return true; 16058 } 16059 16060 return false; 16061 } 16062 16063 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 16064 const Expr *SrcExpr) { 16065 if (!DstType->isFunctionPointerType() || 16066 !SrcExpr->getType()->isFunctionType()) 16067 return false; 16068 16069 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 16070 if (!DRE) 16071 return false; 16072 16073 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 16074 if (!FD) 16075 return false; 16076 16077 return !S.checkAddressOfFunctionIsAvailable(FD, 16078 /*Complain=*/true, 16079 SrcExpr->getBeginLoc()); 16080 } 16081 16082 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 16083 SourceLocation Loc, 16084 QualType DstType, QualType SrcType, 16085 Expr *SrcExpr, AssignmentAction Action, 16086 bool *Complained) { 16087 if (Complained) 16088 *Complained = false; 16089 16090 // Decode the result (notice that AST's are still created for extensions). 16091 bool CheckInferredResultType = false; 16092 bool isInvalid = false; 16093 unsigned DiagKind = 0; 16094 ConversionFixItGenerator ConvHints; 16095 bool MayHaveConvFixit = false; 16096 bool MayHaveFunctionDiff = false; 16097 const ObjCInterfaceDecl *IFace = nullptr; 16098 const ObjCProtocolDecl *PDecl = nullptr; 16099 16100 switch (ConvTy) { 16101 case Compatible: 16102 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 16103 return false; 16104 16105 case PointerToInt: 16106 if (getLangOpts().CPlusPlus) { 16107 DiagKind = diag::err_typecheck_convert_pointer_int; 16108 isInvalid = true; 16109 } else { 16110 DiagKind = diag::ext_typecheck_convert_pointer_int; 16111 } 16112 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16113 MayHaveConvFixit = true; 16114 break; 16115 case IntToPointer: 16116 if (getLangOpts().CPlusPlus) { 16117 DiagKind = diag::err_typecheck_convert_int_pointer; 16118 isInvalid = true; 16119 } else { 16120 DiagKind = diag::ext_typecheck_convert_int_pointer; 16121 } 16122 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16123 MayHaveConvFixit = true; 16124 break; 16125 case IncompatibleFunctionPointer: 16126 if (getLangOpts().CPlusPlus) { 16127 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 16128 isInvalid = true; 16129 } else { 16130 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 16131 } 16132 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16133 MayHaveConvFixit = true; 16134 break; 16135 case IncompatiblePointer: 16136 if (Action == AA_Passing_CFAudited) { 16137 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 16138 } else if (getLangOpts().CPlusPlus) { 16139 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 16140 isInvalid = true; 16141 } else { 16142 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 16143 } 16144 CheckInferredResultType = DstType->isObjCObjectPointerType() && 16145 SrcType->isObjCObjectPointerType(); 16146 if (!CheckInferredResultType) { 16147 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16148 } else if (CheckInferredResultType) { 16149 SrcType = SrcType.getUnqualifiedType(); 16150 DstType = DstType.getUnqualifiedType(); 16151 } 16152 MayHaveConvFixit = true; 16153 break; 16154 case IncompatiblePointerSign: 16155 if (getLangOpts().CPlusPlus) { 16156 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 16157 isInvalid = true; 16158 } else { 16159 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 16160 } 16161 break; 16162 case FunctionVoidPointer: 16163 if (getLangOpts().CPlusPlus) { 16164 DiagKind = diag::err_typecheck_convert_pointer_void_func; 16165 isInvalid = true; 16166 } else { 16167 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 16168 } 16169 break; 16170 case IncompatiblePointerDiscardsQualifiers: { 16171 // Perform array-to-pointer decay if necessary. 16172 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 16173 16174 isInvalid = true; 16175 16176 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 16177 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 16178 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 16179 DiagKind = diag::err_typecheck_incompatible_address_space; 16180 break; 16181 16182 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 16183 DiagKind = diag::err_typecheck_incompatible_ownership; 16184 break; 16185 } 16186 16187 llvm_unreachable("unknown error case for discarding qualifiers!"); 16188 // fallthrough 16189 } 16190 case CompatiblePointerDiscardsQualifiers: 16191 // If the qualifiers lost were because we were applying the 16192 // (deprecated) C++ conversion from a string literal to a char* 16193 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 16194 // Ideally, this check would be performed in 16195 // checkPointerTypesForAssignment. However, that would require a 16196 // bit of refactoring (so that the second argument is an 16197 // expression, rather than a type), which should be done as part 16198 // of a larger effort to fix checkPointerTypesForAssignment for 16199 // C++ semantics. 16200 if (getLangOpts().CPlusPlus && 16201 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 16202 return false; 16203 if (getLangOpts().CPlusPlus) { 16204 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 16205 isInvalid = true; 16206 } else { 16207 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 16208 } 16209 16210 break; 16211 case IncompatibleNestedPointerQualifiers: 16212 if (getLangOpts().CPlusPlus) { 16213 isInvalid = true; 16214 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 16215 } else { 16216 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 16217 } 16218 break; 16219 case IncompatibleNestedPointerAddressSpaceMismatch: 16220 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 16221 isInvalid = true; 16222 break; 16223 case IntToBlockPointer: 16224 DiagKind = diag::err_int_to_block_pointer; 16225 isInvalid = true; 16226 break; 16227 case IncompatibleBlockPointer: 16228 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 16229 isInvalid = true; 16230 break; 16231 case IncompatibleObjCQualifiedId: { 16232 if (SrcType->isObjCQualifiedIdType()) { 16233 const ObjCObjectPointerType *srcOPT = 16234 SrcType->castAs<ObjCObjectPointerType>(); 16235 for (auto *srcProto : srcOPT->quals()) { 16236 PDecl = srcProto; 16237 break; 16238 } 16239 if (const ObjCInterfaceType *IFaceT = 16240 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16241 IFace = IFaceT->getDecl(); 16242 } 16243 else if (DstType->isObjCQualifiedIdType()) { 16244 const ObjCObjectPointerType *dstOPT = 16245 DstType->castAs<ObjCObjectPointerType>(); 16246 for (auto *dstProto : dstOPT->quals()) { 16247 PDecl = dstProto; 16248 break; 16249 } 16250 if (const ObjCInterfaceType *IFaceT = 16251 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 16252 IFace = IFaceT->getDecl(); 16253 } 16254 if (getLangOpts().CPlusPlus) { 16255 DiagKind = diag::err_incompatible_qualified_id; 16256 isInvalid = true; 16257 } else { 16258 DiagKind = diag::warn_incompatible_qualified_id; 16259 } 16260 break; 16261 } 16262 case IncompatibleVectors: 16263 if (getLangOpts().CPlusPlus) { 16264 DiagKind = diag::err_incompatible_vectors; 16265 isInvalid = true; 16266 } else { 16267 DiagKind = diag::warn_incompatible_vectors; 16268 } 16269 break; 16270 case IncompatibleObjCWeakRef: 16271 DiagKind = diag::err_arc_weak_unavailable_assign; 16272 isInvalid = true; 16273 break; 16274 case Incompatible: 16275 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16276 if (Complained) 16277 *Complained = true; 16278 return true; 16279 } 16280 16281 DiagKind = diag::err_typecheck_convert_incompatible; 16282 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16283 MayHaveConvFixit = true; 16284 isInvalid = true; 16285 MayHaveFunctionDiff = true; 16286 break; 16287 } 16288 16289 QualType FirstType, SecondType; 16290 switch (Action) { 16291 case AA_Assigning: 16292 case AA_Initializing: 16293 // The destination type comes first. 16294 FirstType = DstType; 16295 SecondType = SrcType; 16296 break; 16297 16298 case AA_Returning: 16299 case AA_Passing: 16300 case AA_Passing_CFAudited: 16301 case AA_Converting: 16302 case AA_Sending: 16303 case AA_Casting: 16304 // The source type comes first. 16305 FirstType = SrcType; 16306 SecondType = DstType; 16307 break; 16308 } 16309 16310 PartialDiagnostic FDiag = PDiag(DiagKind); 16311 if (Action == AA_Passing_CFAudited) 16312 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16313 else 16314 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16315 16316 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16317 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16318 auto isPlainChar = [](const clang::Type *Type) { 16319 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16320 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16321 }; 16322 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16323 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16324 } 16325 16326 // If we can fix the conversion, suggest the FixIts. 16327 if (!ConvHints.isNull()) { 16328 for (FixItHint &H : ConvHints.Hints) 16329 FDiag << H; 16330 } 16331 16332 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16333 16334 if (MayHaveFunctionDiff) 16335 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16336 16337 Diag(Loc, FDiag); 16338 if ((DiagKind == diag::warn_incompatible_qualified_id || 16339 DiagKind == diag::err_incompatible_qualified_id) && 16340 PDecl && IFace && !IFace->hasDefinition()) 16341 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16342 << IFace << PDecl; 16343 16344 if (SecondType == Context.OverloadTy) 16345 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16346 FirstType, /*TakingAddress=*/true); 16347 16348 if (CheckInferredResultType) 16349 EmitRelatedResultTypeNote(SrcExpr); 16350 16351 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16352 EmitRelatedResultTypeNoteForReturn(DstType); 16353 16354 if (Complained) 16355 *Complained = true; 16356 return isInvalid; 16357 } 16358 16359 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16360 llvm::APSInt *Result, 16361 AllowFoldKind CanFold) { 16362 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16363 public: 16364 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16365 QualType T) override { 16366 return S.Diag(Loc, diag::err_ice_not_integral) 16367 << T << S.LangOpts.CPlusPlus; 16368 } 16369 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16370 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16371 } 16372 } Diagnoser; 16373 16374 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16375 } 16376 16377 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16378 llvm::APSInt *Result, 16379 unsigned DiagID, 16380 AllowFoldKind CanFold) { 16381 class IDDiagnoser : public VerifyICEDiagnoser { 16382 unsigned DiagID; 16383 16384 public: 16385 IDDiagnoser(unsigned DiagID) 16386 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16387 16388 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16389 return S.Diag(Loc, DiagID); 16390 } 16391 } Diagnoser(DiagID); 16392 16393 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16394 } 16395 16396 Sema::SemaDiagnosticBuilder 16397 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16398 QualType T) { 16399 return diagnoseNotICE(S, Loc); 16400 } 16401 16402 Sema::SemaDiagnosticBuilder 16403 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16404 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16405 } 16406 16407 ExprResult 16408 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16409 VerifyICEDiagnoser &Diagnoser, 16410 AllowFoldKind CanFold) { 16411 SourceLocation DiagLoc = E->getBeginLoc(); 16412 16413 if (getLangOpts().CPlusPlus11) { 16414 // C++11 [expr.const]p5: 16415 // If an expression of literal class type is used in a context where an 16416 // integral constant expression is required, then that class type shall 16417 // have a single non-explicit conversion function to an integral or 16418 // unscoped enumeration type 16419 ExprResult Converted; 16420 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16421 VerifyICEDiagnoser &BaseDiagnoser; 16422 public: 16423 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16424 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16425 BaseDiagnoser.Suppress, true), 16426 BaseDiagnoser(BaseDiagnoser) {} 16427 16428 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16429 QualType T) override { 16430 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16431 } 16432 16433 SemaDiagnosticBuilder diagnoseIncomplete( 16434 Sema &S, SourceLocation Loc, QualType T) override { 16435 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16436 } 16437 16438 SemaDiagnosticBuilder diagnoseExplicitConv( 16439 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16440 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16441 } 16442 16443 SemaDiagnosticBuilder noteExplicitConv( 16444 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16445 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16446 << ConvTy->isEnumeralType() << ConvTy; 16447 } 16448 16449 SemaDiagnosticBuilder diagnoseAmbiguous( 16450 Sema &S, SourceLocation Loc, QualType T) override { 16451 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16452 } 16453 16454 SemaDiagnosticBuilder noteAmbiguous( 16455 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16456 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16457 << ConvTy->isEnumeralType() << ConvTy; 16458 } 16459 16460 SemaDiagnosticBuilder diagnoseConversion( 16461 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16462 llvm_unreachable("conversion functions are permitted"); 16463 } 16464 } ConvertDiagnoser(Diagnoser); 16465 16466 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16467 ConvertDiagnoser); 16468 if (Converted.isInvalid()) 16469 return Converted; 16470 E = Converted.get(); 16471 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16472 return ExprError(); 16473 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16474 // An ICE must be of integral or unscoped enumeration type. 16475 if (!Diagnoser.Suppress) 16476 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16477 << E->getSourceRange(); 16478 return ExprError(); 16479 } 16480 16481 ExprResult RValueExpr = DefaultLvalueConversion(E); 16482 if (RValueExpr.isInvalid()) 16483 return ExprError(); 16484 16485 E = RValueExpr.get(); 16486 16487 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16488 // in the non-ICE case. 16489 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16490 if (Result) 16491 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16492 if (!isa<ConstantExpr>(E)) 16493 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16494 : ConstantExpr::Create(Context, E); 16495 return E; 16496 } 16497 16498 Expr::EvalResult EvalResult; 16499 SmallVector<PartialDiagnosticAt, 8> Notes; 16500 EvalResult.Diag = &Notes; 16501 16502 // Try to evaluate the expression, and produce diagnostics explaining why it's 16503 // not a constant expression as a side-effect. 16504 bool Folded = 16505 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16506 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16507 16508 if (!isa<ConstantExpr>(E)) 16509 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16510 16511 // In C++11, we can rely on diagnostics being produced for any expression 16512 // which is not a constant expression. If no diagnostics were produced, then 16513 // this is a constant expression. 16514 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16515 if (Result) 16516 *Result = EvalResult.Val.getInt(); 16517 return E; 16518 } 16519 16520 // If our only note is the usual "invalid subexpression" note, just point 16521 // the caret at its location rather than producing an essentially 16522 // redundant note. 16523 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16524 diag::note_invalid_subexpr_in_const_expr) { 16525 DiagLoc = Notes[0].first; 16526 Notes.clear(); 16527 } 16528 16529 if (!Folded || !CanFold) { 16530 if (!Diagnoser.Suppress) { 16531 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16532 for (const PartialDiagnosticAt &Note : Notes) 16533 Diag(Note.first, Note.second); 16534 } 16535 16536 return ExprError(); 16537 } 16538 16539 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16540 for (const PartialDiagnosticAt &Note : Notes) 16541 Diag(Note.first, Note.second); 16542 16543 if (Result) 16544 *Result = EvalResult.Val.getInt(); 16545 return E; 16546 } 16547 16548 namespace { 16549 // Handle the case where we conclude a expression which we speculatively 16550 // considered to be unevaluated is actually evaluated. 16551 class TransformToPE : public TreeTransform<TransformToPE> { 16552 typedef TreeTransform<TransformToPE> BaseTransform; 16553 16554 public: 16555 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16556 16557 // Make sure we redo semantic analysis 16558 bool AlwaysRebuild() { return true; } 16559 bool ReplacingOriginal() { return true; } 16560 16561 // We need to special-case DeclRefExprs referring to FieldDecls which 16562 // are not part of a member pointer formation; normal TreeTransforming 16563 // doesn't catch this case because of the way we represent them in the AST. 16564 // FIXME: This is a bit ugly; is it really the best way to handle this 16565 // case? 16566 // 16567 // Error on DeclRefExprs referring to FieldDecls. 16568 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16569 if (isa<FieldDecl>(E->getDecl()) && 16570 !SemaRef.isUnevaluatedContext()) 16571 return SemaRef.Diag(E->getLocation(), 16572 diag::err_invalid_non_static_member_use) 16573 << E->getDecl() << E->getSourceRange(); 16574 16575 return BaseTransform::TransformDeclRefExpr(E); 16576 } 16577 16578 // Exception: filter out member pointer formation 16579 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16580 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16581 return E; 16582 16583 return BaseTransform::TransformUnaryOperator(E); 16584 } 16585 16586 // The body of a lambda-expression is in a separate expression evaluation 16587 // context so never needs to be transformed. 16588 // FIXME: Ideally we wouldn't transform the closure type either, and would 16589 // just recreate the capture expressions and lambda expression. 16590 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16591 return SkipLambdaBody(E, Body); 16592 } 16593 }; 16594 } 16595 16596 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16597 assert(isUnevaluatedContext() && 16598 "Should only transform unevaluated expressions"); 16599 ExprEvalContexts.back().Context = 16600 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16601 if (isUnevaluatedContext()) 16602 return E; 16603 return TransformToPE(*this).TransformExpr(E); 16604 } 16605 16606 void 16607 Sema::PushExpressionEvaluationContext( 16608 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16609 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16610 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16611 LambdaContextDecl, ExprContext); 16612 Cleanup.reset(); 16613 if (!MaybeODRUseExprs.empty()) 16614 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16615 } 16616 16617 void 16618 Sema::PushExpressionEvaluationContext( 16619 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16620 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16621 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16622 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16623 } 16624 16625 namespace { 16626 16627 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16628 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16629 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16630 if (E->getOpcode() == UO_Deref) 16631 return CheckPossibleDeref(S, E->getSubExpr()); 16632 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16633 return CheckPossibleDeref(S, E->getBase()); 16634 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16635 return CheckPossibleDeref(S, E->getBase()); 16636 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16637 QualType Inner; 16638 QualType Ty = E->getType(); 16639 if (const auto *Ptr = Ty->getAs<PointerType>()) 16640 Inner = Ptr->getPointeeType(); 16641 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16642 Inner = Arr->getElementType(); 16643 else 16644 return nullptr; 16645 16646 if (Inner->hasAttr(attr::NoDeref)) 16647 return E; 16648 } 16649 return nullptr; 16650 } 16651 16652 } // namespace 16653 16654 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16655 for (const Expr *E : Rec.PossibleDerefs) { 16656 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16657 if (DeclRef) { 16658 const ValueDecl *Decl = DeclRef->getDecl(); 16659 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16660 << Decl->getName() << E->getSourceRange(); 16661 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16662 } else { 16663 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16664 << E->getSourceRange(); 16665 } 16666 } 16667 Rec.PossibleDerefs.clear(); 16668 } 16669 16670 /// Check whether E, which is either a discarded-value expression or an 16671 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16672 /// and if so, remove it from the list of volatile-qualified assignments that 16673 /// we are going to warn are deprecated. 16674 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16675 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16676 return; 16677 16678 // Note: ignoring parens here is not justified by the standard rules, but 16679 // ignoring parentheses seems like a more reasonable approach, and this only 16680 // drives a deprecation warning so doesn't affect conformance. 16681 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16682 if (BO->getOpcode() == BO_Assign) { 16683 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16684 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16685 LHSs.end()); 16686 } 16687 } 16688 } 16689 16690 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16691 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 16692 !Decl->isConsteval() || isConstantEvaluated() || 16693 RebuildingImmediateInvocation) 16694 return E; 16695 16696 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16697 /// It's OK if this fails; we'll also remove this in 16698 /// HandleImmediateInvocations, but catching it here allows us to avoid 16699 /// walking the AST looking for it in simple cases. 16700 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16701 if (auto *DeclRef = 16702 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16703 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16704 16705 E = MaybeCreateExprWithCleanups(E); 16706 16707 ConstantExpr *Res = ConstantExpr::Create( 16708 getASTContext(), E.get(), 16709 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16710 getASTContext()), 16711 /*IsImmediateInvocation*/ true); 16712 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16713 return Res; 16714 } 16715 16716 static void EvaluateAndDiagnoseImmediateInvocation( 16717 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16718 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16719 Expr::EvalResult Eval; 16720 Eval.Diag = &Notes; 16721 ConstantExpr *CE = Candidate.getPointer(); 16722 bool Result = CE->EvaluateAsConstantExpr( 16723 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16724 if (!Result || !Notes.empty()) { 16725 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16726 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16727 InnerExpr = FunctionalCast->getSubExpr(); 16728 FunctionDecl *FD = nullptr; 16729 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16730 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16731 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16732 FD = Call->getConstructor(); 16733 else 16734 llvm_unreachable("unhandled decl kind"); 16735 assert(FD->isConsteval()); 16736 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16737 for (auto &Note : Notes) 16738 SemaRef.Diag(Note.first, Note.second); 16739 return; 16740 } 16741 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16742 } 16743 16744 static void RemoveNestedImmediateInvocation( 16745 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16746 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16747 struct ComplexRemove : TreeTransform<ComplexRemove> { 16748 using Base = TreeTransform<ComplexRemove>; 16749 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16750 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16751 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16752 CurrentII; 16753 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16754 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16755 SmallVector<Sema::ImmediateInvocationCandidate, 16756 4>::reverse_iterator Current) 16757 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16758 void RemoveImmediateInvocation(ConstantExpr* E) { 16759 auto It = std::find_if(CurrentII, IISet.rend(), 16760 [E](Sema::ImmediateInvocationCandidate Elem) { 16761 return Elem.getPointer() == E; 16762 }); 16763 assert(It != IISet.rend() && 16764 "ConstantExpr marked IsImmediateInvocation should " 16765 "be present"); 16766 It->setInt(1); // Mark as deleted 16767 } 16768 ExprResult TransformConstantExpr(ConstantExpr *E) { 16769 if (!E->isImmediateInvocation()) 16770 return Base::TransformConstantExpr(E); 16771 RemoveImmediateInvocation(E); 16772 return Base::TransformExpr(E->getSubExpr()); 16773 } 16774 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16775 /// we need to remove its DeclRefExpr from the DRSet. 16776 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16777 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16778 return Base::TransformCXXOperatorCallExpr(E); 16779 } 16780 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16781 /// here. 16782 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16783 if (!Init) 16784 return Init; 16785 /// ConstantExpr are the first layer of implicit node to be removed so if 16786 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16787 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16788 if (CE->isImmediateInvocation()) 16789 RemoveImmediateInvocation(CE); 16790 return Base::TransformInitializer(Init, NotCopyInit); 16791 } 16792 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16793 DRSet.erase(E); 16794 return E; 16795 } 16796 bool AlwaysRebuild() { return false; } 16797 bool ReplacingOriginal() { return true; } 16798 bool AllowSkippingCXXConstructExpr() { 16799 bool Res = AllowSkippingFirstCXXConstructExpr; 16800 AllowSkippingFirstCXXConstructExpr = true; 16801 return Res; 16802 } 16803 bool AllowSkippingFirstCXXConstructExpr = true; 16804 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16805 Rec.ImmediateInvocationCandidates, It); 16806 16807 /// CXXConstructExpr with a single argument are getting skipped by 16808 /// TreeTransform in some situtation because they could be implicit. This 16809 /// can only occur for the top-level CXXConstructExpr because it is used 16810 /// nowhere in the expression being transformed therefore will not be rebuilt. 16811 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16812 /// skipping the first CXXConstructExpr. 16813 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16814 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16815 16816 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16817 assert(Res.isUsable()); 16818 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16819 It->getPointer()->setSubExpr(Res.get()); 16820 } 16821 16822 static void 16823 HandleImmediateInvocations(Sema &SemaRef, 16824 Sema::ExpressionEvaluationContextRecord &Rec) { 16825 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16826 Rec.ReferenceToConsteval.size() == 0) || 16827 SemaRef.RebuildingImmediateInvocation) 16828 return; 16829 16830 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16831 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16832 /// need to remove ReferenceToConsteval in the immediate invocation. 16833 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16834 16835 /// Prevent sema calls during the tree transform from adding pointers that 16836 /// are already in the sets. 16837 llvm::SaveAndRestore<bool> DisableIITracking( 16838 SemaRef.RebuildingImmediateInvocation, true); 16839 16840 /// Prevent diagnostic during tree transfrom as they are duplicates 16841 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16842 16843 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16844 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16845 if (!It->getInt()) 16846 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16847 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16848 Rec.ReferenceToConsteval.size()) { 16849 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16850 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16851 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16852 bool VisitDeclRefExpr(DeclRefExpr *E) { 16853 DRSet.erase(E); 16854 return DRSet.size(); 16855 } 16856 } Visitor(Rec.ReferenceToConsteval); 16857 Visitor.TraverseStmt( 16858 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16859 } 16860 for (auto CE : Rec.ImmediateInvocationCandidates) 16861 if (!CE.getInt()) 16862 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16863 for (auto DR : Rec.ReferenceToConsteval) { 16864 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16865 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16866 << FD; 16867 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16868 } 16869 } 16870 16871 void Sema::PopExpressionEvaluationContext() { 16872 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16873 unsigned NumTypos = Rec.NumTypos; 16874 16875 if (!Rec.Lambdas.empty()) { 16876 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16877 if (!getLangOpts().CPlusPlus20 && 16878 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 16879 Rec.isUnevaluated() || 16880 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 16881 unsigned D; 16882 if (Rec.isUnevaluated()) { 16883 // C++11 [expr.prim.lambda]p2: 16884 // A lambda-expression shall not appear in an unevaluated operand 16885 // (Clause 5). 16886 D = diag::err_lambda_unevaluated_operand; 16887 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16888 // C++1y [expr.const]p2: 16889 // A conditional-expression e is a core constant expression unless the 16890 // evaluation of e, following the rules of the abstract machine, would 16891 // evaluate [...] a lambda-expression. 16892 D = diag::err_lambda_in_constant_expression; 16893 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16894 // C++17 [expr.prim.lamda]p2: 16895 // A lambda-expression shall not appear [...] in a template-argument. 16896 D = diag::err_lambda_in_invalid_context; 16897 } else 16898 llvm_unreachable("Couldn't infer lambda error message."); 16899 16900 for (const auto *L : Rec.Lambdas) 16901 Diag(L->getBeginLoc(), D); 16902 } 16903 } 16904 16905 WarnOnPendingNoDerefs(Rec); 16906 HandleImmediateInvocations(*this, Rec); 16907 16908 // Warn on any volatile-qualified simple-assignments that are not discarded- 16909 // value expressions nor unevaluated operands (those cases get removed from 16910 // this list by CheckUnusedVolatileAssignment). 16911 for (auto *BO : Rec.VolatileAssignmentLHSs) 16912 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16913 << BO->getType(); 16914 16915 // When are coming out of an unevaluated context, clear out any 16916 // temporaries that we may have created as part of the evaluation of 16917 // the expression in that context: they aren't relevant because they 16918 // will never be constructed. 16919 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16920 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16921 ExprCleanupObjects.end()); 16922 Cleanup = Rec.ParentCleanup; 16923 CleanupVarDeclMarking(); 16924 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16925 // Otherwise, merge the contexts together. 16926 } else { 16927 Cleanup.mergeFrom(Rec.ParentCleanup); 16928 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16929 Rec.SavedMaybeODRUseExprs.end()); 16930 } 16931 16932 // Pop the current expression evaluation context off the stack. 16933 ExprEvalContexts.pop_back(); 16934 16935 // The global expression evaluation context record is never popped. 16936 ExprEvalContexts.back().NumTypos += NumTypos; 16937 } 16938 16939 void Sema::DiscardCleanupsInEvaluationContext() { 16940 ExprCleanupObjects.erase( 16941 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16942 ExprCleanupObjects.end()); 16943 Cleanup.reset(); 16944 MaybeODRUseExprs.clear(); 16945 } 16946 16947 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16948 ExprResult Result = CheckPlaceholderExpr(E); 16949 if (Result.isInvalid()) 16950 return ExprError(); 16951 E = Result.get(); 16952 if (!E->getType()->isVariablyModifiedType()) 16953 return E; 16954 return TransformToPotentiallyEvaluated(E); 16955 } 16956 16957 /// Are we in a context that is potentially constant evaluated per C++20 16958 /// [expr.const]p12? 16959 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16960 /// C++2a [expr.const]p12: 16961 // An expression or conversion is potentially constant evaluated if it is 16962 switch (SemaRef.ExprEvalContexts.back().Context) { 16963 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16964 // -- a manifestly constant-evaluated expression, 16965 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16966 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16967 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16968 // -- a potentially-evaluated expression, 16969 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16970 // -- an immediate subexpression of a braced-init-list, 16971 16972 // -- [FIXME] an expression of the form & cast-expression that occurs 16973 // within a templated entity 16974 // -- a subexpression of one of the above that is not a subexpression of 16975 // a nested unevaluated operand. 16976 return true; 16977 16978 case Sema::ExpressionEvaluationContext::Unevaluated: 16979 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16980 // Expressions in this context are never evaluated. 16981 return false; 16982 } 16983 llvm_unreachable("Invalid context"); 16984 } 16985 16986 /// Return true if this function has a calling convention that requires mangling 16987 /// in the size of the parameter pack. 16988 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16989 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16990 // we don't need parameter type sizes. 16991 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16992 if (!TT.isOSWindows() || !TT.isX86()) 16993 return false; 16994 16995 // If this is C++ and this isn't an extern "C" function, parameters do not 16996 // need to be complete. In this case, C++ mangling will apply, which doesn't 16997 // use the size of the parameters. 16998 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16999 return false; 17000 17001 // Stdcall, fastcall, and vectorcall need this special treatment. 17002 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17003 switch (CC) { 17004 case CC_X86StdCall: 17005 case CC_X86FastCall: 17006 case CC_X86VectorCall: 17007 return true; 17008 default: 17009 break; 17010 } 17011 return false; 17012 } 17013 17014 /// Require that all of the parameter types of function be complete. Normally, 17015 /// parameter types are only required to be complete when a function is called 17016 /// or defined, but to mangle functions with certain calling conventions, the 17017 /// mangler needs to know the size of the parameter list. In this situation, 17018 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 17019 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 17020 /// result in a linker error. Clang doesn't implement this behavior, and instead 17021 /// attempts to error at compile time. 17022 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 17023 SourceLocation Loc) { 17024 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 17025 FunctionDecl *FD; 17026 ParmVarDecl *Param; 17027 17028 public: 17029 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 17030 : FD(FD), Param(Param) {} 17031 17032 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 17033 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 17034 StringRef CCName; 17035 switch (CC) { 17036 case CC_X86StdCall: 17037 CCName = "stdcall"; 17038 break; 17039 case CC_X86FastCall: 17040 CCName = "fastcall"; 17041 break; 17042 case CC_X86VectorCall: 17043 CCName = "vectorcall"; 17044 break; 17045 default: 17046 llvm_unreachable("CC does not need mangling"); 17047 } 17048 17049 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 17050 << Param->getDeclName() << FD->getDeclName() << CCName; 17051 } 17052 }; 17053 17054 for (ParmVarDecl *Param : FD->parameters()) { 17055 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 17056 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 17057 } 17058 } 17059 17060 namespace { 17061 enum class OdrUseContext { 17062 /// Declarations in this context are not odr-used. 17063 None, 17064 /// Declarations in this context are formally odr-used, but this is a 17065 /// dependent context. 17066 Dependent, 17067 /// Declarations in this context are odr-used but not actually used (yet). 17068 FormallyOdrUsed, 17069 /// Declarations in this context are used. 17070 Used 17071 }; 17072 } 17073 17074 /// Are we within a context in which references to resolved functions or to 17075 /// variables result in odr-use? 17076 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 17077 OdrUseContext Result; 17078 17079 switch (SemaRef.ExprEvalContexts.back().Context) { 17080 case Sema::ExpressionEvaluationContext::Unevaluated: 17081 case Sema::ExpressionEvaluationContext::UnevaluatedList: 17082 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 17083 return OdrUseContext::None; 17084 17085 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 17086 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 17087 Result = OdrUseContext::Used; 17088 break; 17089 17090 case Sema::ExpressionEvaluationContext::DiscardedStatement: 17091 Result = OdrUseContext::FormallyOdrUsed; 17092 break; 17093 17094 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 17095 // A default argument formally results in odr-use, but doesn't actually 17096 // result in a use in any real sense until it itself is used. 17097 Result = OdrUseContext::FormallyOdrUsed; 17098 break; 17099 } 17100 17101 if (SemaRef.CurContext->isDependentContext()) 17102 return OdrUseContext::Dependent; 17103 17104 return Result; 17105 } 17106 17107 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 17108 if (!Func->isConstexpr()) 17109 return false; 17110 17111 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 17112 return true; 17113 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 17114 return CCD && CCD->getInheritedConstructor(); 17115 } 17116 17117 /// Mark a function referenced, and check whether it is odr-used 17118 /// (C++ [basic.def.odr]p2, C99 6.9p3) 17119 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 17120 bool MightBeOdrUse) { 17121 assert(Func && "No function?"); 17122 17123 Func->setReferenced(); 17124 17125 // Recursive functions aren't really used until they're used from some other 17126 // context. 17127 bool IsRecursiveCall = CurContext == Func; 17128 17129 // C++11 [basic.def.odr]p3: 17130 // A function whose name appears as a potentially-evaluated expression is 17131 // odr-used if it is the unique lookup result or the selected member of a 17132 // set of overloaded functions [...]. 17133 // 17134 // We (incorrectly) mark overload resolution as an unevaluated context, so we 17135 // can just check that here. 17136 OdrUseContext OdrUse = 17137 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 17138 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 17139 OdrUse = OdrUseContext::FormallyOdrUsed; 17140 17141 // Trivial default constructors and destructors are never actually used. 17142 // FIXME: What about other special members? 17143 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 17144 OdrUse == OdrUseContext::Used) { 17145 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 17146 if (Constructor->isDefaultConstructor()) 17147 OdrUse = OdrUseContext::FormallyOdrUsed; 17148 if (isa<CXXDestructorDecl>(Func)) 17149 OdrUse = OdrUseContext::FormallyOdrUsed; 17150 } 17151 17152 // C++20 [expr.const]p12: 17153 // A function [...] is needed for constant evaluation if it is [...] a 17154 // constexpr function that is named by an expression that is potentially 17155 // constant evaluated 17156 bool NeededForConstantEvaluation = 17157 isPotentiallyConstantEvaluatedContext(*this) && 17158 isImplicitlyDefinableConstexprFunction(Func); 17159 17160 // Determine whether we require a function definition to exist, per 17161 // C++11 [temp.inst]p3: 17162 // Unless a function template specialization has been explicitly 17163 // instantiated or explicitly specialized, the function template 17164 // specialization is implicitly instantiated when the specialization is 17165 // referenced in a context that requires a function definition to exist. 17166 // C++20 [temp.inst]p7: 17167 // The existence of a definition of a [...] function is considered to 17168 // affect the semantics of the program if the [...] function is needed for 17169 // constant evaluation by an expression 17170 // C++20 [basic.def.odr]p10: 17171 // Every program shall contain exactly one definition of every non-inline 17172 // function or variable that is odr-used in that program outside of a 17173 // discarded statement 17174 // C++20 [special]p1: 17175 // The implementation will implicitly define [defaulted special members] 17176 // if they are odr-used or needed for constant evaluation. 17177 // 17178 // Note that we skip the implicit instantiation of templates that are only 17179 // used in unused default arguments or by recursive calls to themselves. 17180 // This is formally non-conforming, but seems reasonable in practice. 17181 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 17182 NeededForConstantEvaluation); 17183 17184 // C++14 [temp.expl.spec]p6: 17185 // If a template [...] is explicitly specialized then that specialization 17186 // shall be declared before the first use of that specialization that would 17187 // cause an implicit instantiation to take place, in every translation unit 17188 // in which such a use occurs 17189 if (NeedDefinition && 17190 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 17191 Func->getMemberSpecializationInfo())) 17192 checkSpecializationVisibility(Loc, Func); 17193 17194 if (getLangOpts().CUDA) 17195 CheckCUDACall(Loc, Func); 17196 17197 if (getLangOpts().SYCLIsDevice) 17198 checkSYCLDeviceFunction(Loc, Func); 17199 17200 // If we need a definition, try to create one. 17201 if (NeedDefinition && !Func->getBody()) { 17202 runWithSufficientStackSpace(Loc, [&] { 17203 if (CXXConstructorDecl *Constructor = 17204 dyn_cast<CXXConstructorDecl>(Func)) { 17205 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 17206 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 17207 if (Constructor->isDefaultConstructor()) { 17208 if (Constructor->isTrivial() && 17209 !Constructor->hasAttr<DLLExportAttr>()) 17210 return; 17211 DefineImplicitDefaultConstructor(Loc, Constructor); 17212 } else if (Constructor->isCopyConstructor()) { 17213 DefineImplicitCopyConstructor(Loc, Constructor); 17214 } else if (Constructor->isMoveConstructor()) { 17215 DefineImplicitMoveConstructor(Loc, Constructor); 17216 } 17217 } else if (Constructor->getInheritedConstructor()) { 17218 DefineInheritingConstructor(Loc, Constructor); 17219 } 17220 } else if (CXXDestructorDecl *Destructor = 17221 dyn_cast<CXXDestructorDecl>(Func)) { 17222 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 17223 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 17224 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 17225 return; 17226 DefineImplicitDestructor(Loc, Destructor); 17227 } 17228 if (Destructor->isVirtual() && getLangOpts().AppleKext) 17229 MarkVTableUsed(Loc, Destructor->getParent()); 17230 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 17231 if (MethodDecl->isOverloadedOperator() && 17232 MethodDecl->getOverloadedOperator() == OO_Equal) { 17233 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 17234 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 17235 if (MethodDecl->isCopyAssignmentOperator()) 17236 DefineImplicitCopyAssignment(Loc, MethodDecl); 17237 else if (MethodDecl->isMoveAssignmentOperator()) 17238 DefineImplicitMoveAssignment(Loc, MethodDecl); 17239 } 17240 } else if (isa<CXXConversionDecl>(MethodDecl) && 17241 MethodDecl->getParent()->isLambda()) { 17242 CXXConversionDecl *Conversion = 17243 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 17244 if (Conversion->isLambdaToBlockPointerConversion()) 17245 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 17246 else 17247 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 17248 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 17249 MarkVTableUsed(Loc, MethodDecl->getParent()); 17250 } 17251 17252 if (Func->isDefaulted() && !Func->isDeleted()) { 17253 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 17254 if (DCK != DefaultedComparisonKind::None) 17255 DefineDefaultedComparison(Loc, Func, DCK); 17256 } 17257 17258 // Implicit instantiation of function templates and member functions of 17259 // class templates. 17260 if (Func->isImplicitlyInstantiable()) { 17261 TemplateSpecializationKind TSK = 17262 Func->getTemplateSpecializationKindForInstantiation(); 17263 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17264 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17265 if (FirstInstantiation) { 17266 PointOfInstantiation = Loc; 17267 if (auto *MSI = Func->getMemberSpecializationInfo()) 17268 MSI->setPointOfInstantiation(Loc); 17269 // FIXME: Notify listener. 17270 else 17271 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17272 } else if (TSK != TSK_ImplicitInstantiation) { 17273 // Use the point of use as the point of instantiation, instead of the 17274 // point of explicit instantiation (which we track as the actual point 17275 // of instantiation). This gives better backtraces in diagnostics. 17276 PointOfInstantiation = Loc; 17277 } 17278 17279 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17280 Func->isConstexpr()) { 17281 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17282 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17283 CodeSynthesisContexts.size()) 17284 PendingLocalImplicitInstantiations.push_back( 17285 std::make_pair(Func, PointOfInstantiation)); 17286 else if (Func->isConstexpr()) 17287 // Do not defer instantiations of constexpr functions, to avoid the 17288 // expression evaluator needing to call back into Sema if it sees a 17289 // call to such a function. 17290 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17291 else { 17292 Func->setInstantiationIsPending(true); 17293 PendingInstantiations.push_back( 17294 std::make_pair(Func, PointOfInstantiation)); 17295 // Notify the consumer that a function was implicitly instantiated. 17296 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17297 } 17298 } 17299 } else { 17300 // Walk redefinitions, as some of them may be instantiable. 17301 for (auto i : Func->redecls()) { 17302 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17303 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17304 } 17305 } 17306 }); 17307 } 17308 17309 // C++14 [except.spec]p17: 17310 // An exception-specification is considered to be needed when: 17311 // - the function is odr-used or, if it appears in an unevaluated operand, 17312 // would be odr-used if the expression were potentially-evaluated; 17313 // 17314 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17315 // function is a pure virtual function we're calling, and in that case the 17316 // function was selected by overload resolution and we need to resolve its 17317 // exception specification for a different reason. 17318 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17319 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17320 ResolveExceptionSpec(Loc, FPT); 17321 17322 // If this is the first "real" use, act on that. 17323 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17324 // Keep track of used but undefined functions. 17325 if (!Func->isDefined()) { 17326 if (mightHaveNonExternalLinkage(Func)) 17327 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17328 else if (Func->getMostRecentDecl()->isInlined() && 17329 !LangOpts.GNUInline && 17330 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17331 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17332 else if (isExternalWithNoLinkageType(Func)) 17333 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17334 } 17335 17336 // Some x86 Windows calling conventions mangle the size of the parameter 17337 // pack into the name. Computing the size of the parameters requires the 17338 // parameter types to be complete. Check that now. 17339 if (funcHasParameterSizeMangling(*this, Func)) 17340 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17341 17342 // In the MS C++ ABI, the compiler emits destructor variants where they are 17343 // used. If the destructor is used here but defined elsewhere, mark the 17344 // virtual base destructors referenced. If those virtual base destructors 17345 // are inline, this will ensure they are defined when emitting the complete 17346 // destructor variant. This checking may be redundant if the destructor is 17347 // provided later in this TU. 17348 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17349 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17350 CXXRecordDecl *Parent = Dtor->getParent(); 17351 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17352 CheckCompleteDestructorVariant(Loc, Dtor); 17353 } 17354 } 17355 17356 Func->markUsed(Context); 17357 } 17358 } 17359 17360 /// Directly mark a variable odr-used. Given a choice, prefer to use 17361 /// MarkVariableReferenced since it does additional checks and then 17362 /// calls MarkVarDeclODRUsed. 17363 /// If the variable must be captured: 17364 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17365 /// - else capture it in the DeclContext that maps to the 17366 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17367 static void 17368 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17369 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17370 // Keep track of used but undefined variables. 17371 // FIXME: We shouldn't suppress this warning for static data members. 17372 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17373 (!Var->isExternallyVisible() || Var->isInline() || 17374 SemaRef.isExternalWithNoLinkageType(Var)) && 17375 !(Var->isStaticDataMember() && Var->hasInit())) { 17376 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17377 if (old.isInvalid()) 17378 old = Loc; 17379 } 17380 QualType CaptureType, DeclRefType; 17381 if (SemaRef.LangOpts.OpenMP) 17382 SemaRef.tryCaptureOpenMPLambdas(Var); 17383 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17384 /*EllipsisLoc*/ SourceLocation(), 17385 /*BuildAndDiagnose*/ true, 17386 CaptureType, DeclRefType, 17387 FunctionScopeIndexToStopAt); 17388 17389 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) { 17390 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17391 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 17392 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 17393 if (VarTarget == Sema::CVT_Host && 17394 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 17395 UserTarget == Sema::CFT_Global)) { 17396 // Diagnose ODR-use of host global variables in device functions. 17397 // Reference of device global variables in host functions is allowed 17398 // through shadow variables therefore it is not diagnosed. 17399 if (SemaRef.LangOpts.CUDAIsDevice) { 17400 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17401 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 17402 SemaRef.targetDiag(Var->getLocation(), 17403 Var->getType().isConstQualified() 17404 ? diag::note_cuda_const_var_unpromoted 17405 : diag::note_cuda_host_var); 17406 } 17407 } else if (VarTarget == Sema::CVT_Device && 17408 (UserTarget == Sema::CFT_Host || 17409 UserTarget == Sema::CFT_HostDevice) && 17410 !Var->hasExternalStorage()) { 17411 // Record a CUDA/HIP device side variable if it is ODR-used 17412 // by host code. This is done conservatively, when the variable is 17413 // referenced in any of the following contexts: 17414 // - a non-function context 17415 // - a host function 17416 // - a host device function 17417 // This makes the ODR-use of the device side variable by host code to 17418 // be visible in the device compilation for the compiler to be able to 17419 // emit template variables instantiated by host code only and to 17420 // externalize the static device side variable ODR-used by host code. 17421 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 17422 } 17423 } 17424 17425 Var->markUsed(SemaRef.Context); 17426 } 17427 17428 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17429 SourceLocation Loc, 17430 unsigned CapturingScopeIndex) { 17431 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17432 } 17433 17434 static void 17435 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17436 ValueDecl *var, DeclContext *DC) { 17437 DeclContext *VarDC = var->getDeclContext(); 17438 17439 // If the parameter still belongs to the translation unit, then 17440 // we're actually just using one parameter in the declaration of 17441 // the next. 17442 if (isa<ParmVarDecl>(var) && 17443 isa<TranslationUnitDecl>(VarDC)) 17444 return; 17445 17446 // For C code, don't diagnose about capture if we're not actually in code 17447 // right now; it's impossible to write a non-constant expression outside of 17448 // function context, so we'll get other (more useful) diagnostics later. 17449 // 17450 // For C++, things get a bit more nasty... it would be nice to suppress this 17451 // diagnostic for certain cases like using a local variable in an array bound 17452 // for a member of a local class, but the correct predicate is not obvious. 17453 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17454 return; 17455 17456 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17457 unsigned ContextKind = 3; // unknown 17458 if (isa<CXXMethodDecl>(VarDC) && 17459 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17460 ContextKind = 2; 17461 } else if (isa<FunctionDecl>(VarDC)) { 17462 ContextKind = 0; 17463 } else if (isa<BlockDecl>(VarDC)) { 17464 ContextKind = 1; 17465 } 17466 17467 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17468 << var << ValueKind << ContextKind << VarDC; 17469 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17470 << var; 17471 17472 // FIXME: Add additional diagnostic info about class etc. which prevents 17473 // capture. 17474 } 17475 17476 17477 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17478 bool &SubCapturesAreNested, 17479 QualType &CaptureType, 17480 QualType &DeclRefType) { 17481 // Check whether we've already captured it. 17482 if (CSI->CaptureMap.count(Var)) { 17483 // If we found a capture, any subcaptures are nested. 17484 SubCapturesAreNested = true; 17485 17486 // Retrieve the capture type for this variable. 17487 CaptureType = CSI->getCapture(Var).getCaptureType(); 17488 17489 // Compute the type of an expression that refers to this variable. 17490 DeclRefType = CaptureType.getNonReferenceType(); 17491 17492 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17493 // are mutable in the sense that user can change their value - they are 17494 // private instances of the captured declarations. 17495 const Capture &Cap = CSI->getCapture(Var); 17496 if (Cap.isCopyCapture() && 17497 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17498 !(isa<CapturedRegionScopeInfo>(CSI) && 17499 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17500 DeclRefType.addConst(); 17501 return true; 17502 } 17503 return false; 17504 } 17505 17506 // Only block literals, captured statements, and lambda expressions can 17507 // capture; other scopes don't work. 17508 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17509 SourceLocation Loc, 17510 const bool Diagnose, Sema &S) { 17511 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17512 return getLambdaAwareParentOfDeclContext(DC); 17513 else if (Var->hasLocalStorage()) { 17514 if (Diagnose) 17515 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17516 } 17517 return nullptr; 17518 } 17519 17520 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17521 // certain types of variables (unnamed, variably modified types etc.) 17522 // so check for eligibility. 17523 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17524 SourceLocation Loc, 17525 const bool Diagnose, Sema &S) { 17526 17527 bool IsBlock = isa<BlockScopeInfo>(CSI); 17528 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17529 17530 // Lambdas are not allowed to capture unnamed variables 17531 // (e.g. anonymous unions). 17532 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17533 // assuming that's the intent. 17534 if (IsLambda && !Var->getDeclName()) { 17535 if (Diagnose) { 17536 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17537 S.Diag(Var->getLocation(), diag::note_declared_at); 17538 } 17539 return false; 17540 } 17541 17542 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17543 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17544 if (Diagnose) { 17545 S.Diag(Loc, diag::err_ref_vm_type); 17546 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17547 } 17548 return false; 17549 } 17550 // Prohibit structs with flexible array members too. 17551 // We cannot capture what is in the tail end of the struct. 17552 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17553 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17554 if (Diagnose) { 17555 if (IsBlock) 17556 S.Diag(Loc, diag::err_ref_flexarray_type); 17557 else 17558 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17559 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17560 } 17561 return false; 17562 } 17563 } 17564 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17565 // Lambdas and captured statements are not allowed to capture __block 17566 // variables; they don't support the expected semantics. 17567 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17568 if (Diagnose) { 17569 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17570 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17571 } 17572 return false; 17573 } 17574 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17575 if (S.getLangOpts().OpenCL && IsBlock && 17576 Var->getType()->isBlockPointerType()) { 17577 if (Diagnose) 17578 S.Diag(Loc, diag::err_opencl_block_ref_block); 17579 return false; 17580 } 17581 17582 return true; 17583 } 17584 17585 // Returns true if the capture by block was successful. 17586 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17587 SourceLocation Loc, 17588 const bool BuildAndDiagnose, 17589 QualType &CaptureType, 17590 QualType &DeclRefType, 17591 const bool Nested, 17592 Sema &S, bool Invalid) { 17593 bool ByRef = false; 17594 17595 // Blocks are not allowed to capture arrays, excepting OpenCL. 17596 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17597 // (decayed to pointers). 17598 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17599 if (BuildAndDiagnose) { 17600 S.Diag(Loc, diag::err_ref_array_type); 17601 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17602 Invalid = true; 17603 } else { 17604 return false; 17605 } 17606 } 17607 17608 // Forbid the block-capture of autoreleasing variables. 17609 if (!Invalid && 17610 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17611 if (BuildAndDiagnose) { 17612 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17613 << /*block*/ 0; 17614 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17615 Invalid = true; 17616 } else { 17617 return false; 17618 } 17619 } 17620 17621 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17622 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17623 QualType PointeeTy = PT->getPointeeType(); 17624 17625 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17626 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17627 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17628 if (BuildAndDiagnose) { 17629 SourceLocation VarLoc = Var->getLocation(); 17630 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17631 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17632 } 17633 } 17634 } 17635 17636 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17637 if (HasBlocksAttr || CaptureType->isReferenceType() || 17638 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17639 // Block capture by reference does not change the capture or 17640 // declaration reference types. 17641 ByRef = true; 17642 } else { 17643 // Block capture by copy introduces 'const'. 17644 CaptureType = CaptureType.getNonReferenceType().withConst(); 17645 DeclRefType = CaptureType; 17646 } 17647 17648 // Actually capture the variable. 17649 if (BuildAndDiagnose) 17650 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17651 CaptureType, Invalid); 17652 17653 return !Invalid; 17654 } 17655 17656 17657 /// Capture the given variable in the captured region. 17658 static bool captureInCapturedRegion( 17659 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17660 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17661 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17662 bool IsTopScope, Sema &S, bool Invalid) { 17663 // By default, capture variables by reference. 17664 bool ByRef = true; 17665 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17666 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17667 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17668 // Using an LValue reference type is consistent with Lambdas (see below). 17669 if (S.isOpenMPCapturedDecl(Var)) { 17670 bool HasConst = DeclRefType.isConstQualified(); 17671 DeclRefType = DeclRefType.getUnqualifiedType(); 17672 // Don't lose diagnostics about assignments to const. 17673 if (HasConst) 17674 DeclRefType.addConst(); 17675 } 17676 // Do not capture firstprivates in tasks. 17677 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17678 OMPC_unknown) 17679 return true; 17680 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17681 RSI->OpenMPCaptureLevel); 17682 } 17683 17684 if (ByRef) 17685 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17686 else 17687 CaptureType = DeclRefType; 17688 17689 // Actually capture the variable. 17690 if (BuildAndDiagnose) 17691 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17692 Loc, SourceLocation(), CaptureType, Invalid); 17693 17694 return !Invalid; 17695 } 17696 17697 /// Capture the given variable in the lambda. 17698 static bool captureInLambda(LambdaScopeInfo *LSI, 17699 VarDecl *Var, 17700 SourceLocation Loc, 17701 const bool BuildAndDiagnose, 17702 QualType &CaptureType, 17703 QualType &DeclRefType, 17704 const bool RefersToCapturedVariable, 17705 const Sema::TryCaptureKind Kind, 17706 SourceLocation EllipsisLoc, 17707 const bool IsTopScope, 17708 Sema &S, bool Invalid) { 17709 // Determine whether we are capturing by reference or by value. 17710 bool ByRef = false; 17711 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17712 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17713 } else { 17714 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17715 } 17716 17717 // Compute the type of the field that will capture this variable. 17718 if (ByRef) { 17719 // C++11 [expr.prim.lambda]p15: 17720 // An entity is captured by reference if it is implicitly or 17721 // explicitly captured but not captured by copy. It is 17722 // unspecified whether additional unnamed non-static data 17723 // members are declared in the closure type for entities 17724 // captured by reference. 17725 // 17726 // FIXME: It is not clear whether we want to build an lvalue reference 17727 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17728 // to do the former, while EDG does the latter. Core issue 1249 will 17729 // clarify, but for now we follow GCC because it's a more permissive and 17730 // easily defensible position. 17731 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17732 } else { 17733 // C++11 [expr.prim.lambda]p14: 17734 // For each entity captured by copy, an unnamed non-static 17735 // data member is declared in the closure type. The 17736 // declaration order of these members is unspecified. The type 17737 // of such a data member is the type of the corresponding 17738 // captured entity if the entity is not a reference to an 17739 // object, or the referenced type otherwise. [Note: If the 17740 // captured entity is a reference to a function, the 17741 // corresponding data member is also a reference to a 17742 // function. - end note ] 17743 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17744 if (!RefType->getPointeeType()->isFunctionType()) 17745 CaptureType = RefType->getPointeeType(); 17746 } 17747 17748 // Forbid the lambda copy-capture of autoreleasing variables. 17749 if (!Invalid && 17750 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17751 if (BuildAndDiagnose) { 17752 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17753 S.Diag(Var->getLocation(), diag::note_previous_decl) 17754 << Var->getDeclName(); 17755 Invalid = true; 17756 } else { 17757 return false; 17758 } 17759 } 17760 17761 // Make sure that by-copy captures are of a complete and non-abstract type. 17762 if (!Invalid && BuildAndDiagnose) { 17763 if (!CaptureType->isDependentType() && 17764 S.RequireCompleteSizedType( 17765 Loc, CaptureType, 17766 diag::err_capture_of_incomplete_or_sizeless_type, 17767 Var->getDeclName())) 17768 Invalid = true; 17769 else if (S.RequireNonAbstractType(Loc, CaptureType, 17770 diag::err_capture_of_abstract_type)) 17771 Invalid = true; 17772 } 17773 } 17774 17775 // Compute the type of a reference to this captured variable. 17776 if (ByRef) 17777 DeclRefType = CaptureType.getNonReferenceType(); 17778 else { 17779 // C++ [expr.prim.lambda]p5: 17780 // The closure type for a lambda-expression has a public inline 17781 // function call operator [...]. This function call operator is 17782 // declared const (9.3.1) if and only if the lambda-expression's 17783 // parameter-declaration-clause is not followed by mutable. 17784 DeclRefType = CaptureType.getNonReferenceType(); 17785 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17786 DeclRefType.addConst(); 17787 } 17788 17789 // Add the capture. 17790 if (BuildAndDiagnose) 17791 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17792 Loc, EllipsisLoc, CaptureType, Invalid); 17793 17794 return !Invalid; 17795 } 17796 17797 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17798 // Offer a Copy fix even if the type is dependent. 17799 if (Var->getType()->isDependentType()) 17800 return true; 17801 QualType T = Var->getType().getNonReferenceType(); 17802 if (T.isTriviallyCopyableType(Context)) 17803 return true; 17804 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17805 17806 if (!(RD = RD->getDefinition())) 17807 return false; 17808 if (RD->hasSimpleCopyConstructor()) 17809 return true; 17810 if (RD->hasUserDeclaredCopyConstructor()) 17811 for (CXXConstructorDecl *Ctor : RD->ctors()) 17812 if (Ctor->isCopyConstructor()) 17813 return !Ctor->isDeleted(); 17814 } 17815 return false; 17816 } 17817 17818 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17819 /// default capture. Fixes may be omitted if they aren't allowed by the 17820 /// standard, for example we can't emit a default copy capture fix-it if we 17821 /// already explicitly copy capture capture another variable. 17822 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17823 VarDecl *Var) { 17824 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17825 // Don't offer Capture by copy of default capture by copy fixes if Var is 17826 // known not to be copy constructible. 17827 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17828 17829 SmallString<32> FixBuffer; 17830 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17831 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17832 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17833 if (ShouldOfferCopyFix) { 17834 // Offer fixes to insert an explicit capture for the variable. 17835 // [] -> [VarName] 17836 // [OtherCapture] -> [OtherCapture, VarName] 17837 FixBuffer.assign({Separator, Var->getName()}); 17838 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17839 << Var << /*value*/ 0 17840 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17841 } 17842 // As above but capture by reference. 17843 FixBuffer.assign({Separator, "&", Var->getName()}); 17844 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17845 << Var << /*reference*/ 1 17846 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17847 } 17848 17849 // Only try to offer default capture if there are no captures excluding this 17850 // and init captures. 17851 // [this]: OK. 17852 // [X = Y]: OK. 17853 // [&A, &B]: Don't offer. 17854 // [A, B]: Don't offer. 17855 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17856 return !C.isThisCapture() && !C.isInitCapture(); 17857 })) 17858 return; 17859 17860 // The default capture specifiers, '=' or '&', must appear first in the 17861 // capture body. 17862 SourceLocation DefaultInsertLoc = 17863 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17864 17865 if (ShouldOfferCopyFix) { 17866 bool CanDefaultCopyCapture = true; 17867 // [=, *this] OK since c++17 17868 // [=, this] OK since c++20 17869 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17870 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17871 ? LSI->getCXXThisCapture().isCopyCapture() 17872 : false; 17873 // We can't use default capture by copy if any captures already specified 17874 // capture by copy. 17875 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17876 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17877 })) { 17878 FixBuffer.assign({"=", Separator}); 17879 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17880 << /*value*/ 0 17881 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17882 } 17883 } 17884 17885 // We can't use default capture by reference if any captures already specified 17886 // capture by reference. 17887 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17888 return !C.isInitCapture() && C.isReferenceCapture() && 17889 !C.isThisCapture(); 17890 })) { 17891 FixBuffer.assign({"&", Separator}); 17892 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17893 << /*reference*/ 1 17894 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17895 } 17896 } 17897 17898 bool Sema::tryCaptureVariable( 17899 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17900 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17901 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17902 // An init-capture is notionally from the context surrounding its 17903 // declaration, but its parent DC is the lambda class. 17904 DeclContext *VarDC = Var->getDeclContext(); 17905 if (Var->isInitCapture()) 17906 VarDC = VarDC->getParent(); 17907 17908 DeclContext *DC = CurContext; 17909 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17910 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17911 // We need to sync up the Declaration Context with the 17912 // FunctionScopeIndexToStopAt 17913 if (FunctionScopeIndexToStopAt) { 17914 unsigned FSIndex = FunctionScopes.size() - 1; 17915 while (FSIndex != MaxFunctionScopesIndex) { 17916 DC = getLambdaAwareParentOfDeclContext(DC); 17917 --FSIndex; 17918 } 17919 } 17920 17921 17922 // If the variable is declared in the current context, there is no need to 17923 // capture it. 17924 if (VarDC == DC) return true; 17925 17926 // Capture global variables if it is required to use private copy of this 17927 // variable. 17928 bool IsGlobal = !Var->hasLocalStorage(); 17929 if (IsGlobal && 17930 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17931 MaxFunctionScopesIndex))) 17932 return true; 17933 Var = Var->getCanonicalDecl(); 17934 17935 // Walk up the stack to determine whether we can capture the variable, 17936 // performing the "simple" checks that don't depend on type. We stop when 17937 // we've either hit the declared scope of the variable or find an existing 17938 // capture of that variable. We start from the innermost capturing-entity 17939 // (the DC) and ensure that all intervening capturing-entities 17940 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17941 // declcontext can either capture the variable or have already captured 17942 // the variable. 17943 CaptureType = Var->getType(); 17944 DeclRefType = CaptureType.getNonReferenceType(); 17945 bool Nested = false; 17946 bool Explicit = (Kind != TryCapture_Implicit); 17947 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17948 do { 17949 // Only block literals, captured statements, and lambda expressions can 17950 // capture; other scopes don't work. 17951 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17952 ExprLoc, 17953 BuildAndDiagnose, 17954 *this); 17955 // We need to check for the parent *first* because, if we *have* 17956 // private-captured a global variable, we need to recursively capture it in 17957 // intermediate blocks, lambdas, etc. 17958 if (!ParentDC) { 17959 if (IsGlobal) { 17960 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17961 break; 17962 } 17963 return true; 17964 } 17965 17966 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17967 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17968 17969 17970 // Check whether we've already captured it. 17971 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17972 DeclRefType)) { 17973 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17974 break; 17975 } 17976 // If we are instantiating a generic lambda call operator body, 17977 // we do not want to capture new variables. What was captured 17978 // during either a lambdas transformation or initial parsing 17979 // should be used. 17980 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17981 if (BuildAndDiagnose) { 17982 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17983 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17984 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17985 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17986 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17987 buildLambdaCaptureFixit(*this, LSI, Var); 17988 } else 17989 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17990 } 17991 return true; 17992 } 17993 17994 // Try to capture variable-length arrays types. 17995 if (Var->getType()->isVariablyModifiedType()) { 17996 // We're going to walk down into the type and look for VLA 17997 // expressions. 17998 QualType QTy = Var->getType(); 17999 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18000 QTy = PVD->getOriginalType(); 18001 captureVariablyModifiedType(Context, QTy, CSI); 18002 } 18003 18004 if (getLangOpts().OpenMP) { 18005 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18006 // OpenMP private variables should not be captured in outer scope, so 18007 // just break here. Similarly, global variables that are captured in a 18008 // target region should not be captured outside the scope of the region. 18009 if (RSI->CapRegionKind == CR_OpenMP) { 18010 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 18011 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 18012 // If the variable is private (i.e. not captured) and has variably 18013 // modified type, we still need to capture the type for correct 18014 // codegen in all regions, associated with the construct. Currently, 18015 // it is captured in the innermost captured region only. 18016 if (IsOpenMPPrivateDecl != OMPC_unknown && 18017 Var->getType()->isVariablyModifiedType()) { 18018 QualType QTy = Var->getType(); 18019 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 18020 QTy = PVD->getOriginalType(); 18021 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 18022 I < E; ++I) { 18023 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 18024 FunctionScopes[FunctionScopesIndex - I]); 18025 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 18026 "Wrong number of captured regions associated with the " 18027 "OpenMP construct."); 18028 captureVariablyModifiedType(Context, QTy, OuterRSI); 18029 } 18030 } 18031 bool IsTargetCap = 18032 IsOpenMPPrivateDecl != OMPC_private && 18033 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 18034 RSI->OpenMPCaptureLevel); 18035 // Do not capture global if it is not privatized in outer regions. 18036 bool IsGlobalCap = 18037 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 18038 RSI->OpenMPCaptureLevel); 18039 18040 // When we detect target captures we are looking from inside the 18041 // target region, therefore we need to propagate the capture from the 18042 // enclosing region. Therefore, the capture is not initially nested. 18043 if (IsTargetCap) 18044 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 18045 18046 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 18047 (IsGlobal && !IsGlobalCap)) { 18048 Nested = !IsTargetCap; 18049 bool HasConst = DeclRefType.isConstQualified(); 18050 DeclRefType = DeclRefType.getUnqualifiedType(); 18051 // Don't lose diagnostics about assignments to const. 18052 if (HasConst) 18053 DeclRefType.addConst(); 18054 CaptureType = Context.getLValueReferenceType(DeclRefType); 18055 break; 18056 } 18057 } 18058 } 18059 } 18060 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 18061 // No capture-default, and this is not an explicit capture 18062 // so cannot capture this variable. 18063 if (BuildAndDiagnose) { 18064 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 18065 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18066 auto *LSI = cast<LambdaScopeInfo>(CSI); 18067 if (LSI->Lambda) { 18068 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 18069 buildLambdaCaptureFixit(*this, LSI, Var); 18070 } 18071 // FIXME: If we error out because an outer lambda can not implicitly 18072 // capture a variable that an inner lambda explicitly captures, we 18073 // should have the inner lambda do the explicit capture - because 18074 // it makes for cleaner diagnostics later. This would purely be done 18075 // so that the diagnostic does not misleadingly claim that a variable 18076 // can not be captured by a lambda implicitly even though it is captured 18077 // explicitly. Suggestion: 18078 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 18079 // at the function head 18080 // - cache the StartingDeclContext - this must be a lambda 18081 // - captureInLambda in the innermost lambda the variable. 18082 } 18083 return true; 18084 } 18085 18086 FunctionScopesIndex--; 18087 DC = ParentDC; 18088 Explicit = false; 18089 } while (!VarDC->Equals(DC)); 18090 18091 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 18092 // computing the type of the capture at each step, checking type-specific 18093 // requirements, and adding captures if requested. 18094 // If the variable had already been captured previously, we start capturing 18095 // at the lambda nested within that one. 18096 bool Invalid = false; 18097 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 18098 ++I) { 18099 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 18100 18101 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18102 // certain types of variables (unnamed, variably modified types etc.) 18103 // so check for eligibility. 18104 if (!Invalid) 18105 Invalid = 18106 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 18107 18108 // After encountering an error, if we're actually supposed to capture, keep 18109 // capturing in nested contexts to suppress any follow-on diagnostics. 18110 if (Invalid && !BuildAndDiagnose) 18111 return true; 18112 18113 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 18114 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18115 DeclRefType, Nested, *this, Invalid); 18116 Nested = true; 18117 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 18118 Invalid = !captureInCapturedRegion( 18119 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 18120 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 18121 Nested = true; 18122 } else { 18123 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 18124 Invalid = 18125 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 18126 DeclRefType, Nested, Kind, EllipsisLoc, 18127 /*IsTopScope*/ I == N - 1, *this, Invalid); 18128 Nested = true; 18129 } 18130 18131 if (Invalid && !BuildAndDiagnose) 18132 return true; 18133 } 18134 return Invalid; 18135 } 18136 18137 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 18138 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 18139 QualType CaptureType; 18140 QualType DeclRefType; 18141 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 18142 /*BuildAndDiagnose=*/true, CaptureType, 18143 DeclRefType, nullptr); 18144 } 18145 18146 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 18147 QualType CaptureType; 18148 QualType DeclRefType; 18149 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18150 /*BuildAndDiagnose=*/false, CaptureType, 18151 DeclRefType, nullptr); 18152 } 18153 18154 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 18155 QualType CaptureType; 18156 QualType DeclRefType; 18157 18158 // Determine whether we can capture this variable. 18159 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 18160 /*BuildAndDiagnose=*/false, CaptureType, 18161 DeclRefType, nullptr)) 18162 return QualType(); 18163 18164 return DeclRefType; 18165 } 18166 18167 namespace { 18168 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 18169 // The produced TemplateArgumentListInfo* points to data stored within this 18170 // object, so should only be used in contexts where the pointer will not be 18171 // used after the CopiedTemplateArgs object is destroyed. 18172 class CopiedTemplateArgs { 18173 bool HasArgs; 18174 TemplateArgumentListInfo TemplateArgStorage; 18175 public: 18176 template<typename RefExpr> 18177 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 18178 if (HasArgs) 18179 E->copyTemplateArgumentsInto(TemplateArgStorage); 18180 } 18181 operator TemplateArgumentListInfo*() 18182 #ifdef __has_cpp_attribute 18183 #if __has_cpp_attribute(clang::lifetimebound) 18184 [[clang::lifetimebound]] 18185 #endif 18186 #endif 18187 { 18188 return HasArgs ? &TemplateArgStorage : nullptr; 18189 } 18190 }; 18191 } 18192 18193 /// Walk the set of potential results of an expression and mark them all as 18194 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 18195 /// 18196 /// \return A new expression if we found any potential results, ExprEmpty() if 18197 /// not, and ExprError() if we diagnosed an error. 18198 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 18199 NonOdrUseReason NOUR) { 18200 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 18201 // an object that satisfies the requirements for appearing in a 18202 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 18203 // is immediately applied." This function handles the lvalue-to-rvalue 18204 // conversion part. 18205 // 18206 // If we encounter a node that claims to be an odr-use but shouldn't be, we 18207 // transform it into the relevant kind of non-odr-use node and rebuild the 18208 // tree of nodes leading to it. 18209 // 18210 // This is a mini-TreeTransform that only transforms a restricted subset of 18211 // nodes (and only certain operands of them). 18212 18213 // Rebuild a subexpression. 18214 auto Rebuild = [&](Expr *Sub) { 18215 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 18216 }; 18217 18218 // Check whether a potential result satisfies the requirements of NOUR. 18219 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 18220 // Any entity other than a VarDecl is always odr-used whenever it's named 18221 // in a potentially-evaluated expression. 18222 auto *VD = dyn_cast<VarDecl>(D); 18223 if (!VD) 18224 return true; 18225 18226 // C++2a [basic.def.odr]p4: 18227 // A variable x whose name appears as a potentially-evalauted expression 18228 // e is odr-used by e unless 18229 // -- x is a reference that is usable in constant expressions, or 18230 // -- x is a variable of non-reference type that is usable in constant 18231 // expressions and has no mutable subobjects, and e is an element of 18232 // the set of potential results of an expression of 18233 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18234 // conversion is applied, or 18235 // -- x is a variable of non-reference type, and e is an element of the 18236 // set of potential results of a discarded-value expression to which 18237 // the lvalue-to-rvalue conversion is not applied 18238 // 18239 // We check the first bullet and the "potentially-evaluated" condition in 18240 // BuildDeclRefExpr. We check the type requirements in the second bullet 18241 // in CheckLValueToRValueConversionOperand below. 18242 switch (NOUR) { 18243 case NOUR_None: 18244 case NOUR_Unevaluated: 18245 llvm_unreachable("unexpected non-odr-use-reason"); 18246 18247 case NOUR_Constant: 18248 // Constant references were handled when they were built. 18249 if (VD->getType()->isReferenceType()) 18250 return true; 18251 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 18252 if (RD->hasMutableFields()) 18253 return true; 18254 if (!VD->isUsableInConstantExpressions(S.Context)) 18255 return true; 18256 break; 18257 18258 case NOUR_Discarded: 18259 if (VD->getType()->isReferenceType()) 18260 return true; 18261 break; 18262 } 18263 return false; 18264 }; 18265 18266 // Mark that this expression does not constitute an odr-use. 18267 auto MarkNotOdrUsed = [&] { 18268 S.MaybeODRUseExprs.remove(E); 18269 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18270 LSI->markVariableExprAsNonODRUsed(E); 18271 }; 18272 18273 // C++2a [basic.def.odr]p2: 18274 // The set of potential results of an expression e is defined as follows: 18275 switch (E->getStmtClass()) { 18276 // -- If e is an id-expression, ... 18277 case Expr::DeclRefExprClass: { 18278 auto *DRE = cast<DeclRefExpr>(E); 18279 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18280 break; 18281 18282 // Rebuild as a non-odr-use DeclRefExpr. 18283 MarkNotOdrUsed(); 18284 return DeclRefExpr::Create( 18285 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18286 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18287 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18288 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18289 } 18290 18291 case Expr::FunctionParmPackExprClass: { 18292 auto *FPPE = cast<FunctionParmPackExpr>(E); 18293 // If any of the declarations in the pack is odr-used, then the expression 18294 // as a whole constitutes an odr-use. 18295 for (VarDecl *D : *FPPE) 18296 if (IsPotentialResultOdrUsed(D)) 18297 return ExprEmpty(); 18298 18299 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18300 // nothing cares about whether we marked this as an odr-use, but it might 18301 // be useful for non-compiler tools. 18302 MarkNotOdrUsed(); 18303 break; 18304 } 18305 18306 // -- If e is a subscripting operation with an array operand... 18307 case Expr::ArraySubscriptExprClass: { 18308 auto *ASE = cast<ArraySubscriptExpr>(E); 18309 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18310 if (!OldBase->getType()->isArrayType()) 18311 break; 18312 ExprResult Base = Rebuild(OldBase); 18313 if (!Base.isUsable()) 18314 return Base; 18315 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18316 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18317 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18318 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18319 ASE->getRBracketLoc()); 18320 } 18321 18322 case Expr::MemberExprClass: { 18323 auto *ME = cast<MemberExpr>(E); 18324 // -- If e is a class member access expression [...] naming a non-static 18325 // data member... 18326 if (isa<FieldDecl>(ME->getMemberDecl())) { 18327 ExprResult Base = Rebuild(ME->getBase()); 18328 if (!Base.isUsable()) 18329 return Base; 18330 return MemberExpr::Create( 18331 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18332 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18333 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18334 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18335 ME->getObjectKind(), ME->isNonOdrUse()); 18336 } 18337 18338 if (ME->getMemberDecl()->isCXXInstanceMember()) 18339 break; 18340 18341 // -- If e is a class member access expression naming a static data member, 18342 // ... 18343 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18344 break; 18345 18346 // Rebuild as a non-odr-use MemberExpr. 18347 MarkNotOdrUsed(); 18348 return MemberExpr::Create( 18349 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18350 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18351 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18352 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18353 } 18354 18355 case Expr::BinaryOperatorClass: { 18356 auto *BO = cast<BinaryOperator>(E); 18357 Expr *LHS = BO->getLHS(); 18358 Expr *RHS = BO->getRHS(); 18359 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18360 if (BO->getOpcode() == BO_PtrMemD) { 18361 ExprResult Sub = Rebuild(LHS); 18362 if (!Sub.isUsable()) 18363 return Sub; 18364 LHS = Sub.get(); 18365 // -- If e is a comma expression, ... 18366 } else if (BO->getOpcode() == BO_Comma) { 18367 ExprResult Sub = Rebuild(RHS); 18368 if (!Sub.isUsable()) 18369 return Sub; 18370 RHS = Sub.get(); 18371 } else { 18372 break; 18373 } 18374 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18375 LHS, RHS); 18376 } 18377 18378 // -- If e has the form (e1)... 18379 case Expr::ParenExprClass: { 18380 auto *PE = cast<ParenExpr>(E); 18381 ExprResult Sub = Rebuild(PE->getSubExpr()); 18382 if (!Sub.isUsable()) 18383 return Sub; 18384 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18385 } 18386 18387 // -- If e is a glvalue conditional expression, ... 18388 // We don't apply this to a binary conditional operator. FIXME: Should we? 18389 case Expr::ConditionalOperatorClass: { 18390 auto *CO = cast<ConditionalOperator>(E); 18391 ExprResult LHS = Rebuild(CO->getLHS()); 18392 if (LHS.isInvalid()) 18393 return ExprError(); 18394 ExprResult RHS = Rebuild(CO->getRHS()); 18395 if (RHS.isInvalid()) 18396 return ExprError(); 18397 if (!LHS.isUsable() && !RHS.isUsable()) 18398 return ExprEmpty(); 18399 if (!LHS.isUsable()) 18400 LHS = CO->getLHS(); 18401 if (!RHS.isUsable()) 18402 RHS = CO->getRHS(); 18403 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18404 CO->getCond(), LHS.get(), RHS.get()); 18405 } 18406 18407 // [Clang extension] 18408 // -- If e has the form __extension__ e1... 18409 case Expr::UnaryOperatorClass: { 18410 auto *UO = cast<UnaryOperator>(E); 18411 if (UO->getOpcode() != UO_Extension) 18412 break; 18413 ExprResult Sub = Rebuild(UO->getSubExpr()); 18414 if (!Sub.isUsable()) 18415 return Sub; 18416 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18417 Sub.get()); 18418 } 18419 18420 // [Clang extension] 18421 // -- If e has the form _Generic(...), the set of potential results is the 18422 // union of the sets of potential results of the associated expressions. 18423 case Expr::GenericSelectionExprClass: { 18424 auto *GSE = cast<GenericSelectionExpr>(E); 18425 18426 SmallVector<Expr *, 4> AssocExprs; 18427 bool AnyChanged = false; 18428 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18429 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18430 if (AssocExpr.isInvalid()) 18431 return ExprError(); 18432 if (AssocExpr.isUsable()) { 18433 AssocExprs.push_back(AssocExpr.get()); 18434 AnyChanged = true; 18435 } else { 18436 AssocExprs.push_back(OrigAssocExpr); 18437 } 18438 } 18439 18440 return AnyChanged ? S.CreateGenericSelectionExpr( 18441 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18442 GSE->getRParenLoc(), GSE->getControllingExpr(), 18443 GSE->getAssocTypeSourceInfos(), AssocExprs) 18444 : ExprEmpty(); 18445 } 18446 18447 // [Clang extension] 18448 // -- If e has the form __builtin_choose_expr(...), the set of potential 18449 // results is the union of the sets of potential results of the 18450 // second and third subexpressions. 18451 case Expr::ChooseExprClass: { 18452 auto *CE = cast<ChooseExpr>(E); 18453 18454 ExprResult LHS = Rebuild(CE->getLHS()); 18455 if (LHS.isInvalid()) 18456 return ExprError(); 18457 18458 ExprResult RHS = Rebuild(CE->getLHS()); 18459 if (RHS.isInvalid()) 18460 return ExprError(); 18461 18462 if (!LHS.get() && !RHS.get()) 18463 return ExprEmpty(); 18464 if (!LHS.isUsable()) 18465 LHS = CE->getLHS(); 18466 if (!RHS.isUsable()) 18467 RHS = CE->getRHS(); 18468 18469 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18470 RHS.get(), CE->getRParenLoc()); 18471 } 18472 18473 // Step through non-syntactic nodes. 18474 case Expr::ConstantExprClass: { 18475 auto *CE = cast<ConstantExpr>(E); 18476 ExprResult Sub = Rebuild(CE->getSubExpr()); 18477 if (!Sub.isUsable()) 18478 return Sub; 18479 return ConstantExpr::Create(S.Context, Sub.get()); 18480 } 18481 18482 // We could mostly rely on the recursive rebuilding to rebuild implicit 18483 // casts, but not at the top level, so rebuild them here. 18484 case Expr::ImplicitCastExprClass: { 18485 auto *ICE = cast<ImplicitCastExpr>(E); 18486 // Only step through the narrow set of cast kinds we expect to encounter. 18487 // Anything else suggests we've left the region in which potential results 18488 // can be found. 18489 switch (ICE->getCastKind()) { 18490 case CK_NoOp: 18491 case CK_DerivedToBase: 18492 case CK_UncheckedDerivedToBase: { 18493 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18494 if (!Sub.isUsable()) 18495 return Sub; 18496 CXXCastPath Path(ICE->path()); 18497 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18498 ICE->getValueKind(), &Path); 18499 } 18500 18501 default: 18502 break; 18503 } 18504 break; 18505 } 18506 18507 default: 18508 break; 18509 } 18510 18511 // Can't traverse through this node. Nothing to do. 18512 return ExprEmpty(); 18513 } 18514 18515 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18516 // Check whether the operand is or contains an object of non-trivial C union 18517 // type. 18518 if (E->getType().isVolatileQualified() && 18519 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18520 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18521 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18522 Sema::NTCUC_LValueToRValueVolatile, 18523 NTCUK_Destruct|NTCUK_Copy); 18524 18525 // C++2a [basic.def.odr]p4: 18526 // [...] an expression of non-volatile-qualified non-class type to which 18527 // the lvalue-to-rvalue conversion is applied [...] 18528 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18529 return E; 18530 18531 ExprResult Result = 18532 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18533 if (Result.isInvalid()) 18534 return ExprError(); 18535 return Result.get() ? Result : E; 18536 } 18537 18538 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18539 Res = CorrectDelayedTyposInExpr(Res); 18540 18541 if (!Res.isUsable()) 18542 return Res; 18543 18544 // If a constant-expression is a reference to a variable where we delay 18545 // deciding whether it is an odr-use, just assume we will apply the 18546 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18547 // (a non-type template argument), we have special handling anyway. 18548 return CheckLValueToRValueConversionOperand(Res.get()); 18549 } 18550 18551 void Sema::CleanupVarDeclMarking() { 18552 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18553 // call. 18554 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18555 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18556 18557 for (Expr *E : LocalMaybeODRUseExprs) { 18558 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18559 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18560 DRE->getLocation(), *this); 18561 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18562 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18563 *this); 18564 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18565 for (VarDecl *VD : *FP) 18566 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18567 } else { 18568 llvm_unreachable("Unexpected expression"); 18569 } 18570 } 18571 18572 assert(MaybeODRUseExprs.empty() && 18573 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18574 } 18575 18576 static void DoMarkVarDeclReferenced( 18577 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 18578 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18579 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18580 isa<FunctionParmPackExpr>(E)) && 18581 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18582 Var->setReferenced(); 18583 18584 if (Var->isInvalidDecl()) 18585 return; 18586 18587 auto *MSI = Var->getMemberSpecializationInfo(); 18588 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18589 : Var->getTemplateSpecializationKind(); 18590 18591 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18592 bool UsableInConstantExpr = 18593 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18594 18595 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 18596 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 18597 } 18598 18599 // C++20 [expr.const]p12: 18600 // A variable [...] is needed for constant evaluation if it is [...] a 18601 // variable whose name appears as a potentially constant evaluated 18602 // expression that is either a contexpr variable or is of non-volatile 18603 // const-qualified integral type or of reference type 18604 bool NeededForConstantEvaluation = 18605 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18606 18607 bool NeedDefinition = 18608 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18609 18610 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18611 "Can't instantiate a partial template specialization."); 18612 18613 // If this might be a member specialization of a static data member, check 18614 // the specialization is visible. We already did the checks for variable 18615 // template specializations when we created them. 18616 if (NeedDefinition && TSK != TSK_Undeclared && 18617 !isa<VarTemplateSpecializationDecl>(Var)) 18618 SemaRef.checkSpecializationVisibility(Loc, Var); 18619 18620 // Perform implicit instantiation of static data members, static data member 18621 // templates of class templates, and variable template specializations. Delay 18622 // instantiations of variable templates, except for those that could be used 18623 // in a constant expression. 18624 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18625 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18626 // instantiation declaration if a variable is usable in a constant 18627 // expression (among other cases). 18628 bool TryInstantiating = 18629 TSK == TSK_ImplicitInstantiation || 18630 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18631 18632 if (TryInstantiating) { 18633 SourceLocation PointOfInstantiation = 18634 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18635 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18636 if (FirstInstantiation) { 18637 PointOfInstantiation = Loc; 18638 if (MSI) 18639 MSI->setPointOfInstantiation(PointOfInstantiation); 18640 // FIXME: Notify listener. 18641 else 18642 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18643 } 18644 18645 if (UsableInConstantExpr) { 18646 // Do not defer instantiations of variables that could be used in a 18647 // constant expression. 18648 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18649 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18650 }); 18651 18652 // Re-set the member to trigger a recomputation of the dependence bits 18653 // for the expression. 18654 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18655 DRE->setDecl(DRE->getDecl()); 18656 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18657 ME->setMemberDecl(ME->getMemberDecl()); 18658 } else if (FirstInstantiation || 18659 isa<VarTemplateSpecializationDecl>(Var)) { 18660 // FIXME: For a specialization of a variable template, we don't 18661 // distinguish between "declaration and type implicitly instantiated" 18662 // and "implicit instantiation of definition requested", so we have 18663 // no direct way to avoid enqueueing the pending instantiation 18664 // multiple times. 18665 SemaRef.PendingInstantiations 18666 .push_back(std::make_pair(Var, PointOfInstantiation)); 18667 } 18668 } 18669 } 18670 18671 // C++2a [basic.def.odr]p4: 18672 // A variable x whose name appears as a potentially-evaluated expression e 18673 // is odr-used by e unless 18674 // -- x is a reference that is usable in constant expressions 18675 // -- x is a variable of non-reference type that is usable in constant 18676 // expressions and has no mutable subobjects [FIXME], and e is an 18677 // element of the set of potential results of an expression of 18678 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18679 // conversion is applied 18680 // -- x is a variable of non-reference type, and e is an element of the set 18681 // of potential results of a discarded-value expression to which the 18682 // lvalue-to-rvalue conversion is not applied [FIXME] 18683 // 18684 // We check the first part of the second bullet here, and 18685 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18686 // FIXME: To get the third bullet right, we need to delay this even for 18687 // variables that are not usable in constant expressions. 18688 18689 // If we already know this isn't an odr-use, there's nothing more to do. 18690 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18691 if (DRE->isNonOdrUse()) 18692 return; 18693 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18694 if (ME->isNonOdrUse()) 18695 return; 18696 18697 switch (OdrUse) { 18698 case OdrUseContext::None: 18699 assert((!E || isa<FunctionParmPackExpr>(E)) && 18700 "missing non-odr-use marking for unevaluated decl ref"); 18701 break; 18702 18703 case OdrUseContext::FormallyOdrUsed: 18704 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18705 // behavior. 18706 break; 18707 18708 case OdrUseContext::Used: 18709 // If we might later find that this expression isn't actually an odr-use, 18710 // delay the marking. 18711 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18712 SemaRef.MaybeODRUseExprs.insert(E); 18713 else 18714 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18715 break; 18716 18717 case OdrUseContext::Dependent: 18718 // If this is a dependent context, we don't need to mark variables as 18719 // odr-used, but we may still need to track them for lambda capture. 18720 // FIXME: Do we also need to do this inside dependent typeid expressions 18721 // (which are modeled as unevaluated at this point)? 18722 const bool RefersToEnclosingScope = 18723 (SemaRef.CurContext != Var->getDeclContext() && 18724 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18725 if (RefersToEnclosingScope) { 18726 LambdaScopeInfo *const LSI = 18727 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18728 if (LSI && (!LSI->CallOperator || 18729 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18730 // If a variable could potentially be odr-used, defer marking it so 18731 // until we finish analyzing the full expression for any 18732 // lvalue-to-rvalue 18733 // or discarded value conversions that would obviate odr-use. 18734 // Add it to the list of potential captures that will be analyzed 18735 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18736 // unless the variable is a reference that was initialized by a constant 18737 // expression (this will never need to be captured or odr-used). 18738 // 18739 // FIXME: We can simplify this a lot after implementing P0588R1. 18740 assert(E && "Capture variable should be used in an expression."); 18741 if (!Var->getType()->isReferenceType() || 18742 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18743 LSI->addPotentialCapture(E->IgnoreParens()); 18744 } 18745 } 18746 break; 18747 } 18748 } 18749 18750 /// Mark a variable referenced, and check whether it is odr-used 18751 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18752 /// used directly for normal expressions referring to VarDecl. 18753 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18754 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 18755 } 18756 18757 static void 18758 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 18759 bool MightBeOdrUse, 18760 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 18761 if (SemaRef.isInOpenMPDeclareTargetContext()) 18762 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18763 18764 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18765 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 18766 return; 18767 } 18768 18769 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18770 18771 // If this is a call to a method via a cast, also mark the method in the 18772 // derived class used in case codegen can devirtualize the call. 18773 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18774 if (!ME) 18775 return; 18776 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18777 if (!MD) 18778 return; 18779 // Only attempt to devirtualize if this is truly a virtual call. 18780 bool IsVirtualCall = MD->isVirtual() && 18781 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18782 if (!IsVirtualCall) 18783 return; 18784 18785 // If it's possible to devirtualize the call, mark the called function 18786 // referenced. 18787 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18788 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18789 if (DM) 18790 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18791 } 18792 18793 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18794 /// 18795 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18796 /// handled with care if the DeclRefExpr is not newly-created. 18797 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18798 // TODO: update this with DR# once a defect report is filed. 18799 // C++11 defect. The address of a pure member should not be an ODR use, even 18800 // if it's a qualified reference. 18801 bool OdrUse = true; 18802 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18803 if (Method->isVirtual() && 18804 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18805 OdrUse = false; 18806 18807 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18808 if (!isUnevaluatedContext() && !isConstantEvaluated() && 18809 FD->isConsteval() && !RebuildingImmediateInvocation) 18810 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18811 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 18812 RefsMinusAssignments); 18813 } 18814 18815 /// Perform reference-marking and odr-use handling for a MemberExpr. 18816 void Sema::MarkMemberReferenced(MemberExpr *E) { 18817 // C++11 [basic.def.odr]p2: 18818 // A non-overloaded function whose name appears as a potentially-evaluated 18819 // expression or a member of a set of candidate functions, if selected by 18820 // overload resolution when referred to from a potentially-evaluated 18821 // expression, is odr-used, unless it is a pure virtual function and its 18822 // name is not explicitly qualified. 18823 bool MightBeOdrUse = true; 18824 if (E->performsVirtualDispatch(getLangOpts())) { 18825 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18826 if (Method->isPure()) 18827 MightBeOdrUse = false; 18828 } 18829 SourceLocation Loc = 18830 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18831 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 18832 RefsMinusAssignments); 18833 } 18834 18835 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18836 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18837 for (VarDecl *VD : *E) 18838 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 18839 RefsMinusAssignments); 18840 } 18841 18842 /// Perform marking for a reference to an arbitrary declaration. It 18843 /// marks the declaration referenced, and performs odr-use checking for 18844 /// functions and variables. This method should not be used when building a 18845 /// normal expression which refers to a variable. 18846 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18847 bool MightBeOdrUse) { 18848 if (MightBeOdrUse) { 18849 if (auto *VD = dyn_cast<VarDecl>(D)) { 18850 MarkVariableReferenced(Loc, VD); 18851 return; 18852 } 18853 } 18854 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18855 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18856 return; 18857 } 18858 D->setReferenced(); 18859 } 18860 18861 namespace { 18862 // Mark all of the declarations used by a type as referenced. 18863 // FIXME: Not fully implemented yet! We need to have a better understanding 18864 // of when we're entering a context we should not recurse into. 18865 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18866 // TreeTransforms rebuilding the type in a new context. Rather than 18867 // duplicating the TreeTransform logic, we should consider reusing it here. 18868 // Currently that causes problems when rebuilding LambdaExprs. 18869 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18870 Sema &S; 18871 SourceLocation Loc; 18872 18873 public: 18874 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18875 18876 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18877 18878 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18879 }; 18880 } 18881 18882 bool MarkReferencedDecls::TraverseTemplateArgument( 18883 const TemplateArgument &Arg) { 18884 { 18885 // A non-type template argument is a constant-evaluated context. 18886 EnterExpressionEvaluationContext Evaluated( 18887 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18888 if (Arg.getKind() == TemplateArgument::Declaration) { 18889 if (Decl *D = Arg.getAsDecl()) 18890 S.MarkAnyDeclReferenced(Loc, D, true); 18891 } else if (Arg.getKind() == TemplateArgument::Expression) { 18892 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18893 } 18894 } 18895 18896 return Inherited::TraverseTemplateArgument(Arg); 18897 } 18898 18899 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18900 MarkReferencedDecls Marker(*this, Loc); 18901 Marker.TraverseType(T); 18902 } 18903 18904 namespace { 18905 /// Helper class that marks all of the declarations referenced by 18906 /// potentially-evaluated subexpressions as "referenced". 18907 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18908 public: 18909 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18910 bool SkipLocalVariables; 18911 18912 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18913 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18914 18915 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18916 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18917 } 18918 18919 void VisitDeclRefExpr(DeclRefExpr *E) { 18920 // If we were asked not to visit local variables, don't. 18921 if (SkipLocalVariables) { 18922 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18923 if (VD->hasLocalStorage()) 18924 return; 18925 } 18926 18927 // FIXME: This can trigger the instantiation of the initializer of a 18928 // variable, which can cause the expression to become value-dependent 18929 // or error-dependent. Do we need to propagate the new dependence bits? 18930 S.MarkDeclRefReferenced(E); 18931 } 18932 18933 void VisitMemberExpr(MemberExpr *E) { 18934 S.MarkMemberReferenced(E); 18935 Visit(E->getBase()); 18936 } 18937 }; 18938 } // namespace 18939 18940 /// Mark any declarations that appear within this expression or any 18941 /// potentially-evaluated subexpressions as "referenced". 18942 /// 18943 /// \param SkipLocalVariables If true, don't mark local variables as 18944 /// 'referenced'. 18945 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18946 bool SkipLocalVariables) { 18947 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18948 } 18949 18950 /// Emit a diagnostic that describes an effect on the run-time behavior 18951 /// of the program being compiled. 18952 /// 18953 /// This routine emits the given diagnostic when the code currently being 18954 /// type-checked is "potentially evaluated", meaning that there is a 18955 /// possibility that the code will actually be executable. Code in sizeof() 18956 /// expressions, code used only during overload resolution, etc., are not 18957 /// potentially evaluated. This routine will suppress such diagnostics or, 18958 /// in the absolutely nutty case of potentially potentially evaluated 18959 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18960 /// later. 18961 /// 18962 /// This routine should be used for all diagnostics that describe the run-time 18963 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18964 /// Failure to do so will likely result in spurious diagnostics or failures 18965 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18966 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18967 const PartialDiagnostic &PD) { 18968 switch (ExprEvalContexts.back().Context) { 18969 case ExpressionEvaluationContext::Unevaluated: 18970 case ExpressionEvaluationContext::UnevaluatedList: 18971 case ExpressionEvaluationContext::UnevaluatedAbstract: 18972 case ExpressionEvaluationContext::DiscardedStatement: 18973 // The argument will never be evaluated, so don't complain. 18974 break; 18975 18976 case ExpressionEvaluationContext::ConstantEvaluated: 18977 // Relevant diagnostics should be produced by constant evaluation. 18978 break; 18979 18980 case ExpressionEvaluationContext::PotentiallyEvaluated: 18981 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18982 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18983 FunctionScopes.back()->PossiblyUnreachableDiags. 18984 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18985 return true; 18986 } 18987 18988 // The initializer of a constexpr variable or of the first declaration of a 18989 // static data member is not syntactically a constant evaluated constant, 18990 // but nonetheless is always required to be a constant expression, so we 18991 // can skip diagnosing. 18992 // FIXME: Using the mangling context here is a hack. 18993 if (auto *VD = dyn_cast_or_null<VarDecl>( 18994 ExprEvalContexts.back().ManglingContextDecl)) { 18995 if (VD->isConstexpr() || 18996 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18997 break; 18998 // FIXME: For any other kind of variable, we should build a CFG for its 18999 // initializer and check whether the context in question is reachable. 19000 } 19001 19002 Diag(Loc, PD); 19003 return true; 19004 } 19005 19006 return false; 19007 } 19008 19009 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 19010 const PartialDiagnostic &PD) { 19011 return DiagRuntimeBehavior( 19012 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 19013 } 19014 19015 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 19016 CallExpr *CE, FunctionDecl *FD) { 19017 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 19018 return false; 19019 19020 // If we're inside a decltype's expression, don't check for a valid return 19021 // type or construct temporaries until we know whether this is the last call. 19022 if (ExprEvalContexts.back().ExprContext == 19023 ExpressionEvaluationContextRecord::EK_Decltype) { 19024 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 19025 return false; 19026 } 19027 19028 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 19029 FunctionDecl *FD; 19030 CallExpr *CE; 19031 19032 public: 19033 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 19034 : FD(FD), CE(CE) { } 19035 19036 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 19037 if (!FD) { 19038 S.Diag(Loc, diag::err_call_incomplete_return) 19039 << T << CE->getSourceRange(); 19040 return; 19041 } 19042 19043 S.Diag(Loc, diag::err_call_function_incomplete_return) 19044 << CE->getSourceRange() << FD << T; 19045 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 19046 << FD->getDeclName(); 19047 } 19048 } Diagnoser(FD, CE); 19049 19050 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 19051 return true; 19052 19053 return false; 19054 } 19055 19056 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 19057 // will prevent this condition from triggering, which is what we want. 19058 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 19059 SourceLocation Loc; 19060 19061 unsigned diagnostic = diag::warn_condition_is_assignment; 19062 bool IsOrAssign = false; 19063 19064 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 19065 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 19066 return; 19067 19068 IsOrAssign = Op->getOpcode() == BO_OrAssign; 19069 19070 // Greylist some idioms by putting them into a warning subcategory. 19071 if (ObjCMessageExpr *ME 19072 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 19073 Selector Sel = ME->getSelector(); 19074 19075 // self = [<foo> init...] 19076 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 19077 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19078 19079 // <foo> = [<bar> nextObject] 19080 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 19081 diagnostic = diag::warn_condition_is_idiomatic_assignment; 19082 } 19083 19084 Loc = Op->getOperatorLoc(); 19085 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 19086 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 19087 return; 19088 19089 IsOrAssign = Op->getOperator() == OO_PipeEqual; 19090 Loc = Op->getOperatorLoc(); 19091 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 19092 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 19093 else { 19094 // Not an assignment. 19095 return; 19096 } 19097 19098 Diag(Loc, diagnostic) << E->getSourceRange(); 19099 19100 SourceLocation Open = E->getBeginLoc(); 19101 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 19102 Diag(Loc, diag::note_condition_assign_silence) 19103 << FixItHint::CreateInsertion(Open, "(") 19104 << FixItHint::CreateInsertion(Close, ")"); 19105 19106 if (IsOrAssign) 19107 Diag(Loc, diag::note_condition_or_assign_to_comparison) 19108 << FixItHint::CreateReplacement(Loc, "!="); 19109 else 19110 Diag(Loc, diag::note_condition_assign_to_comparison) 19111 << FixItHint::CreateReplacement(Loc, "=="); 19112 } 19113 19114 /// Redundant parentheses over an equality comparison can indicate 19115 /// that the user intended an assignment used as condition. 19116 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 19117 // Don't warn if the parens came from a macro. 19118 SourceLocation parenLoc = ParenE->getBeginLoc(); 19119 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 19120 return; 19121 // Don't warn for dependent expressions. 19122 if (ParenE->isTypeDependent()) 19123 return; 19124 19125 Expr *E = ParenE->IgnoreParens(); 19126 19127 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 19128 if (opE->getOpcode() == BO_EQ && 19129 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 19130 == Expr::MLV_Valid) { 19131 SourceLocation Loc = opE->getOperatorLoc(); 19132 19133 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 19134 SourceRange ParenERange = ParenE->getSourceRange(); 19135 Diag(Loc, diag::note_equality_comparison_silence) 19136 << FixItHint::CreateRemoval(ParenERange.getBegin()) 19137 << FixItHint::CreateRemoval(ParenERange.getEnd()); 19138 Diag(Loc, diag::note_equality_comparison_to_assign) 19139 << FixItHint::CreateReplacement(Loc, "="); 19140 } 19141 } 19142 19143 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 19144 bool IsConstexpr) { 19145 DiagnoseAssignmentAsCondition(E); 19146 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 19147 DiagnoseEqualityWithExtraParens(parenE); 19148 19149 ExprResult result = CheckPlaceholderExpr(E); 19150 if (result.isInvalid()) return ExprError(); 19151 E = result.get(); 19152 19153 if (!E->isTypeDependent()) { 19154 if (getLangOpts().CPlusPlus) 19155 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 19156 19157 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 19158 if (ERes.isInvalid()) 19159 return ExprError(); 19160 E = ERes.get(); 19161 19162 QualType T = E->getType(); 19163 if (!T->isScalarType()) { // C99 6.8.4.1p1 19164 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 19165 << T << E->getSourceRange(); 19166 return ExprError(); 19167 } 19168 CheckBoolLikeConversion(E, Loc); 19169 } 19170 19171 return E; 19172 } 19173 19174 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 19175 Expr *SubExpr, ConditionKind CK) { 19176 // Empty conditions are valid in for-statements. 19177 if (!SubExpr) 19178 return ConditionResult(); 19179 19180 ExprResult Cond; 19181 switch (CK) { 19182 case ConditionKind::Boolean: 19183 Cond = CheckBooleanCondition(Loc, SubExpr); 19184 break; 19185 19186 case ConditionKind::ConstexprIf: 19187 Cond = CheckBooleanCondition(Loc, SubExpr, true); 19188 break; 19189 19190 case ConditionKind::Switch: 19191 Cond = CheckSwitchCondition(Loc, SubExpr); 19192 break; 19193 } 19194 if (Cond.isInvalid()) { 19195 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 19196 {SubExpr}); 19197 if (!Cond.get()) 19198 return ConditionError(); 19199 } 19200 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 19201 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 19202 if (!FullExpr.get()) 19203 return ConditionError(); 19204 19205 return ConditionResult(*this, nullptr, FullExpr, 19206 CK == ConditionKind::ConstexprIf); 19207 } 19208 19209 namespace { 19210 /// A visitor for rebuilding a call to an __unknown_any expression 19211 /// to have an appropriate type. 19212 struct RebuildUnknownAnyFunction 19213 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 19214 19215 Sema &S; 19216 19217 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 19218 19219 ExprResult VisitStmt(Stmt *S) { 19220 llvm_unreachable("unexpected statement!"); 19221 } 19222 19223 ExprResult VisitExpr(Expr *E) { 19224 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 19225 << E->getSourceRange(); 19226 return ExprError(); 19227 } 19228 19229 /// Rebuild an expression which simply semantically wraps another 19230 /// expression which it shares the type and value kind of. 19231 template <class T> ExprResult rebuildSugarExpr(T *E) { 19232 ExprResult SubResult = Visit(E->getSubExpr()); 19233 if (SubResult.isInvalid()) return ExprError(); 19234 19235 Expr *SubExpr = SubResult.get(); 19236 E->setSubExpr(SubExpr); 19237 E->setType(SubExpr->getType()); 19238 E->setValueKind(SubExpr->getValueKind()); 19239 assert(E->getObjectKind() == OK_Ordinary); 19240 return E; 19241 } 19242 19243 ExprResult VisitParenExpr(ParenExpr *E) { 19244 return rebuildSugarExpr(E); 19245 } 19246 19247 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19248 return rebuildSugarExpr(E); 19249 } 19250 19251 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19252 ExprResult SubResult = Visit(E->getSubExpr()); 19253 if (SubResult.isInvalid()) return ExprError(); 19254 19255 Expr *SubExpr = SubResult.get(); 19256 E->setSubExpr(SubExpr); 19257 E->setType(S.Context.getPointerType(SubExpr->getType())); 19258 assert(E->isPRValue()); 19259 assert(E->getObjectKind() == OK_Ordinary); 19260 return E; 19261 } 19262 19263 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19264 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19265 19266 E->setType(VD->getType()); 19267 19268 assert(E->isPRValue()); 19269 if (S.getLangOpts().CPlusPlus && 19270 !(isa<CXXMethodDecl>(VD) && 19271 cast<CXXMethodDecl>(VD)->isInstance())) 19272 E->setValueKind(VK_LValue); 19273 19274 return E; 19275 } 19276 19277 ExprResult VisitMemberExpr(MemberExpr *E) { 19278 return resolveDecl(E, E->getMemberDecl()); 19279 } 19280 19281 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19282 return resolveDecl(E, E->getDecl()); 19283 } 19284 }; 19285 } 19286 19287 /// Given a function expression of unknown-any type, try to rebuild it 19288 /// to have a function type. 19289 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19290 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19291 if (Result.isInvalid()) return ExprError(); 19292 return S.DefaultFunctionArrayConversion(Result.get()); 19293 } 19294 19295 namespace { 19296 /// A visitor for rebuilding an expression of type __unknown_anytype 19297 /// into one which resolves the type directly on the referring 19298 /// expression. Strict preservation of the original source 19299 /// structure is not a goal. 19300 struct RebuildUnknownAnyExpr 19301 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19302 19303 Sema &S; 19304 19305 /// The current destination type. 19306 QualType DestType; 19307 19308 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19309 : S(S), DestType(CastType) {} 19310 19311 ExprResult VisitStmt(Stmt *S) { 19312 llvm_unreachable("unexpected statement!"); 19313 } 19314 19315 ExprResult VisitExpr(Expr *E) { 19316 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19317 << E->getSourceRange(); 19318 return ExprError(); 19319 } 19320 19321 ExprResult VisitCallExpr(CallExpr *E); 19322 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19323 19324 /// Rebuild an expression which simply semantically wraps another 19325 /// expression which it shares the type and value kind of. 19326 template <class T> ExprResult rebuildSugarExpr(T *E) { 19327 ExprResult SubResult = Visit(E->getSubExpr()); 19328 if (SubResult.isInvalid()) return ExprError(); 19329 Expr *SubExpr = SubResult.get(); 19330 E->setSubExpr(SubExpr); 19331 E->setType(SubExpr->getType()); 19332 E->setValueKind(SubExpr->getValueKind()); 19333 assert(E->getObjectKind() == OK_Ordinary); 19334 return E; 19335 } 19336 19337 ExprResult VisitParenExpr(ParenExpr *E) { 19338 return rebuildSugarExpr(E); 19339 } 19340 19341 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19342 return rebuildSugarExpr(E); 19343 } 19344 19345 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19346 const PointerType *Ptr = DestType->getAs<PointerType>(); 19347 if (!Ptr) { 19348 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19349 << E->getSourceRange(); 19350 return ExprError(); 19351 } 19352 19353 if (isa<CallExpr>(E->getSubExpr())) { 19354 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19355 << E->getSourceRange(); 19356 return ExprError(); 19357 } 19358 19359 assert(E->isPRValue()); 19360 assert(E->getObjectKind() == OK_Ordinary); 19361 E->setType(DestType); 19362 19363 // Build the sub-expression as if it were an object of the pointee type. 19364 DestType = Ptr->getPointeeType(); 19365 ExprResult SubResult = Visit(E->getSubExpr()); 19366 if (SubResult.isInvalid()) return ExprError(); 19367 E->setSubExpr(SubResult.get()); 19368 return E; 19369 } 19370 19371 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19372 19373 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19374 19375 ExprResult VisitMemberExpr(MemberExpr *E) { 19376 return resolveDecl(E, E->getMemberDecl()); 19377 } 19378 19379 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19380 return resolveDecl(E, E->getDecl()); 19381 } 19382 }; 19383 } 19384 19385 /// Rebuilds a call expression which yielded __unknown_anytype. 19386 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19387 Expr *CalleeExpr = E->getCallee(); 19388 19389 enum FnKind { 19390 FK_MemberFunction, 19391 FK_FunctionPointer, 19392 FK_BlockPointer 19393 }; 19394 19395 FnKind Kind; 19396 QualType CalleeType = CalleeExpr->getType(); 19397 if (CalleeType == S.Context.BoundMemberTy) { 19398 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19399 Kind = FK_MemberFunction; 19400 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19401 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19402 CalleeType = Ptr->getPointeeType(); 19403 Kind = FK_FunctionPointer; 19404 } else { 19405 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19406 Kind = FK_BlockPointer; 19407 } 19408 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19409 19410 // Verify that this is a legal result type of a function. 19411 if (DestType->isArrayType() || DestType->isFunctionType()) { 19412 unsigned diagID = diag::err_func_returning_array_function; 19413 if (Kind == FK_BlockPointer) 19414 diagID = diag::err_block_returning_array_function; 19415 19416 S.Diag(E->getExprLoc(), diagID) 19417 << DestType->isFunctionType() << DestType; 19418 return ExprError(); 19419 } 19420 19421 // Otherwise, go ahead and set DestType as the call's result. 19422 E->setType(DestType.getNonLValueExprType(S.Context)); 19423 E->setValueKind(Expr::getValueKindForType(DestType)); 19424 assert(E->getObjectKind() == OK_Ordinary); 19425 19426 // Rebuild the function type, replacing the result type with DestType. 19427 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19428 if (Proto) { 19429 // __unknown_anytype(...) is a special case used by the debugger when 19430 // it has no idea what a function's signature is. 19431 // 19432 // We want to build this call essentially under the K&R 19433 // unprototyped rules, but making a FunctionNoProtoType in C++ 19434 // would foul up all sorts of assumptions. However, we cannot 19435 // simply pass all arguments as variadic arguments, nor can we 19436 // portably just call the function under a non-variadic type; see 19437 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19438 // However, it turns out that in practice it is generally safe to 19439 // call a function declared as "A foo(B,C,D);" under the prototype 19440 // "A foo(B,C,D,...);". The only known exception is with the 19441 // Windows ABI, where any variadic function is implicitly cdecl 19442 // regardless of its normal CC. Therefore we change the parameter 19443 // types to match the types of the arguments. 19444 // 19445 // This is a hack, but it is far superior to moving the 19446 // corresponding target-specific code from IR-gen to Sema/AST. 19447 19448 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19449 SmallVector<QualType, 8> ArgTypes; 19450 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19451 ArgTypes.reserve(E->getNumArgs()); 19452 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19453 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 19454 } 19455 ParamTypes = ArgTypes; 19456 } 19457 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19458 Proto->getExtProtoInfo()); 19459 } else { 19460 DestType = S.Context.getFunctionNoProtoType(DestType, 19461 FnType->getExtInfo()); 19462 } 19463 19464 // Rebuild the appropriate pointer-to-function type. 19465 switch (Kind) { 19466 case FK_MemberFunction: 19467 // Nothing to do. 19468 break; 19469 19470 case FK_FunctionPointer: 19471 DestType = S.Context.getPointerType(DestType); 19472 break; 19473 19474 case FK_BlockPointer: 19475 DestType = S.Context.getBlockPointerType(DestType); 19476 break; 19477 } 19478 19479 // Finally, we can recurse. 19480 ExprResult CalleeResult = Visit(CalleeExpr); 19481 if (!CalleeResult.isUsable()) return ExprError(); 19482 E->setCallee(CalleeResult.get()); 19483 19484 // Bind a temporary if necessary. 19485 return S.MaybeBindToTemporary(E); 19486 } 19487 19488 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19489 // Verify that this is a legal result type of a call. 19490 if (DestType->isArrayType() || DestType->isFunctionType()) { 19491 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19492 << DestType->isFunctionType() << DestType; 19493 return ExprError(); 19494 } 19495 19496 // Rewrite the method result type if available. 19497 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19498 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19499 Method->setReturnType(DestType); 19500 } 19501 19502 // Change the type of the message. 19503 E->setType(DestType.getNonReferenceType()); 19504 E->setValueKind(Expr::getValueKindForType(DestType)); 19505 19506 return S.MaybeBindToTemporary(E); 19507 } 19508 19509 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19510 // The only case we should ever see here is a function-to-pointer decay. 19511 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19512 assert(E->isPRValue()); 19513 assert(E->getObjectKind() == OK_Ordinary); 19514 19515 E->setType(DestType); 19516 19517 // Rebuild the sub-expression as the pointee (function) type. 19518 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19519 19520 ExprResult Result = Visit(E->getSubExpr()); 19521 if (!Result.isUsable()) return ExprError(); 19522 19523 E->setSubExpr(Result.get()); 19524 return E; 19525 } else if (E->getCastKind() == CK_LValueToRValue) { 19526 assert(E->isPRValue()); 19527 assert(E->getObjectKind() == OK_Ordinary); 19528 19529 assert(isa<BlockPointerType>(E->getType())); 19530 19531 E->setType(DestType); 19532 19533 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19534 DestType = S.Context.getLValueReferenceType(DestType); 19535 19536 ExprResult Result = Visit(E->getSubExpr()); 19537 if (!Result.isUsable()) return ExprError(); 19538 19539 E->setSubExpr(Result.get()); 19540 return E; 19541 } else { 19542 llvm_unreachable("Unhandled cast type!"); 19543 } 19544 } 19545 19546 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19547 ExprValueKind ValueKind = VK_LValue; 19548 QualType Type = DestType; 19549 19550 // We know how to make this work for certain kinds of decls: 19551 19552 // - functions 19553 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19554 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19555 DestType = Ptr->getPointeeType(); 19556 ExprResult Result = resolveDecl(E, VD); 19557 if (Result.isInvalid()) return ExprError(); 19558 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 19559 VK_PRValue); 19560 } 19561 19562 if (!Type->isFunctionType()) { 19563 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19564 << VD << E->getSourceRange(); 19565 return ExprError(); 19566 } 19567 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19568 // We must match the FunctionDecl's type to the hack introduced in 19569 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19570 // type. See the lengthy commentary in that routine. 19571 QualType FDT = FD->getType(); 19572 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19573 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19574 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19575 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19576 SourceLocation Loc = FD->getLocation(); 19577 FunctionDecl *NewFD = FunctionDecl::Create( 19578 S.Context, FD->getDeclContext(), Loc, Loc, 19579 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19580 SC_None, S.getCurFPFeatures().isFPConstrained(), 19581 false /*isInlineSpecified*/, FD->hasPrototype(), 19582 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19583 19584 if (FD->getQualifier()) 19585 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19586 19587 SmallVector<ParmVarDecl*, 16> Params; 19588 for (const auto &AI : FT->param_types()) { 19589 ParmVarDecl *Param = 19590 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19591 Param->setScopeInfo(0, Params.size()); 19592 Params.push_back(Param); 19593 } 19594 NewFD->setParams(Params); 19595 DRE->setDecl(NewFD); 19596 VD = DRE->getDecl(); 19597 } 19598 } 19599 19600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19601 if (MD->isInstance()) { 19602 ValueKind = VK_PRValue; 19603 Type = S.Context.BoundMemberTy; 19604 } 19605 19606 // Function references aren't l-values in C. 19607 if (!S.getLangOpts().CPlusPlus) 19608 ValueKind = VK_PRValue; 19609 19610 // - variables 19611 } else if (isa<VarDecl>(VD)) { 19612 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19613 Type = RefTy->getPointeeType(); 19614 } else if (Type->isFunctionType()) { 19615 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19616 << VD << E->getSourceRange(); 19617 return ExprError(); 19618 } 19619 19620 // - nothing else 19621 } else { 19622 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19623 << VD << E->getSourceRange(); 19624 return ExprError(); 19625 } 19626 19627 // Modifying the declaration like this is friendly to IR-gen but 19628 // also really dangerous. 19629 VD->setType(DestType); 19630 E->setType(Type); 19631 E->setValueKind(ValueKind); 19632 return E; 19633 } 19634 19635 /// Check a cast of an unknown-any type. We intentionally only 19636 /// trigger this for C-style casts. 19637 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19638 Expr *CastExpr, CastKind &CastKind, 19639 ExprValueKind &VK, CXXCastPath &Path) { 19640 // The type we're casting to must be either void or complete. 19641 if (!CastType->isVoidType() && 19642 RequireCompleteType(TypeRange.getBegin(), CastType, 19643 diag::err_typecheck_cast_to_incomplete)) 19644 return ExprError(); 19645 19646 // Rewrite the casted expression from scratch. 19647 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19648 if (!result.isUsable()) return ExprError(); 19649 19650 CastExpr = result.get(); 19651 VK = CastExpr->getValueKind(); 19652 CastKind = CK_NoOp; 19653 19654 return CastExpr; 19655 } 19656 19657 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19658 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19659 } 19660 19661 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19662 Expr *arg, QualType ¶mType) { 19663 // If the syntactic form of the argument is not an explicit cast of 19664 // any sort, just do default argument promotion. 19665 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19666 if (!castArg) { 19667 ExprResult result = DefaultArgumentPromotion(arg); 19668 if (result.isInvalid()) return ExprError(); 19669 paramType = result.get()->getType(); 19670 return result; 19671 } 19672 19673 // Otherwise, use the type that was written in the explicit cast. 19674 assert(!arg->hasPlaceholderType()); 19675 paramType = castArg->getTypeAsWritten(); 19676 19677 // Copy-initialize a parameter of that type. 19678 InitializedEntity entity = 19679 InitializedEntity::InitializeParameter(Context, paramType, 19680 /*consumed*/ false); 19681 return PerformCopyInitialization(entity, callLoc, arg); 19682 } 19683 19684 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19685 Expr *orig = E; 19686 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19687 while (true) { 19688 E = E->IgnoreParenImpCasts(); 19689 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19690 E = call->getCallee(); 19691 diagID = diag::err_uncasted_call_of_unknown_any; 19692 } else { 19693 break; 19694 } 19695 } 19696 19697 SourceLocation loc; 19698 NamedDecl *d; 19699 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19700 loc = ref->getLocation(); 19701 d = ref->getDecl(); 19702 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19703 loc = mem->getMemberLoc(); 19704 d = mem->getMemberDecl(); 19705 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19706 diagID = diag::err_uncasted_call_of_unknown_any; 19707 loc = msg->getSelectorStartLoc(); 19708 d = msg->getMethodDecl(); 19709 if (!d) { 19710 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19711 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19712 << orig->getSourceRange(); 19713 return ExprError(); 19714 } 19715 } else { 19716 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19717 << E->getSourceRange(); 19718 return ExprError(); 19719 } 19720 19721 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19722 19723 // Never recoverable. 19724 return ExprError(); 19725 } 19726 19727 /// Check for operands with placeholder types and complain if found. 19728 /// Returns ExprError() if there was an error and no recovery was possible. 19729 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19730 if (!Context.isDependenceAllowed()) { 19731 // C cannot handle TypoExpr nodes on either side of a binop because it 19732 // doesn't handle dependent types properly, so make sure any TypoExprs have 19733 // been dealt with before checking the operands. 19734 ExprResult Result = CorrectDelayedTyposInExpr(E); 19735 if (!Result.isUsable()) return ExprError(); 19736 E = Result.get(); 19737 } 19738 19739 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19740 if (!placeholderType) return E; 19741 19742 switch (placeholderType->getKind()) { 19743 19744 // Overloaded expressions. 19745 case BuiltinType::Overload: { 19746 // Try to resolve a single function template specialization. 19747 // This is obligatory. 19748 ExprResult Result = E; 19749 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19750 return Result; 19751 19752 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19753 // leaves Result unchanged on failure. 19754 Result = E; 19755 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19756 return Result; 19757 19758 // If that failed, try to recover with a call. 19759 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19760 /*complain*/ true); 19761 return Result; 19762 } 19763 19764 // Bound member functions. 19765 case BuiltinType::BoundMember: { 19766 ExprResult result = E; 19767 const Expr *BME = E->IgnoreParens(); 19768 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19769 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19770 if (isa<CXXPseudoDestructorExpr>(BME)) { 19771 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19772 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19773 if (ME->getMemberNameInfo().getName().getNameKind() == 19774 DeclarationName::CXXDestructorName) 19775 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19776 } 19777 tryToRecoverWithCall(result, PD, 19778 /*complain*/ true); 19779 return result; 19780 } 19781 19782 // ARC unbridged casts. 19783 case BuiltinType::ARCUnbridgedCast: { 19784 Expr *realCast = stripARCUnbridgedCast(E); 19785 diagnoseARCUnbridgedCast(realCast); 19786 return realCast; 19787 } 19788 19789 // Expressions of unknown type. 19790 case BuiltinType::UnknownAny: 19791 return diagnoseUnknownAnyExpr(*this, E); 19792 19793 // Pseudo-objects. 19794 case BuiltinType::PseudoObject: 19795 return checkPseudoObjectRValue(E); 19796 19797 case BuiltinType::BuiltinFn: { 19798 // Accept __noop without parens by implicitly converting it to a call expr. 19799 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19800 if (DRE) { 19801 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19802 if (FD->getBuiltinID() == Builtin::BI__noop) { 19803 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19804 CK_BuiltinFnToFnPtr) 19805 .get(); 19806 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19807 VK_PRValue, SourceLocation(), 19808 FPOptionsOverride()); 19809 } 19810 } 19811 19812 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19813 return ExprError(); 19814 } 19815 19816 case BuiltinType::IncompleteMatrixIdx: 19817 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19818 ->getRowIdx() 19819 ->getBeginLoc(), 19820 diag::err_matrix_incomplete_index); 19821 return ExprError(); 19822 19823 // Expressions of unknown type. 19824 case BuiltinType::OMPArraySection: 19825 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19826 return ExprError(); 19827 19828 // Expressions of unknown type. 19829 case BuiltinType::OMPArrayShaping: 19830 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19831 19832 case BuiltinType::OMPIterator: 19833 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19834 19835 // Everything else should be impossible. 19836 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19837 case BuiltinType::Id: 19838 #include "clang/Basic/OpenCLImageTypes.def" 19839 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19840 case BuiltinType::Id: 19841 #include "clang/Basic/OpenCLExtensionTypes.def" 19842 #define SVE_TYPE(Name, Id, SingletonId) \ 19843 case BuiltinType::Id: 19844 #include "clang/Basic/AArch64SVEACLETypes.def" 19845 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19846 case BuiltinType::Id: 19847 #include "clang/Basic/PPCTypes.def" 19848 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19849 #include "clang/Basic/RISCVVTypes.def" 19850 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19851 #define PLACEHOLDER_TYPE(Id, SingletonId) 19852 #include "clang/AST/BuiltinTypes.def" 19853 break; 19854 } 19855 19856 llvm_unreachable("invalid placeholder type!"); 19857 } 19858 19859 bool Sema::CheckCaseExpression(Expr *E) { 19860 if (E->isTypeDependent()) 19861 return true; 19862 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19863 return E->getType()->isIntegralOrEnumerationType(); 19864 return false; 19865 } 19866 19867 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19868 ExprResult 19869 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19870 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19871 "Unknown Objective-C Boolean value!"); 19872 QualType BoolT = Context.ObjCBuiltinBoolTy; 19873 if (!Context.getBOOLDecl()) { 19874 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19875 Sema::LookupOrdinaryName); 19876 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19877 NamedDecl *ND = Result.getFoundDecl(); 19878 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19879 Context.setBOOLDecl(TD); 19880 } 19881 } 19882 if (Context.getBOOLDecl()) 19883 BoolT = Context.getBOOLType(); 19884 return new (Context) 19885 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19886 } 19887 19888 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19889 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19890 SourceLocation RParen) { 19891 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> { 19892 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19893 return Spec.getPlatform() == Platform; 19894 }); 19895 // Transcribe the "ios" availability check to "maccatalyst" when compiling 19896 // for "maccatalyst" if "maccatalyst" is not specified. 19897 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 19898 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19899 return Spec.getPlatform() == "ios"; 19900 }); 19901 } 19902 if (Spec == AvailSpecs.end()) 19903 return None; 19904 return Spec->getVersion(); 19905 }; 19906 19907 VersionTuple Version; 19908 if (auto MaybeVersion = 19909 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 19910 Version = *MaybeVersion; 19911 19912 // The use of `@available` in the enclosing context should be analyzed to 19913 // warn when it's used inappropriately (i.e. not if(@available)). 19914 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 19915 Context->HasPotentialAvailabilityViolations = true; 19916 19917 return new (Context) 19918 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19919 } 19920 19921 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19922 ArrayRef<Expr *> SubExprs, QualType T) { 19923 if (!Context.getLangOpts().RecoveryAST) 19924 return ExprError(); 19925 19926 if (isSFINAEContext()) 19927 return ExprError(); 19928 19929 if (T.isNull() || T->isUndeducedType() || 19930 !Context.getLangOpts().RecoveryASTType) 19931 // We don't know the concrete type, fallback to dependent type. 19932 T = Context.DependentTy; 19933 19934 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19935 } 19936