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/Support/ConvertUTF.h" 51 #include "llvm/Support/SaveAndRestore.h" 52 using namespace clang; 53 using namespace sema; 54 using llvm::RoundingMode; 55 56 /// Determine whether the use of this declaration is valid, without 57 /// emitting diagnostics. 58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 59 // See if this is an auto-typed variable whose initializer we are parsing. 60 if (ParsingInitForAutoVars.count(D)) 61 return false; 62 63 // See if this is a deleted function. 64 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 65 if (FD->isDeleted()) 66 return false; 67 68 // If the function has a deduced return type, and we can't deduce it, 69 // then we can't use it either. 70 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 71 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 72 return false; 73 74 // See if this is an aligned allocation/deallocation function that is 75 // unavailable. 76 if (TreatUnavailableAsInvalid && 77 isUnavailableAlignedAllocationFunction(*FD)) 78 return false; 79 } 80 81 // See if this function is unavailable. 82 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 83 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 84 return false; 85 86 return true; 87 } 88 89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 90 // Warn if this is used but marked unused. 91 if (const auto *A = D->getAttr<UnusedAttr>()) { 92 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 93 // should diagnose them. 94 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 95 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 96 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 97 if (DC && !DC->hasAttr<UnusedAttr>()) 98 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 99 } 100 } 101 } 102 103 /// Emit a note explaining that this function is deleted. 104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 105 assert(Decl && Decl->isDeleted()); 106 107 if (Decl->isDefaulted()) { 108 // If the method was explicitly defaulted, point at that declaration. 109 if (!Decl->isImplicit()) 110 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 111 112 // Try to diagnose why this special member function was implicitly 113 // deleted. This might fail, if that reason no longer applies. 114 DiagnoseDeletedDefaultedFunction(Decl); 115 return; 116 } 117 118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 119 if (Ctor && Ctor->isInheritingConstructor()) 120 return NoteDeletedInheritingConstructor(Ctor); 121 122 Diag(Decl->getLocation(), diag::note_availability_specified_here) 123 << Decl << 1; 124 } 125 126 /// Determine whether a FunctionDecl was ever declared with an 127 /// explicit storage class. 128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 129 for (auto I : D->redecls()) { 130 if (I->getStorageClass() != SC_None) 131 return true; 132 } 133 return false; 134 } 135 136 /// Check whether we're in an extern inline function and referring to a 137 /// variable or function with internal linkage (C11 6.7.4p3). 138 /// 139 /// This is only a warning because we used to silently accept this code, but 140 /// in many cases it will not behave correctly. This is not enabled in C++ mode 141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 142 /// and so while there may still be user mistakes, most of the time we can't 143 /// prove that there are errors. 144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 145 const NamedDecl *D, 146 SourceLocation Loc) { 147 // This is disabled under C++; there are too many ways for this to fire in 148 // contexts where the warning is a false positive, or where it is technically 149 // correct but benign. 150 if (S.getLangOpts().CPlusPlus) 151 return; 152 153 // Check if this is an inlined function or method. 154 FunctionDecl *Current = S.getCurFunctionDecl(); 155 if (!Current) 156 return; 157 if (!Current->isInlined()) 158 return; 159 if (!Current->isExternallyVisible()) 160 return; 161 162 // Check if the decl has internal linkage. 163 if (D->getFormalLinkage() != InternalLinkage) 164 return; 165 166 // Downgrade from ExtWarn to Extension if 167 // (1) the supposedly external inline function is in the main file, 168 // and probably won't be included anywhere else. 169 // (2) the thing we're referencing is a pure function. 170 // (3) the thing we're referencing is another inline function. 171 // This last can give us false negatives, but it's better than warning on 172 // wrappers for simple C library functions. 173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 175 if (!DowngradeWarning && UsedFn) 176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 177 178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 179 : diag::ext_internal_in_extern_inline) 180 << /*IsVar=*/!UsedFn << D; 181 182 S.MaybeSuggestAddingStaticToDecl(Current); 183 184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 185 << D; 186 } 187 188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 189 const FunctionDecl *First = Cur->getFirstDecl(); 190 191 // Suggest "static" on the function, if possible. 192 if (!hasAnyExplicitStorageClass(First)) { 193 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 194 Diag(DeclBegin, diag::note_convert_inline_to_static) 195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 196 } 197 } 198 199 /// Determine whether the use of this declaration is valid, and 200 /// emit any corresponding diagnostics. 201 /// 202 /// This routine diagnoses various problems with referencing 203 /// declarations that can occur when using a declaration. For example, 204 /// it might warn if a deprecated or unavailable declaration is being 205 /// used, or produce an error (and return true) if a C++0x deleted 206 /// function is being used. 207 /// 208 /// \returns true if there was an error (this declaration cannot be 209 /// referenced), false otherwise. 210 /// 211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 212 const ObjCInterfaceDecl *UnknownObjCClass, 213 bool ObjCPropertyAccess, 214 bool AvoidPartialAvailabilityChecks, 215 ObjCInterfaceDecl *ClassReceiver) { 216 SourceLocation Loc = Locs.front(); 217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 218 // If there were any diagnostics suppressed by template argument deduction, 219 // emit them now. 220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 221 if (Pos != SuppressedDiagnostics.end()) { 222 for (const PartialDiagnosticAt &Suppressed : Pos->second) 223 Diag(Suppressed.first, Suppressed.second); 224 225 // Clear out the list of suppressed diagnostics, so that we don't emit 226 // them again for this specialization. However, we don't obsolete this 227 // entry from the table, because we want to avoid ever emitting these 228 // diagnostics again. 229 Pos->second.clear(); 230 } 231 232 // C++ [basic.start.main]p3: 233 // The function 'main' shall not be used within a program. 234 if (cast<FunctionDecl>(D)->isMain()) 235 Diag(Loc, diag::ext_main_used); 236 237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 238 } 239 240 // See if this is an auto-typed variable whose initializer we are parsing. 241 if (ParsingInitForAutoVars.count(D)) { 242 if (isa<BindingDecl>(D)) { 243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 244 << D->getDeclName(); 245 } else { 246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 247 << D->getDeclName() << cast<VarDecl>(D)->getType(); 248 } 249 return true; 250 } 251 252 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 253 // See if this is a deleted function. 254 if (FD->isDeleted()) { 255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 256 if (Ctor && Ctor->isInheritingConstructor()) 257 Diag(Loc, diag::err_deleted_inherited_ctor_use) 258 << Ctor->getParent() 259 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 260 else 261 Diag(Loc, diag::err_deleted_function_use); 262 NoteDeletedFunction(FD); 263 return true; 264 } 265 266 // [expr.prim.id]p4 267 // A program that refers explicitly or implicitly to a function with a 268 // trailing requires-clause whose constraint-expression is not satisfied, 269 // other than to declare it, is ill-formed. [...] 270 // 271 // See if this is a function with constraints that need to be satisfied. 272 // Check this before deducing the return type, as it might instantiate the 273 // definition. 274 if (FD->getTrailingRequiresClause()) { 275 ConstraintSatisfaction Satisfaction; 276 if (CheckFunctionConstraints(FD, Satisfaction, Loc)) 277 // A diagnostic will have already been generated (non-constant 278 // constraint expression, for example) 279 return true; 280 if (!Satisfaction.IsSatisfied) { 281 Diag(Loc, 282 diag::err_reference_to_function_with_unsatisfied_constraints) 283 << D; 284 DiagnoseUnsatisfiedConstraint(Satisfaction); 285 return true; 286 } 287 } 288 289 // If the function has a deduced return type, and we can't deduce it, 290 // then we can't use it either. 291 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 292 DeduceReturnType(FD, Loc)) 293 return true; 294 295 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 296 return true; 297 298 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 299 return true; 300 } 301 302 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 303 // Lambdas are only default-constructible or assignable in C++2a onwards. 304 if (MD->getParent()->isLambda() && 305 ((isa<CXXConstructorDecl>(MD) && 306 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 307 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 308 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 309 << !isa<CXXConstructorDecl>(MD); 310 } 311 } 312 313 auto getReferencedObjCProp = [](const NamedDecl *D) -> 314 const ObjCPropertyDecl * { 315 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 316 return MD->findPropertyDecl(); 317 return nullptr; 318 }; 319 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 320 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 321 return true; 322 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 323 return true; 324 } 325 326 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 327 // Only the variables omp_in and omp_out are allowed in the combiner. 328 // Only the variables omp_priv and omp_orig are allowed in the 329 // initializer-clause. 330 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 331 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 332 isa<VarDecl>(D)) { 333 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 334 << getCurFunction()->HasOMPDeclareReductionCombiner; 335 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 336 return true; 337 } 338 339 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 340 // List-items in map clauses on this construct may only refer to the declared 341 // variable var and entities that could be referenced by a procedure defined 342 // at the same location 343 if (LangOpts.OpenMP && isa<VarDecl>(D) && 344 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 346 << getOpenMPDeclareMapperVarName(); 347 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 348 return true; 349 } 350 351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 352 AvoidPartialAvailabilityChecks, ClassReceiver); 353 354 DiagnoseUnusedOfDecl(*this, D, Loc); 355 356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 357 358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 359 if (auto *VD = dyn_cast<ValueDecl>(D)) 360 checkDeviceDecl(VD, Loc); 361 362 if (!Context.getTargetInfo().isTLSSupported()) 363 if (const auto *VD = dyn_cast<VarDecl>(D)) 364 if (VD->getTLSKind() != VarDecl::TLS_None) 365 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 366 } 367 368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 369 !isUnevaluatedContext()) { 370 // C++ [expr.prim.req.nested] p3 371 // A local parameter shall only appear as an unevaluated operand 372 // (Clause 8) within the constraint-expression. 373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 374 << D; 375 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 376 return true; 377 } 378 379 return false; 380 } 381 382 /// DiagnoseSentinelCalls - This routine checks whether a call or 383 /// message-send is to a declaration with the sentinel attribute, and 384 /// if so, it checks that the requirements of the sentinel are 385 /// satisfied. 386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 387 ArrayRef<Expr *> Args) { 388 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 389 if (!attr) 390 return; 391 392 // The number of formal parameters of the declaration. 393 unsigned numFormalParams; 394 395 // The kind of declaration. This is also an index into a %select in 396 // the diagnostic. 397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 398 399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 400 numFormalParams = MD->param_size(); 401 calleeType = CT_Method; 402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 403 numFormalParams = FD->param_size(); 404 calleeType = CT_Function; 405 } else if (isa<VarDecl>(D)) { 406 QualType type = cast<ValueDecl>(D)->getType(); 407 const FunctionType *fn = nullptr; 408 if (const PointerType *ptr = type->getAs<PointerType>()) { 409 fn = ptr->getPointeeType()->getAs<FunctionType>(); 410 if (!fn) return; 411 calleeType = CT_Function; 412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 413 fn = ptr->getPointeeType()->castAs<FunctionType>(); 414 calleeType = CT_Block; 415 } else { 416 return; 417 } 418 419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 420 numFormalParams = proto->getNumParams(); 421 } else { 422 numFormalParams = 0; 423 } 424 } else { 425 return; 426 } 427 428 // "nullPos" is the number of formal parameters at the end which 429 // effectively count as part of the variadic arguments. This is 430 // useful if you would prefer to not have *any* formal parameters, 431 // but the language forces you to have at least one. 432 unsigned nullPos = attr->getNullPos(); 433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 435 436 // The number of arguments which should follow the sentinel. 437 unsigned numArgsAfterSentinel = attr->getSentinel(); 438 439 // If there aren't enough arguments for all the formal parameters, 440 // the sentinel, and the args after the sentinel, complain. 441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 444 return; 445 } 446 447 // Otherwise, find the sentinel expression. 448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 449 if (!sentinelExpr) return; 450 if (sentinelExpr->isValueDependent()) return; 451 if (Context.isSentinelNullExpr(sentinelExpr)) return; 452 453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 454 // or 'NULL' if those are actually defined in the context. Only use 455 // 'nil' for ObjC methods, where it's much more likely that the 456 // variadic arguments form a list of object pointers. 457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 458 std::string NullValue; 459 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 460 NullValue = "nil"; 461 else if (getLangOpts().CPlusPlus11) 462 NullValue = "nullptr"; 463 else if (PP.isMacroDefined("NULL")) 464 NullValue = "NULL"; 465 else 466 NullValue = "(void*) 0"; 467 468 if (MissingNilLoc.isInvalid()) 469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 470 else 471 Diag(MissingNilLoc, diag::warn_missing_sentinel) 472 << int(calleeType) 473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 475 } 476 477 SourceRange Sema::getExprRange(Expr *E) const { 478 return E ? E->getSourceRange() : SourceRange(); 479 } 480 481 //===----------------------------------------------------------------------===// 482 // Standard Promotions and Conversions 483 //===----------------------------------------------------------------------===// 484 485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 487 // Handle any placeholder expressions which made it here. 488 if (E->getType()->isPlaceholderType()) { 489 ExprResult result = CheckPlaceholderExpr(E); 490 if (result.isInvalid()) return ExprError(); 491 E = result.get(); 492 } 493 494 QualType Ty = E->getType(); 495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 496 497 if (Ty->isFunctionType()) { 498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 501 return ExprError(); 502 503 E = ImpCastExprToType(E, Context.getPointerType(Ty), 504 CK_FunctionToPointerDecay).get(); 505 } else if (Ty->isArrayType()) { 506 // In C90 mode, arrays only promote to pointers if the array expression is 507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 508 // type 'array of type' is converted to an expression that has type 'pointer 509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 510 // that has type 'array of type' ...". The relevant change is "an lvalue" 511 // (C90) to "an expression" (C99). 512 // 513 // C++ 4.2p1: 514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 515 // T" can be converted to an rvalue of type "pointer to T". 516 // 517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 519 CK_ArrayToPointerDecay).get(); 520 } 521 return E; 522 } 523 524 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 525 // Check to see if we are dereferencing a null pointer. If so, 526 // and if not volatile-qualified, this is undefined behavior that the 527 // optimizer will delete, so warn about it. People sometimes try to use this 528 // to get a deterministic trap and are surprised by clang's behavior. This 529 // only handles the pattern "*null", which is a very syntactic check. 530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 531 if (UO && UO->getOpcode() == UO_Deref && 532 UO->getSubExpr()->getType()->isPointerType()) { 533 const LangAS AS = 534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 535 if ((!isTargetAddressSpace(AS) || 536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 538 S.Context, Expr::NPC_ValueDependentIsNotNull) && 539 !UO->getType().isVolatileQualified()) { 540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 541 S.PDiag(diag::warn_indirection_through_null) 542 << UO->getSubExpr()->getSourceRange()); 543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 544 S.PDiag(diag::note_indirection_through_null)); 545 } 546 } 547 } 548 549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 550 SourceLocation AssignLoc, 551 const Expr* RHS) { 552 const ObjCIvarDecl *IV = OIRE->getDecl(); 553 if (!IV) 554 return; 555 556 DeclarationName MemberName = IV->getDeclName(); 557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 558 if (!Member || !Member->isStr("isa")) 559 return; 560 561 const Expr *Base = OIRE->getBase(); 562 QualType BaseType = Base->getType(); 563 if (OIRE->isArrow()) 564 BaseType = BaseType->getPointeeType(); 565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 567 ObjCInterfaceDecl *ClassDeclared = nullptr; 568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 569 if (!ClassDeclared->getSuperClass() 570 && (*ClassDeclared->ivar_begin()) == IV) { 571 if (RHS) { 572 NamedDecl *ObjectSetClass = 573 S.LookupSingleName(S.TUScope, 574 &S.Context.Idents.get("object_setClass"), 575 SourceLocation(), S.LookupOrdinaryName); 576 if (ObjectSetClass) { 577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 580 "object_setClass(") 581 << FixItHint::CreateReplacement( 582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 583 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 584 } 585 else 586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 587 } else { 588 NamedDecl *ObjectGetClass = 589 S.LookupSingleName(S.TUScope, 590 &S.Context.Idents.get("object_getClass"), 591 SourceLocation(), S.LookupOrdinaryName); 592 if (ObjectGetClass) 593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 595 "object_getClass(") 596 << FixItHint::CreateReplacement( 597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 598 else 599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 600 } 601 S.Diag(IV->getLocation(), diag::note_ivar_decl); 602 } 603 } 604 } 605 606 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 607 // Handle any placeholder expressions which made it here. 608 if (E->getType()->isPlaceholderType()) { 609 ExprResult result = CheckPlaceholderExpr(E); 610 if (result.isInvalid()) return ExprError(); 611 E = result.get(); 612 } 613 614 // C++ [conv.lval]p1: 615 // A glvalue of a non-function, non-array type T can be 616 // converted to a prvalue. 617 if (!E->isGLValue()) return E; 618 619 QualType T = E->getType(); 620 assert(!T.isNull() && "r-value conversion on typeless expression?"); 621 622 // lvalue-to-rvalue conversion cannot be applied to function or array types. 623 if (T->isFunctionType() || T->isArrayType()) 624 return E; 625 626 // We don't want to throw lvalue-to-rvalue casts on top of 627 // expressions of certain types in C++. 628 if (getLangOpts().CPlusPlus && 629 (E->getType() == Context.OverloadTy || 630 T->isDependentType() || 631 T->isRecordType())) 632 return E; 633 634 // The C standard is actually really unclear on this point, and 635 // DR106 tells us what the result should be but not why. It's 636 // generally best to say that void types just doesn't undergo 637 // lvalue-to-rvalue at all. Note that expressions of unqualified 638 // 'void' type are never l-values, but qualified void can be. 639 if (T->isVoidType()) 640 return E; 641 642 // OpenCL usually rejects direct accesses to values of 'half' type. 643 if (getLangOpts().OpenCL && 644 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 645 T->isHalfType()) { 646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 647 << 0 << T; 648 return ExprError(); 649 } 650 651 CheckForNullPointerDereference(*this, E); 652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 654 &Context.Idents.get("object_getClass"), 655 SourceLocation(), LookupOrdinaryName); 656 if (ObjectGetClass) 657 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 658 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 659 << FixItHint::CreateReplacement( 660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 661 else 662 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 663 } 664 else if (const ObjCIvarRefExpr *OIRE = 665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 667 668 // C++ [conv.lval]p1: 669 // [...] If T is a non-class type, the type of the prvalue is the 670 // cv-unqualified version of T. Otherwise, the type of the 671 // rvalue is T. 672 // 673 // C99 6.3.2.1p2: 674 // If the lvalue has qualified type, the value has the unqualified 675 // version of the type of the lvalue; otherwise, the value has the 676 // type of the lvalue. 677 if (T.hasQualifiers()) 678 T = T.getUnqualifiedType(); 679 680 // Under the MS ABI, lock down the inheritance model now. 681 if (T->isMemberPointerType() && 682 Context.getTargetInfo().getCXXABI().isMicrosoft()) 683 (void)isCompleteType(E->getExprLoc(), T); 684 685 ExprResult Res = CheckLValueToRValueConversionOperand(E); 686 if (Res.isInvalid()) 687 return Res; 688 E = Res.get(); 689 690 // Loading a __weak object implicitly retains the value, so we need a cleanup to 691 // balance that. 692 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 693 Cleanup.setExprNeedsCleanups(true); 694 695 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 696 Cleanup.setExprNeedsCleanups(true); 697 698 // C++ [conv.lval]p3: 699 // If T is cv std::nullptr_t, the result is a null pointer constant. 700 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 701 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue, 702 CurFPFeatureOverrides()); 703 704 // C11 6.3.2.1p2: 705 // ... if the lvalue has atomic type, the value has the non-atomic version 706 // of the type of the lvalue ... 707 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 708 T = Atomic->getValueType().getUnqualifiedType(); 709 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 710 nullptr, VK_RValue, FPOptionsOverride()); 711 } 712 713 return Res; 714 } 715 716 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 717 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 718 if (Res.isInvalid()) 719 return ExprError(); 720 Res = DefaultLvalueConversion(Res.get()); 721 if (Res.isInvalid()) 722 return ExprError(); 723 return Res; 724 } 725 726 /// CallExprUnaryConversions - a special case of an unary conversion 727 /// performed on a function designator of a call expression. 728 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 729 QualType Ty = E->getType(); 730 ExprResult Res = E; 731 // Only do implicit cast for a function type, but not for a pointer 732 // to function type. 733 if (Ty->isFunctionType()) { 734 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 735 CK_FunctionToPointerDecay); 736 if (Res.isInvalid()) 737 return ExprError(); 738 } 739 Res = DefaultLvalueConversion(Res.get()); 740 if (Res.isInvalid()) 741 return ExprError(); 742 return Res.get(); 743 } 744 745 /// UsualUnaryConversions - Performs various conversions that are common to most 746 /// operators (C99 6.3). The conversions of array and function types are 747 /// sometimes suppressed. For example, the array->pointer conversion doesn't 748 /// apply if the array is an argument to the sizeof or address (&) operators. 749 /// In these instances, this routine should *not* be called. 750 ExprResult Sema::UsualUnaryConversions(Expr *E) { 751 // First, convert to an r-value. 752 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 753 if (Res.isInvalid()) 754 return ExprError(); 755 E = Res.get(); 756 757 QualType Ty = E->getType(); 758 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 759 760 // Half FP have to be promoted to float unless it is natively supported 761 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 762 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 763 764 // Try to perform integral promotions if the object has a theoretically 765 // promotable type. 766 if (Ty->isIntegralOrUnscopedEnumerationType()) { 767 // C99 6.3.1.1p2: 768 // 769 // The following may be used in an expression wherever an int or 770 // unsigned int may be used: 771 // - an object or expression with an integer type whose integer 772 // conversion rank is less than or equal to the rank of int 773 // and unsigned int. 774 // - A bit-field of type _Bool, int, signed int, or unsigned int. 775 // 776 // If an int can represent all values of the original type, the 777 // value is converted to an int; otherwise, it is converted to an 778 // unsigned int. These are called the integer promotions. All 779 // other types are unchanged by the integer promotions. 780 781 QualType PTy = Context.isPromotableBitField(E); 782 if (!PTy.isNull()) { 783 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 784 return E; 785 } 786 if (Ty->isPromotableIntegerType()) { 787 QualType PT = Context.getPromotedIntegerType(Ty); 788 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 789 return E; 790 } 791 } 792 return E; 793 } 794 795 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 796 /// do not have a prototype. Arguments that have type float or __fp16 797 /// are promoted to double. All other argument types are converted by 798 /// UsualUnaryConversions(). 799 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 800 QualType Ty = E->getType(); 801 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 802 803 ExprResult Res = UsualUnaryConversions(E); 804 if (Res.isInvalid()) 805 return ExprError(); 806 E = Res.get(); 807 808 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 809 // promote to double. 810 // Note that default argument promotion applies only to float (and 811 // half/fp16); it does not apply to _Float16. 812 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 813 if (BTy && (BTy->getKind() == BuiltinType::Half || 814 BTy->getKind() == BuiltinType::Float)) { 815 if (getLangOpts().OpenCL && 816 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 817 if (BTy->getKind() == BuiltinType::Half) { 818 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 819 } 820 } else { 821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 822 } 823 } 824 825 // C++ performs lvalue-to-rvalue conversion as a default argument 826 // promotion, even on class types, but note: 827 // C++11 [conv.lval]p2: 828 // When an lvalue-to-rvalue conversion occurs in an unevaluated 829 // operand or a subexpression thereof the value contained in the 830 // referenced object is not accessed. Otherwise, if the glvalue 831 // has a class type, the conversion copy-initializes a temporary 832 // of type T from the glvalue and the result of the conversion 833 // is a prvalue for the temporary. 834 // FIXME: add some way to gate this entire thing for correctness in 835 // potentially potentially evaluated contexts. 836 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 837 ExprResult Temp = PerformCopyInitialization( 838 InitializedEntity::InitializeTemporary(E->getType()), 839 E->getExprLoc(), E); 840 if (Temp.isInvalid()) 841 return ExprError(); 842 E = Temp.get(); 843 } 844 845 return E; 846 } 847 848 /// Determine the degree of POD-ness for an expression. 849 /// Incomplete types are considered POD, since this check can be performed 850 /// when we're in an unevaluated context. 851 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 852 if (Ty->isIncompleteType()) { 853 // C++11 [expr.call]p7: 854 // After these conversions, if the argument does not have arithmetic, 855 // enumeration, pointer, pointer to member, or class type, the program 856 // is ill-formed. 857 // 858 // Since we've already performed array-to-pointer and function-to-pointer 859 // decay, the only such type in C++ is cv void. This also handles 860 // initializer lists as variadic arguments. 861 if (Ty->isVoidType()) 862 return VAK_Invalid; 863 864 if (Ty->isObjCObjectType()) 865 return VAK_Invalid; 866 return VAK_Valid; 867 } 868 869 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 870 return VAK_Invalid; 871 872 if (Ty.isCXX98PODType(Context)) 873 return VAK_Valid; 874 875 // C++11 [expr.call]p7: 876 // Passing a potentially-evaluated argument of class type (Clause 9) 877 // having a non-trivial copy constructor, a non-trivial move constructor, 878 // or a non-trivial destructor, with no corresponding parameter, 879 // is conditionally-supported with implementation-defined semantics. 880 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 881 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 882 if (!Record->hasNonTrivialCopyConstructor() && 883 !Record->hasNonTrivialMoveConstructor() && 884 !Record->hasNonTrivialDestructor()) 885 return VAK_ValidInCXX11; 886 887 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 888 return VAK_Valid; 889 890 if (Ty->isObjCObjectType()) 891 return VAK_Invalid; 892 893 if (getLangOpts().MSVCCompat) 894 return VAK_MSVCUndefined; 895 896 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 897 // permitted to reject them. We should consider doing so. 898 return VAK_Undefined; 899 } 900 901 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 902 // Don't allow one to pass an Objective-C interface to a vararg. 903 const QualType &Ty = E->getType(); 904 VarArgKind VAK = isValidVarArgType(Ty); 905 906 // Complain about passing non-POD types through varargs. 907 switch (VAK) { 908 case VAK_ValidInCXX11: 909 DiagRuntimeBehavior( 910 E->getBeginLoc(), nullptr, 911 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 912 LLVM_FALLTHROUGH; 913 case VAK_Valid: 914 if (Ty->isRecordType()) { 915 // This is unlikely to be what the user intended. If the class has a 916 // 'c_str' member function, the user probably meant to call that. 917 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 918 PDiag(diag::warn_pass_class_arg_to_vararg) 919 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 920 } 921 break; 922 923 case VAK_Undefined: 924 case VAK_MSVCUndefined: 925 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 926 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 927 << getLangOpts().CPlusPlus11 << Ty << CT); 928 break; 929 930 case VAK_Invalid: 931 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 932 Diag(E->getBeginLoc(), 933 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 934 << Ty << CT; 935 else if (Ty->isObjCObjectType()) 936 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 937 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 938 << Ty << CT); 939 else 940 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 941 << isa<InitListExpr>(E) << Ty << CT; 942 break; 943 } 944 } 945 946 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 947 /// will create a trap if the resulting type is not a POD type. 948 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 949 FunctionDecl *FDecl) { 950 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 951 // Strip the unbridged-cast placeholder expression off, if applicable. 952 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 953 (CT == VariadicMethod || 954 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 955 E = stripARCUnbridgedCast(E); 956 957 // Otherwise, do normal placeholder checking. 958 } else { 959 ExprResult ExprRes = CheckPlaceholderExpr(E); 960 if (ExprRes.isInvalid()) 961 return ExprError(); 962 E = ExprRes.get(); 963 } 964 } 965 966 ExprResult ExprRes = DefaultArgumentPromotion(E); 967 if (ExprRes.isInvalid()) 968 return ExprError(); 969 970 // Copy blocks to the heap. 971 if (ExprRes.get()->getType()->isBlockPointerType()) 972 maybeExtendBlockObject(ExprRes); 973 974 E = ExprRes.get(); 975 976 // Diagnostics regarding non-POD argument types are 977 // emitted along with format string checking in Sema::CheckFunctionCall(). 978 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 979 // Turn this into a trap. 980 CXXScopeSpec SS; 981 SourceLocation TemplateKWLoc; 982 UnqualifiedId Name; 983 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 984 E->getBeginLoc()); 985 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 986 /*HasTrailingLParen=*/true, 987 /*IsAddressOfOperand=*/false); 988 if (TrapFn.isInvalid()) 989 return ExprError(); 990 991 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 992 None, E->getEndLoc()); 993 if (Call.isInvalid()) 994 return ExprError(); 995 996 ExprResult Comma = 997 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 998 if (Comma.isInvalid()) 999 return ExprError(); 1000 return Comma.get(); 1001 } 1002 1003 if (!getLangOpts().CPlusPlus && 1004 RequireCompleteType(E->getExprLoc(), E->getType(), 1005 diag::err_call_incomplete_argument)) 1006 return ExprError(); 1007 1008 return E; 1009 } 1010 1011 /// Converts an integer to complex float type. Helper function of 1012 /// UsualArithmeticConversions() 1013 /// 1014 /// \return false if the integer expression is an integer type and is 1015 /// successfully converted to the complex type. 1016 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1017 ExprResult &ComplexExpr, 1018 QualType IntTy, 1019 QualType ComplexTy, 1020 bool SkipCast) { 1021 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1022 if (SkipCast) return false; 1023 if (IntTy->isIntegerType()) { 1024 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1025 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1026 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1027 CK_FloatingRealToComplex); 1028 } else { 1029 assert(IntTy->isComplexIntegerType()); 1030 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1031 CK_IntegralComplexToFloatingComplex); 1032 } 1033 return false; 1034 } 1035 1036 /// Handle arithmetic conversion with complex types. Helper function of 1037 /// UsualArithmeticConversions() 1038 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1039 ExprResult &RHS, QualType LHSType, 1040 QualType RHSType, 1041 bool IsCompAssign) { 1042 // if we have an integer operand, the result is the complex type. 1043 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1044 /*skipCast*/false)) 1045 return LHSType; 1046 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1047 /*skipCast*/IsCompAssign)) 1048 return RHSType; 1049 1050 // This handles complex/complex, complex/float, or float/complex. 1051 // When both operands are complex, the shorter operand is converted to the 1052 // type of the longer, and that is the type of the result. This corresponds 1053 // to what is done when combining two real floating-point operands. 1054 // The fun begins when size promotion occur across type domains. 1055 // From H&S 6.3.4: When one operand is complex and the other is a real 1056 // floating-point type, the less precise type is converted, within it's 1057 // real or complex domain, to the precision of the other type. For example, 1058 // when combining a "long double" with a "double _Complex", the 1059 // "double _Complex" is promoted to "long double _Complex". 1060 1061 // Compute the rank of the two types, regardless of whether they are complex. 1062 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1063 1064 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1065 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1066 QualType LHSElementType = 1067 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1068 QualType RHSElementType = 1069 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1070 1071 QualType ResultType = S.Context.getComplexType(LHSElementType); 1072 if (Order < 0) { 1073 // Promote the precision of the LHS if not an assignment. 1074 ResultType = S.Context.getComplexType(RHSElementType); 1075 if (!IsCompAssign) { 1076 if (LHSComplexType) 1077 LHS = 1078 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1079 else 1080 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1081 } 1082 } else if (Order > 0) { 1083 // Promote the precision of the RHS. 1084 if (RHSComplexType) 1085 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1086 else 1087 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1088 } 1089 return ResultType; 1090 } 1091 1092 /// Handle arithmetic conversion from integer to float. Helper function 1093 /// of UsualArithmeticConversions() 1094 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1095 ExprResult &IntExpr, 1096 QualType FloatTy, QualType IntTy, 1097 bool ConvertFloat, bool ConvertInt) { 1098 if (IntTy->isIntegerType()) { 1099 if (ConvertInt) 1100 // Convert intExpr to the lhs floating point type. 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1102 CK_IntegralToFloating); 1103 return FloatTy; 1104 } 1105 1106 // Convert both sides to the appropriate complex float. 1107 assert(IntTy->isComplexIntegerType()); 1108 QualType result = S.Context.getComplexType(FloatTy); 1109 1110 // _Complex int -> _Complex float 1111 if (ConvertInt) 1112 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1113 CK_IntegralComplexToFloatingComplex); 1114 1115 // float -> _Complex float 1116 if (ConvertFloat) 1117 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1118 CK_FloatingRealToComplex); 1119 1120 return result; 1121 } 1122 1123 /// Handle arithmethic conversion with floating point types. Helper 1124 /// function of UsualArithmeticConversions() 1125 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1126 ExprResult &RHS, QualType LHSType, 1127 QualType RHSType, bool IsCompAssign) { 1128 bool LHSFloat = LHSType->isRealFloatingType(); 1129 bool RHSFloat = RHSType->isRealFloatingType(); 1130 1131 // N1169 4.1.4: If one of the operands has a floating type and the other 1132 // operand has a fixed-point type, the fixed-point operand 1133 // is converted to the floating type [...] 1134 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1135 if (LHSFloat) 1136 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1137 else if (!IsCompAssign) 1138 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1139 return LHSFloat ? LHSType : RHSType; 1140 } 1141 1142 // If we have two real floating types, convert the smaller operand 1143 // to the bigger result. 1144 if (LHSFloat && RHSFloat) { 1145 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1146 if (order > 0) { 1147 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1148 return LHSType; 1149 } 1150 1151 assert(order < 0 && "illegal float comparison"); 1152 if (!IsCompAssign) 1153 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1154 return RHSType; 1155 } 1156 1157 if (LHSFloat) { 1158 // Half FP has to be promoted to float unless it is natively supported 1159 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1160 LHSType = S.Context.FloatTy; 1161 1162 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1163 /*ConvertFloat=*/!IsCompAssign, 1164 /*ConvertInt=*/ true); 1165 } 1166 assert(RHSFloat); 1167 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1168 /*ConvertFloat=*/ true, 1169 /*ConvertInt=*/!IsCompAssign); 1170 } 1171 1172 /// Diagnose attempts to convert between __float128 and long double if 1173 /// there is no support for such conversion. Helper function of 1174 /// UsualArithmeticConversions(). 1175 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1176 QualType RHSType) { 1177 /* No issue converting if at least one of the types is not a floating point 1178 type or the two types have the same rank. 1179 */ 1180 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1181 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1182 return false; 1183 1184 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1185 "The remaining types must be floating point types."); 1186 1187 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1188 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1189 1190 QualType LHSElemType = LHSComplex ? 1191 LHSComplex->getElementType() : LHSType; 1192 QualType RHSElemType = RHSComplex ? 1193 RHSComplex->getElementType() : RHSType; 1194 1195 // No issue if the two types have the same representation 1196 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1197 &S.Context.getFloatTypeSemantics(RHSElemType)) 1198 return false; 1199 1200 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1201 RHSElemType == S.Context.LongDoubleTy); 1202 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1203 RHSElemType == S.Context.Float128Ty); 1204 1205 // We've handled the situation where __float128 and long double have the same 1206 // representation. We allow all conversions for all possible long double types 1207 // except PPC's double double. 1208 return Float128AndLongDouble && 1209 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1210 &llvm::APFloat::PPCDoubleDouble()); 1211 } 1212 1213 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1214 1215 namespace { 1216 /// These helper callbacks are placed in an anonymous namespace to 1217 /// permit their use as function template parameters. 1218 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1219 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1220 } 1221 1222 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1223 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1224 CK_IntegralComplexCast); 1225 } 1226 } 1227 1228 /// Handle integer arithmetic conversions. Helper function of 1229 /// UsualArithmeticConversions() 1230 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1231 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1232 ExprResult &RHS, QualType LHSType, 1233 QualType RHSType, bool IsCompAssign) { 1234 // The rules for this case are in C99 6.3.1.8 1235 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1236 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1237 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1238 if (LHSSigned == RHSSigned) { 1239 // Same signedness; use the higher-ranked type 1240 if (order >= 0) { 1241 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1242 return LHSType; 1243 } else if (!IsCompAssign) 1244 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1245 return RHSType; 1246 } else if (order != (LHSSigned ? 1 : -1)) { 1247 // The unsigned type has greater than or equal rank to the 1248 // signed type, so use the unsigned type 1249 if (RHSSigned) { 1250 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1251 return LHSType; 1252 } else if (!IsCompAssign) 1253 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1254 return RHSType; 1255 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1256 // The two types are different widths; if we are here, that 1257 // means the signed type is larger than the unsigned type, so 1258 // use the signed type. 1259 if (LHSSigned) { 1260 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1261 return LHSType; 1262 } else if (!IsCompAssign) 1263 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1264 return RHSType; 1265 } else { 1266 // The signed type is higher-ranked than the unsigned type, 1267 // but isn't actually any bigger (like unsigned int and long 1268 // on most 32-bit systems). Use the unsigned type corresponding 1269 // to the signed type. 1270 QualType result = 1271 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1272 RHS = (*doRHSCast)(S, RHS.get(), result); 1273 if (!IsCompAssign) 1274 LHS = (*doLHSCast)(S, LHS.get(), result); 1275 return result; 1276 } 1277 } 1278 1279 /// Handle conversions with GCC complex int extension. Helper function 1280 /// of UsualArithmeticConversions() 1281 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1282 ExprResult &RHS, QualType LHSType, 1283 QualType RHSType, 1284 bool IsCompAssign) { 1285 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1286 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1287 1288 if (LHSComplexInt && RHSComplexInt) { 1289 QualType LHSEltType = LHSComplexInt->getElementType(); 1290 QualType RHSEltType = RHSComplexInt->getElementType(); 1291 QualType ScalarType = 1292 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1293 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1294 1295 return S.Context.getComplexType(ScalarType); 1296 } 1297 1298 if (LHSComplexInt) { 1299 QualType LHSEltType = LHSComplexInt->getElementType(); 1300 QualType ScalarType = 1301 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1302 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1303 QualType ComplexType = S.Context.getComplexType(ScalarType); 1304 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1305 CK_IntegralRealToComplex); 1306 1307 return ComplexType; 1308 } 1309 1310 assert(RHSComplexInt); 1311 1312 QualType RHSEltType = RHSComplexInt->getElementType(); 1313 QualType ScalarType = 1314 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1315 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1316 QualType ComplexType = S.Context.getComplexType(ScalarType); 1317 1318 if (!IsCompAssign) 1319 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1320 CK_IntegralRealToComplex); 1321 return ComplexType; 1322 } 1323 1324 /// Return the rank of a given fixed point or integer type. The value itself 1325 /// doesn't matter, but the values must be increasing with proper increasing 1326 /// rank as described in N1169 4.1.1. 1327 static unsigned GetFixedPointRank(QualType Ty) { 1328 const auto *BTy = Ty->getAs<BuiltinType>(); 1329 assert(BTy && "Expected a builtin type."); 1330 1331 switch (BTy->getKind()) { 1332 case BuiltinType::ShortFract: 1333 case BuiltinType::UShortFract: 1334 case BuiltinType::SatShortFract: 1335 case BuiltinType::SatUShortFract: 1336 return 1; 1337 case BuiltinType::Fract: 1338 case BuiltinType::UFract: 1339 case BuiltinType::SatFract: 1340 case BuiltinType::SatUFract: 1341 return 2; 1342 case BuiltinType::LongFract: 1343 case BuiltinType::ULongFract: 1344 case BuiltinType::SatLongFract: 1345 case BuiltinType::SatULongFract: 1346 return 3; 1347 case BuiltinType::ShortAccum: 1348 case BuiltinType::UShortAccum: 1349 case BuiltinType::SatShortAccum: 1350 case BuiltinType::SatUShortAccum: 1351 return 4; 1352 case BuiltinType::Accum: 1353 case BuiltinType::UAccum: 1354 case BuiltinType::SatAccum: 1355 case BuiltinType::SatUAccum: 1356 return 5; 1357 case BuiltinType::LongAccum: 1358 case BuiltinType::ULongAccum: 1359 case BuiltinType::SatLongAccum: 1360 case BuiltinType::SatULongAccum: 1361 return 6; 1362 default: 1363 if (BTy->isInteger()) 1364 return 0; 1365 llvm_unreachable("Unexpected fixed point or integer type"); 1366 } 1367 } 1368 1369 /// handleFixedPointConversion - Fixed point operations between fixed 1370 /// point types and integers or other fixed point types do not fall under 1371 /// usual arithmetic conversion since these conversions could result in loss 1372 /// of precsision (N1169 4.1.4). These operations should be calculated with 1373 /// the full precision of their result type (N1169 4.1.6.2.1). 1374 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1375 QualType RHSTy) { 1376 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1377 "Expected at least one of the operands to be a fixed point type"); 1378 assert((LHSTy->isFixedPointOrIntegerType() || 1379 RHSTy->isFixedPointOrIntegerType()) && 1380 "Special fixed point arithmetic operation conversions are only " 1381 "applied to ints or other fixed point types"); 1382 1383 // If one operand has signed fixed-point type and the other operand has 1384 // unsigned fixed-point type, then the unsigned fixed-point operand is 1385 // converted to its corresponding signed fixed-point type and the resulting 1386 // type is the type of the converted operand. 1387 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1388 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1389 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1390 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1391 1392 // The result type is the type with the highest rank, whereby a fixed-point 1393 // conversion rank is always greater than an integer conversion rank; if the 1394 // type of either of the operands is a saturating fixedpoint type, the result 1395 // type shall be the saturating fixed-point type corresponding to the type 1396 // with the highest rank; the resulting value is converted (taking into 1397 // account rounding and overflow) to the precision of the resulting type. 1398 // Same ranks between signed and unsigned types are resolved earlier, so both 1399 // types are either signed or both unsigned at this point. 1400 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1401 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1402 1403 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1404 1405 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1406 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1407 1408 return ResultTy; 1409 } 1410 1411 /// Check that the usual arithmetic conversions can be performed on this pair of 1412 /// expressions that might be of enumeration type. 1413 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1414 SourceLocation Loc, 1415 Sema::ArithConvKind ACK) { 1416 // C++2a [expr.arith.conv]p1: 1417 // If one operand is of enumeration type and the other operand is of a 1418 // different enumeration type or a floating-point type, this behavior is 1419 // deprecated ([depr.arith.conv.enum]). 1420 // 1421 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1422 // Eventually we will presumably reject these cases (in C++23 onwards?). 1423 QualType L = LHS->getType(), R = RHS->getType(); 1424 bool LEnum = L->isUnscopedEnumerationType(), 1425 REnum = R->isUnscopedEnumerationType(); 1426 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1427 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1428 (REnum && L->isFloatingType())) { 1429 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1430 ? diag::warn_arith_conv_enum_float_cxx20 1431 : diag::warn_arith_conv_enum_float) 1432 << LHS->getSourceRange() << RHS->getSourceRange() 1433 << (int)ACK << LEnum << L << R; 1434 } else if (!IsCompAssign && LEnum && REnum && 1435 !S.Context.hasSameUnqualifiedType(L, R)) { 1436 unsigned DiagID; 1437 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1438 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1439 // If either enumeration type is unnamed, it's less likely that the 1440 // user cares about this, but this situation is still deprecated in 1441 // C++2a. Use a different warning group. 1442 DiagID = S.getLangOpts().CPlusPlus20 1443 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1444 : diag::warn_arith_conv_mixed_anon_enum_types; 1445 } else if (ACK == Sema::ACK_Conditional) { 1446 // Conditional expressions are separated out because they have 1447 // historically had a different warning flag. 1448 DiagID = S.getLangOpts().CPlusPlus20 1449 ? diag::warn_conditional_mixed_enum_types_cxx20 1450 : diag::warn_conditional_mixed_enum_types; 1451 } else if (ACK == Sema::ACK_Comparison) { 1452 // Comparison expressions are separated out because they have 1453 // historically had a different warning flag. 1454 DiagID = S.getLangOpts().CPlusPlus20 1455 ? diag::warn_comparison_mixed_enum_types_cxx20 1456 : diag::warn_comparison_mixed_enum_types; 1457 } else { 1458 DiagID = S.getLangOpts().CPlusPlus20 1459 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1460 : diag::warn_arith_conv_mixed_enum_types; 1461 } 1462 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1463 << (int)ACK << L << R; 1464 } 1465 } 1466 1467 /// UsualArithmeticConversions - Performs various conversions that are common to 1468 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1469 /// routine returns the first non-arithmetic type found. The client is 1470 /// responsible for emitting appropriate error diagnostics. 1471 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1472 SourceLocation Loc, 1473 ArithConvKind ACK) { 1474 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1475 1476 if (ACK != ACK_CompAssign) { 1477 LHS = UsualUnaryConversions(LHS.get()); 1478 if (LHS.isInvalid()) 1479 return QualType(); 1480 } 1481 1482 RHS = UsualUnaryConversions(RHS.get()); 1483 if (RHS.isInvalid()) 1484 return QualType(); 1485 1486 // For conversion purposes, we ignore any qualifiers. 1487 // For example, "const float" and "float" are equivalent. 1488 QualType LHSType = 1489 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1490 QualType RHSType = 1491 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1492 1493 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1494 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1495 LHSType = AtomicLHS->getValueType(); 1496 1497 // If both types are identical, no conversion is needed. 1498 if (LHSType == RHSType) 1499 return LHSType; 1500 1501 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1502 // The caller can deal with this (e.g. pointer + int). 1503 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1504 return QualType(); 1505 1506 // Apply unary and bitfield promotions to the LHS's type. 1507 QualType LHSUnpromotedType = LHSType; 1508 if (LHSType->isPromotableIntegerType()) 1509 LHSType = Context.getPromotedIntegerType(LHSType); 1510 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1511 if (!LHSBitfieldPromoteTy.isNull()) 1512 LHSType = LHSBitfieldPromoteTy; 1513 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1514 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1515 1516 // If both types are identical, no conversion is needed. 1517 if (LHSType == RHSType) 1518 return LHSType; 1519 1520 // ExtInt types aren't subject to conversions between them or normal integers, 1521 // so this fails. 1522 if(LHSType->isExtIntType() || RHSType->isExtIntType()) 1523 return QualType(); 1524 1525 // At this point, we have two different arithmetic types. 1526 1527 // Diagnose attempts to convert between __float128 and long double where 1528 // such conversions currently can't be handled. 1529 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1530 return QualType(); 1531 1532 // Handle complex types first (C99 6.3.1.8p1). 1533 if (LHSType->isComplexType() || RHSType->isComplexType()) 1534 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1535 ACK == ACK_CompAssign); 1536 1537 // Now handle "real" floating types (i.e. float, double, long double). 1538 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1539 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1540 ACK == ACK_CompAssign); 1541 1542 // Handle GCC complex int extension. 1543 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1544 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1545 ACK == ACK_CompAssign); 1546 1547 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1548 return handleFixedPointConversion(*this, LHSType, RHSType); 1549 1550 // Finally, we have two differing integer types. 1551 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1552 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1553 } 1554 1555 //===----------------------------------------------------------------------===// 1556 // Semantic Analysis for various Expression Types 1557 //===----------------------------------------------------------------------===// 1558 1559 1560 ExprResult 1561 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1562 SourceLocation DefaultLoc, 1563 SourceLocation RParenLoc, 1564 Expr *ControllingExpr, 1565 ArrayRef<ParsedType> ArgTypes, 1566 ArrayRef<Expr *> ArgExprs) { 1567 unsigned NumAssocs = ArgTypes.size(); 1568 assert(NumAssocs == ArgExprs.size()); 1569 1570 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1571 for (unsigned i = 0; i < NumAssocs; ++i) { 1572 if (ArgTypes[i]) 1573 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1574 else 1575 Types[i] = nullptr; 1576 } 1577 1578 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1579 ControllingExpr, 1580 llvm::makeArrayRef(Types, NumAssocs), 1581 ArgExprs); 1582 delete [] Types; 1583 return ER; 1584 } 1585 1586 ExprResult 1587 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1588 SourceLocation DefaultLoc, 1589 SourceLocation RParenLoc, 1590 Expr *ControllingExpr, 1591 ArrayRef<TypeSourceInfo *> Types, 1592 ArrayRef<Expr *> Exprs) { 1593 unsigned NumAssocs = Types.size(); 1594 assert(NumAssocs == Exprs.size()); 1595 1596 // Decay and strip qualifiers for the controlling expression type, and handle 1597 // placeholder type replacement. See committee discussion from WG14 DR423. 1598 { 1599 EnterExpressionEvaluationContext Unevaluated( 1600 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1601 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1602 if (R.isInvalid()) 1603 return ExprError(); 1604 ControllingExpr = R.get(); 1605 } 1606 1607 // The controlling expression is an unevaluated operand, so side effects are 1608 // likely unintended. 1609 if (!inTemplateInstantiation() && 1610 ControllingExpr->HasSideEffects(Context, false)) 1611 Diag(ControllingExpr->getExprLoc(), 1612 diag::warn_side_effects_unevaluated_context); 1613 1614 bool TypeErrorFound = false, 1615 IsResultDependent = ControllingExpr->isTypeDependent(), 1616 ContainsUnexpandedParameterPack 1617 = ControllingExpr->containsUnexpandedParameterPack(); 1618 1619 for (unsigned i = 0; i < NumAssocs; ++i) { 1620 if (Exprs[i]->containsUnexpandedParameterPack()) 1621 ContainsUnexpandedParameterPack = true; 1622 1623 if (Types[i]) { 1624 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1625 ContainsUnexpandedParameterPack = true; 1626 1627 if (Types[i]->getType()->isDependentType()) { 1628 IsResultDependent = true; 1629 } else { 1630 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1631 // complete object type other than a variably modified type." 1632 unsigned D = 0; 1633 if (Types[i]->getType()->isIncompleteType()) 1634 D = diag::err_assoc_type_incomplete; 1635 else if (!Types[i]->getType()->isObjectType()) 1636 D = diag::err_assoc_type_nonobject; 1637 else if (Types[i]->getType()->isVariablyModifiedType()) 1638 D = diag::err_assoc_type_variably_modified; 1639 1640 if (D != 0) { 1641 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1642 << Types[i]->getTypeLoc().getSourceRange() 1643 << Types[i]->getType(); 1644 TypeErrorFound = true; 1645 } 1646 1647 // C11 6.5.1.1p2 "No two generic associations in the same generic 1648 // selection shall specify compatible types." 1649 for (unsigned j = i+1; j < NumAssocs; ++j) 1650 if (Types[j] && !Types[j]->getType()->isDependentType() && 1651 Context.typesAreCompatible(Types[i]->getType(), 1652 Types[j]->getType())) { 1653 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1654 diag::err_assoc_compatible_types) 1655 << Types[j]->getTypeLoc().getSourceRange() 1656 << Types[j]->getType() 1657 << Types[i]->getType(); 1658 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1659 diag::note_compat_assoc) 1660 << Types[i]->getTypeLoc().getSourceRange() 1661 << Types[i]->getType(); 1662 TypeErrorFound = true; 1663 } 1664 } 1665 } 1666 } 1667 if (TypeErrorFound) 1668 return ExprError(); 1669 1670 // If we determined that the generic selection is result-dependent, don't 1671 // try to compute the result expression. 1672 if (IsResultDependent) 1673 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1674 Exprs, DefaultLoc, RParenLoc, 1675 ContainsUnexpandedParameterPack); 1676 1677 SmallVector<unsigned, 1> CompatIndices; 1678 unsigned DefaultIndex = -1U; 1679 for (unsigned i = 0; i < NumAssocs; ++i) { 1680 if (!Types[i]) 1681 DefaultIndex = i; 1682 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1683 Types[i]->getType())) 1684 CompatIndices.push_back(i); 1685 } 1686 1687 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1688 // type compatible with at most one of the types named in its generic 1689 // association list." 1690 if (CompatIndices.size() > 1) { 1691 // We strip parens here because the controlling expression is typically 1692 // parenthesized in macro definitions. 1693 ControllingExpr = ControllingExpr->IgnoreParens(); 1694 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1695 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1696 << (unsigned)CompatIndices.size(); 1697 for (unsigned I : CompatIndices) { 1698 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1699 diag::note_compat_assoc) 1700 << Types[I]->getTypeLoc().getSourceRange() 1701 << Types[I]->getType(); 1702 } 1703 return ExprError(); 1704 } 1705 1706 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1707 // its controlling expression shall have type compatible with exactly one of 1708 // the types named in its generic association list." 1709 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1710 // We strip parens here because the controlling expression is typically 1711 // parenthesized in macro definitions. 1712 ControllingExpr = ControllingExpr->IgnoreParens(); 1713 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1714 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1715 return ExprError(); 1716 } 1717 1718 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1719 // type name that is compatible with the type of the controlling expression, 1720 // then the result expression of the generic selection is the expression 1721 // in that generic association. Otherwise, the result expression of the 1722 // generic selection is the expression in the default generic association." 1723 unsigned ResultIndex = 1724 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1725 1726 return GenericSelectionExpr::Create( 1727 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1728 ContainsUnexpandedParameterPack, ResultIndex); 1729 } 1730 1731 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1732 /// location of the token and the offset of the ud-suffix within it. 1733 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1734 unsigned Offset) { 1735 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1736 S.getLangOpts()); 1737 } 1738 1739 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1740 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1741 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1742 IdentifierInfo *UDSuffix, 1743 SourceLocation UDSuffixLoc, 1744 ArrayRef<Expr*> Args, 1745 SourceLocation LitEndLoc) { 1746 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1747 1748 QualType ArgTy[2]; 1749 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1750 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1751 if (ArgTy[ArgIdx]->isArrayType()) 1752 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1753 } 1754 1755 DeclarationName OpName = 1756 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1757 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1758 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1759 1760 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1761 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1762 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1763 /*AllowStringTemplatePack*/ false, 1764 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1765 return ExprError(); 1766 1767 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1768 } 1769 1770 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1771 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1772 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1773 /// multiple tokens. However, the common case is that StringToks points to one 1774 /// string. 1775 /// 1776 ExprResult 1777 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1778 assert(!StringToks.empty() && "Must have at least one string!"); 1779 1780 StringLiteralParser Literal(StringToks, PP); 1781 if (Literal.hadError) 1782 return ExprError(); 1783 1784 SmallVector<SourceLocation, 4> StringTokLocs; 1785 for (const Token &Tok : StringToks) 1786 StringTokLocs.push_back(Tok.getLocation()); 1787 1788 QualType CharTy = Context.CharTy; 1789 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1790 if (Literal.isWide()) { 1791 CharTy = Context.getWideCharType(); 1792 Kind = StringLiteral::Wide; 1793 } else if (Literal.isUTF8()) { 1794 if (getLangOpts().Char8) 1795 CharTy = Context.Char8Ty; 1796 Kind = StringLiteral::UTF8; 1797 } else if (Literal.isUTF16()) { 1798 CharTy = Context.Char16Ty; 1799 Kind = StringLiteral::UTF16; 1800 } else if (Literal.isUTF32()) { 1801 CharTy = Context.Char32Ty; 1802 Kind = StringLiteral::UTF32; 1803 } else if (Literal.isPascal()) { 1804 CharTy = Context.UnsignedCharTy; 1805 } 1806 1807 // Warn on initializing an array of char from a u8 string literal; this 1808 // becomes ill-formed in C++2a. 1809 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1810 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1811 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1812 1813 // Create removals for all 'u8' prefixes in the string literal(s). This 1814 // ensures C++2a compatibility (but may change the program behavior when 1815 // built by non-Clang compilers for which the execution character set is 1816 // not always UTF-8). 1817 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1818 SourceLocation RemovalDiagLoc; 1819 for (const Token &Tok : StringToks) { 1820 if (Tok.getKind() == tok::utf8_string_literal) { 1821 if (RemovalDiagLoc.isInvalid()) 1822 RemovalDiagLoc = Tok.getLocation(); 1823 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1824 Tok.getLocation(), 1825 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1826 getSourceManager(), getLangOpts()))); 1827 } 1828 } 1829 Diag(RemovalDiagLoc, RemovalDiag); 1830 } 1831 1832 QualType StrTy = 1833 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1834 1835 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1836 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1837 Kind, Literal.Pascal, StrTy, 1838 &StringTokLocs[0], 1839 StringTokLocs.size()); 1840 if (Literal.getUDSuffix().empty()) 1841 return Lit; 1842 1843 // We're building a user-defined literal. 1844 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1845 SourceLocation UDSuffixLoc = 1846 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1847 Literal.getUDSuffixOffset()); 1848 1849 // Make sure we're allowed user-defined literals here. 1850 if (!UDLScope) 1851 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1852 1853 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1854 // operator "" X (str, len) 1855 QualType SizeType = Context.getSizeType(); 1856 1857 DeclarationName OpName = 1858 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1859 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1860 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1861 1862 QualType ArgTy[] = { 1863 Context.getArrayDecayedType(StrTy), SizeType 1864 }; 1865 1866 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1867 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1868 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1869 /*AllowStringTemplatePack*/ true, 1870 /*DiagnoseMissing*/ true, Lit)) { 1871 1872 case LOLR_Cooked: { 1873 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1874 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1875 StringTokLocs[0]); 1876 Expr *Args[] = { Lit, LenArg }; 1877 1878 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1879 } 1880 1881 case LOLR_Template: { 1882 TemplateArgumentListInfo ExplicitArgs; 1883 TemplateArgument Arg(Lit); 1884 TemplateArgumentLocInfo ArgInfo(Lit); 1885 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1886 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1887 &ExplicitArgs); 1888 } 1889 1890 case LOLR_StringTemplatePack: { 1891 TemplateArgumentListInfo ExplicitArgs; 1892 1893 unsigned CharBits = Context.getIntWidth(CharTy); 1894 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1895 llvm::APSInt Value(CharBits, CharIsUnsigned); 1896 1897 TemplateArgument TypeArg(CharTy); 1898 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1899 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1900 1901 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1902 Value = Lit->getCodeUnit(I); 1903 TemplateArgument Arg(Context, Value, CharTy); 1904 TemplateArgumentLocInfo ArgInfo; 1905 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1906 } 1907 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1908 &ExplicitArgs); 1909 } 1910 case LOLR_Raw: 1911 case LOLR_ErrorNoDiagnostic: 1912 llvm_unreachable("unexpected literal operator lookup result"); 1913 case LOLR_Error: 1914 return ExprError(); 1915 } 1916 llvm_unreachable("unexpected literal operator lookup result"); 1917 } 1918 1919 DeclRefExpr * 1920 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1921 SourceLocation Loc, 1922 const CXXScopeSpec *SS) { 1923 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1924 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1925 } 1926 1927 DeclRefExpr * 1928 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1929 const DeclarationNameInfo &NameInfo, 1930 const CXXScopeSpec *SS, NamedDecl *FoundD, 1931 SourceLocation TemplateKWLoc, 1932 const TemplateArgumentListInfo *TemplateArgs) { 1933 NestedNameSpecifierLoc NNS = 1934 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 1935 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 1936 TemplateArgs); 1937 } 1938 1939 // CUDA/HIP: Check whether a captured reference variable is referencing a 1940 // host variable in a device or host device lambda. 1941 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 1942 VarDecl *VD) { 1943 if (!S.getLangOpts().CUDA || !VD->hasInit()) 1944 return false; 1945 assert(VD->getType()->isReferenceType()); 1946 1947 // Check whether the reference variable is referencing a host variable. 1948 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 1949 if (!DRE) 1950 return false; 1951 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 1952 if (!Referee || !Referee->hasGlobalStorage() || 1953 Referee->hasAttr<CUDADeviceAttr>()) 1954 return false; 1955 1956 // Check whether the current function is a device or host device lambda. 1957 // Check whether the reference variable is a capture by getDeclContext() 1958 // since refersToEnclosingVariableOrCapture() is not ready at this point. 1959 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 1960 if (MD && MD->getParent()->isLambda() && 1961 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 1962 VD->getDeclContext() != MD) 1963 return true; 1964 1965 return false; 1966 } 1967 1968 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 1969 // A declaration named in an unevaluated operand never constitutes an odr-use. 1970 if (isUnevaluatedContext()) 1971 return NOUR_Unevaluated; 1972 1973 // C++2a [basic.def.odr]p4: 1974 // A variable x whose name appears as a potentially-evaluated expression e 1975 // is odr-used by e unless [...] x is a reference that is usable in 1976 // constant expressions. 1977 // CUDA/HIP: 1978 // If a reference variable referencing a host variable is captured in a 1979 // device or host device lambda, the value of the referee must be copied 1980 // to the capture and the reference variable must be treated as odr-use 1981 // since the value of the referee is not known at compile time and must 1982 // be loaded from the captured. 1983 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 1984 if (VD->getType()->isReferenceType() && 1985 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 1986 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 1987 VD->isUsableInConstantExpressions(Context)) 1988 return NOUR_Constant; 1989 } 1990 1991 // All remaining non-variable cases constitute an odr-use. For variables, we 1992 // need to wait and see how the expression is used. 1993 return NOUR_None; 1994 } 1995 1996 /// BuildDeclRefExpr - Build an expression that references a 1997 /// declaration that does not require a closure capture. 1998 DeclRefExpr * 1999 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2000 const DeclarationNameInfo &NameInfo, 2001 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2002 SourceLocation TemplateKWLoc, 2003 const TemplateArgumentListInfo *TemplateArgs) { 2004 bool RefersToCapturedVariable = 2005 isa<VarDecl>(D) && 2006 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 2007 2008 DeclRefExpr *E = DeclRefExpr::Create( 2009 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2010 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2011 MarkDeclRefReferenced(E); 2012 2013 // C++ [except.spec]p17: 2014 // An exception-specification is considered to be needed when: 2015 // - in an expression, the function is the unique lookup result or 2016 // the selected member of a set of overloaded functions. 2017 // 2018 // We delay doing this until after we've built the function reference and 2019 // marked it as used so that: 2020 // a) if the function is defaulted, we get errors from defining it before / 2021 // instead of errors from computing its exception specification, and 2022 // b) if the function is a defaulted comparison, we can use the body we 2023 // build when defining it as input to the exception specification 2024 // computation rather than computing a new body. 2025 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2026 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2027 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2028 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2029 } 2030 } 2031 2032 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2033 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2034 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2035 getCurFunction()->recordUseOfWeak(E); 2036 2037 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2038 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2039 FD = IFD->getAnonField(); 2040 if (FD) { 2041 UnusedPrivateFields.remove(FD); 2042 // Just in case we're building an illegal pointer-to-member. 2043 if (FD->isBitField()) 2044 E->setObjectKind(OK_BitField); 2045 } 2046 2047 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2048 // designates a bit-field. 2049 if (auto *BD = dyn_cast<BindingDecl>(D)) 2050 if (auto *BE = BD->getBinding()) 2051 E->setObjectKind(BE->getObjectKind()); 2052 2053 return E; 2054 } 2055 2056 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2057 /// possibly a list of template arguments. 2058 /// 2059 /// If this produces template arguments, it is permitted to call 2060 /// DecomposeTemplateName. 2061 /// 2062 /// This actually loses a lot of source location information for 2063 /// non-standard name kinds; we should consider preserving that in 2064 /// some way. 2065 void 2066 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2067 TemplateArgumentListInfo &Buffer, 2068 DeclarationNameInfo &NameInfo, 2069 const TemplateArgumentListInfo *&TemplateArgs) { 2070 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2071 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2072 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2073 2074 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2075 Id.TemplateId->NumArgs); 2076 translateTemplateArguments(TemplateArgsPtr, Buffer); 2077 2078 TemplateName TName = Id.TemplateId->Template.get(); 2079 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2080 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2081 TemplateArgs = &Buffer; 2082 } else { 2083 NameInfo = GetNameFromUnqualifiedId(Id); 2084 TemplateArgs = nullptr; 2085 } 2086 } 2087 2088 static void emitEmptyLookupTypoDiagnostic( 2089 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2090 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2091 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2092 DeclContext *Ctx = 2093 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2094 if (!TC) { 2095 // Emit a special diagnostic for failed member lookups. 2096 // FIXME: computing the declaration context might fail here (?) 2097 if (Ctx) 2098 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2099 << SS.getRange(); 2100 else 2101 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2102 return; 2103 } 2104 2105 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2106 bool DroppedSpecifier = 2107 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2108 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2109 ? diag::note_implicit_param_decl 2110 : diag::note_previous_decl; 2111 if (!Ctx) 2112 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2113 SemaRef.PDiag(NoteID)); 2114 else 2115 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2116 << Typo << Ctx << DroppedSpecifier 2117 << SS.getRange(), 2118 SemaRef.PDiag(NoteID)); 2119 } 2120 2121 /// Diagnose a lookup that found results in an enclosing class during error 2122 /// recovery. This usually indicates that the results were found in a dependent 2123 /// base class that could not be searched as part of a template definition. 2124 /// Always issues a diagnostic (though this may be only a warning in MS 2125 /// compatibility mode). 2126 /// 2127 /// Return \c true if the error is unrecoverable, or \c false if the caller 2128 /// should attempt to recover using these lookup results. 2129 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2130 // During a default argument instantiation the CurContext points 2131 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2132 // function parameter list, hence add an explicit check. 2133 bool isDefaultArgument = 2134 !CodeSynthesisContexts.empty() && 2135 CodeSynthesisContexts.back().Kind == 2136 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2137 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2138 bool isInstance = CurMethod && CurMethod->isInstance() && 2139 R.getNamingClass() == CurMethod->getParent() && 2140 !isDefaultArgument; 2141 2142 // There are two ways we can find a class-scope declaration during template 2143 // instantiation that we did not find in the template definition: if it is a 2144 // member of a dependent base class, or if it is declared after the point of 2145 // use in the same class. Distinguish these by comparing the class in which 2146 // the member was found to the naming class of the lookup. 2147 unsigned DiagID = diag::err_found_in_dependent_base; 2148 unsigned NoteID = diag::note_member_declared_at; 2149 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2150 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2151 : diag::err_found_later_in_class; 2152 } else if (getLangOpts().MSVCCompat) { 2153 DiagID = diag::ext_found_in_dependent_base; 2154 NoteID = diag::note_dependent_member_use; 2155 } 2156 2157 if (isInstance) { 2158 // Give a code modification hint to insert 'this->'. 2159 Diag(R.getNameLoc(), DiagID) 2160 << R.getLookupName() 2161 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2162 CheckCXXThisCapture(R.getNameLoc()); 2163 } else { 2164 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2165 // they're not shadowed). 2166 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2167 } 2168 2169 for (NamedDecl *D : R) 2170 Diag(D->getLocation(), NoteID); 2171 2172 // Return true if we are inside a default argument instantiation 2173 // and the found name refers to an instance member function, otherwise 2174 // the caller will try to create an implicit member call and this is wrong 2175 // for default arguments. 2176 // 2177 // FIXME: Is this special case necessary? We could allow the caller to 2178 // diagnose this. 2179 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2180 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2181 return true; 2182 } 2183 2184 // Tell the callee to try to recover. 2185 return false; 2186 } 2187 2188 /// Diagnose an empty lookup. 2189 /// 2190 /// \return false if new lookup candidates were found 2191 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2192 CorrectionCandidateCallback &CCC, 2193 TemplateArgumentListInfo *ExplicitTemplateArgs, 2194 ArrayRef<Expr *> Args, TypoExpr **Out) { 2195 DeclarationName Name = R.getLookupName(); 2196 2197 unsigned diagnostic = diag::err_undeclared_var_use; 2198 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2199 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2200 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2201 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2202 diagnostic = diag::err_undeclared_use; 2203 diagnostic_suggest = diag::err_undeclared_use_suggest; 2204 } 2205 2206 // If the original lookup was an unqualified lookup, fake an 2207 // unqualified lookup. This is useful when (for example) the 2208 // original lookup would not have found something because it was a 2209 // dependent name. 2210 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2211 while (DC) { 2212 if (isa<CXXRecordDecl>(DC)) { 2213 LookupQualifiedName(R, DC); 2214 2215 if (!R.empty()) { 2216 // Don't give errors about ambiguities in this lookup. 2217 R.suppressDiagnostics(); 2218 2219 // If there's a best viable function among the results, only mention 2220 // that one in the notes. 2221 OverloadCandidateSet Candidates(R.getNameLoc(), 2222 OverloadCandidateSet::CSK_Normal); 2223 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2224 OverloadCandidateSet::iterator Best; 2225 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2226 OR_Success) { 2227 R.clear(); 2228 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2229 R.resolveKind(); 2230 } 2231 2232 return DiagnoseDependentMemberLookup(R); 2233 } 2234 2235 R.clear(); 2236 } 2237 2238 DC = DC->getLookupParent(); 2239 } 2240 2241 // We didn't find anything, so try to correct for a typo. 2242 TypoCorrection Corrected; 2243 if (S && Out) { 2244 SourceLocation TypoLoc = R.getNameLoc(); 2245 assert(!ExplicitTemplateArgs && 2246 "Diagnosing an empty lookup with explicit template args!"); 2247 *Out = CorrectTypoDelayed( 2248 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2249 [=](const TypoCorrection &TC) { 2250 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2251 diagnostic, diagnostic_suggest); 2252 }, 2253 nullptr, CTK_ErrorRecovery); 2254 if (*Out) 2255 return true; 2256 } else if (S && 2257 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2258 S, &SS, CCC, CTK_ErrorRecovery))) { 2259 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2260 bool DroppedSpecifier = 2261 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2262 R.setLookupName(Corrected.getCorrection()); 2263 2264 bool AcceptableWithRecovery = false; 2265 bool AcceptableWithoutRecovery = false; 2266 NamedDecl *ND = Corrected.getFoundDecl(); 2267 if (ND) { 2268 if (Corrected.isOverloaded()) { 2269 OverloadCandidateSet OCS(R.getNameLoc(), 2270 OverloadCandidateSet::CSK_Normal); 2271 OverloadCandidateSet::iterator Best; 2272 for (NamedDecl *CD : Corrected) { 2273 if (FunctionTemplateDecl *FTD = 2274 dyn_cast<FunctionTemplateDecl>(CD)) 2275 AddTemplateOverloadCandidate( 2276 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2277 Args, OCS); 2278 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2279 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2280 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2281 Args, OCS); 2282 } 2283 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2284 case OR_Success: 2285 ND = Best->FoundDecl; 2286 Corrected.setCorrectionDecl(ND); 2287 break; 2288 default: 2289 // FIXME: Arbitrarily pick the first declaration for the note. 2290 Corrected.setCorrectionDecl(ND); 2291 break; 2292 } 2293 } 2294 R.addDecl(ND); 2295 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2296 CXXRecordDecl *Record = nullptr; 2297 if (Corrected.getCorrectionSpecifier()) { 2298 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2299 Record = Ty->getAsCXXRecordDecl(); 2300 } 2301 if (!Record) 2302 Record = cast<CXXRecordDecl>( 2303 ND->getDeclContext()->getRedeclContext()); 2304 R.setNamingClass(Record); 2305 } 2306 2307 auto *UnderlyingND = ND->getUnderlyingDecl(); 2308 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2309 isa<FunctionTemplateDecl>(UnderlyingND); 2310 // FIXME: If we ended up with a typo for a type name or 2311 // Objective-C class name, we're in trouble because the parser 2312 // is in the wrong place to recover. Suggest the typo 2313 // correction, but don't make it a fix-it since we're not going 2314 // to recover well anyway. 2315 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2316 getAsTypeTemplateDecl(UnderlyingND) || 2317 isa<ObjCInterfaceDecl>(UnderlyingND); 2318 } else { 2319 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2320 // because we aren't able to recover. 2321 AcceptableWithoutRecovery = true; 2322 } 2323 2324 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2325 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2326 ? diag::note_implicit_param_decl 2327 : diag::note_previous_decl; 2328 if (SS.isEmpty()) 2329 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2330 PDiag(NoteID), AcceptableWithRecovery); 2331 else 2332 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2333 << Name << computeDeclContext(SS, false) 2334 << DroppedSpecifier << SS.getRange(), 2335 PDiag(NoteID), AcceptableWithRecovery); 2336 2337 // Tell the callee whether to try to recover. 2338 return !AcceptableWithRecovery; 2339 } 2340 } 2341 R.clear(); 2342 2343 // Emit a special diagnostic for failed member lookups. 2344 // FIXME: computing the declaration context might fail here (?) 2345 if (!SS.isEmpty()) { 2346 Diag(R.getNameLoc(), diag::err_no_member) 2347 << Name << computeDeclContext(SS, false) 2348 << SS.getRange(); 2349 return true; 2350 } 2351 2352 // Give up, we can't recover. 2353 Diag(R.getNameLoc(), diagnostic) << Name; 2354 return true; 2355 } 2356 2357 /// In Microsoft mode, if we are inside a template class whose parent class has 2358 /// dependent base classes, and we can't resolve an unqualified identifier, then 2359 /// assume the identifier is a member of a dependent base class. We can only 2360 /// recover successfully in static methods, instance methods, and other contexts 2361 /// where 'this' is available. This doesn't precisely match MSVC's 2362 /// instantiation model, but it's close enough. 2363 static Expr * 2364 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2365 DeclarationNameInfo &NameInfo, 2366 SourceLocation TemplateKWLoc, 2367 const TemplateArgumentListInfo *TemplateArgs) { 2368 // Only try to recover from lookup into dependent bases in static methods or 2369 // contexts where 'this' is available. 2370 QualType ThisType = S.getCurrentThisType(); 2371 const CXXRecordDecl *RD = nullptr; 2372 if (!ThisType.isNull()) 2373 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2374 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2375 RD = MD->getParent(); 2376 if (!RD || !RD->hasAnyDependentBases()) 2377 return nullptr; 2378 2379 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2380 // is available, suggest inserting 'this->' as a fixit. 2381 SourceLocation Loc = NameInfo.getLoc(); 2382 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2383 DB << NameInfo.getName() << RD; 2384 2385 if (!ThisType.isNull()) { 2386 DB << FixItHint::CreateInsertion(Loc, "this->"); 2387 return CXXDependentScopeMemberExpr::Create( 2388 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2389 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2390 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2391 } 2392 2393 // Synthesize a fake NNS that points to the derived class. This will 2394 // perform name lookup during template instantiation. 2395 CXXScopeSpec SS; 2396 auto *NNS = 2397 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2398 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2399 return DependentScopeDeclRefExpr::Create( 2400 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2401 TemplateArgs); 2402 } 2403 2404 ExprResult 2405 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2406 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2407 bool HasTrailingLParen, bool IsAddressOfOperand, 2408 CorrectionCandidateCallback *CCC, 2409 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2410 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2411 "cannot be direct & operand and have a trailing lparen"); 2412 if (SS.isInvalid()) 2413 return ExprError(); 2414 2415 TemplateArgumentListInfo TemplateArgsBuffer; 2416 2417 // Decompose the UnqualifiedId into the following data. 2418 DeclarationNameInfo NameInfo; 2419 const TemplateArgumentListInfo *TemplateArgs; 2420 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2421 2422 DeclarationName Name = NameInfo.getName(); 2423 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2424 SourceLocation NameLoc = NameInfo.getLoc(); 2425 2426 if (II && II->isEditorPlaceholder()) { 2427 // FIXME: When typed placeholders are supported we can create a typed 2428 // placeholder expression node. 2429 return ExprError(); 2430 } 2431 2432 // C++ [temp.dep.expr]p3: 2433 // An id-expression is type-dependent if it contains: 2434 // -- an identifier that was declared with a dependent type, 2435 // (note: handled after lookup) 2436 // -- a template-id that is dependent, 2437 // (note: handled in BuildTemplateIdExpr) 2438 // -- a conversion-function-id that specifies a dependent type, 2439 // -- a nested-name-specifier that contains a class-name that 2440 // names a dependent type. 2441 // Determine whether this is a member of an unknown specialization; 2442 // we need to handle these differently. 2443 bool DependentID = false; 2444 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2445 Name.getCXXNameType()->isDependentType()) { 2446 DependentID = true; 2447 } else if (SS.isSet()) { 2448 if (DeclContext *DC = computeDeclContext(SS, false)) { 2449 if (RequireCompleteDeclContext(SS, DC)) 2450 return ExprError(); 2451 } else { 2452 DependentID = true; 2453 } 2454 } 2455 2456 if (DependentID) 2457 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2458 IsAddressOfOperand, TemplateArgs); 2459 2460 // Perform the required lookup. 2461 LookupResult R(*this, NameInfo, 2462 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2463 ? LookupObjCImplicitSelfParam 2464 : LookupOrdinaryName); 2465 if (TemplateKWLoc.isValid() || TemplateArgs) { 2466 // Lookup the template name again to correctly establish the context in 2467 // which it was found. This is really unfortunate as we already did the 2468 // lookup to determine that it was a template name in the first place. If 2469 // this becomes a performance hit, we can work harder to preserve those 2470 // results until we get here but it's likely not worth it. 2471 bool MemberOfUnknownSpecialization; 2472 AssumedTemplateKind AssumedTemplate; 2473 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2474 MemberOfUnknownSpecialization, TemplateKWLoc, 2475 &AssumedTemplate)) 2476 return ExprError(); 2477 2478 if (MemberOfUnknownSpecialization || 2479 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2480 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2481 IsAddressOfOperand, TemplateArgs); 2482 } else { 2483 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2484 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2485 2486 // If the result might be in a dependent base class, this is a dependent 2487 // id-expression. 2488 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2489 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2490 IsAddressOfOperand, TemplateArgs); 2491 2492 // If this reference is in an Objective-C method, then we need to do 2493 // some special Objective-C lookup, too. 2494 if (IvarLookupFollowUp) { 2495 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2496 if (E.isInvalid()) 2497 return ExprError(); 2498 2499 if (Expr *Ex = E.getAs<Expr>()) 2500 return Ex; 2501 } 2502 } 2503 2504 if (R.isAmbiguous()) 2505 return ExprError(); 2506 2507 // This could be an implicitly declared function reference (legal in C90, 2508 // extension in C99, forbidden in C++). 2509 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2510 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2511 if (D) R.addDecl(D); 2512 } 2513 2514 // Determine whether this name might be a candidate for 2515 // argument-dependent lookup. 2516 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2517 2518 if (R.empty() && !ADL) { 2519 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2520 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2521 TemplateKWLoc, TemplateArgs)) 2522 return E; 2523 } 2524 2525 // Don't diagnose an empty lookup for inline assembly. 2526 if (IsInlineAsmIdentifier) 2527 return ExprError(); 2528 2529 // If this name wasn't predeclared and if this is not a function 2530 // call, diagnose the problem. 2531 TypoExpr *TE = nullptr; 2532 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2533 : nullptr); 2534 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2535 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2536 "Typo correction callback misconfigured"); 2537 if (CCC) { 2538 // Make sure the callback knows what the typo being diagnosed is. 2539 CCC->setTypoName(II); 2540 if (SS.isValid()) 2541 CCC->setTypoNNS(SS.getScopeRep()); 2542 } 2543 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2544 // a template name, but we happen to have always already looked up the name 2545 // before we get here if it must be a template name. 2546 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2547 None, &TE)) { 2548 if (TE && KeywordReplacement) { 2549 auto &State = getTypoExprState(TE); 2550 auto BestTC = State.Consumer->getNextCorrection(); 2551 if (BestTC.isKeyword()) { 2552 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2553 if (State.DiagHandler) 2554 State.DiagHandler(BestTC); 2555 KeywordReplacement->startToken(); 2556 KeywordReplacement->setKind(II->getTokenID()); 2557 KeywordReplacement->setIdentifierInfo(II); 2558 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2559 // Clean up the state associated with the TypoExpr, since it has 2560 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2561 clearDelayedTypo(TE); 2562 // Signal that a correction to a keyword was performed by returning a 2563 // valid-but-null ExprResult. 2564 return (Expr*)nullptr; 2565 } 2566 State.Consumer->resetCorrectionStream(); 2567 } 2568 return TE ? TE : ExprError(); 2569 } 2570 2571 assert(!R.empty() && 2572 "DiagnoseEmptyLookup returned false but added no results"); 2573 2574 // If we found an Objective-C instance variable, let 2575 // LookupInObjCMethod build the appropriate expression to 2576 // reference the ivar. 2577 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2578 R.clear(); 2579 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2580 // In a hopelessly buggy code, Objective-C instance variable 2581 // lookup fails and no expression will be built to reference it. 2582 if (!E.isInvalid() && !E.get()) 2583 return ExprError(); 2584 return E; 2585 } 2586 } 2587 2588 // This is guaranteed from this point on. 2589 assert(!R.empty() || ADL); 2590 2591 // Check whether this might be a C++ implicit instance member access. 2592 // C++ [class.mfct.non-static]p3: 2593 // When an id-expression that is not part of a class member access 2594 // syntax and not used to form a pointer to member is used in the 2595 // body of a non-static member function of class X, if name lookup 2596 // resolves the name in the id-expression to a non-static non-type 2597 // member of some class C, the id-expression is transformed into a 2598 // class member access expression using (*this) as the 2599 // postfix-expression to the left of the . operator. 2600 // 2601 // But we don't actually need to do this for '&' operands if R 2602 // resolved to a function or overloaded function set, because the 2603 // expression is ill-formed if it actually works out to be a 2604 // non-static member function: 2605 // 2606 // C++ [expr.ref]p4: 2607 // Otherwise, if E1.E2 refers to a non-static member function. . . 2608 // [t]he expression can be used only as the left-hand operand of a 2609 // member function call. 2610 // 2611 // There are other safeguards against such uses, but it's important 2612 // to get this right here so that we don't end up making a 2613 // spuriously dependent expression if we're inside a dependent 2614 // instance method. 2615 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2616 bool MightBeImplicitMember; 2617 if (!IsAddressOfOperand) 2618 MightBeImplicitMember = true; 2619 else if (!SS.isEmpty()) 2620 MightBeImplicitMember = false; 2621 else if (R.isOverloadedResult()) 2622 MightBeImplicitMember = false; 2623 else if (R.isUnresolvableResult()) 2624 MightBeImplicitMember = true; 2625 else 2626 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2627 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2628 isa<MSPropertyDecl>(R.getFoundDecl()); 2629 2630 if (MightBeImplicitMember) 2631 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2632 R, TemplateArgs, S); 2633 } 2634 2635 if (TemplateArgs || TemplateKWLoc.isValid()) { 2636 2637 // In C++1y, if this is a variable template id, then check it 2638 // in BuildTemplateIdExpr(). 2639 // The single lookup result must be a variable template declaration. 2640 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2641 Id.TemplateId->Kind == TNK_Var_template) { 2642 assert(R.getAsSingle<VarTemplateDecl>() && 2643 "There should only be one declaration found."); 2644 } 2645 2646 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2647 } 2648 2649 return BuildDeclarationNameExpr(SS, R, ADL); 2650 } 2651 2652 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2653 /// declaration name, generally during template instantiation. 2654 /// There's a large number of things which don't need to be done along 2655 /// this path. 2656 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2657 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2658 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2659 DeclContext *DC = computeDeclContext(SS, false); 2660 if (!DC) 2661 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2662 NameInfo, /*TemplateArgs=*/nullptr); 2663 2664 if (RequireCompleteDeclContext(SS, DC)) 2665 return ExprError(); 2666 2667 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2668 LookupQualifiedName(R, DC); 2669 2670 if (R.isAmbiguous()) 2671 return ExprError(); 2672 2673 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2674 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2675 NameInfo, /*TemplateArgs=*/nullptr); 2676 2677 if (R.empty()) { 2678 // Don't diagnose problems with invalid record decl, the secondary no_member 2679 // diagnostic during template instantiation is likely bogus, e.g. if a class 2680 // is invalid because it's derived from an invalid base class, then missing 2681 // members were likely supposed to be inherited. 2682 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2683 if (CD->isInvalidDecl()) 2684 return ExprError(); 2685 Diag(NameInfo.getLoc(), diag::err_no_member) 2686 << NameInfo.getName() << DC << SS.getRange(); 2687 return ExprError(); 2688 } 2689 2690 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2691 // Diagnose a missing typename if this resolved unambiguously to a type in 2692 // a dependent context. If we can recover with a type, downgrade this to 2693 // a warning in Microsoft compatibility mode. 2694 unsigned DiagID = diag::err_typename_missing; 2695 if (RecoveryTSI && getLangOpts().MSVCCompat) 2696 DiagID = diag::ext_typename_missing; 2697 SourceLocation Loc = SS.getBeginLoc(); 2698 auto D = Diag(Loc, DiagID); 2699 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2700 << SourceRange(Loc, NameInfo.getEndLoc()); 2701 2702 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2703 // context. 2704 if (!RecoveryTSI) 2705 return ExprError(); 2706 2707 // Only issue the fixit if we're prepared to recover. 2708 D << FixItHint::CreateInsertion(Loc, "typename "); 2709 2710 // Recover by pretending this was an elaborated type. 2711 QualType Ty = Context.getTypeDeclType(TD); 2712 TypeLocBuilder TLB; 2713 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2714 2715 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2716 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2717 QTL.setElaboratedKeywordLoc(SourceLocation()); 2718 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2719 2720 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2721 2722 return ExprEmpty(); 2723 } 2724 2725 // Defend against this resolving to an implicit member access. We usually 2726 // won't get here if this might be a legitimate a class member (we end up in 2727 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2728 // a pointer-to-member or in an unevaluated context in C++11. 2729 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2730 return BuildPossibleImplicitMemberExpr(SS, 2731 /*TemplateKWLoc=*/SourceLocation(), 2732 R, /*TemplateArgs=*/nullptr, S); 2733 2734 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2735 } 2736 2737 /// The parser has read a name in, and Sema has detected that we're currently 2738 /// inside an ObjC method. Perform some additional checks and determine if we 2739 /// should form a reference to an ivar. 2740 /// 2741 /// Ideally, most of this would be done by lookup, but there's 2742 /// actually quite a lot of extra work involved. 2743 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2744 IdentifierInfo *II) { 2745 SourceLocation Loc = Lookup.getNameLoc(); 2746 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2747 2748 // Check for error condition which is already reported. 2749 if (!CurMethod) 2750 return DeclResult(true); 2751 2752 // There are two cases to handle here. 1) scoped lookup could have failed, 2753 // in which case we should look for an ivar. 2) scoped lookup could have 2754 // found a decl, but that decl is outside the current instance method (i.e. 2755 // a global variable). In these two cases, we do a lookup for an ivar with 2756 // this name, if the lookup sucedes, we replace it our current decl. 2757 2758 // If we're in a class method, we don't normally want to look for 2759 // ivars. But if we don't find anything else, and there's an 2760 // ivar, that's an error. 2761 bool IsClassMethod = CurMethod->isClassMethod(); 2762 2763 bool LookForIvars; 2764 if (Lookup.empty()) 2765 LookForIvars = true; 2766 else if (IsClassMethod) 2767 LookForIvars = false; 2768 else 2769 LookForIvars = (Lookup.isSingleResult() && 2770 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2771 ObjCInterfaceDecl *IFace = nullptr; 2772 if (LookForIvars) { 2773 IFace = CurMethod->getClassInterface(); 2774 ObjCInterfaceDecl *ClassDeclared; 2775 ObjCIvarDecl *IV = nullptr; 2776 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2777 // Diagnose using an ivar in a class method. 2778 if (IsClassMethod) { 2779 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2780 return DeclResult(true); 2781 } 2782 2783 // Diagnose the use of an ivar outside of the declaring class. 2784 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2785 !declaresSameEntity(ClassDeclared, IFace) && 2786 !getLangOpts().DebuggerSupport) 2787 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2788 2789 // Success. 2790 return IV; 2791 } 2792 } else if (CurMethod->isInstanceMethod()) { 2793 // We should warn if a local variable hides an ivar. 2794 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2795 ObjCInterfaceDecl *ClassDeclared; 2796 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2797 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2798 declaresSameEntity(IFace, ClassDeclared)) 2799 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2800 } 2801 } 2802 } else if (Lookup.isSingleResult() && 2803 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2804 // If accessing a stand-alone ivar in a class method, this is an error. 2805 if (const ObjCIvarDecl *IV = 2806 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2807 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2808 return DeclResult(true); 2809 } 2810 } 2811 2812 // Didn't encounter an error, didn't find an ivar. 2813 return DeclResult(false); 2814 } 2815 2816 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2817 ObjCIvarDecl *IV) { 2818 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2819 assert(CurMethod && CurMethod->isInstanceMethod() && 2820 "should not reference ivar from this context"); 2821 2822 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2823 assert(IFace && "should not reference ivar from this context"); 2824 2825 // If we're referencing an invalid decl, just return this as a silent 2826 // error node. The error diagnostic was already emitted on the decl. 2827 if (IV->isInvalidDecl()) 2828 return ExprError(); 2829 2830 // Check if referencing a field with __attribute__((deprecated)). 2831 if (DiagnoseUseOfDecl(IV, Loc)) 2832 return ExprError(); 2833 2834 // FIXME: This should use a new expr for a direct reference, don't 2835 // turn this into Self->ivar, just return a BareIVarExpr or something. 2836 IdentifierInfo &II = Context.Idents.get("self"); 2837 UnqualifiedId SelfName; 2838 SelfName.setImplicitSelfParam(&II); 2839 CXXScopeSpec SelfScopeSpec; 2840 SourceLocation TemplateKWLoc; 2841 ExprResult SelfExpr = 2842 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2843 /*HasTrailingLParen=*/false, 2844 /*IsAddressOfOperand=*/false); 2845 if (SelfExpr.isInvalid()) 2846 return ExprError(); 2847 2848 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2849 if (SelfExpr.isInvalid()) 2850 return ExprError(); 2851 2852 MarkAnyDeclReferenced(Loc, IV, true); 2853 2854 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2855 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2856 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2857 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2858 2859 ObjCIvarRefExpr *Result = new (Context) 2860 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2861 IV->getLocation(), SelfExpr.get(), true, true); 2862 2863 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2864 if (!isUnevaluatedContext() && 2865 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2866 getCurFunction()->recordUseOfWeak(Result); 2867 } 2868 if (getLangOpts().ObjCAutoRefCount) 2869 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2870 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2871 2872 return Result; 2873 } 2874 2875 /// The parser has read a name in, and Sema has detected that we're currently 2876 /// inside an ObjC method. Perform some additional checks and determine if we 2877 /// should form a reference to an ivar. If so, build an expression referencing 2878 /// that ivar. 2879 ExprResult 2880 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2881 IdentifierInfo *II, bool AllowBuiltinCreation) { 2882 // FIXME: Integrate this lookup step into LookupParsedName. 2883 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2884 if (Ivar.isInvalid()) 2885 return ExprError(); 2886 if (Ivar.isUsable()) 2887 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2888 cast<ObjCIvarDecl>(Ivar.get())); 2889 2890 if (Lookup.empty() && II && AllowBuiltinCreation) 2891 LookupBuiltin(Lookup); 2892 2893 // Sentinel value saying that we didn't do anything special. 2894 return ExprResult(false); 2895 } 2896 2897 /// Cast a base object to a member's actual type. 2898 /// 2899 /// There are two relevant checks: 2900 /// 2901 /// C++ [class.access.base]p7: 2902 /// 2903 /// If a class member access operator [...] is used to access a non-static 2904 /// data member or non-static member function, the reference is ill-formed if 2905 /// the left operand [...] cannot be implicitly converted to a pointer to the 2906 /// naming class of the right operand. 2907 /// 2908 /// C++ [expr.ref]p7: 2909 /// 2910 /// If E2 is a non-static data member or a non-static member function, the 2911 /// program is ill-formed if the class of which E2 is directly a member is an 2912 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2913 /// 2914 /// Note that the latter check does not consider access; the access of the 2915 /// "real" base class is checked as appropriate when checking the access of the 2916 /// member name. 2917 ExprResult 2918 Sema::PerformObjectMemberConversion(Expr *From, 2919 NestedNameSpecifier *Qualifier, 2920 NamedDecl *FoundDecl, 2921 NamedDecl *Member) { 2922 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2923 if (!RD) 2924 return From; 2925 2926 QualType DestRecordType; 2927 QualType DestType; 2928 QualType FromRecordType; 2929 QualType FromType = From->getType(); 2930 bool PointerConversions = false; 2931 if (isa<FieldDecl>(Member)) { 2932 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2933 auto FromPtrType = FromType->getAs<PointerType>(); 2934 DestRecordType = Context.getAddrSpaceQualType( 2935 DestRecordType, FromPtrType 2936 ? FromType->getPointeeType().getAddressSpace() 2937 : FromType.getAddressSpace()); 2938 2939 if (FromPtrType) { 2940 DestType = Context.getPointerType(DestRecordType); 2941 FromRecordType = FromPtrType->getPointeeType(); 2942 PointerConversions = true; 2943 } else { 2944 DestType = DestRecordType; 2945 FromRecordType = FromType; 2946 } 2947 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2948 if (Method->isStatic()) 2949 return From; 2950 2951 DestType = Method->getThisType(); 2952 DestRecordType = DestType->getPointeeType(); 2953 2954 if (FromType->getAs<PointerType>()) { 2955 FromRecordType = FromType->getPointeeType(); 2956 PointerConversions = true; 2957 } else { 2958 FromRecordType = FromType; 2959 DestType = DestRecordType; 2960 } 2961 2962 LangAS FromAS = FromRecordType.getAddressSpace(); 2963 LangAS DestAS = DestRecordType.getAddressSpace(); 2964 if (FromAS != DestAS) { 2965 QualType FromRecordTypeWithoutAS = 2966 Context.removeAddrSpaceQualType(FromRecordType); 2967 QualType FromTypeWithDestAS = 2968 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 2969 if (PointerConversions) 2970 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 2971 From = ImpCastExprToType(From, FromTypeWithDestAS, 2972 CK_AddressSpaceConversion, From->getValueKind()) 2973 .get(); 2974 } 2975 } else { 2976 // No conversion necessary. 2977 return From; 2978 } 2979 2980 if (DestType->isDependentType() || FromType->isDependentType()) 2981 return From; 2982 2983 // If the unqualified types are the same, no conversion is necessary. 2984 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2985 return From; 2986 2987 SourceRange FromRange = From->getSourceRange(); 2988 SourceLocation FromLoc = FromRange.getBegin(); 2989 2990 ExprValueKind VK = From->getValueKind(); 2991 2992 // C++ [class.member.lookup]p8: 2993 // [...] Ambiguities can often be resolved by qualifying a name with its 2994 // class name. 2995 // 2996 // If the member was a qualified name and the qualified referred to a 2997 // specific base subobject type, we'll cast to that intermediate type 2998 // first and then to the object in which the member is declared. That allows 2999 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3000 // 3001 // class Base { public: int x; }; 3002 // class Derived1 : public Base { }; 3003 // class Derived2 : public Base { }; 3004 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3005 // 3006 // void VeryDerived::f() { 3007 // x = 17; // error: ambiguous base subobjects 3008 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3009 // } 3010 if (Qualifier && Qualifier->getAsType()) { 3011 QualType QType = QualType(Qualifier->getAsType(), 0); 3012 assert(QType->isRecordType() && "lookup done with non-record type"); 3013 3014 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 3015 3016 // In C++98, the qualifier type doesn't actually have to be a base 3017 // type of the object type, in which case we just ignore it. 3018 // Otherwise build the appropriate casts. 3019 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3020 CXXCastPath BasePath; 3021 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3022 FromLoc, FromRange, &BasePath)) 3023 return ExprError(); 3024 3025 if (PointerConversions) 3026 QType = Context.getPointerType(QType); 3027 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3028 VK, &BasePath).get(); 3029 3030 FromType = QType; 3031 FromRecordType = QRecordType; 3032 3033 // If the qualifier type was the same as the destination type, 3034 // we're done. 3035 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3036 return From; 3037 } 3038 } 3039 3040 CXXCastPath BasePath; 3041 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3042 FromLoc, FromRange, &BasePath, 3043 /*IgnoreAccess=*/true)) 3044 return ExprError(); 3045 3046 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3047 VK, &BasePath); 3048 } 3049 3050 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3051 const LookupResult &R, 3052 bool HasTrailingLParen) { 3053 // Only when used directly as the postfix-expression of a call. 3054 if (!HasTrailingLParen) 3055 return false; 3056 3057 // Never if a scope specifier was provided. 3058 if (SS.isSet()) 3059 return false; 3060 3061 // Only in C++ or ObjC++. 3062 if (!getLangOpts().CPlusPlus) 3063 return false; 3064 3065 // Turn off ADL when we find certain kinds of declarations during 3066 // normal lookup: 3067 for (NamedDecl *D : R) { 3068 // C++0x [basic.lookup.argdep]p3: 3069 // -- a declaration of a class member 3070 // Since using decls preserve this property, we check this on the 3071 // original decl. 3072 if (D->isCXXClassMember()) 3073 return false; 3074 3075 // C++0x [basic.lookup.argdep]p3: 3076 // -- a block-scope function declaration that is not a 3077 // using-declaration 3078 // NOTE: we also trigger this for function templates (in fact, we 3079 // don't check the decl type at all, since all other decl types 3080 // turn off ADL anyway). 3081 if (isa<UsingShadowDecl>(D)) 3082 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3083 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3084 return false; 3085 3086 // C++0x [basic.lookup.argdep]p3: 3087 // -- a declaration that is neither a function or a function 3088 // template 3089 // And also for builtin functions. 3090 if (isa<FunctionDecl>(D)) { 3091 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3092 3093 // But also builtin functions. 3094 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3095 return false; 3096 } else if (!isa<FunctionTemplateDecl>(D)) 3097 return false; 3098 } 3099 3100 return true; 3101 } 3102 3103 3104 /// Diagnoses obvious problems with the use of the given declaration 3105 /// as an expression. This is only actually called for lookups that 3106 /// were not overloaded, and it doesn't promise that the declaration 3107 /// will in fact be used. 3108 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 3109 if (D->isInvalidDecl()) 3110 return true; 3111 3112 if (isa<TypedefNameDecl>(D)) { 3113 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3114 return true; 3115 } 3116 3117 if (isa<ObjCInterfaceDecl>(D)) { 3118 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3119 return true; 3120 } 3121 3122 if (isa<NamespaceDecl>(D)) { 3123 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3124 return true; 3125 } 3126 3127 return false; 3128 } 3129 3130 // Certain multiversion types should be treated as overloaded even when there is 3131 // only one result. 3132 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3133 assert(R.isSingleResult() && "Expected only a single result"); 3134 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3135 return FD && 3136 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3137 } 3138 3139 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3140 LookupResult &R, bool NeedsADL, 3141 bool AcceptInvalidDecl) { 3142 // If this is a single, fully-resolved result and we don't need ADL, 3143 // just build an ordinary singleton decl ref. 3144 if (!NeedsADL && R.isSingleResult() && 3145 !R.getAsSingle<FunctionTemplateDecl>() && 3146 !ShouldLookupResultBeMultiVersionOverload(R)) 3147 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3148 R.getRepresentativeDecl(), nullptr, 3149 AcceptInvalidDecl); 3150 3151 // We only need to check the declaration if there's exactly one 3152 // result, because in the overloaded case the results can only be 3153 // functions and function templates. 3154 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3155 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 3156 return ExprError(); 3157 3158 // Otherwise, just build an unresolved lookup expression. Suppress 3159 // any lookup-related diagnostics; we'll hash these out later, when 3160 // we've picked a target. 3161 R.suppressDiagnostics(); 3162 3163 UnresolvedLookupExpr *ULE 3164 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3165 SS.getWithLocInContext(Context), 3166 R.getLookupNameInfo(), 3167 NeedsADL, R.isOverloadedResult(), 3168 R.begin(), R.end()); 3169 3170 return ULE; 3171 } 3172 3173 static void 3174 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 3175 ValueDecl *var, DeclContext *DC); 3176 3177 /// Complete semantic analysis for a reference to the given declaration. 3178 ExprResult Sema::BuildDeclarationNameExpr( 3179 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3180 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3181 bool AcceptInvalidDecl) { 3182 assert(D && "Cannot refer to a NULL declaration"); 3183 assert(!isa<FunctionTemplateDecl>(D) && 3184 "Cannot refer unambiguously to a function template"); 3185 3186 SourceLocation Loc = NameInfo.getLoc(); 3187 if (CheckDeclInExpr(*this, Loc, D)) 3188 return ExprError(); 3189 3190 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3191 // Specifically diagnose references to class templates that are missing 3192 // a template argument list. 3193 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3194 return ExprError(); 3195 } 3196 3197 // Make sure that we're referring to a value. 3198 ValueDecl *VD = dyn_cast<ValueDecl>(D); 3199 if (!VD) { 3200 Diag(Loc, diag::err_ref_non_value) 3201 << D << SS.getRange(); 3202 Diag(D->getLocation(), diag::note_declared_at); 3203 return ExprError(); 3204 } 3205 3206 // Check whether this declaration can be used. Note that we suppress 3207 // this check when we're going to perform argument-dependent lookup 3208 // on this function name, because this might not be the function 3209 // that overload resolution actually selects. 3210 if (DiagnoseUseOfDecl(VD, Loc)) 3211 return ExprError(); 3212 3213 // Only create DeclRefExpr's for valid Decl's. 3214 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3215 return ExprError(); 3216 3217 // Handle members of anonymous structs and unions. If we got here, 3218 // and the reference is to a class member indirect field, then this 3219 // must be the subject of a pointer-to-member expression. 3220 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3221 if (!indirectField->isCXXClassMember()) 3222 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3223 indirectField); 3224 3225 { 3226 QualType type = VD->getType(); 3227 if (type.isNull()) 3228 return ExprError(); 3229 ExprValueKind valueKind = VK_RValue; 3230 3231 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3232 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3233 // is expanded by some outer '...' in the context of the use. 3234 type = type.getNonPackExpansionType(); 3235 3236 switch (D->getKind()) { 3237 // Ignore all the non-ValueDecl kinds. 3238 #define ABSTRACT_DECL(kind) 3239 #define VALUE(type, base) 3240 #define DECL(type, base) \ 3241 case Decl::type: 3242 #include "clang/AST/DeclNodes.inc" 3243 llvm_unreachable("invalid value decl kind"); 3244 3245 // These shouldn't make it here. 3246 case Decl::ObjCAtDefsField: 3247 llvm_unreachable("forming non-member reference to ivar?"); 3248 3249 // Enum constants are always r-values and never references. 3250 // Unresolved using declarations are dependent. 3251 case Decl::EnumConstant: 3252 case Decl::UnresolvedUsingValue: 3253 case Decl::OMPDeclareReduction: 3254 case Decl::OMPDeclareMapper: 3255 valueKind = VK_RValue; 3256 break; 3257 3258 // Fields and indirect fields that got here must be for 3259 // pointer-to-member expressions; we just call them l-values for 3260 // internal consistency, because this subexpression doesn't really 3261 // exist in the high-level semantics. 3262 case Decl::Field: 3263 case Decl::IndirectField: 3264 case Decl::ObjCIvar: 3265 assert(getLangOpts().CPlusPlus && 3266 "building reference to field in C?"); 3267 3268 // These can't have reference type in well-formed programs, but 3269 // for internal consistency we do this anyway. 3270 type = type.getNonReferenceType(); 3271 valueKind = VK_LValue; 3272 break; 3273 3274 // Non-type template parameters are either l-values or r-values 3275 // depending on the type. 3276 case Decl::NonTypeTemplateParm: { 3277 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3278 type = reftype->getPointeeType(); 3279 valueKind = VK_LValue; // even if the parameter is an r-value reference 3280 break; 3281 } 3282 3283 // [expr.prim.id.unqual]p2: 3284 // If the entity is a template parameter object for a template 3285 // parameter of type T, the type of the expression is const T. 3286 // [...] The expression is an lvalue if the entity is a [...] template 3287 // parameter object. 3288 if (type->isRecordType()) { 3289 type = type.getUnqualifiedType().withConst(); 3290 valueKind = VK_LValue; 3291 break; 3292 } 3293 3294 // For non-references, we need to strip qualifiers just in case 3295 // the template parameter was declared as 'const int' or whatever. 3296 valueKind = VK_RValue; 3297 type = type.getUnqualifiedType(); 3298 break; 3299 } 3300 3301 case Decl::Var: 3302 case Decl::VarTemplateSpecialization: 3303 case Decl::VarTemplatePartialSpecialization: 3304 case Decl::Decomposition: 3305 case Decl::OMPCapturedExpr: 3306 // In C, "extern void blah;" is valid and is an r-value. 3307 if (!getLangOpts().CPlusPlus && 3308 !type.hasQualifiers() && 3309 type->isVoidType()) { 3310 valueKind = VK_RValue; 3311 break; 3312 } 3313 LLVM_FALLTHROUGH; 3314 3315 case Decl::ImplicitParam: 3316 case Decl::ParmVar: { 3317 // These are always l-values. 3318 valueKind = VK_LValue; 3319 type = type.getNonReferenceType(); 3320 3321 // FIXME: Does the addition of const really only apply in 3322 // potentially-evaluated contexts? Since the variable isn't actually 3323 // captured in an unevaluated context, it seems that the answer is no. 3324 if (!isUnevaluatedContext()) { 3325 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3326 if (!CapturedType.isNull()) 3327 type = CapturedType; 3328 } 3329 3330 break; 3331 } 3332 3333 case Decl::Binding: { 3334 // These are always lvalues. 3335 valueKind = VK_LValue; 3336 type = type.getNonReferenceType(); 3337 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 3338 // decides how that's supposed to work. 3339 auto *BD = cast<BindingDecl>(VD); 3340 if (BD->getDeclContext() != CurContext) { 3341 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl()); 3342 if (DD && DD->hasLocalStorage()) 3343 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 3344 } 3345 break; 3346 } 3347 3348 case Decl::Function: { 3349 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3350 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 3351 type = Context.BuiltinFnTy; 3352 valueKind = VK_RValue; 3353 break; 3354 } 3355 } 3356 3357 const FunctionType *fty = type->castAs<FunctionType>(); 3358 3359 // If we're referring to a function with an __unknown_anytype 3360 // result type, make the entire expression __unknown_anytype. 3361 if (fty->getReturnType() == Context.UnknownAnyTy) { 3362 type = Context.UnknownAnyTy; 3363 valueKind = VK_RValue; 3364 break; 3365 } 3366 3367 // Functions are l-values in C++. 3368 if (getLangOpts().CPlusPlus) { 3369 valueKind = VK_LValue; 3370 break; 3371 } 3372 3373 // C99 DR 316 says that, if a function type comes from a 3374 // function definition (without a prototype), that type is only 3375 // used for checking compatibility. Therefore, when referencing 3376 // the function, we pretend that we don't have the full function 3377 // type. 3378 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3379 isa<FunctionProtoType>(fty)) 3380 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3381 fty->getExtInfo()); 3382 3383 // Functions are r-values in C. 3384 valueKind = VK_RValue; 3385 break; 3386 } 3387 3388 case Decl::CXXDeductionGuide: 3389 llvm_unreachable("building reference to deduction guide"); 3390 3391 case Decl::MSProperty: 3392 case Decl::MSGuid: 3393 case Decl::TemplateParamObject: 3394 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3395 // capture in OpenMP, or duplicated between host and device? 3396 valueKind = VK_LValue; 3397 break; 3398 3399 case Decl::CXXMethod: 3400 // If we're referring to a method with an __unknown_anytype 3401 // result type, make the entire expression __unknown_anytype. 3402 // This should only be possible with a type written directly. 3403 if (const FunctionProtoType *proto 3404 = dyn_cast<FunctionProtoType>(VD->getType())) 3405 if (proto->getReturnType() == Context.UnknownAnyTy) { 3406 type = Context.UnknownAnyTy; 3407 valueKind = VK_RValue; 3408 break; 3409 } 3410 3411 // C++ methods are l-values if static, r-values if non-static. 3412 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3413 valueKind = VK_LValue; 3414 break; 3415 } 3416 LLVM_FALLTHROUGH; 3417 3418 case Decl::CXXConversion: 3419 case Decl::CXXDestructor: 3420 case Decl::CXXConstructor: 3421 valueKind = VK_RValue; 3422 break; 3423 } 3424 3425 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3426 /*FIXME: TemplateKWLoc*/ SourceLocation(), 3427 TemplateArgs); 3428 } 3429 } 3430 3431 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3432 SmallString<32> &Target) { 3433 Target.resize(CharByteWidth * (Source.size() + 1)); 3434 char *ResultPtr = &Target[0]; 3435 const llvm::UTF8 *ErrorPtr; 3436 bool success = 3437 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3438 (void)success; 3439 assert(success); 3440 Target.resize(ResultPtr - &Target[0]); 3441 } 3442 3443 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3444 PredefinedExpr::IdentKind IK) { 3445 // Pick the current block, lambda, captured statement or function. 3446 Decl *currentDecl = nullptr; 3447 if (const BlockScopeInfo *BSI = getCurBlock()) 3448 currentDecl = BSI->TheDecl; 3449 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3450 currentDecl = LSI->CallOperator; 3451 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3452 currentDecl = CSI->TheCapturedDecl; 3453 else 3454 currentDecl = getCurFunctionOrMethodDecl(); 3455 3456 if (!currentDecl) { 3457 Diag(Loc, diag::ext_predef_outside_function); 3458 currentDecl = Context.getTranslationUnitDecl(); 3459 } 3460 3461 QualType ResTy; 3462 StringLiteral *SL = nullptr; 3463 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3464 ResTy = Context.DependentTy; 3465 else { 3466 // Pre-defined identifiers are of type char[x], where x is the length of 3467 // the string. 3468 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3469 unsigned Length = Str.length(); 3470 3471 llvm::APInt LengthI(32, Length + 1); 3472 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3473 ResTy = 3474 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3475 SmallString<32> RawChars; 3476 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3477 Str, RawChars); 3478 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3479 ArrayType::Normal, 3480 /*IndexTypeQuals*/ 0); 3481 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3482 /*Pascal*/ false, ResTy, Loc); 3483 } else { 3484 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3485 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3486 ArrayType::Normal, 3487 /*IndexTypeQuals*/ 0); 3488 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3489 /*Pascal*/ false, ResTy, Loc); 3490 } 3491 } 3492 3493 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3494 } 3495 3496 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3497 PredefinedExpr::IdentKind IK; 3498 3499 switch (Kind) { 3500 default: llvm_unreachable("Unknown simple primary expr!"); 3501 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3502 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3503 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3504 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3505 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3506 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3507 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3508 } 3509 3510 return BuildPredefinedExpr(Loc, IK); 3511 } 3512 3513 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3514 SmallString<16> CharBuffer; 3515 bool Invalid = false; 3516 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3517 if (Invalid) 3518 return ExprError(); 3519 3520 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3521 PP, Tok.getKind()); 3522 if (Literal.hadError()) 3523 return ExprError(); 3524 3525 QualType Ty; 3526 if (Literal.isWide()) 3527 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3528 else if (Literal.isUTF8() && getLangOpts().Char8) 3529 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3530 else if (Literal.isUTF16()) 3531 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3532 else if (Literal.isUTF32()) 3533 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3534 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3535 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3536 else 3537 Ty = Context.CharTy; // 'x' -> char in C++ 3538 3539 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3540 if (Literal.isWide()) 3541 Kind = CharacterLiteral::Wide; 3542 else if (Literal.isUTF16()) 3543 Kind = CharacterLiteral::UTF16; 3544 else if (Literal.isUTF32()) 3545 Kind = CharacterLiteral::UTF32; 3546 else if (Literal.isUTF8()) 3547 Kind = CharacterLiteral::UTF8; 3548 3549 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3550 Tok.getLocation()); 3551 3552 if (Literal.getUDSuffix().empty()) 3553 return Lit; 3554 3555 // We're building a user-defined literal. 3556 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3557 SourceLocation UDSuffixLoc = 3558 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3559 3560 // Make sure we're allowed user-defined literals here. 3561 if (!UDLScope) 3562 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3563 3564 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3565 // operator "" X (ch) 3566 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3567 Lit, Tok.getLocation()); 3568 } 3569 3570 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3571 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3572 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3573 Context.IntTy, Loc); 3574 } 3575 3576 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3577 QualType Ty, SourceLocation Loc) { 3578 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3579 3580 using llvm::APFloat; 3581 APFloat Val(Format); 3582 3583 APFloat::opStatus result = Literal.GetFloatValue(Val); 3584 3585 // Overflow is always an error, but underflow is only an error if 3586 // we underflowed to zero (APFloat reports denormals as underflow). 3587 if ((result & APFloat::opOverflow) || 3588 ((result & APFloat::opUnderflow) && Val.isZero())) { 3589 unsigned diagnostic; 3590 SmallString<20> buffer; 3591 if (result & APFloat::opOverflow) { 3592 diagnostic = diag::warn_float_overflow; 3593 APFloat::getLargest(Format).toString(buffer); 3594 } else { 3595 diagnostic = diag::warn_float_underflow; 3596 APFloat::getSmallest(Format).toString(buffer); 3597 } 3598 3599 S.Diag(Loc, diagnostic) 3600 << Ty 3601 << StringRef(buffer.data(), buffer.size()); 3602 } 3603 3604 bool isExact = (result == APFloat::opOK); 3605 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3606 } 3607 3608 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3609 assert(E && "Invalid expression"); 3610 3611 if (E->isValueDependent()) 3612 return false; 3613 3614 QualType QT = E->getType(); 3615 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3616 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3617 return true; 3618 } 3619 3620 llvm::APSInt ValueAPS; 3621 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3622 3623 if (R.isInvalid()) 3624 return true; 3625 3626 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3627 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3628 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3629 << ValueAPS.toString(10) << ValueIsPositive; 3630 return true; 3631 } 3632 3633 return false; 3634 } 3635 3636 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3637 // Fast path for a single digit (which is quite common). A single digit 3638 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3639 if (Tok.getLength() == 1) { 3640 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3641 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3642 } 3643 3644 SmallString<128> SpellingBuffer; 3645 // NumericLiteralParser wants to overread by one character. Add padding to 3646 // the buffer in case the token is copied to the buffer. If getSpelling() 3647 // returns a StringRef to the memory buffer, it should have a null char at 3648 // the EOF, so it is also safe. 3649 SpellingBuffer.resize(Tok.getLength() + 1); 3650 3651 // Get the spelling of the token, which eliminates trigraphs, etc. 3652 bool Invalid = false; 3653 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3654 if (Invalid) 3655 return ExprError(); 3656 3657 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3658 PP.getSourceManager(), PP.getLangOpts(), 3659 PP.getTargetInfo(), PP.getDiagnostics()); 3660 if (Literal.hadError) 3661 return ExprError(); 3662 3663 if (Literal.hasUDSuffix()) { 3664 // We're building a user-defined literal. 3665 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3666 SourceLocation UDSuffixLoc = 3667 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3668 3669 // Make sure we're allowed user-defined literals here. 3670 if (!UDLScope) 3671 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3672 3673 QualType CookedTy; 3674 if (Literal.isFloatingLiteral()) { 3675 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3676 // long double, the literal is treated as a call of the form 3677 // operator "" X (f L) 3678 CookedTy = Context.LongDoubleTy; 3679 } else { 3680 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3681 // unsigned long long, the literal is treated as a call of the form 3682 // operator "" X (n ULL) 3683 CookedTy = Context.UnsignedLongLongTy; 3684 } 3685 3686 DeclarationName OpName = 3687 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3688 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3689 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3690 3691 SourceLocation TokLoc = Tok.getLocation(); 3692 3693 // Perform literal operator lookup to determine if we're building a raw 3694 // literal or a cooked one. 3695 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3696 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3697 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3698 /*AllowStringTemplatePack*/ false, 3699 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3700 case LOLR_ErrorNoDiagnostic: 3701 // Lookup failure for imaginary constants isn't fatal, there's still the 3702 // GNU extension producing _Complex types. 3703 break; 3704 case LOLR_Error: 3705 return ExprError(); 3706 case LOLR_Cooked: { 3707 Expr *Lit; 3708 if (Literal.isFloatingLiteral()) { 3709 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3710 } else { 3711 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3712 if (Literal.GetIntegerValue(ResultVal)) 3713 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3714 << /* Unsigned */ 1; 3715 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3716 Tok.getLocation()); 3717 } 3718 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3719 } 3720 3721 case LOLR_Raw: { 3722 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3723 // literal is treated as a call of the form 3724 // operator "" X ("n") 3725 unsigned Length = Literal.getUDSuffixOffset(); 3726 QualType StrTy = Context.getConstantArrayType( 3727 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3728 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3729 Expr *Lit = StringLiteral::Create( 3730 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3731 /*Pascal*/false, StrTy, &TokLoc, 1); 3732 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3733 } 3734 3735 case LOLR_Template: { 3736 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3737 // template), L is treated as a call fo the form 3738 // operator "" X <'c1', 'c2', ... 'ck'>() 3739 // where n is the source character sequence c1 c2 ... ck. 3740 TemplateArgumentListInfo ExplicitArgs; 3741 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3742 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3743 llvm::APSInt Value(CharBits, CharIsUnsigned); 3744 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3745 Value = TokSpelling[I]; 3746 TemplateArgument Arg(Context, Value, Context.CharTy); 3747 TemplateArgumentLocInfo ArgInfo; 3748 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3749 } 3750 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3751 &ExplicitArgs); 3752 } 3753 case LOLR_StringTemplatePack: 3754 llvm_unreachable("unexpected literal operator lookup result"); 3755 } 3756 } 3757 3758 Expr *Res; 3759 3760 if (Literal.isFixedPointLiteral()) { 3761 QualType Ty; 3762 3763 if (Literal.isAccum) { 3764 if (Literal.isHalf) { 3765 Ty = Context.ShortAccumTy; 3766 } else if (Literal.isLong) { 3767 Ty = Context.LongAccumTy; 3768 } else { 3769 Ty = Context.AccumTy; 3770 } 3771 } else if (Literal.isFract) { 3772 if (Literal.isHalf) { 3773 Ty = Context.ShortFractTy; 3774 } else if (Literal.isLong) { 3775 Ty = Context.LongFractTy; 3776 } else { 3777 Ty = Context.FractTy; 3778 } 3779 } 3780 3781 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3782 3783 bool isSigned = !Literal.isUnsigned; 3784 unsigned scale = Context.getFixedPointScale(Ty); 3785 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3786 3787 llvm::APInt Val(bit_width, 0, isSigned); 3788 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3789 bool ValIsZero = Val.isNullValue() && !Overflowed; 3790 3791 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3792 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3793 // Clause 6.4.4 - The value of a constant shall be in the range of 3794 // representable values for its type, with exception for constants of a 3795 // fract type with a value of exactly 1; such a constant shall denote 3796 // the maximal value for the type. 3797 --Val; 3798 else if (Val.ugt(MaxVal) || Overflowed) 3799 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3800 3801 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3802 Tok.getLocation(), scale); 3803 } else if (Literal.isFloatingLiteral()) { 3804 QualType Ty; 3805 if (Literal.isHalf){ 3806 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3807 Ty = Context.HalfTy; 3808 else { 3809 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3810 return ExprError(); 3811 } 3812 } else if (Literal.isFloat) 3813 Ty = Context.FloatTy; 3814 else if (Literal.isLong) 3815 Ty = Context.LongDoubleTy; 3816 else if (Literal.isFloat16) 3817 Ty = Context.Float16Ty; 3818 else if (Literal.isFloat128) 3819 Ty = Context.Float128Ty; 3820 else 3821 Ty = Context.DoubleTy; 3822 3823 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3824 3825 if (Ty == Context.DoubleTy) { 3826 if (getLangOpts().SinglePrecisionConstants) { 3827 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3828 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3829 } 3830 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3831 "cl_khr_fp64", getLangOpts())) { 3832 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3833 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3834 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3835 } 3836 } 3837 } else if (!Literal.isIntegerLiteral()) { 3838 return ExprError(); 3839 } else { 3840 QualType Ty; 3841 3842 // 'long long' is a C99 or C++11 feature. 3843 if (!getLangOpts().C99 && Literal.isLongLong) { 3844 if (getLangOpts().CPlusPlus) 3845 Diag(Tok.getLocation(), 3846 getLangOpts().CPlusPlus11 ? 3847 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3848 else 3849 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3850 } 3851 3852 // 'z/uz' literals are a C++2b feature. 3853 if (Literal.isSizeT) 3854 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3855 ? getLangOpts().CPlusPlus2b 3856 ? diag::warn_cxx20_compat_size_t_suffix 3857 : diag::ext_cxx2b_size_t_suffix 3858 : diag::err_cxx2b_size_t_suffix); 3859 3860 // Get the value in the widest-possible width. 3861 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3862 llvm::APInt ResultVal(MaxWidth, 0); 3863 3864 if (Literal.GetIntegerValue(ResultVal)) { 3865 // If this value didn't fit into uintmax_t, error and force to ull. 3866 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3867 << /* Unsigned */ 1; 3868 Ty = Context.UnsignedLongLongTy; 3869 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3870 "long long is not intmax_t?"); 3871 } else { 3872 // If this value fits into a ULL, try to figure out what else it fits into 3873 // according to the rules of C99 6.4.4.1p5. 3874 3875 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3876 // be an unsigned int. 3877 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3878 3879 // Check from smallest to largest, picking the smallest type we can. 3880 unsigned Width = 0; 3881 3882 // Microsoft specific integer suffixes are explicitly sized. 3883 if (Literal.MicrosoftInteger) { 3884 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3885 Width = 8; 3886 Ty = Context.CharTy; 3887 } else { 3888 Width = Literal.MicrosoftInteger; 3889 Ty = Context.getIntTypeForBitwidth(Width, 3890 /*Signed=*/!Literal.isUnsigned); 3891 } 3892 } 3893 3894 // Check C++2b size_t literals. 3895 if (Literal.isSizeT) { 3896 assert(!Literal.MicrosoftInteger && 3897 "size_t literals can't be Microsoft literals"); 3898 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 3899 Context.getTargetInfo().getSizeType()); 3900 3901 // Does it fit in size_t? 3902 if (ResultVal.isIntN(SizeTSize)) { 3903 // Does it fit in ssize_t? 3904 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 3905 Ty = Context.getSignedSizeType(); 3906 else if (AllowUnsigned) 3907 Ty = Context.getSizeType(); 3908 Width = SizeTSize; 3909 } 3910 } 3911 3912 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 3913 !Literal.isSizeT) { 3914 // Are int/unsigned possibilities? 3915 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3916 3917 // Does it fit in a unsigned int? 3918 if (ResultVal.isIntN(IntSize)) { 3919 // Does it fit in a signed int? 3920 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3921 Ty = Context.IntTy; 3922 else if (AllowUnsigned) 3923 Ty = Context.UnsignedIntTy; 3924 Width = IntSize; 3925 } 3926 } 3927 3928 // Are long/unsigned long possibilities? 3929 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 3930 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3931 3932 // Does it fit in a unsigned long? 3933 if (ResultVal.isIntN(LongSize)) { 3934 // Does it fit in a signed long? 3935 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3936 Ty = Context.LongTy; 3937 else if (AllowUnsigned) 3938 Ty = Context.UnsignedLongTy; 3939 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3940 // is compatible. 3941 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3942 const unsigned LongLongSize = 3943 Context.getTargetInfo().getLongLongWidth(); 3944 Diag(Tok.getLocation(), 3945 getLangOpts().CPlusPlus 3946 ? Literal.isLong 3947 ? diag::warn_old_implicitly_unsigned_long_cxx 3948 : /*C++98 UB*/ diag:: 3949 ext_old_implicitly_unsigned_long_cxx 3950 : diag::warn_old_implicitly_unsigned_long) 3951 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3952 : /*will be ill-formed*/ 1); 3953 Ty = Context.UnsignedLongTy; 3954 } 3955 Width = LongSize; 3956 } 3957 } 3958 3959 // Check long long if needed. 3960 if (Ty.isNull() && !Literal.isSizeT) { 3961 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3962 3963 // Does it fit in a unsigned long long? 3964 if (ResultVal.isIntN(LongLongSize)) { 3965 // Does it fit in a signed long long? 3966 // To be compatible with MSVC, hex integer literals ending with the 3967 // LL or i64 suffix are always signed in Microsoft mode. 3968 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3969 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3970 Ty = Context.LongLongTy; 3971 else if (AllowUnsigned) 3972 Ty = Context.UnsignedLongLongTy; 3973 Width = LongLongSize; 3974 } 3975 } 3976 3977 // If we still couldn't decide a type, we either have 'size_t' literal 3978 // that is out of range, or a decimal literal that does not fit in a 3979 // signed long long and has no U suffix. 3980 if (Ty.isNull()) { 3981 if (Literal.isSizeT) 3982 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 3983 << Literal.isUnsigned; 3984 else 3985 Diag(Tok.getLocation(), 3986 diag::ext_integer_literal_too_large_for_signed); 3987 Ty = Context.UnsignedLongLongTy; 3988 Width = Context.getTargetInfo().getLongLongWidth(); 3989 } 3990 3991 if (ResultVal.getBitWidth() != Width) 3992 ResultVal = ResultVal.trunc(Width); 3993 } 3994 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3995 } 3996 3997 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3998 if (Literal.isImaginary) { 3999 Res = new (Context) ImaginaryLiteral(Res, 4000 Context.getComplexType(Res->getType())); 4001 4002 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4003 } 4004 return Res; 4005 } 4006 4007 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4008 assert(E && "ActOnParenExpr() missing expr"); 4009 return new (Context) ParenExpr(L, R, E); 4010 } 4011 4012 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4013 SourceLocation Loc, 4014 SourceRange ArgRange) { 4015 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4016 // scalar or vector data type argument..." 4017 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4018 // type (C99 6.2.5p18) or void. 4019 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4020 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4021 << T << ArgRange; 4022 return true; 4023 } 4024 4025 assert((T->isVoidType() || !T->isIncompleteType()) && 4026 "Scalar types should always be complete"); 4027 return false; 4028 } 4029 4030 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4031 SourceLocation Loc, 4032 SourceRange ArgRange, 4033 UnaryExprOrTypeTrait TraitKind) { 4034 // Invalid types must be hard errors for SFINAE in C++. 4035 if (S.LangOpts.CPlusPlus) 4036 return true; 4037 4038 // C99 6.5.3.4p1: 4039 if (T->isFunctionType() && 4040 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4041 TraitKind == UETT_PreferredAlignOf)) { 4042 // sizeof(function)/alignof(function) is allowed as an extension. 4043 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4044 << getTraitSpelling(TraitKind) << ArgRange; 4045 return false; 4046 } 4047 4048 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4049 // this is an error (OpenCL v1.1 s6.3.k) 4050 if (T->isVoidType()) { 4051 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4052 : diag::ext_sizeof_alignof_void_type; 4053 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4054 return false; 4055 } 4056 4057 return true; 4058 } 4059 4060 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4061 SourceLocation Loc, 4062 SourceRange ArgRange, 4063 UnaryExprOrTypeTrait TraitKind) { 4064 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4065 // runtime doesn't allow it. 4066 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4067 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4068 << T << (TraitKind == UETT_SizeOf) 4069 << ArgRange; 4070 return true; 4071 } 4072 4073 return false; 4074 } 4075 4076 /// Check whether E is a pointer from a decayed array type (the decayed 4077 /// pointer type is equal to T) and emit a warning if it is. 4078 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4079 Expr *E) { 4080 // Don't warn if the operation changed the type. 4081 if (T != E->getType()) 4082 return; 4083 4084 // Now look for array decays. 4085 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4086 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4087 return; 4088 4089 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4090 << ICE->getType() 4091 << ICE->getSubExpr()->getType(); 4092 } 4093 4094 /// Check the constraints on expression operands to unary type expression 4095 /// and type traits. 4096 /// 4097 /// Completes any types necessary and validates the constraints on the operand 4098 /// expression. The logic mostly mirrors the type-based overload, but may modify 4099 /// the expression as it completes the type for that expression through template 4100 /// instantiation, etc. 4101 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4102 UnaryExprOrTypeTrait ExprKind) { 4103 QualType ExprTy = E->getType(); 4104 assert(!ExprTy->isReferenceType()); 4105 4106 bool IsUnevaluatedOperand = 4107 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4108 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4109 if (IsUnevaluatedOperand) { 4110 ExprResult Result = CheckUnevaluatedOperand(E); 4111 if (Result.isInvalid()) 4112 return true; 4113 E = Result.get(); 4114 } 4115 4116 // The operand for sizeof and alignof is in an unevaluated expression context, 4117 // so side effects could result in unintended consequences. 4118 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4119 // used to build SFINAE gadgets. 4120 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4121 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4122 !E->isInstantiationDependent() && 4123 E->HasSideEffects(Context, false)) 4124 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4125 4126 if (ExprKind == UETT_VecStep) 4127 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4128 E->getSourceRange()); 4129 4130 // Explicitly list some types as extensions. 4131 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4132 E->getSourceRange(), ExprKind)) 4133 return false; 4134 4135 // 'alignof' applied to an expression only requires the base element type of 4136 // the expression to be complete. 'sizeof' requires the expression's type to 4137 // be complete (and will attempt to complete it if it's an array of unknown 4138 // bound). 4139 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4140 if (RequireCompleteSizedType( 4141 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4142 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4143 getTraitSpelling(ExprKind), E->getSourceRange())) 4144 return true; 4145 } else { 4146 if (RequireCompleteSizedExprType( 4147 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4148 getTraitSpelling(ExprKind), E->getSourceRange())) 4149 return true; 4150 } 4151 4152 // Completing the expression's type may have changed it. 4153 ExprTy = E->getType(); 4154 assert(!ExprTy->isReferenceType()); 4155 4156 if (ExprTy->isFunctionType()) { 4157 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4158 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4159 return true; 4160 } 4161 4162 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4163 E->getSourceRange(), ExprKind)) 4164 return true; 4165 4166 if (ExprKind == UETT_SizeOf) { 4167 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4168 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4169 QualType OType = PVD->getOriginalType(); 4170 QualType Type = PVD->getType(); 4171 if (Type->isPointerType() && OType->isArrayType()) { 4172 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4173 << Type << OType; 4174 Diag(PVD->getLocation(), diag::note_declared_at); 4175 } 4176 } 4177 } 4178 4179 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4180 // decays into a pointer and returns an unintended result. This is most 4181 // likely a typo for "sizeof(array) op x". 4182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4183 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4184 BO->getLHS()); 4185 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4186 BO->getRHS()); 4187 } 4188 } 4189 4190 return false; 4191 } 4192 4193 /// Check the constraints on operands to unary expression and type 4194 /// traits. 4195 /// 4196 /// This will complete any types necessary, and validate the various constraints 4197 /// on those operands. 4198 /// 4199 /// The UsualUnaryConversions() function is *not* called by this routine. 4200 /// C99 6.3.2.1p[2-4] all state: 4201 /// Except when it is the operand of the sizeof operator ... 4202 /// 4203 /// C++ [expr.sizeof]p4 4204 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4205 /// standard conversions are not applied to the operand of sizeof. 4206 /// 4207 /// This policy is followed for all of the unary trait expressions. 4208 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4209 SourceLocation OpLoc, 4210 SourceRange ExprRange, 4211 UnaryExprOrTypeTrait ExprKind) { 4212 if (ExprType->isDependentType()) 4213 return false; 4214 4215 // C++ [expr.sizeof]p2: 4216 // When applied to a reference or a reference type, the result 4217 // is the size of the referenced type. 4218 // C++11 [expr.alignof]p3: 4219 // When alignof is applied to a reference type, the result 4220 // shall be the alignment of the referenced type. 4221 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4222 ExprType = Ref->getPointeeType(); 4223 4224 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4225 // When alignof or _Alignof is applied to an array type, the result 4226 // is the alignment of the element type. 4227 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4228 ExprKind == UETT_OpenMPRequiredSimdAlign) 4229 ExprType = Context.getBaseElementType(ExprType); 4230 4231 if (ExprKind == UETT_VecStep) 4232 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4233 4234 // Explicitly list some types as extensions. 4235 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4236 ExprKind)) 4237 return false; 4238 4239 if (RequireCompleteSizedType( 4240 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4241 getTraitSpelling(ExprKind), ExprRange)) 4242 return true; 4243 4244 if (ExprType->isFunctionType()) { 4245 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4246 << getTraitSpelling(ExprKind) << ExprRange; 4247 return true; 4248 } 4249 4250 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4251 ExprKind)) 4252 return true; 4253 4254 return false; 4255 } 4256 4257 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4258 // Cannot know anything else if the expression is dependent. 4259 if (E->isTypeDependent()) 4260 return false; 4261 4262 if (E->getObjectKind() == OK_BitField) { 4263 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4264 << 1 << E->getSourceRange(); 4265 return true; 4266 } 4267 4268 ValueDecl *D = nullptr; 4269 Expr *Inner = E->IgnoreParens(); 4270 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4271 D = DRE->getDecl(); 4272 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4273 D = ME->getMemberDecl(); 4274 } 4275 4276 // If it's a field, require the containing struct to have a 4277 // complete definition so that we can compute the layout. 4278 // 4279 // This can happen in C++11 onwards, either by naming the member 4280 // in a way that is not transformed into a member access expression 4281 // (in an unevaluated operand, for instance), or by naming the member 4282 // in a trailing-return-type. 4283 // 4284 // For the record, since __alignof__ on expressions is a GCC 4285 // extension, GCC seems to permit this but always gives the 4286 // nonsensical answer 0. 4287 // 4288 // We don't really need the layout here --- we could instead just 4289 // directly check for all the appropriate alignment-lowing 4290 // attributes --- but that would require duplicating a lot of 4291 // logic that just isn't worth duplicating for such a marginal 4292 // use-case. 4293 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4294 // Fast path this check, since we at least know the record has a 4295 // definition if we can find a member of it. 4296 if (!FD->getParent()->isCompleteDefinition()) { 4297 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4298 << E->getSourceRange(); 4299 return true; 4300 } 4301 4302 // Otherwise, if it's a field, and the field doesn't have 4303 // reference type, then it must have a complete type (or be a 4304 // flexible array member, which we explicitly want to 4305 // white-list anyway), which makes the following checks trivial. 4306 if (!FD->getType()->isReferenceType()) 4307 return false; 4308 } 4309 4310 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4311 } 4312 4313 bool Sema::CheckVecStepExpr(Expr *E) { 4314 E = E->IgnoreParens(); 4315 4316 // Cannot know anything else if the expression is dependent. 4317 if (E->isTypeDependent()) 4318 return false; 4319 4320 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4321 } 4322 4323 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4324 CapturingScopeInfo *CSI) { 4325 assert(T->isVariablyModifiedType()); 4326 assert(CSI != nullptr); 4327 4328 // We're going to walk down into the type and look for VLA expressions. 4329 do { 4330 const Type *Ty = T.getTypePtr(); 4331 switch (Ty->getTypeClass()) { 4332 #define TYPE(Class, Base) 4333 #define ABSTRACT_TYPE(Class, Base) 4334 #define NON_CANONICAL_TYPE(Class, Base) 4335 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4336 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4337 #include "clang/AST/TypeNodes.inc" 4338 T = QualType(); 4339 break; 4340 // These types are never variably-modified. 4341 case Type::Builtin: 4342 case Type::Complex: 4343 case Type::Vector: 4344 case Type::ExtVector: 4345 case Type::ConstantMatrix: 4346 case Type::Record: 4347 case Type::Enum: 4348 case Type::Elaborated: 4349 case Type::TemplateSpecialization: 4350 case Type::ObjCObject: 4351 case Type::ObjCInterface: 4352 case Type::ObjCObjectPointer: 4353 case Type::ObjCTypeParam: 4354 case Type::Pipe: 4355 case Type::ExtInt: 4356 llvm_unreachable("type class is never variably-modified!"); 4357 case Type::Adjusted: 4358 T = cast<AdjustedType>(Ty)->getOriginalType(); 4359 break; 4360 case Type::Decayed: 4361 T = cast<DecayedType>(Ty)->getPointeeType(); 4362 break; 4363 case Type::Pointer: 4364 T = cast<PointerType>(Ty)->getPointeeType(); 4365 break; 4366 case Type::BlockPointer: 4367 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4368 break; 4369 case Type::LValueReference: 4370 case Type::RValueReference: 4371 T = cast<ReferenceType>(Ty)->getPointeeType(); 4372 break; 4373 case Type::MemberPointer: 4374 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4375 break; 4376 case Type::ConstantArray: 4377 case Type::IncompleteArray: 4378 // Losing element qualification here is fine. 4379 T = cast<ArrayType>(Ty)->getElementType(); 4380 break; 4381 case Type::VariableArray: { 4382 // Losing element qualification here is fine. 4383 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4384 4385 // Unknown size indication requires no size computation. 4386 // Otherwise, evaluate and record it. 4387 auto Size = VAT->getSizeExpr(); 4388 if (Size && !CSI->isVLATypeCaptured(VAT) && 4389 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4390 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4391 4392 T = VAT->getElementType(); 4393 break; 4394 } 4395 case Type::FunctionProto: 4396 case Type::FunctionNoProto: 4397 T = cast<FunctionType>(Ty)->getReturnType(); 4398 break; 4399 case Type::Paren: 4400 case Type::TypeOf: 4401 case Type::UnaryTransform: 4402 case Type::Attributed: 4403 case Type::SubstTemplateTypeParm: 4404 case Type::MacroQualified: 4405 // Keep walking after single level desugaring. 4406 T = T.getSingleStepDesugaredType(Context); 4407 break; 4408 case Type::Typedef: 4409 T = cast<TypedefType>(Ty)->desugar(); 4410 break; 4411 case Type::Decltype: 4412 T = cast<DecltypeType>(Ty)->desugar(); 4413 break; 4414 case Type::Auto: 4415 case Type::DeducedTemplateSpecialization: 4416 T = cast<DeducedType>(Ty)->getDeducedType(); 4417 break; 4418 case Type::TypeOfExpr: 4419 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4420 break; 4421 case Type::Atomic: 4422 T = cast<AtomicType>(Ty)->getValueType(); 4423 break; 4424 } 4425 } while (!T.isNull() && T->isVariablyModifiedType()); 4426 } 4427 4428 /// Build a sizeof or alignof expression given a type operand. 4429 ExprResult 4430 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4431 SourceLocation OpLoc, 4432 UnaryExprOrTypeTrait ExprKind, 4433 SourceRange R) { 4434 if (!TInfo) 4435 return ExprError(); 4436 4437 QualType T = TInfo->getType(); 4438 4439 if (!T->isDependentType() && 4440 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4441 return ExprError(); 4442 4443 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4444 if (auto *TT = T->getAs<TypedefType>()) { 4445 for (auto I = FunctionScopes.rbegin(), 4446 E = std::prev(FunctionScopes.rend()); 4447 I != E; ++I) { 4448 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4449 if (CSI == nullptr) 4450 break; 4451 DeclContext *DC = nullptr; 4452 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4453 DC = LSI->CallOperator; 4454 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4455 DC = CRSI->TheCapturedDecl; 4456 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4457 DC = BSI->TheDecl; 4458 if (DC) { 4459 if (DC->containsDecl(TT->getDecl())) 4460 break; 4461 captureVariablyModifiedType(Context, T, CSI); 4462 } 4463 } 4464 } 4465 } 4466 4467 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4468 return new (Context) UnaryExprOrTypeTraitExpr( 4469 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4470 } 4471 4472 /// Build a sizeof or alignof expression given an expression 4473 /// operand. 4474 ExprResult 4475 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4476 UnaryExprOrTypeTrait ExprKind) { 4477 ExprResult PE = CheckPlaceholderExpr(E); 4478 if (PE.isInvalid()) 4479 return ExprError(); 4480 4481 E = PE.get(); 4482 4483 // Verify that the operand is valid. 4484 bool isInvalid = false; 4485 if (E->isTypeDependent()) { 4486 // Delay type-checking for type-dependent expressions. 4487 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4488 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4489 } else if (ExprKind == UETT_VecStep) { 4490 isInvalid = CheckVecStepExpr(E); 4491 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4492 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4493 isInvalid = true; 4494 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4495 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4496 isInvalid = true; 4497 } else { 4498 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4499 } 4500 4501 if (isInvalid) 4502 return ExprError(); 4503 4504 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4505 PE = TransformToPotentiallyEvaluated(E); 4506 if (PE.isInvalid()) return ExprError(); 4507 E = PE.get(); 4508 } 4509 4510 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4511 return new (Context) UnaryExprOrTypeTraitExpr( 4512 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4513 } 4514 4515 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4516 /// expr and the same for @c alignof and @c __alignof 4517 /// Note that the ArgRange is invalid if isType is false. 4518 ExprResult 4519 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4520 UnaryExprOrTypeTrait ExprKind, bool IsType, 4521 void *TyOrEx, SourceRange ArgRange) { 4522 // If error parsing type, ignore. 4523 if (!TyOrEx) return ExprError(); 4524 4525 if (IsType) { 4526 TypeSourceInfo *TInfo; 4527 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4528 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4529 } 4530 4531 Expr *ArgEx = (Expr *)TyOrEx; 4532 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4533 return Result; 4534 } 4535 4536 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4537 bool IsReal) { 4538 if (V.get()->isTypeDependent()) 4539 return S.Context.DependentTy; 4540 4541 // _Real and _Imag are only l-values for normal l-values. 4542 if (V.get()->getObjectKind() != OK_Ordinary) { 4543 V = S.DefaultLvalueConversion(V.get()); 4544 if (V.isInvalid()) 4545 return QualType(); 4546 } 4547 4548 // These operators return the element type of a complex type. 4549 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4550 return CT->getElementType(); 4551 4552 // Otherwise they pass through real integer and floating point types here. 4553 if (V.get()->getType()->isArithmeticType()) 4554 return V.get()->getType(); 4555 4556 // Test for placeholders. 4557 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4558 if (PR.isInvalid()) return QualType(); 4559 if (PR.get() != V.get()) { 4560 V = PR; 4561 return CheckRealImagOperand(S, V, Loc, IsReal); 4562 } 4563 4564 // Reject anything else. 4565 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4566 << (IsReal ? "__real" : "__imag"); 4567 return QualType(); 4568 } 4569 4570 4571 4572 ExprResult 4573 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4574 tok::TokenKind Kind, Expr *Input) { 4575 UnaryOperatorKind Opc; 4576 switch (Kind) { 4577 default: llvm_unreachable("Unknown unary op!"); 4578 case tok::plusplus: Opc = UO_PostInc; break; 4579 case tok::minusminus: Opc = UO_PostDec; break; 4580 } 4581 4582 // Since this might is a postfix expression, get rid of ParenListExprs. 4583 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4584 if (Result.isInvalid()) return ExprError(); 4585 Input = Result.get(); 4586 4587 return BuildUnaryOp(S, OpLoc, Opc, Input); 4588 } 4589 4590 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4591 /// 4592 /// \return true on error 4593 static bool checkArithmeticOnObjCPointer(Sema &S, 4594 SourceLocation opLoc, 4595 Expr *op) { 4596 assert(op->getType()->isObjCObjectPointerType()); 4597 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4598 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4599 return false; 4600 4601 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4602 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4603 << op->getSourceRange(); 4604 return true; 4605 } 4606 4607 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4608 auto *BaseNoParens = Base->IgnoreParens(); 4609 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4610 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4611 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4612 } 4613 4614 ExprResult 4615 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4616 Expr *idx, SourceLocation rbLoc) { 4617 if (base && !base->getType().isNull() && 4618 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4619 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4620 SourceLocation(), /*Length*/ nullptr, 4621 /*Stride=*/nullptr, rbLoc); 4622 4623 // Since this might be a postfix expression, get rid of ParenListExprs. 4624 if (isa<ParenListExpr>(base)) { 4625 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4626 if (result.isInvalid()) return ExprError(); 4627 base = result.get(); 4628 } 4629 4630 // Check if base and idx form a MatrixSubscriptExpr. 4631 // 4632 // Helper to check for comma expressions, which are not allowed as indices for 4633 // matrix subscript expressions. 4634 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4635 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4636 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4637 << SourceRange(base->getBeginLoc(), rbLoc); 4638 return true; 4639 } 4640 return false; 4641 }; 4642 // The matrix subscript operator ([][])is considered a single operator. 4643 // Separating the index expressions by parenthesis is not allowed. 4644 if (base->getType()->isSpecificPlaceholderType( 4645 BuiltinType::IncompleteMatrixIdx) && 4646 !isa<MatrixSubscriptExpr>(base)) { 4647 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4648 << SourceRange(base->getBeginLoc(), rbLoc); 4649 return ExprError(); 4650 } 4651 // If the base is a MatrixSubscriptExpr, try to create a new 4652 // MatrixSubscriptExpr. 4653 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4654 if (matSubscriptE) { 4655 if (CheckAndReportCommaError(idx)) 4656 return ExprError(); 4657 4658 assert(matSubscriptE->isIncomplete() && 4659 "base has to be an incomplete matrix subscript"); 4660 return CreateBuiltinMatrixSubscriptExpr( 4661 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc); 4662 } 4663 4664 // Handle any non-overload placeholder types in the base and index 4665 // expressions. We can't handle overloads here because the other 4666 // operand might be an overloadable type, in which case the overload 4667 // resolution for the operator overload should get the first crack 4668 // at the overload. 4669 bool IsMSPropertySubscript = false; 4670 if (base->getType()->isNonOverloadPlaceholderType()) { 4671 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4672 if (!IsMSPropertySubscript) { 4673 ExprResult result = CheckPlaceholderExpr(base); 4674 if (result.isInvalid()) 4675 return ExprError(); 4676 base = result.get(); 4677 } 4678 } 4679 4680 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4681 if (base->getType()->isMatrixType()) { 4682 if (CheckAndReportCommaError(idx)) 4683 return ExprError(); 4684 4685 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc); 4686 } 4687 4688 // A comma-expression as the index is deprecated in C++2a onwards. 4689 if (getLangOpts().CPlusPlus20 && 4690 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4691 (isa<CXXOperatorCallExpr>(idx) && 4692 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) { 4693 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4694 << SourceRange(base->getBeginLoc(), rbLoc); 4695 } 4696 4697 if (idx->getType()->isNonOverloadPlaceholderType()) { 4698 ExprResult result = CheckPlaceholderExpr(idx); 4699 if (result.isInvalid()) return ExprError(); 4700 idx = result.get(); 4701 } 4702 4703 // Build an unanalyzed expression if either operand is type-dependent. 4704 if (getLangOpts().CPlusPlus && 4705 (base->isTypeDependent() || idx->isTypeDependent())) { 4706 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4707 VK_LValue, OK_Ordinary, rbLoc); 4708 } 4709 4710 // MSDN, property (C++) 4711 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4712 // This attribute can also be used in the declaration of an empty array in a 4713 // class or structure definition. For example: 4714 // __declspec(property(get=GetX, put=PutX)) int x[]; 4715 // The above statement indicates that x[] can be used with one or more array 4716 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4717 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4718 if (IsMSPropertySubscript) { 4719 // Build MS property subscript expression if base is MS property reference 4720 // or MS property subscript. 4721 return new (Context) MSPropertySubscriptExpr( 4722 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4723 } 4724 4725 // Use C++ overloaded-operator rules if either operand has record 4726 // type. The spec says to do this if either type is *overloadable*, 4727 // but enum types can't declare subscript operators or conversion 4728 // operators, so there's nothing interesting for overload resolution 4729 // to do if there aren't any record types involved. 4730 // 4731 // ObjC pointers have their own subscripting logic that is not tied 4732 // to overload resolution and so should not take this path. 4733 if (getLangOpts().CPlusPlus && 4734 (base->getType()->isRecordType() || 4735 (!base->getType()->isObjCObjectPointerType() && 4736 idx->getType()->isRecordType()))) { 4737 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4738 } 4739 4740 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4741 4742 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4743 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4744 4745 return Res; 4746 } 4747 4748 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4749 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4750 InitializationKind Kind = 4751 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4752 InitializationSequence InitSeq(*this, Entity, Kind, E); 4753 return InitSeq.Perform(*this, Entity, Kind, E); 4754 } 4755 4756 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4757 Expr *ColumnIdx, 4758 SourceLocation RBLoc) { 4759 ExprResult BaseR = CheckPlaceholderExpr(Base); 4760 if (BaseR.isInvalid()) 4761 return BaseR; 4762 Base = BaseR.get(); 4763 4764 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4765 if (RowR.isInvalid()) 4766 return RowR; 4767 RowIdx = RowR.get(); 4768 4769 if (!ColumnIdx) 4770 return new (Context) MatrixSubscriptExpr( 4771 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4772 4773 // Build an unanalyzed expression if any of the operands is type-dependent. 4774 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4775 ColumnIdx->isTypeDependent()) 4776 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4777 Context.DependentTy, RBLoc); 4778 4779 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 4780 if (ColumnR.isInvalid()) 4781 return ColumnR; 4782 ColumnIdx = ColumnR.get(); 4783 4784 // Check that IndexExpr is an integer expression. If it is a constant 4785 // expression, check that it is less than Dim (= the number of elements in the 4786 // corresponding dimension). 4787 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 4788 bool IsColumnIdx) -> Expr * { 4789 if (!IndexExpr->getType()->isIntegerType() && 4790 !IndexExpr->isTypeDependent()) { 4791 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 4792 << IsColumnIdx; 4793 return nullptr; 4794 } 4795 4796 if (Optional<llvm::APSInt> Idx = 4797 IndexExpr->getIntegerConstantExpr(Context)) { 4798 if ((*Idx < 0 || *Idx >= Dim)) { 4799 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 4800 << IsColumnIdx << Dim; 4801 return nullptr; 4802 } 4803 } 4804 4805 ExprResult ConvExpr = 4806 tryConvertExprToType(IndexExpr, Context.getSizeType()); 4807 assert(!ConvExpr.isInvalid() && 4808 "should be able to convert any integer type to size type"); 4809 return ConvExpr.get(); 4810 }; 4811 4812 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 4813 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 4814 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 4815 if (!RowIdx || !ColumnIdx) 4816 return ExprError(); 4817 4818 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 4819 MTy->getElementType(), RBLoc); 4820 } 4821 4822 void Sema::CheckAddressOfNoDeref(const Expr *E) { 4823 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4824 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 4825 4826 // For expressions like `&(*s).b`, the base is recorded and what should be 4827 // checked. 4828 const MemberExpr *Member = nullptr; 4829 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 4830 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 4831 4832 LastRecord.PossibleDerefs.erase(StrippedExpr); 4833 } 4834 4835 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 4836 if (isUnevaluatedContext()) 4837 return; 4838 4839 QualType ResultTy = E->getType(); 4840 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 4841 4842 // Bail if the element is an array since it is not memory access. 4843 if (isa<ArrayType>(ResultTy)) 4844 return; 4845 4846 if (ResultTy->hasAttr(attr::NoDeref)) { 4847 LastRecord.PossibleDerefs.insert(E); 4848 return; 4849 } 4850 4851 // Check if the base type is a pointer to a member access of a struct 4852 // marked with noderef. 4853 const Expr *Base = E->getBase(); 4854 QualType BaseTy = Base->getType(); 4855 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 4856 // Not a pointer access 4857 return; 4858 4859 const MemberExpr *Member = nullptr; 4860 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 4861 Member->isArrow()) 4862 Base = Member->getBase(); 4863 4864 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 4865 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 4866 LastRecord.PossibleDerefs.insert(E); 4867 } 4868 } 4869 4870 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4871 Expr *LowerBound, 4872 SourceLocation ColonLocFirst, 4873 SourceLocation ColonLocSecond, 4874 Expr *Length, Expr *Stride, 4875 SourceLocation RBLoc) { 4876 if (Base->getType()->isPlaceholderType() && 4877 !Base->getType()->isSpecificPlaceholderType( 4878 BuiltinType::OMPArraySection)) { 4879 ExprResult Result = CheckPlaceholderExpr(Base); 4880 if (Result.isInvalid()) 4881 return ExprError(); 4882 Base = Result.get(); 4883 } 4884 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4885 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4886 if (Result.isInvalid()) 4887 return ExprError(); 4888 Result = DefaultLvalueConversion(Result.get()); 4889 if (Result.isInvalid()) 4890 return ExprError(); 4891 LowerBound = Result.get(); 4892 } 4893 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4894 ExprResult Result = CheckPlaceholderExpr(Length); 4895 if (Result.isInvalid()) 4896 return ExprError(); 4897 Result = DefaultLvalueConversion(Result.get()); 4898 if (Result.isInvalid()) 4899 return ExprError(); 4900 Length = Result.get(); 4901 } 4902 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 4903 ExprResult Result = CheckPlaceholderExpr(Stride); 4904 if (Result.isInvalid()) 4905 return ExprError(); 4906 Result = DefaultLvalueConversion(Result.get()); 4907 if (Result.isInvalid()) 4908 return ExprError(); 4909 Stride = Result.get(); 4910 } 4911 4912 // Build an unanalyzed expression if either operand is type-dependent. 4913 if (Base->isTypeDependent() || 4914 (LowerBound && 4915 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4916 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 4917 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 4918 return new (Context) OMPArraySectionExpr( 4919 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 4920 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 4921 } 4922 4923 // Perform default conversions. 4924 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4925 QualType ResultTy; 4926 if (OriginalTy->isAnyPointerType()) { 4927 ResultTy = OriginalTy->getPointeeType(); 4928 } else if (OriginalTy->isArrayType()) { 4929 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4930 } else { 4931 return ExprError( 4932 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4933 << Base->getSourceRange()); 4934 } 4935 // C99 6.5.2.1p1 4936 if (LowerBound) { 4937 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4938 LowerBound); 4939 if (Res.isInvalid()) 4940 return ExprError(Diag(LowerBound->getExprLoc(), 4941 diag::err_omp_typecheck_section_not_integer) 4942 << 0 << LowerBound->getSourceRange()); 4943 LowerBound = Res.get(); 4944 4945 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4946 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4947 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4948 << 0 << LowerBound->getSourceRange(); 4949 } 4950 if (Length) { 4951 auto Res = 4952 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4953 if (Res.isInvalid()) 4954 return ExprError(Diag(Length->getExprLoc(), 4955 diag::err_omp_typecheck_section_not_integer) 4956 << 1 << Length->getSourceRange()); 4957 Length = Res.get(); 4958 4959 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4960 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4961 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4962 << 1 << Length->getSourceRange(); 4963 } 4964 if (Stride) { 4965 ExprResult Res = 4966 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 4967 if (Res.isInvalid()) 4968 return ExprError(Diag(Stride->getExprLoc(), 4969 diag::err_omp_typecheck_section_not_integer) 4970 << 1 << Stride->getSourceRange()); 4971 Stride = Res.get(); 4972 4973 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4974 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4975 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 4976 << 1 << Stride->getSourceRange(); 4977 } 4978 4979 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4980 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4981 // type. Note that functions are not objects, and that (in C99 parlance) 4982 // incomplete types are not object types. 4983 if (ResultTy->isFunctionType()) { 4984 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4985 << ResultTy << Base->getSourceRange(); 4986 return ExprError(); 4987 } 4988 4989 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4990 diag::err_omp_section_incomplete_type, Base)) 4991 return ExprError(); 4992 4993 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4994 Expr::EvalResult Result; 4995 if (LowerBound->EvaluateAsInt(Result, Context)) { 4996 // OpenMP 5.0, [2.1.5 Array Sections] 4997 // The array section must be a subset of the original array. 4998 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4999 if (LowerBoundValue.isNegative()) { 5000 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5001 << LowerBound->getSourceRange(); 5002 return ExprError(); 5003 } 5004 } 5005 } 5006 5007 if (Length) { 5008 Expr::EvalResult Result; 5009 if (Length->EvaluateAsInt(Result, Context)) { 5010 // OpenMP 5.0, [2.1.5 Array Sections] 5011 // The length must evaluate to non-negative integers. 5012 llvm::APSInt LengthValue = Result.Val.getInt(); 5013 if (LengthValue.isNegative()) { 5014 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5015 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 5016 << Length->getSourceRange(); 5017 return ExprError(); 5018 } 5019 } 5020 } else if (ColonLocFirst.isValid() && 5021 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5022 !OriginalTy->isVariableArrayType()))) { 5023 // OpenMP 5.0, [2.1.5 Array Sections] 5024 // When the size of the array dimension is not known, the length must be 5025 // specified explicitly. 5026 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5027 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5028 return ExprError(); 5029 } 5030 5031 if (Stride) { 5032 Expr::EvalResult Result; 5033 if (Stride->EvaluateAsInt(Result, Context)) { 5034 // OpenMP 5.0, [2.1.5 Array Sections] 5035 // The stride must evaluate to a positive integer. 5036 llvm::APSInt StrideValue = Result.Val.getInt(); 5037 if (!StrideValue.isStrictlyPositive()) { 5038 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5039 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true) 5040 << Stride->getSourceRange(); 5041 return ExprError(); 5042 } 5043 } 5044 } 5045 5046 if (!Base->getType()->isSpecificPlaceholderType( 5047 BuiltinType::OMPArraySection)) { 5048 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5049 if (Result.isInvalid()) 5050 return ExprError(); 5051 Base = Result.get(); 5052 } 5053 return new (Context) OMPArraySectionExpr( 5054 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5055 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5056 } 5057 5058 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5059 SourceLocation RParenLoc, 5060 ArrayRef<Expr *> Dims, 5061 ArrayRef<SourceRange> Brackets) { 5062 if (Base->getType()->isPlaceholderType()) { 5063 ExprResult Result = CheckPlaceholderExpr(Base); 5064 if (Result.isInvalid()) 5065 return ExprError(); 5066 Result = DefaultLvalueConversion(Result.get()); 5067 if (Result.isInvalid()) 5068 return ExprError(); 5069 Base = Result.get(); 5070 } 5071 QualType BaseTy = Base->getType(); 5072 // Delay analysis of the types/expressions if instantiation/specialization is 5073 // required. 5074 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5075 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5076 LParenLoc, RParenLoc, Dims, Brackets); 5077 if (!BaseTy->isPointerType() || 5078 (!Base->isTypeDependent() && 5079 BaseTy->getPointeeType()->isIncompleteType())) 5080 return ExprError(Diag(Base->getExprLoc(), 5081 diag::err_omp_non_pointer_type_array_shaping_base) 5082 << Base->getSourceRange()); 5083 5084 SmallVector<Expr *, 4> NewDims; 5085 bool ErrorFound = false; 5086 for (Expr *Dim : Dims) { 5087 if (Dim->getType()->isPlaceholderType()) { 5088 ExprResult Result = CheckPlaceholderExpr(Dim); 5089 if (Result.isInvalid()) { 5090 ErrorFound = true; 5091 continue; 5092 } 5093 Result = DefaultLvalueConversion(Result.get()); 5094 if (Result.isInvalid()) { 5095 ErrorFound = true; 5096 continue; 5097 } 5098 Dim = Result.get(); 5099 } 5100 if (!Dim->isTypeDependent()) { 5101 ExprResult Result = 5102 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5103 if (Result.isInvalid()) { 5104 ErrorFound = true; 5105 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5106 << Dim->getSourceRange(); 5107 continue; 5108 } 5109 Dim = Result.get(); 5110 Expr::EvalResult EvResult; 5111 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5112 // OpenMP 5.0, [2.1.4 Array Shaping] 5113 // Each si is an integral type expression that must evaluate to a 5114 // positive integer. 5115 llvm::APSInt Value = EvResult.Val.getInt(); 5116 if (!Value.isStrictlyPositive()) { 5117 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5118 << Value.toString(/*Radix=*/10, /*Signed=*/true) 5119 << Dim->getSourceRange(); 5120 ErrorFound = true; 5121 continue; 5122 } 5123 } 5124 } 5125 NewDims.push_back(Dim); 5126 } 5127 if (ErrorFound) 5128 return ExprError(); 5129 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5130 LParenLoc, RParenLoc, NewDims, Brackets); 5131 } 5132 5133 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5134 SourceLocation LLoc, SourceLocation RLoc, 5135 ArrayRef<OMPIteratorData> Data) { 5136 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5137 bool IsCorrect = true; 5138 for (const OMPIteratorData &D : Data) { 5139 TypeSourceInfo *TInfo = nullptr; 5140 SourceLocation StartLoc; 5141 QualType DeclTy; 5142 if (!D.Type.getAsOpaquePtr()) { 5143 // OpenMP 5.0, 2.1.6 Iterators 5144 // In an iterator-specifier, if the iterator-type is not specified then 5145 // the type of that iterator is of int type. 5146 DeclTy = Context.IntTy; 5147 StartLoc = D.DeclIdentLoc; 5148 } else { 5149 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5150 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5151 } 5152 5153 bool IsDeclTyDependent = DeclTy->isDependentType() || 5154 DeclTy->containsUnexpandedParameterPack() || 5155 DeclTy->isInstantiationDependentType(); 5156 if (!IsDeclTyDependent) { 5157 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5158 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5159 // The iterator-type must be an integral or pointer type. 5160 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5161 << DeclTy; 5162 IsCorrect = false; 5163 continue; 5164 } 5165 if (DeclTy.isConstant(Context)) { 5166 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5167 // The iterator-type must not be const qualified. 5168 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5169 << DeclTy; 5170 IsCorrect = false; 5171 continue; 5172 } 5173 } 5174 5175 // Iterator declaration. 5176 assert(D.DeclIdent && "Identifier expected."); 5177 // Always try to create iterator declarator to avoid extra error messages 5178 // about unknown declarations use. 5179 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5180 D.DeclIdent, DeclTy, TInfo, SC_None); 5181 VD->setImplicit(); 5182 if (S) { 5183 // Check for conflicting previous declaration. 5184 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5185 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5186 ForVisibleRedeclaration); 5187 Previous.suppressDiagnostics(); 5188 LookupName(Previous, S); 5189 5190 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5191 /*AllowInlineNamespace=*/false); 5192 if (!Previous.empty()) { 5193 NamedDecl *Old = Previous.getRepresentativeDecl(); 5194 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5195 Diag(Old->getLocation(), diag::note_previous_definition); 5196 } else { 5197 PushOnScopeChains(VD, S); 5198 } 5199 } else { 5200 CurContext->addDecl(VD); 5201 } 5202 Expr *Begin = D.Range.Begin; 5203 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5204 ExprResult BeginRes = 5205 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5206 Begin = BeginRes.get(); 5207 } 5208 Expr *End = D.Range.End; 5209 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5210 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5211 End = EndRes.get(); 5212 } 5213 Expr *Step = D.Range.Step; 5214 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5215 if (!Step->getType()->isIntegralType(Context)) { 5216 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5217 << Step << Step->getSourceRange(); 5218 IsCorrect = false; 5219 continue; 5220 } 5221 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context); 5222 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5223 // If the step expression of a range-specification equals zero, the 5224 // behavior is unspecified. 5225 if (Result && Result->isNullValue()) { 5226 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5227 << Step << Step->getSourceRange(); 5228 IsCorrect = false; 5229 continue; 5230 } 5231 } 5232 if (!Begin || !End || !IsCorrect) { 5233 IsCorrect = false; 5234 continue; 5235 } 5236 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5237 IDElem.IteratorDecl = VD; 5238 IDElem.AssignmentLoc = D.AssignLoc; 5239 IDElem.Range.Begin = Begin; 5240 IDElem.Range.End = End; 5241 IDElem.Range.Step = Step; 5242 IDElem.ColonLoc = D.ColonLoc; 5243 IDElem.SecondColonLoc = D.SecColonLoc; 5244 } 5245 if (!IsCorrect) { 5246 // Invalidate all created iterator declarations if error is found. 5247 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5248 if (Decl *ID = D.IteratorDecl) 5249 ID->setInvalidDecl(); 5250 } 5251 return ExprError(); 5252 } 5253 SmallVector<OMPIteratorHelperData, 4> Helpers; 5254 if (!CurContext->isDependentContext()) { 5255 // Build number of ityeration for each iteration range. 5256 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5257 // ((Begini-Stepi-1-Endi) / -Stepi); 5258 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5259 // (Endi - Begini) 5260 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5261 D.Range.Begin); 5262 if(!Res.isUsable()) { 5263 IsCorrect = false; 5264 continue; 5265 } 5266 ExprResult St, St1; 5267 if (D.Range.Step) { 5268 St = D.Range.Step; 5269 // (Endi - Begini) + Stepi 5270 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5271 if (!Res.isUsable()) { 5272 IsCorrect = false; 5273 continue; 5274 } 5275 // (Endi - Begini) + Stepi - 1 5276 Res = 5277 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5278 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5279 if (!Res.isUsable()) { 5280 IsCorrect = false; 5281 continue; 5282 } 5283 // ((Endi - Begini) + Stepi - 1) / Stepi 5284 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5285 if (!Res.isUsable()) { 5286 IsCorrect = false; 5287 continue; 5288 } 5289 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5290 // (Begini - Endi) 5291 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5292 D.Range.Begin, D.Range.End); 5293 if (!Res1.isUsable()) { 5294 IsCorrect = false; 5295 continue; 5296 } 5297 // (Begini - Endi) - Stepi 5298 Res1 = 5299 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5300 if (!Res1.isUsable()) { 5301 IsCorrect = false; 5302 continue; 5303 } 5304 // (Begini - Endi) - Stepi - 1 5305 Res1 = 5306 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5307 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5308 if (!Res1.isUsable()) { 5309 IsCorrect = false; 5310 continue; 5311 } 5312 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5313 Res1 = 5314 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5315 if (!Res1.isUsable()) { 5316 IsCorrect = false; 5317 continue; 5318 } 5319 // Stepi > 0. 5320 ExprResult CmpRes = 5321 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5322 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5323 if (!CmpRes.isUsable()) { 5324 IsCorrect = false; 5325 continue; 5326 } 5327 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5328 Res.get(), Res1.get()); 5329 if (!Res.isUsable()) { 5330 IsCorrect = false; 5331 continue; 5332 } 5333 } 5334 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5335 if (!Res.isUsable()) { 5336 IsCorrect = false; 5337 continue; 5338 } 5339 5340 // Build counter update. 5341 // Build counter. 5342 auto *CounterVD = 5343 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5344 D.IteratorDecl->getBeginLoc(), nullptr, 5345 Res.get()->getType(), nullptr, SC_None); 5346 CounterVD->setImplicit(); 5347 ExprResult RefRes = 5348 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5349 D.IteratorDecl->getBeginLoc()); 5350 // Build counter update. 5351 // I = Begini + counter * Stepi; 5352 ExprResult UpdateRes; 5353 if (D.Range.Step) { 5354 UpdateRes = CreateBuiltinBinOp( 5355 D.AssignmentLoc, BO_Mul, 5356 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5357 } else { 5358 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5359 } 5360 if (!UpdateRes.isUsable()) { 5361 IsCorrect = false; 5362 continue; 5363 } 5364 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5365 UpdateRes.get()); 5366 if (!UpdateRes.isUsable()) { 5367 IsCorrect = false; 5368 continue; 5369 } 5370 ExprResult VDRes = 5371 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5372 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5373 D.IteratorDecl->getBeginLoc()); 5374 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5375 UpdateRes.get()); 5376 if (!UpdateRes.isUsable()) { 5377 IsCorrect = false; 5378 continue; 5379 } 5380 UpdateRes = 5381 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5382 if (!UpdateRes.isUsable()) { 5383 IsCorrect = false; 5384 continue; 5385 } 5386 ExprResult CounterUpdateRes = 5387 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5388 if (!CounterUpdateRes.isUsable()) { 5389 IsCorrect = false; 5390 continue; 5391 } 5392 CounterUpdateRes = 5393 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5394 if (!CounterUpdateRes.isUsable()) { 5395 IsCorrect = false; 5396 continue; 5397 } 5398 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5399 HD.CounterVD = CounterVD; 5400 HD.Upper = Res.get(); 5401 HD.Update = UpdateRes.get(); 5402 HD.CounterUpdate = CounterUpdateRes.get(); 5403 } 5404 } else { 5405 Helpers.assign(ID.size(), {}); 5406 } 5407 if (!IsCorrect) { 5408 // Invalidate all created iterator declarations if error is found. 5409 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5410 if (Decl *ID = D.IteratorDecl) 5411 ID->setInvalidDecl(); 5412 } 5413 return ExprError(); 5414 } 5415 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5416 LLoc, RLoc, ID, Helpers); 5417 } 5418 5419 ExprResult 5420 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5421 Expr *Idx, SourceLocation RLoc) { 5422 Expr *LHSExp = Base; 5423 Expr *RHSExp = Idx; 5424 5425 ExprValueKind VK = VK_LValue; 5426 ExprObjectKind OK = OK_Ordinary; 5427 5428 // Per C++ core issue 1213, the result is an xvalue if either operand is 5429 // a non-lvalue array, and an lvalue otherwise. 5430 if (getLangOpts().CPlusPlus11) { 5431 for (auto *Op : {LHSExp, RHSExp}) { 5432 Op = Op->IgnoreImplicit(); 5433 if (Op->getType()->isArrayType() && !Op->isLValue()) 5434 VK = VK_XValue; 5435 } 5436 } 5437 5438 // Perform default conversions. 5439 if (!LHSExp->getType()->getAs<VectorType>()) { 5440 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5441 if (Result.isInvalid()) 5442 return ExprError(); 5443 LHSExp = Result.get(); 5444 } 5445 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5446 if (Result.isInvalid()) 5447 return ExprError(); 5448 RHSExp = Result.get(); 5449 5450 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5451 5452 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5453 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5454 // in the subscript position. As a result, we need to derive the array base 5455 // and index from the expression types. 5456 Expr *BaseExpr, *IndexExpr; 5457 QualType ResultType; 5458 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5459 BaseExpr = LHSExp; 5460 IndexExpr = RHSExp; 5461 ResultType = Context.DependentTy; 5462 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5463 BaseExpr = LHSExp; 5464 IndexExpr = RHSExp; 5465 ResultType = PTy->getPointeeType(); 5466 } else if (const ObjCObjectPointerType *PTy = 5467 LHSTy->getAs<ObjCObjectPointerType>()) { 5468 BaseExpr = LHSExp; 5469 IndexExpr = RHSExp; 5470 5471 // Use custom logic if this should be the pseudo-object subscript 5472 // expression. 5473 if (!LangOpts.isSubscriptPointerArithmetic()) 5474 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5475 nullptr); 5476 5477 ResultType = PTy->getPointeeType(); 5478 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5479 // Handle the uncommon case of "123[Ptr]". 5480 BaseExpr = RHSExp; 5481 IndexExpr = LHSExp; 5482 ResultType = PTy->getPointeeType(); 5483 } else if (const ObjCObjectPointerType *PTy = 5484 RHSTy->getAs<ObjCObjectPointerType>()) { 5485 // Handle the uncommon case of "123[Ptr]". 5486 BaseExpr = RHSExp; 5487 IndexExpr = LHSExp; 5488 ResultType = PTy->getPointeeType(); 5489 if (!LangOpts.isSubscriptPointerArithmetic()) { 5490 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5491 << ResultType << BaseExpr->getSourceRange(); 5492 return ExprError(); 5493 } 5494 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5495 BaseExpr = LHSExp; // vectors: V[123] 5496 IndexExpr = RHSExp; 5497 // We apply C++ DR1213 to vector subscripting too. 5498 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 5499 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5500 if (Materialized.isInvalid()) 5501 return ExprError(); 5502 LHSExp = Materialized.get(); 5503 } 5504 VK = LHSExp->getValueKind(); 5505 if (VK != VK_RValue) 5506 OK = OK_VectorComponent; 5507 5508 ResultType = VTy->getElementType(); 5509 QualType BaseType = BaseExpr->getType(); 5510 Qualifiers BaseQuals = BaseType.getQualifiers(); 5511 Qualifiers MemberQuals = ResultType.getQualifiers(); 5512 Qualifiers Combined = BaseQuals + MemberQuals; 5513 if (Combined != MemberQuals) 5514 ResultType = Context.getQualifiedType(ResultType, Combined); 5515 } else if (LHSTy->isArrayType()) { 5516 // If we see an array that wasn't promoted by 5517 // DefaultFunctionArrayLvalueConversion, it must be an array that 5518 // wasn't promoted because of the C90 rule that doesn't 5519 // allow promoting non-lvalue arrays. Warn, then 5520 // force the promotion here. 5521 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5522 << LHSExp->getSourceRange(); 5523 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5524 CK_ArrayToPointerDecay).get(); 5525 LHSTy = LHSExp->getType(); 5526 5527 BaseExpr = LHSExp; 5528 IndexExpr = RHSExp; 5529 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5530 } else if (RHSTy->isArrayType()) { 5531 // Same as previous, except for 123[f().a] case 5532 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5533 << RHSExp->getSourceRange(); 5534 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5535 CK_ArrayToPointerDecay).get(); 5536 RHSTy = RHSExp->getType(); 5537 5538 BaseExpr = RHSExp; 5539 IndexExpr = LHSExp; 5540 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5541 } else { 5542 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5543 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5544 } 5545 // C99 6.5.2.1p1 5546 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5547 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5548 << IndexExpr->getSourceRange()); 5549 5550 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5551 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5552 && !IndexExpr->isTypeDependent()) 5553 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5554 5555 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5556 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5557 // type. Note that Functions are not objects, and that (in C99 parlance) 5558 // incomplete types are not object types. 5559 if (ResultType->isFunctionType()) { 5560 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5561 << ResultType << BaseExpr->getSourceRange(); 5562 return ExprError(); 5563 } 5564 5565 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5566 // GNU extension: subscripting on pointer to void 5567 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5568 << BaseExpr->getSourceRange(); 5569 5570 // C forbids expressions of unqualified void type from being l-values. 5571 // See IsCForbiddenLValueType. 5572 if (!ResultType.hasQualifiers()) VK = VK_RValue; 5573 } else if (!ResultType->isDependentType() && 5574 RequireCompleteSizedType( 5575 LLoc, ResultType, 5576 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5577 return ExprError(); 5578 5579 assert(VK == VK_RValue || LangOpts.CPlusPlus || 5580 !ResultType.isCForbiddenLValueType()); 5581 5582 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5583 FunctionScopes.size() > 1) { 5584 if (auto *TT = 5585 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5586 for (auto I = FunctionScopes.rbegin(), 5587 E = std::prev(FunctionScopes.rend()); 5588 I != E; ++I) { 5589 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5590 if (CSI == nullptr) 5591 break; 5592 DeclContext *DC = nullptr; 5593 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5594 DC = LSI->CallOperator; 5595 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5596 DC = CRSI->TheCapturedDecl; 5597 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5598 DC = BSI->TheDecl; 5599 if (DC) { 5600 if (DC->containsDecl(TT->getDecl())) 5601 break; 5602 captureVariablyModifiedType( 5603 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5604 } 5605 } 5606 } 5607 } 5608 5609 return new (Context) 5610 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5611 } 5612 5613 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5614 ParmVarDecl *Param) { 5615 if (Param->hasUnparsedDefaultArg()) { 5616 // If we've already cleared out the location for the default argument, 5617 // that means we're parsing it right now. 5618 if (!UnparsedDefaultArgLocs.count(Param)) { 5619 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5620 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5621 Param->setInvalidDecl(); 5622 return true; 5623 } 5624 5625 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5626 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5627 Diag(UnparsedDefaultArgLocs[Param], 5628 diag::note_default_argument_declared_here); 5629 return true; 5630 } 5631 5632 if (Param->hasUninstantiatedDefaultArg() && 5633 InstantiateDefaultArgument(CallLoc, FD, Param)) 5634 return true; 5635 5636 assert(Param->hasInit() && "default argument but no initializer?"); 5637 5638 // If the default expression creates temporaries, we need to 5639 // push them to the current stack of expression temporaries so they'll 5640 // be properly destroyed. 5641 // FIXME: We should really be rebuilding the default argument with new 5642 // bound temporaries; see the comment in PR5810. 5643 // We don't need to do that with block decls, though, because 5644 // blocks in default argument expression can never capture anything. 5645 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 5646 // Set the "needs cleanups" bit regardless of whether there are 5647 // any explicit objects. 5648 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 5649 5650 // Append all the objects to the cleanup list. Right now, this 5651 // should always be a no-op, because blocks in default argument 5652 // expressions should never be able to capture anything. 5653 assert(!Init->getNumObjects() && 5654 "default argument expression has capturing blocks?"); 5655 } 5656 5657 // We already type-checked the argument, so we know it works. 5658 // Just mark all of the declarations in this potentially-evaluated expression 5659 // as being "referenced". 5660 EnterExpressionEvaluationContext EvalContext( 5661 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5662 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 5663 /*SkipLocalVariables=*/true); 5664 return false; 5665 } 5666 5667 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5668 FunctionDecl *FD, ParmVarDecl *Param) { 5669 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5670 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 5671 return ExprError(); 5672 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext); 5673 } 5674 5675 Sema::VariadicCallType 5676 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 5677 Expr *Fn) { 5678 if (Proto && Proto->isVariadic()) { 5679 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 5680 return VariadicConstructor; 5681 else if (Fn && Fn->getType()->isBlockPointerType()) 5682 return VariadicBlock; 5683 else if (FDecl) { 5684 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5685 if (Method->isInstance()) 5686 return VariadicMethod; 5687 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 5688 return VariadicMethod; 5689 return VariadicFunction; 5690 } 5691 return VariadicDoesNotApply; 5692 } 5693 5694 namespace { 5695 class FunctionCallCCC final : public FunctionCallFilterCCC { 5696 public: 5697 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 5698 unsigned NumArgs, MemberExpr *ME) 5699 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 5700 FunctionName(FuncName) {} 5701 5702 bool ValidateCandidate(const TypoCorrection &candidate) override { 5703 if (!candidate.getCorrectionSpecifier() || 5704 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 5705 return false; 5706 } 5707 5708 return FunctionCallFilterCCC::ValidateCandidate(candidate); 5709 } 5710 5711 std::unique_ptr<CorrectionCandidateCallback> clone() override { 5712 return std::make_unique<FunctionCallCCC>(*this); 5713 } 5714 5715 private: 5716 const IdentifierInfo *const FunctionName; 5717 }; 5718 } 5719 5720 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 5721 FunctionDecl *FDecl, 5722 ArrayRef<Expr *> Args) { 5723 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 5724 DeclarationName FuncName = FDecl->getDeclName(); 5725 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 5726 5727 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 5728 if (TypoCorrection Corrected = S.CorrectTypo( 5729 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 5730 S.getScopeForContext(S.CurContext), nullptr, CCC, 5731 Sema::CTK_ErrorRecovery)) { 5732 if (NamedDecl *ND = Corrected.getFoundDecl()) { 5733 if (Corrected.isOverloaded()) { 5734 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 5735 OverloadCandidateSet::iterator Best; 5736 for (NamedDecl *CD : Corrected) { 5737 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 5738 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 5739 OCS); 5740 } 5741 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 5742 case OR_Success: 5743 ND = Best->FoundDecl; 5744 Corrected.setCorrectionDecl(ND); 5745 break; 5746 default: 5747 break; 5748 } 5749 } 5750 ND = ND->getUnderlyingDecl(); 5751 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 5752 return Corrected; 5753 } 5754 } 5755 return TypoCorrection(); 5756 } 5757 5758 /// ConvertArgumentsForCall - Converts the arguments specified in 5759 /// Args/NumArgs to the parameter types of the function FDecl with 5760 /// function prototype Proto. Call is the call expression itself, and 5761 /// Fn is the function expression. For a C++ member function, this 5762 /// routine does not attempt to convert the object argument. Returns 5763 /// true if the call is ill-formed. 5764 bool 5765 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5766 FunctionDecl *FDecl, 5767 const FunctionProtoType *Proto, 5768 ArrayRef<Expr *> Args, 5769 SourceLocation RParenLoc, 5770 bool IsExecConfig) { 5771 // Bail out early if calling a builtin with custom typechecking. 5772 if (FDecl) 5773 if (unsigned ID = FDecl->getBuiltinID()) 5774 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 5775 return false; 5776 5777 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 5778 // assignment, to the types of the corresponding parameter, ... 5779 unsigned NumParams = Proto->getNumParams(); 5780 bool Invalid = false; 5781 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 5782 unsigned FnKind = Fn->getType()->isBlockPointerType() 5783 ? 1 /* block */ 5784 : (IsExecConfig ? 3 /* kernel function (exec config) */ 5785 : 0 /* function */); 5786 5787 // If too few arguments are available (and we don't have default 5788 // arguments for the remaining parameters), don't make the call. 5789 if (Args.size() < NumParams) { 5790 if (Args.size() < MinArgs) { 5791 TypoCorrection TC; 5792 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5793 unsigned diag_id = 5794 MinArgs == NumParams && !Proto->isVariadic() 5795 ? diag::err_typecheck_call_too_few_args_suggest 5796 : diag::err_typecheck_call_too_few_args_at_least_suggest; 5797 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 5798 << static_cast<unsigned>(Args.size()) 5799 << TC.getCorrectionRange()); 5800 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 5801 Diag(RParenLoc, 5802 MinArgs == NumParams && !Proto->isVariadic() 5803 ? diag::err_typecheck_call_too_few_args_one 5804 : diag::err_typecheck_call_too_few_args_at_least_one) 5805 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 5806 else 5807 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 5808 ? diag::err_typecheck_call_too_few_args 5809 : diag::err_typecheck_call_too_few_args_at_least) 5810 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 5811 << Fn->getSourceRange(); 5812 5813 // Emit the location of the prototype. 5814 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5815 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5816 5817 return true; 5818 } 5819 // We reserve space for the default arguments when we create 5820 // the call expression, before calling ConvertArgumentsForCall. 5821 assert((Call->getNumArgs() == NumParams) && 5822 "We should have reserved space for the default arguments before!"); 5823 } 5824 5825 // If too many are passed and not variadic, error on the extras and drop 5826 // them. 5827 if (Args.size() > NumParams) { 5828 if (!Proto->isVariadic()) { 5829 TypoCorrection TC; 5830 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 5831 unsigned diag_id = 5832 MinArgs == NumParams && !Proto->isVariadic() 5833 ? diag::err_typecheck_call_too_many_args_suggest 5834 : diag::err_typecheck_call_too_many_args_at_most_suggest; 5835 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 5836 << static_cast<unsigned>(Args.size()) 5837 << TC.getCorrectionRange()); 5838 } else if (NumParams == 1 && FDecl && 5839 FDecl->getParamDecl(0)->getDeclName()) 5840 Diag(Args[NumParams]->getBeginLoc(), 5841 MinArgs == NumParams 5842 ? diag::err_typecheck_call_too_many_args_one 5843 : diag::err_typecheck_call_too_many_args_at_most_one) 5844 << FnKind << FDecl->getParamDecl(0) 5845 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 5846 << SourceRange(Args[NumParams]->getBeginLoc(), 5847 Args.back()->getEndLoc()); 5848 else 5849 Diag(Args[NumParams]->getBeginLoc(), 5850 MinArgs == NumParams 5851 ? diag::err_typecheck_call_too_many_args 5852 : diag::err_typecheck_call_too_many_args_at_most) 5853 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 5854 << Fn->getSourceRange() 5855 << SourceRange(Args[NumParams]->getBeginLoc(), 5856 Args.back()->getEndLoc()); 5857 5858 // Emit the location of the prototype. 5859 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 5860 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 5861 5862 // This deletes the extra arguments. 5863 Call->shrinkNumArgs(NumParams); 5864 return true; 5865 } 5866 } 5867 SmallVector<Expr *, 8> AllArgs; 5868 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 5869 5870 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 5871 AllArgs, CallType); 5872 if (Invalid) 5873 return true; 5874 unsigned TotalNumArgs = AllArgs.size(); 5875 for (unsigned i = 0; i < TotalNumArgs; ++i) 5876 Call->setArg(i, AllArgs[i]); 5877 5878 return false; 5879 } 5880 5881 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 5882 const FunctionProtoType *Proto, 5883 unsigned FirstParam, ArrayRef<Expr *> Args, 5884 SmallVectorImpl<Expr *> &AllArgs, 5885 VariadicCallType CallType, bool AllowExplicit, 5886 bool IsListInitialization) { 5887 unsigned NumParams = Proto->getNumParams(); 5888 bool Invalid = false; 5889 size_t ArgIx = 0; 5890 // Continue to check argument types (even if we have too few/many args). 5891 for (unsigned i = FirstParam; i < NumParams; i++) { 5892 QualType ProtoArgType = Proto->getParamType(i); 5893 5894 Expr *Arg; 5895 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 5896 if (ArgIx < Args.size()) { 5897 Arg = Args[ArgIx++]; 5898 5899 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 5900 diag::err_call_incomplete_argument, Arg)) 5901 return true; 5902 5903 // Strip the unbridged-cast placeholder expression off, if applicable. 5904 bool CFAudited = false; 5905 if (Arg->getType() == Context.ARCUnbridgedCastTy && 5906 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5907 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5908 Arg = stripARCUnbridgedCast(Arg); 5909 else if (getLangOpts().ObjCAutoRefCount && 5910 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 5911 (!Param || !Param->hasAttr<CFConsumedAttr>())) 5912 CFAudited = true; 5913 5914 if (Proto->getExtParameterInfo(i).isNoEscape()) 5915 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 5916 BE->getBlockDecl()->setDoesNotEscape(); 5917 5918 InitializedEntity Entity = 5919 Param ? InitializedEntity::InitializeParameter(Context, Param, 5920 ProtoArgType) 5921 : InitializedEntity::InitializeParameter( 5922 Context, ProtoArgType, Proto->isParamConsumed(i)); 5923 5924 // Remember that parameter belongs to a CF audited API. 5925 if (CFAudited) 5926 Entity.setParameterCFAudited(); 5927 5928 ExprResult ArgE = PerformCopyInitialization( 5929 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 5930 if (ArgE.isInvalid()) 5931 return true; 5932 5933 Arg = ArgE.getAs<Expr>(); 5934 } else { 5935 assert(Param && "can't use default arguments without a known callee"); 5936 5937 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 5938 if (ArgExpr.isInvalid()) 5939 return true; 5940 5941 Arg = ArgExpr.getAs<Expr>(); 5942 } 5943 5944 // Check for array bounds violations for each argument to the call. This 5945 // check only triggers warnings when the argument isn't a more complex Expr 5946 // with its own checking, such as a BinaryOperator. 5947 CheckArrayAccess(Arg); 5948 5949 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5950 CheckStaticArrayArgument(CallLoc, Param, Arg); 5951 5952 AllArgs.push_back(Arg); 5953 } 5954 5955 // If this is a variadic call, handle args passed through "...". 5956 if (CallType != VariadicDoesNotApply) { 5957 // Assume that extern "C" functions with variadic arguments that 5958 // return __unknown_anytype aren't *really* variadic. 5959 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5960 FDecl->isExternC()) { 5961 for (Expr *A : Args.slice(ArgIx)) { 5962 QualType paramType; // ignored 5963 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5964 Invalid |= arg.isInvalid(); 5965 AllArgs.push_back(arg.get()); 5966 } 5967 5968 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5969 } else { 5970 for (Expr *A : Args.slice(ArgIx)) { 5971 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5972 Invalid |= Arg.isInvalid(); 5973 AllArgs.push_back(Arg.get()); 5974 } 5975 } 5976 5977 // Check for array bounds violations. 5978 for (Expr *A : Args.slice(ArgIx)) 5979 CheckArrayAccess(A); 5980 } 5981 return Invalid; 5982 } 5983 5984 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5985 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5986 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5987 TL = DTL.getOriginalLoc(); 5988 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5989 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5990 << ATL.getLocalSourceRange(); 5991 } 5992 5993 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5994 /// array parameter, check that it is non-null, and that if it is formed by 5995 /// array-to-pointer decay, the underlying array is sufficiently large. 5996 /// 5997 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5998 /// array type derivation, then for each call to the function, the value of the 5999 /// corresponding actual argument shall provide access to the first element of 6000 /// an array with at least as many elements as specified by the size expression. 6001 void 6002 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6003 ParmVarDecl *Param, 6004 const Expr *ArgExpr) { 6005 // Static array parameters are not supported in C++. 6006 if (!Param || getLangOpts().CPlusPlus) 6007 return; 6008 6009 QualType OrigTy = Param->getOriginalType(); 6010 6011 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6012 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6013 return; 6014 6015 if (ArgExpr->isNullPointerConstant(Context, 6016 Expr::NPC_NeverValueDependent)) { 6017 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6018 DiagnoseCalleeStaticArrayParam(*this, Param); 6019 return; 6020 } 6021 6022 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6023 if (!CAT) 6024 return; 6025 6026 const ConstantArrayType *ArgCAT = 6027 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6028 if (!ArgCAT) 6029 return; 6030 6031 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6032 ArgCAT->getElementType())) { 6033 if (ArgCAT->getSize().ult(CAT->getSize())) { 6034 Diag(CallLoc, diag::warn_static_array_too_small) 6035 << ArgExpr->getSourceRange() 6036 << (unsigned)ArgCAT->getSize().getZExtValue() 6037 << (unsigned)CAT->getSize().getZExtValue() << 0; 6038 DiagnoseCalleeStaticArrayParam(*this, Param); 6039 } 6040 return; 6041 } 6042 6043 Optional<CharUnits> ArgSize = 6044 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6045 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT); 6046 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6047 Diag(CallLoc, diag::warn_static_array_too_small) 6048 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6049 << (unsigned)ParmSize->getQuantity() << 1; 6050 DiagnoseCalleeStaticArrayParam(*this, Param); 6051 } 6052 } 6053 6054 /// Given a function expression of unknown-any type, try to rebuild it 6055 /// to have a function type. 6056 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6057 6058 /// Is the given type a placeholder that we need to lower out 6059 /// immediately during argument processing? 6060 static bool isPlaceholderToRemoveAsArg(QualType type) { 6061 // Placeholders are never sugared. 6062 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6063 if (!placeholder) return false; 6064 6065 switch (placeholder->getKind()) { 6066 // Ignore all the non-placeholder types. 6067 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6068 case BuiltinType::Id: 6069 #include "clang/Basic/OpenCLImageTypes.def" 6070 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6071 case BuiltinType::Id: 6072 #include "clang/Basic/OpenCLExtensionTypes.def" 6073 // In practice we'll never use this, since all SVE types are sugared 6074 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6075 #define SVE_TYPE(Name, Id, SingletonId) \ 6076 case BuiltinType::Id: 6077 #include "clang/Basic/AArch64SVEACLETypes.def" 6078 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6079 case BuiltinType::Id: 6080 #include "clang/Basic/PPCTypes.def" 6081 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6082 #include "clang/Basic/RISCVVTypes.def" 6083 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6084 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6085 #include "clang/AST/BuiltinTypes.def" 6086 return false; 6087 6088 // We cannot lower out overload sets; they might validly be resolved 6089 // by the call machinery. 6090 case BuiltinType::Overload: 6091 return false; 6092 6093 // Unbridged casts in ARC can be handled in some call positions and 6094 // should be left in place. 6095 case BuiltinType::ARCUnbridgedCast: 6096 return false; 6097 6098 // Pseudo-objects should be converted as soon as possible. 6099 case BuiltinType::PseudoObject: 6100 return true; 6101 6102 // The debugger mode could theoretically but currently does not try 6103 // to resolve unknown-typed arguments based on known parameter types. 6104 case BuiltinType::UnknownAny: 6105 return true; 6106 6107 // These are always invalid as call arguments and should be reported. 6108 case BuiltinType::BoundMember: 6109 case BuiltinType::BuiltinFn: 6110 case BuiltinType::IncompleteMatrixIdx: 6111 case BuiltinType::OMPArraySection: 6112 case BuiltinType::OMPArrayShaping: 6113 case BuiltinType::OMPIterator: 6114 return true; 6115 6116 } 6117 llvm_unreachable("bad builtin type kind"); 6118 } 6119 6120 /// Check an argument list for placeholders that we won't try to 6121 /// handle later. 6122 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6123 // Apply this processing to all the arguments at once instead of 6124 // dying at the first failure. 6125 bool hasInvalid = false; 6126 for (size_t i = 0, e = args.size(); i != e; i++) { 6127 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6128 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6129 if (result.isInvalid()) hasInvalid = true; 6130 else args[i] = result.get(); 6131 } 6132 } 6133 return hasInvalid; 6134 } 6135 6136 /// If a builtin function has a pointer argument with no explicit address 6137 /// space, then it should be able to accept a pointer to any address 6138 /// space as input. In order to do this, we need to replace the 6139 /// standard builtin declaration with one that uses the same address space 6140 /// as the call. 6141 /// 6142 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6143 /// it does not contain any pointer arguments without 6144 /// an address space qualifer. Otherwise the rewritten 6145 /// FunctionDecl is returned. 6146 /// TODO: Handle pointer return types. 6147 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6148 FunctionDecl *FDecl, 6149 MultiExprArg ArgExprs) { 6150 6151 QualType DeclType = FDecl->getType(); 6152 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6153 6154 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6155 ArgExprs.size() < FT->getNumParams()) 6156 return nullptr; 6157 6158 bool NeedsNewDecl = false; 6159 unsigned i = 0; 6160 SmallVector<QualType, 8> OverloadParams; 6161 6162 for (QualType ParamType : FT->param_types()) { 6163 6164 // Convert array arguments to pointer to simplify type lookup. 6165 ExprResult ArgRes = 6166 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6167 if (ArgRes.isInvalid()) 6168 return nullptr; 6169 Expr *Arg = ArgRes.get(); 6170 QualType ArgType = Arg->getType(); 6171 if (!ParamType->isPointerType() || 6172 ParamType.hasAddressSpace() || 6173 !ArgType->isPointerType() || 6174 !ArgType->getPointeeType().hasAddressSpace()) { 6175 OverloadParams.push_back(ParamType); 6176 continue; 6177 } 6178 6179 QualType PointeeType = ParamType->getPointeeType(); 6180 if (PointeeType.hasAddressSpace()) 6181 continue; 6182 6183 NeedsNewDecl = true; 6184 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6185 6186 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6187 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6188 } 6189 6190 if (!NeedsNewDecl) 6191 return nullptr; 6192 6193 FunctionProtoType::ExtProtoInfo EPI; 6194 EPI.Variadic = FT->isVariadic(); 6195 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6196 OverloadParams, EPI); 6197 DeclContext *Parent = FDecl->getParent(); 6198 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 6199 FDecl->getLocation(), 6200 FDecl->getLocation(), 6201 FDecl->getIdentifier(), 6202 OverloadTy, 6203 /*TInfo=*/nullptr, 6204 SC_Extern, false, 6205 /*hasPrototype=*/true); 6206 SmallVector<ParmVarDecl*, 16> Params; 6207 FT = cast<FunctionProtoType>(OverloadTy); 6208 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6209 QualType ParamType = FT->getParamType(i); 6210 ParmVarDecl *Parm = 6211 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6212 SourceLocation(), nullptr, ParamType, 6213 /*TInfo=*/nullptr, SC_None, nullptr); 6214 Parm->setScopeInfo(0, i); 6215 Params.push_back(Parm); 6216 } 6217 OverloadDecl->setParams(Params); 6218 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6219 return OverloadDecl; 6220 } 6221 6222 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6223 FunctionDecl *Callee, 6224 MultiExprArg ArgExprs) { 6225 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6226 // similar attributes) really don't like it when functions are called with an 6227 // invalid number of args. 6228 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6229 /*PartialOverloading=*/false) && 6230 !Callee->isVariadic()) 6231 return; 6232 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6233 return; 6234 6235 if (const EnableIfAttr *Attr = 6236 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6237 S.Diag(Fn->getBeginLoc(), 6238 isa<CXXMethodDecl>(Callee) 6239 ? diag::err_ovl_no_viable_member_function_in_call 6240 : diag::err_ovl_no_viable_function_in_call) 6241 << Callee << Callee->getSourceRange(); 6242 S.Diag(Callee->getLocation(), 6243 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6244 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6245 return; 6246 } 6247 } 6248 6249 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6250 const UnresolvedMemberExpr *const UME, Sema &S) { 6251 6252 const auto GetFunctionLevelDCIfCXXClass = 6253 [](Sema &S) -> const CXXRecordDecl * { 6254 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6255 if (!DC || !DC->getParent()) 6256 return nullptr; 6257 6258 // If the call to some member function was made from within a member 6259 // function body 'M' return return 'M's parent. 6260 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6261 return MD->getParent()->getCanonicalDecl(); 6262 // else the call was made from within a default member initializer of a 6263 // class, so return the class. 6264 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6265 return RD->getCanonicalDecl(); 6266 return nullptr; 6267 }; 6268 // If our DeclContext is neither a member function nor a class (in the 6269 // case of a lambda in a default member initializer), we can't have an 6270 // enclosing 'this'. 6271 6272 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6273 if (!CurParentClass) 6274 return false; 6275 6276 // The naming class for implicit member functions call is the class in which 6277 // name lookup starts. 6278 const CXXRecordDecl *const NamingClass = 6279 UME->getNamingClass()->getCanonicalDecl(); 6280 assert(NamingClass && "Must have naming class even for implicit access"); 6281 6282 // If the unresolved member functions were found in a 'naming class' that is 6283 // related (either the same or derived from) to the class that contains the 6284 // member function that itself contained the implicit member access. 6285 6286 return CurParentClass == NamingClass || 6287 CurParentClass->isDerivedFrom(NamingClass); 6288 } 6289 6290 static void 6291 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6292 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6293 6294 if (!UME) 6295 return; 6296 6297 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6298 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6299 // already been captured, or if this is an implicit member function call (if 6300 // it isn't, an attempt to capture 'this' should already have been made). 6301 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6302 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6303 return; 6304 6305 // Check if the naming class in which the unresolved members were found is 6306 // related (same as or is a base of) to the enclosing class. 6307 6308 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6309 return; 6310 6311 6312 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6313 // If the enclosing function is not dependent, then this lambda is 6314 // capture ready, so if we can capture this, do so. 6315 if (!EnclosingFunctionCtx->isDependentContext()) { 6316 // If the current lambda and all enclosing lambdas can capture 'this' - 6317 // then go ahead and capture 'this' (since our unresolved overload set 6318 // contains at least one non-static member function). 6319 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6320 S.CheckCXXThisCapture(CallLoc); 6321 } else if (S.CurContext->isDependentContext()) { 6322 // ... since this is an implicit member reference, that might potentially 6323 // involve a 'this' capture, mark 'this' for potential capture in 6324 // enclosing lambdas. 6325 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6326 CurLSI->addPotentialThisCapture(CallLoc); 6327 } 6328 } 6329 6330 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6331 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6332 Expr *ExecConfig) { 6333 ExprResult Call = 6334 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6335 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6336 if (Call.isInvalid()) 6337 return Call; 6338 6339 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6340 // language modes. 6341 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6342 if (ULE->hasExplicitTemplateArgs() && 6343 ULE->decls_begin() == ULE->decls_end()) { 6344 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6345 ? diag::warn_cxx17_compat_adl_only_template_id 6346 : diag::ext_adl_only_template_id) 6347 << ULE->getName(); 6348 } 6349 } 6350 6351 if (LangOpts.OpenMP) 6352 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6353 ExecConfig); 6354 6355 return Call; 6356 } 6357 6358 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6359 /// This provides the location of the left/right parens and a list of comma 6360 /// locations. 6361 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6362 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6363 Expr *ExecConfig, bool IsExecConfig, 6364 bool AllowRecovery) { 6365 // Since this might be a postfix expression, get rid of ParenListExprs. 6366 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6367 if (Result.isInvalid()) return ExprError(); 6368 Fn = Result.get(); 6369 6370 if (checkArgsForPlaceholders(*this, ArgExprs)) 6371 return ExprError(); 6372 6373 if (getLangOpts().CPlusPlus) { 6374 // If this is a pseudo-destructor expression, build the call immediately. 6375 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6376 if (!ArgExprs.empty()) { 6377 // Pseudo-destructor calls should not have any arguments. 6378 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6379 << FixItHint::CreateRemoval( 6380 SourceRange(ArgExprs.front()->getBeginLoc(), 6381 ArgExprs.back()->getEndLoc())); 6382 } 6383 6384 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6385 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6386 } 6387 if (Fn->getType() == Context.PseudoObjectTy) { 6388 ExprResult result = CheckPlaceholderExpr(Fn); 6389 if (result.isInvalid()) return ExprError(); 6390 Fn = result.get(); 6391 } 6392 6393 // Determine whether this is a dependent call inside a C++ template, 6394 // in which case we won't do any semantic analysis now. 6395 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6396 if (ExecConfig) { 6397 return CUDAKernelCallExpr::Create( 6398 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 6399 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6400 } else { 6401 6402 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6403 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6404 Fn->getBeginLoc()); 6405 6406 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6407 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6408 } 6409 } 6410 6411 // Determine whether this is a call to an object (C++ [over.call.object]). 6412 if (Fn->getType()->isRecordType()) 6413 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6414 RParenLoc); 6415 6416 if (Fn->getType() == Context.UnknownAnyTy) { 6417 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6418 if (result.isInvalid()) return ExprError(); 6419 Fn = result.get(); 6420 } 6421 6422 if (Fn->getType() == Context.BoundMemberTy) { 6423 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6424 RParenLoc, AllowRecovery); 6425 } 6426 } 6427 6428 // Check for overloaded calls. This can happen even in C due to extensions. 6429 if (Fn->getType() == Context.OverloadTy) { 6430 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6431 6432 // We aren't supposed to apply this logic if there's an '&' involved. 6433 if (!find.HasFormOfMemberPointer) { 6434 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6435 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6436 VK_RValue, RParenLoc, CurFPFeatureOverrides()); 6437 OverloadExpr *ovl = find.Expression; 6438 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6439 return BuildOverloadedCallExpr( 6440 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6441 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6442 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6443 RParenLoc, AllowRecovery); 6444 } 6445 } 6446 6447 // If we're directly calling a function, get the appropriate declaration. 6448 if (Fn->getType() == Context.UnknownAnyTy) { 6449 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6450 if (result.isInvalid()) return ExprError(); 6451 Fn = result.get(); 6452 } 6453 6454 Expr *NakedFn = Fn->IgnoreParens(); 6455 6456 bool CallingNDeclIndirectly = false; 6457 NamedDecl *NDecl = nullptr; 6458 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6459 if (UnOp->getOpcode() == UO_AddrOf) { 6460 CallingNDeclIndirectly = true; 6461 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6462 } 6463 } 6464 6465 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6466 NDecl = DRE->getDecl(); 6467 6468 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6469 if (FDecl && FDecl->getBuiltinID()) { 6470 // Rewrite the function decl for this builtin by replacing parameters 6471 // with no explicit address space with the address space of the arguments 6472 // in ArgExprs. 6473 if ((FDecl = 6474 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6475 NDecl = FDecl; 6476 Fn = DeclRefExpr::Create( 6477 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 6478 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 6479 nullptr, DRE->isNonOdrUse()); 6480 } 6481 } 6482 } else if (isa<MemberExpr>(NakedFn)) 6483 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 6484 6485 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 6486 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 6487 FD, /*Complain=*/true, Fn->getBeginLoc())) 6488 return ExprError(); 6489 6490 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 6491 return ExprError(); 6492 6493 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 6494 } 6495 6496 if (Context.isDependenceAllowed() && 6497 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 6498 assert(!getLangOpts().CPlusPlus); 6499 assert((Fn->containsErrors() || 6500 llvm::any_of(ArgExprs, 6501 [](clang::Expr *E) { return E->containsErrors(); })) && 6502 "should only occur in error-recovery path."); 6503 QualType ReturnType = 6504 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 6505 ? cast<FunctionDecl>(NDecl)->getCallResultType() 6506 : Context.DependentTy; 6507 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 6508 Expr::getValueKindForType(ReturnType), RParenLoc, 6509 CurFPFeatureOverrides()); 6510 } 6511 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 6512 ExecConfig, IsExecConfig); 6513 } 6514 6515 /// Parse a __builtin_astype expression. 6516 /// 6517 /// __builtin_astype( value, dst type ) 6518 /// 6519 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6520 SourceLocation BuiltinLoc, 6521 SourceLocation RParenLoc) { 6522 QualType DstTy = GetTypeFromParser(ParsedDestTy); 6523 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 6524 } 6525 6526 /// Create a new AsTypeExpr node (bitcast) from the arguments. 6527 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 6528 SourceLocation BuiltinLoc, 6529 SourceLocation RParenLoc) { 6530 ExprValueKind VK = VK_RValue; 6531 ExprObjectKind OK = OK_Ordinary; 6532 QualType SrcTy = E->getType(); 6533 if (!SrcTy->isDependentType() && 6534 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 6535 return ExprError( 6536 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 6537 << DestTy << SrcTy << E->getSourceRange()); 6538 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 6539 } 6540 6541 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 6542 /// provided arguments. 6543 /// 6544 /// __builtin_convertvector( value, dst type ) 6545 /// 6546 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6547 SourceLocation BuiltinLoc, 6548 SourceLocation RParenLoc) { 6549 TypeSourceInfo *TInfo; 6550 GetTypeFromParser(ParsedDestTy, &TInfo); 6551 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 6552 } 6553 6554 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6555 /// i.e. an expression not of \p OverloadTy. The expression should 6556 /// unary-convert to an expression of function-pointer or 6557 /// block-pointer type. 6558 /// 6559 /// \param NDecl the declaration being called, if available 6560 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 6561 SourceLocation LParenLoc, 6562 ArrayRef<Expr *> Args, 6563 SourceLocation RParenLoc, Expr *Config, 6564 bool IsExecConfig, ADLCallKind UsesADL) { 6565 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 6566 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 6567 6568 // Functions with 'interrupt' attribute cannot be called directly. 6569 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 6570 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 6571 return ExprError(); 6572 } 6573 6574 // Interrupt handlers don't save off the VFP regs automatically on ARM, 6575 // so there's some risk when calling out to non-interrupt handler functions 6576 // that the callee might not preserve them. This is easy to diagnose here, 6577 // but can be very challenging to debug. 6578 // Likewise, X86 interrupt handlers may only call routines with attribute 6579 // no_caller_saved_registers since there is no efficient way to 6580 // save and restore the non-GPR state. 6581 if (auto *Caller = getCurFunctionDecl()) { 6582 if (Caller->hasAttr<ARMInterruptAttr>()) { 6583 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 6584 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 6585 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 6586 if (FDecl) 6587 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6588 } 6589 } 6590 if (Caller->hasAttr<AnyX86InterruptAttr>() && 6591 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 6592 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 6593 if (FDecl) 6594 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6595 } 6596 } 6597 6598 // Promote the function operand. 6599 // We special-case function promotion here because we only allow promoting 6600 // builtin functions to function pointers in the callee of a call. 6601 ExprResult Result; 6602 QualType ResultTy; 6603 if (BuiltinID && 6604 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 6605 // Extract the return type from the (builtin) function pointer type. 6606 // FIXME Several builtins still have setType in 6607 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 6608 // Builtins.def to ensure they are correct before removing setType calls. 6609 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 6610 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 6611 ResultTy = FDecl->getCallResultType(); 6612 } else { 6613 Result = CallExprUnaryConversions(Fn); 6614 ResultTy = Context.BoolTy; 6615 } 6616 if (Result.isInvalid()) 6617 return ExprError(); 6618 Fn = Result.get(); 6619 6620 // Check for a valid function type, but only if it is not a builtin which 6621 // requires custom type checking. These will be handled by 6622 // CheckBuiltinFunctionCall below just after creation of the call expression. 6623 const FunctionType *FuncT = nullptr; 6624 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 6625 retry: 6626 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 6627 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 6628 // have type pointer to function". 6629 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 6630 if (!FuncT) 6631 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6632 << Fn->getType() << Fn->getSourceRange()); 6633 } else if (const BlockPointerType *BPT = 6634 Fn->getType()->getAs<BlockPointerType>()) { 6635 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 6636 } else { 6637 // Handle calls to expressions of unknown-any type. 6638 if (Fn->getType() == Context.UnknownAnyTy) { 6639 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 6640 if (rewrite.isInvalid()) 6641 return ExprError(); 6642 Fn = rewrite.get(); 6643 goto retry; 6644 } 6645 6646 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 6647 << Fn->getType() << Fn->getSourceRange()); 6648 } 6649 } 6650 6651 // Get the number of parameters in the function prototype, if any. 6652 // We will allocate space for max(Args.size(), NumParams) arguments 6653 // in the call expression. 6654 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 6655 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 6656 6657 CallExpr *TheCall; 6658 if (Config) { 6659 assert(UsesADL == ADLCallKind::NotADL && 6660 "CUDAKernelCallExpr should not use ADL"); 6661 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 6662 Args, ResultTy, VK_RValue, RParenLoc, 6663 CurFPFeatureOverrides(), NumParams); 6664 } else { 6665 TheCall = 6666 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6667 CurFPFeatureOverrides(), NumParams, UsesADL); 6668 } 6669 6670 if (!Context.isDependenceAllowed()) { 6671 // Forget about the nulled arguments since typo correction 6672 // do not handle them well. 6673 TheCall->shrinkNumArgs(Args.size()); 6674 // C cannot always handle TypoExpr nodes in builtin calls and direct 6675 // function calls as their argument checking don't necessarily handle 6676 // dependent types properly, so make sure any TypoExprs have been 6677 // dealt with. 6678 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 6679 if (!Result.isUsable()) return ExprError(); 6680 CallExpr *TheOldCall = TheCall; 6681 TheCall = dyn_cast<CallExpr>(Result.get()); 6682 bool CorrectedTypos = TheCall != TheOldCall; 6683 if (!TheCall) return Result; 6684 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 6685 6686 // A new call expression node was created if some typos were corrected. 6687 // However it may not have been constructed with enough storage. In this 6688 // case, rebuild the node with enough storage. The waste of space is 6689 // immaterial since this only happens when some typos were corrected. 6690 if (CorrectedTypos && Args.size() < NumParams) { 6691 if (Config) 6692 TheCall = CUDAKernelCallExpr::Create( 6693 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue, 6694 RParenLoc, CurFPFeatureOverrides(), NumParams); 6695 else 6696 TheCall = 6697 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, 6698 CurFPFeatureOverrides(), NumParams, UsesADL); 6699 } 6700 // We can now handle the nulled arguments for the default arguments. 6701 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 6702 } 6703 6704 // Bail out early if calling a builtin with custom type checking. 6705 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 6706 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6707 6708 if (getLangOpts().CUDA) { 6709 if (Config) { 6710 // CUDA: Kernel calls must be to global functions 6711 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 6712 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 6713 << FDecl << Fn->getSourceRange()); 6714 6715 // CUDA: Kernel function must have 'void' return type 6716 if (!FuncT->getReturnType()->isVoidType() && 6717 !FuncT->getReturnType()->getAs<AutoType>() && 6718 !FuncT->getReturnType()->isInstantiationDependentType()) 6719 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 6720 << Fn->getType() << Fn->getSourceRange()); 6721 } else { 6722 // CUDA: Calls to global functions must be configured 6723 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 6724 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 6725 << FDecl << Fn->getSourceRange()); 6726 } 6727 } 6728 6729 // Check for a valid return type 6730 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 6731 FDecl)) 6732 return ExprError(); 6733 6734 // We know the result type of the call, set it. 6735 TheCall->setType(FuncT->getCallResultType(Context)); 6736 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 6737 6738 if (Proto) { 6739 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 6740 IsExecConfig)) 6741 return ExprError(); 6742 } else { 6743 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 6744 6745 if (FDecl) { 6746 // Check if we have too few/too many template arguments, based 6747 // on our knowledge of the function definition. 6748 const FunctionDecl *Def = nullptr; 6749 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 6750 Proto = Def->getType()->getAs<FunctionProtoType>(); 6751 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 6752 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 6753 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 6754 } 6755 6756 // If the function we're calling isn't a function prototype, but we have 6757 // a function prototype from a prior declaratiom, use that prototype. 6758 if (!FDecl->hasPrototype()) 6759 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 6760 } 6761 6762 // Promote the arguments (C99 6.5.2.2p6). 6763 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6764 Expr *Arg = Args[i]; 6765 6766 if (Proto && i < Proto->getNumParams()) { 6767 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6768 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 6769 ExprResult ArgE = 6770 PerformCopyInitialization(Entity, SourceLocation(), Arg); 6771 if (ArgE.isInvalid()) 6772 return true; 6773 6774 Arg = ArgE.getAs<Expr>(); 6775 6776 } else { 6777 ExprResult ArgE = DefaultArgumentPromotion(Arg); 6778 6779 if (ArgE.isInvalid()) 6780 return true; 6781 6782 Arg = ArgE.getAs<Expr>(); 6783 } 6784 6785 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 6786 diag::err_call_incomplete_argument, Arg)) 6787 return ExprError(); 6788 6789 TheCall->setArg(i, Arg); 6790 } 6791 } 6792 6793 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6794 if (!Method->isStatic()) 6795 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 6796 << Fn->getSourceRange()); 6797 6798 // Check for sentinels 6799 if (NDecl) 6800 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 6801 6802 // Warn for unions passing across security boundary (CMSE). 6803 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 6804 for (unsigned i = 0, e = Args.size(); i != e; i++) { 6805 if (const auto *RT = 6806 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 6807 if (RT->getDecl()->isOrContainsUnion()) 6808 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 6809 << 0 << i; 6810 } 6811 } 6812 } 6813 6814 // Do special checking on direct calls to functions. 6815 if (FDecl) { 6816 if (CheckFunctionCall(FDecl, TheCall, Proto)) 6817 return ExprError(); 6818 6819 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 6820 6821 if (BuiltinID) 6822 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 6823 } else if (NDecl) { 6824 if (CheckPointerCall(NDecl, TheCall, Proto)) 6825 return ExprError(); 6826 } else { 6827 if (CheckOtherCall(TheCall, Proto)) 6828 return ExprError(); 6829 } 6830 6831 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 6832 } 6833 6834 ExprResult 6835 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 6836 SourceLocation RParenLoc, Expr *InitExpr) { 6837 assert(Ty && "ActOnCompoundLiteral(): missing type"); 6838 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 6839 6840 TypeSourceInfo *TInfo; 6841 QualType literalType = GetTypeFromParser(Ty, &TInfo); 6842 if (!TInfo) 6843 TInfo = Context.getTrivialTypeSourceInfo(literalType); 6844 6845 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 6846 } 6847 6848 ExprResult 6849 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 6850 SourceLocation RParenLoc, Expr *LiteralExpr) { 6851 QualType literalType = TInfo->getType(); 6852 6853 if (literalType->isArrayType()) { 6854 if (RequireCompleteSizedType( 6855 LParenLoc, Context.getBaseElementType(literalType), 6856 diag::err_array_incomplete_or_sizeless_type, 6857 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6858 return ExprError(); 6859 if (literalType->isVariableArrayType()) { 6860 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 6861 diag::err_variable_object_no_init)) { 6862 return ExprError(); 6863 } 6864 } 6865 } else if (!literalType->isDependentType() && 6866 RequireCompleteType(LParenLoc, literalType, 6867 diag::err_typecheck_decl_incomplete_type, 6868 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 6869 return ExprError(); 6870 6871 InitializedEntity Entity 6872 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 6873 InitializationKind Kind 6874 = InitializationKind::CreateCStyleCast(LParenLoc, 6875 SourceRange(LParenLoc, RParenLoc), 6876 /*InitList=*/true); 6877 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 6878 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 6879 &literalType); 6880 if (Result.isInvalid()) 6881 return ExprError(); 6882 LiteralExpr = Result.get(); 6883 6884 bool isFileScope = !CurContext->isFunctionOrMethod(); 6885 6886 // In C, compound literals are l-values for some reason. 6887 // For GCC compatibility, in C++, file-scope array compound literals with 6888 // constant initializers are also l-values, and compound literals are 6889 // otherwise prvalues. 6890 // 6891 // (GCC also treats C++ list-initialized file-scope array prvalues with 6892 // constant initializers as l-values, but that's non-conforming, so we don't 6893 // follow it there.) 6894 // 6895 // FIXME: It would be better to handle the lvalue cases as materializing and 6896 // lifetime-extending a temporary object, but our materialized temporaries 6897 // representation only supports lifetime extension from a variable, not "out 6898 // of thin air". 6899 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 6900 // is bound to the result of applying array-to-pointer decay to the compound 6901 // literal. 6902 // FIXME: GCC supports compound literals of reference type, which should 6903 // obviously have a value kind derived from the kind of reference involved. 6904 ExprValueKind VK = 6905 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 6906 ? VK_RValue 6907 : VK_LValue; 6908 6909 if (isFileScope) 6910 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 6911 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 6912 Expr *Init = ILE->getInit(i); 6913 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 6914 } 6915 6916 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 6917 VK, LiteralExpr, isFileScope); 6918 if (isFileScope) { 6919 if (!LiteralExpr->isTypeDependent() && 6920 !LiteralExpr->isValueDependent() && 6921 !literalType->isDependentType()) // C99 6.5.2.5p3 6922 if (CheckForConstantInitializer(LiteralExpr, literalType)) 6923 return ExprError(); 6924 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 6925 literalType.getAddressSpace() != LangAS::Default) { 6926 // Embedded-C extensions to C99 6.5.2.5: 6927 // "If the compound literal occurs inside the body of a function, the 6928 // type name shall not be qualified by an address-space qualifier." 6929 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 6930 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 6931 return ExprError(); 6932 } 6933 6934 if (!isFileScope && !getLangOpts().CPlusPlus) { 6935 // Compound literals that have automatic storage duration are destroyed at 6936 // the end of the scope in C; in C++, they're just temporaries. 6937 6938 // Emit diagnostics if it is or contains a C union type that is non-trivial 6939 // to destruct. 6940 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 6941 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 6942 NTCUC_CompoundLiteral, NTCUK_Destruct); 6943 6944 // Diagnose jumps that enter or exit the lifetime of the compound literal. 6945 if (literalType.isDestructedType()) { 6946 Cleanup.setExprNeedsCleanups(true); 6947 ExprCleanupObjects.push_back(E); 6948 getCurFunction()->setHasBranchProtectedScope(); 6949 } 6950 } 6951 6952 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 6953 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 6954 checkNonTrivialCUnionInInitializer(E->getInitializer(), 6955 E->getInitializer()->getExprLoc()); 6956 6957 return MaybeBindToTemporary(E); 6958 } 6959 6960 ExprResult 6961 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 6962 SourceLocation RBraceLoc) { 6963 // Only produce each kind of designated initialization diagnostic once. 6964 SourceLocation FirstDesignator; 6965 bool DiagnosedArrayDesignator = false; 6966 bool DiagnosedNestedDesignator = false; 6967 bool DiagnosedMixedDesignator = false; 6968 6969 // Check that any designated initializers are syntactically valid in the 6970 // current language mode. 6971 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 6972 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 6973 if (FirstDesignator.isInvalid()) 6974 FirstDesignator = DIE->getBeginLoc(); 6975 6976 if (!getLangOpts().CPlusPlus) 6977 break; 6978 6979 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 6980 DiagnosedNestedDesignator = true; 6981 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 6982 << DIE->getDesignatorsSourceRange(); 6983 } 6984 6985 for (auto &Desig : DIE->designators()) { 6986 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 6987 DiagnosedArrayDesignator = true; 6988 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 6989 << Desig.getSourceRange(); 6990 } 6991 } 6992 6993 if (!DiagnosedMixedDesignator && 6994 !isa<DesignatedInitExpr>(InitArgList[0])) { 6995 DiagnosedMixedDesignator = true; 6996 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 6997 << DIE->getSourceRange(); 6998 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 6999 << InitArgList[0]->getSourceRange(); 7000 } 7001 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7002 isa<DesignatedInitExpr>(InitArgList[0])) { 7003 DiagnosedMixedDesignator = true; 7004 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7005 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7006 << DIE->getSourceRange(); 7007 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7008 << InitArgList[I]->getSourceRange(); 7009 } 7010 } 7011 7012 if (FirstDesignator.isValid()) { 7013 // Only diagnose designated initiaization as a C++20 extension if we didn't 7014 // already diagnose use of (non-C++20) C99 designator syntax. 7015 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7016 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7017 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7018 ? diag::warn_cxx17_compat_designated_init 7019 : diag::ext_cxx_designated_init); 7020 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7021 Diag(FirstDesignator, diag::ext_designated_init); 7022 } 7023 } 7024 7025 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7026 } 7027 7028 ExprResult 7029 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7030 SourceLocation RBraceLoc) { 7031 // Semantic analysis for initializers is done by ActOnDeclarator() and 7032 // CheckInitializer() - it requires knowledge of the object being initialized. 7033 7034 // Immediately handle non-overload placeholders. Overloads can be 7035 // resolved contextually, but everything else here can't. 7036 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7037 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7038 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7039 7040 // Ignore failures; dropping the entire initializer list because 7041 // of one failure would be terrible for indexing/etc. 7042 if (result.isInvalid()) continue; 7043 7044 InitArgList[I] = result.get(); 7045 } 7046 } 7047 7048 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7049 RBraceLoc); 7050 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7051 return E; 7052 } 7053 7054 /// Do an explicit extend of the given block pointer if we're in ARC. 7055 void Sema::maybeExtendBlockObject(ExprResult &E) { 7056 assert(E.get()->getType()->isBlockPointerType()); 7057 assert(E.get()->isRValue()); 7058 7059 // Only do this in an r-value context. 7060 if (!getLangOpts().ObjCAutoRefCount) return; 7061 7062 E = ImplicitCastExpr::Create( 7063 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7064 /*base path*/ nullptr, VK_RValue, FPOptionsOverride()); 7065 Cleanup.setExprNeedsCleanups(true); 7066 } 7067 7068 /// Prepare a conversion of the given expression to an ObjC object 7069 /// pointer type. 7070 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7071 QualType type = E.get()->getType(); 7072 if (type->isObjCObjectPointerType()) { 7073 return CK_BitCast; 7074 } else if (type->isBlockPointerType()) { 7075 maybeExtendBlockObject(E); 7076 return CK_BlockPointerToObjCPointerCast; 7077 } else { 7078 assert(type->isPointerType()); 7079 return CK_CPointerToObjCPointerCast; 7080 } 7081 } 7082 7083 /// Prepares for a scalar cast, performing all the necessary stages 7084 /// except the final cast and returning the kind required. 7085 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7086 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7087 // Also, callers should have filtered out the invalid cases with 7088 // pointers. Everything else should be possible. 7089 7090 QualType SrcTy = Src.get()->getType(); 7091 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7092 return CK_NoOp; 7093 7094 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7095 case Type::STK_MemberPointer: 7096 llvm_unreachable("member pointer type in C"); 7097 7098 case Type::STK_CPointer: 7099 case Type::STK_BlockPointer: 7100 case Type::STK_ObjCObjectPointer: 7101 switch (DestTy->getScalarTypeKind()) { 7102 case Type::STK_CPointer: { 7103 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7104 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7105 if (SrcAS != DestAS) 7106 return CK_AddressSpaceConversion; 7107 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7108 return CK_NoOp; 7109 return CK_BitCast; 7110 } 7111 case Type::STK_BlockPointer: 7112 return (SrcKind == Type::STK_BlockPointer 7113 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7114 case Type::STK_ObjCObjectPointer: 7115 if (SrcKind == Type::STK_ObjCObjectPointer) 7116 return CK_BitCast; 7117 if (SrcKind == Type::STK_CPointer) 7118 return CK_CPointerToObjCPointerCast; 7119 maybeExtendBlockObject(Src); 7120 return CK_BlockPointerToObjCPointerCast; 7121 case Type::STK_Bool: 7122 return CK_PointerToBoolean; 7123 case Type::STK_Integral: 7124 return CK_PointerToIntegral; 7125 case Type::STK_Floating: 7126 case Type::STK_FloatingComplex: 7127 case Type::STK_IntegralComplex: 7128 case Type::STK_MemberPointer: 7129 case Type::STK_FixedPoint: 7130 llvm_unreachable("illegal cast from pointer"); 7131 } 7132 llvm_unreachable("Should have returned before this"); 7133 7134 case Type::STK_FixedPoint: 7135 switch (DestTy->getScalarTypeKind()) { 7136 case Type::STK_FixedPoint: 7137 return CK_FixedPointCast; 7138 case Type::STK_Bool: 7139 return CK_FixedPointToBoolean; 7140 case Type::STK_Integral: 7141 return CK_FixedPointToIntegral; 7142 case Type::STK_Floating: 7143 return CK_FixedPointToFloating; 7144 case Type::STK_IntegralComplex: 7145 case Type::STK_FloatingComplex: 7146 Diag(Src.get()->getExprLoc(), 7147 diag::err_unimplemented_conversion_with_fixed_point_type) 7148 << DestTy; 7149 return CK_IntegralCast; 7150 case Type::STK_CPointer: 7151 case Type::STK_ObjCObjectPointer: 7152 case Type::STK_BlockPointer: 7153 case Type::STK_MemberPointer: 7154 llvm_unreachable("illegal cast to pointer type"); 7155 } 7156 llvm_unreachable("Should have returned before this"); 7157 7158 case Type::STK_Bool: // casting from bool is like casting from an integer 7159 case Type::STK_Integral: 7160 switch (DestTy->getScalarTypeKind()) { 7161 case Type::STK_CPointer: 7162 case Type::STK_ObjCObjectPointer: 7163 case Type::STK_BlockPointer: 7164 if (Src.get()->isNullPointerConstant(Context, 7165 Expr::NPC_ValueDependentIsNull)) 7166 return CK_NullToPointer; 7167 return CK_IntegralToPointer; 7168 case Type::STK_Bool: 7169 return CK_IntegralToBoolean; 7170 case Type::STK_Integral: 7171 return CK_IntegralCast; 7172 case Type::STK_Floating: 7173 return CK_IntegralToFloating; 7174 case Type::STK_IntegralComplex: 7175 Src = ImpCastExprToType(Src.get(), 7176 DestTy->castAs<ComplexType>()->getElementType(), 7177 CK_IntegralCast); 7178 return CK_IntegralRealToComplex; 7179 case Type::STK_FloatingComplex: 7180 Src = ImpCastExprToType(Src.get(), 7181 DestTy->castAs<ComplexType>()->getElementType(), 7182 CK_IntegralToFloating); 7183 return CK_FloatingRealToComplex; 7184 case Type::STK_MemberPointer: 7185 llvm_unreachable("member pointer type in C"); 7186 case Type::STK_FixedPoint: 7187 return CK_IntegralToFixedPoint; 7188 } 7189 llvm_unreachable("Should have returned before this"); 7190 7191 case Type::STK_Floating: 7192 switch (DestTy->getScalarTypeKind()) { 7193 case Type::STK_Floating: 7194 return CK_FloatingCast; 7195 case Type::STK_Bool: 7196 return CK_FloatingToBoolean; 7197 case Type::STK_Integral: 7198 return CK_FloatingToIntegral; 7199 case Type::STK_FloatingComplex: 7200 Src = ImpCastExprToType(Src.get(), 7201 DestTy->castAs<ComplexType>()->getElementType(), 7202 CK_FloatingCast); 7203 return CK_FloatingRealToComplex; 7204 case Type::STK_IntegralComplex: 7205 Src = ImpCastExprToType(Src.get(), 7206 DestTy->castAs<ComplexType>()->getElementType(), 7207 CK_FloatingToIntegral); 7208 return CK_IntegralRealToComplex; 7209 case Type::STK_CPointer: 7210 case Type::STK_ObjCObjectPointer: 7211 case Type::STK_BlockPointer: 7212 llvm_unreachable("valid float->pointer cast?"); 7213 case Type::STK_MemberPointer: 7214 llvm_unreachable("member pointer type in C"); 7215 case Type::STK_FixedPoint: 7216 return CK_FloatingToFixedPoint; 7217 } 7218 llvm_unreachable("Should have returned before this"); 7219 7220 case Type::STK_FloatingComplex: 7221 switch (DestTy->getScalarTypeKind()) { 7222 case Type::STK_FloatingComplex: 7223 return CK_FloatingComplexCast; 7224 case Type::STK_IntegralComplex: 7225 return CK_FloatingComplexToIntegralComplex; 7226 case Type::STK_Floating: { 7227 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7228 if (Context.hasSameType(ET, DestTy)) 7229 return CK_FloatingComplexToReal; 7230 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7231 return CK_FloatingCast; 7232 } 7233 case Type::STK_Bool: 7234 return CK_FloatingComplexToBoolean; 7235 case Type::STK_Integral: 7236 Src = ImpCastExprToType(Src.get(), 7237 SrcTy->castAs<ComplexType>()->getElementType(), 7238 CK_FloatingComplexToReal); 7239 return CK_FloatingToIntegral; 7240 case Type::STK_CPointer: 7241 case Type::STK_ObjCObjectPointer: 7242 case Type::STK_BlockPointer: 7243 llvm_unreachable("valid complex float->pointer cast?"); 7244 case Type::STK_MemberPointer: 7245 llvm_unreachable("member pointer type in C"); 7246 case Type::STK_FixedPoint: 7247 Diag(Src.get()->getExprLoc(), 7248 diag::err_unimplemented_conversion_with_fixed_point_type) 7249 << SrcTy; 7250 return CK_IntegralCast; 7251 } 7252 llvm_unreachable("Should have returned before this"); 7253 7254 case Type::STK_IntegralComplex: 7255 switch (DestTy->getScalarTypeKind()) { 7256 case Type::STK_FloatingComplex: 7257 return CK_IntegralComplexToFloatingComplex; 7258 case Type::STK_IntegralComplex: 7259 return CK_IntegralComplexCast; 7260 case Type::STK_Integral: { 7261 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7262 if (Context.hasSameType(ET, DestTy)) 7263 return CK_IntegralComplexToReal; 7264 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7265 return CK_IntegralCast; 7266 } 7267 case Type::STK_Bool: 7268 return CK_IntegralComplexToBoolean; 7269 case Type::STK_Floating: 7270 Src = ImpCastExprToType(Src.get(), 7271 SrcTy->castAs<ComplexType>()->getElementType(), 7272 CK_IntegralComplexToReal); 7273 return CK_IntegralToFloating; 7274 case Type::STK_CPointer: 7275 case Type::STK_ObjCObjectPointer: 7276 case Type::STK_BlockPointer: 7277 llvm_unreachable("valid complex int->pointer cast?"); 7278 case Type::STK_MemberPointer: 7279 llvm_unreachable("member pointer type in C"); 7280 case Type::STK_FixedPoint: 7281 Diag(Src.get()->getExprLoc(), 7282 diag::err_unimplemented_conversion_with_fixed_point_type) 7283 << SrcTy; 7284 return CK_IntegralCast; 7285 } 7286 llvm_unreachable("Should have returned before this"); 7287 } 7288 7289 llvm_unreachable("Unhandled scalar cast"); 7290 } 7291 7292 static bool breakDownVectorType(QualType type, uint64_t &len, 7293 QualType &eltType) { 7294 // Vectors are simple. 7295 if (const VectorType *vecType = type->getAs<VectorType>()) { 7296 len = vecType->getNumElements(); 7297 eltType = vecType->getElementType(); 7298 assert(eltType->isScalarType()); 7299 return true; 7300 } 7301 7302 // We allow lax conversion to and from non-vector types, but only if 7303 // they're real types (i.e. non-complex, non-pointer scalar types). 7304 if (!type->isRealType()) return false; 7305 7306 len = 1; 7307 eltType = type; 7308 return true; 7309 } 7310 7311 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7312 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7313 /// allowed? 7314 /// 7315 /// This will also return false if the two given types do not make sense from 7316 /// the perspective of SVE bitcasts. 7317 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7318 assert(srcTy->isVectorType() || destTy->isVectorType()); 7319 7320 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7321 if (!FirstType->isSizelessBuiltinType()) 7322 return false; 7323 7324 const auto *VecTy = SecondType->getAs<VectorType>(); 7325 return VecTy && 7326 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7327 }; 7328 7329 return ValidScalableConversion(srcTy, destTy) || 7330 ValidScalableConversion(destTy, srcTy); 7331 } 7332 7333 /// Are the two types matrix types and do they have the same dimensions i.e. 7334 /// do they have the same number of rows and the same number of columns? 7335 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7336 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7337 return false; 7338 7339 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7340 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7341 7342 return matSrcType->getNumRows() == matDestType->getNumRows() && 7343 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7344 } 7345 7346 /// Are the two types lax-compatible vector types? That is, given 7347 /// that one of them is a vector, do they have equal storage sizes, 7348 /// where the storage size is the number of elements times the element 7349 /// size? 7350 /// 7351 /// This will also return false if either of the types is neither a 7352 /// vector nor a real type. 7353 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 7354 assert(destTy->isVectorType() || srcTy->isVectorType()); 7355 7356 // Disallow lax conversions between scalars and ExtVectors (these 7357 // conversions are allowed for other vector types because common headers 7358 // depend on them). Most scalar OP ExtVector cases are handled by the 7359 // splat path anyway, which does what we want (convert, not bitcast). 7360 // What this rules out for ExtVectors is crazy things like char4*float. 7361 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 7362 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 7363 7364 uint64_t srcLen, destLen; 7365 QualType srcEltTy, destEltTy; 7366 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 7367 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 7368 7369 // ASTContext::getTypeSize will return the size rounded up to a 7370 // power of 2, so instead of using that, we need to use the raw 7371 // element size multiplied by the element count. 7372 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 7373 uint64_t destEltSize = Context.getTypeSize(destEltTy); 7374 7375 return (srcLen * srcEltSize == destLen * destEltSize); 7376 } 7377 7378 /// Is this a legal conversion between two types, one of which is 7379 /// known to be a vector type? 7380 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 7381 assert(destTy->isVectorType() || srcTy->isVectorType()); 7382 7383 switch (Context.getLangOpts().getLaxVectorConversions()) { 7384 case LangOptions::LaxVectorConversionKind::None: 7385 return false; 7386 7387 case LangOptions::LaxVectorConversionKind::Integer: 7388 if (!srcTy->isIntegralOrEnumerationType()) { 7389 auto *Vec = srcTy->getAs<VectorType>(); 7390 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7391 return false; 7392 } 7393 if (!destTy->isIntegralOrEnumerationType()) { 7394 auto *Vec = destTy->getAs<VectorType>(); 7395 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 7396 return false; 7397 } 7398 // OK, integer (vector) -> integer (vector) bitcast. 7399 break; 7400 7401 case LangOptions::LaxVectorConversionKind::All: 7402 break; 7403 } 7404 7405 return areLaxCompatibleVectorTypes(srcTy, destTy); 7406 } 7407 7408 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7409 CastKind &Kind) { 7410 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 7411 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 7412 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 7413 << DestTy << SrcTy << R; 7414 } 7415 } else if (SrcTy->isMatrixType()) { 7416 return Diag(R.getBegin(), 7417 diag::err_invalid_conversion_between_matrix_and_type) 7418 << SrcTy << DestTy << R; 7419 } else if (DestTy->isMatrixType()) { 7420 return Diag(R.getBegin(), 7421 diag::err_invalid_conversion_between_matrix_and_type) 7422 << DestTy << SrcTy << R; 7423 } 7424 7425 Kind = CK_MatrixCast; 7426 return false; 7427 } 7428 7429 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7430 CastKind &Kind) { 7431 assert(VectorTy->isVectorType() && "Not a vector type!"); 7432 7433 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 7434 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 7435 return Diag(R.getBegin(), 7436 Ty->isVectorType() ? 7437 diag::err_invalid_conversion_between_vectors : 7438 diag::err_invalid_conversion_between_vector_and_integer) 7439 << VectorTy << Ty << R; 7440 } else 7441 return Diag(R.getBegin(), 7442 diag::err_invalid_conversion_between_vector_and_scalar) 7443 << VectorTy << Ty << R; 7444 7445 Kind = CK_BitCast; 7446 return false; 7447 } 7448 7449 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 7450 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 7451 7452 if (DestElemTy == SplattedExpr->getType()) 7453 return SplattedExpr; 7454 7455 assert(DestElemTy->isFloatingType() || 7456 DestElemTy->isIntegralOrEnumerationType()); 7457 7458 CastKind CK; 7459 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 7460 // OpenCL requires that we convert `true` boolean expressions to -1, but 7461 // only when splatting vectors. 7462 if (DestElemTy->isFloatingType()) { 7463 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 7464 // in two steps: boolean to signed integral, then to floating. 7465 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 7466 CK_BooleanToSignedIntegral); 7467 SplattedExpr = CastExprRes.get(); 7468 CK = CK_IntegralToFloating; 7469 } else { 7470 CK = CK_BooleanToSignedIntegral; 7471 } 7472 } else { 7473 ExprResult CastExprRes = SplattedExpr; 7474 CK = PrepareScalarCast(CastExprRes, DestElemTy); 7475 if (CastExprRes.isInvalid()) 7476 return ExprError(); 7477 SplattedExpr = CastExprRes.get(); 7478 } 7479 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 7480 } 7481 7482 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 7483 Expr *CastExpr, CastKind &Kind) { 7484 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 7485 7486 QualType SrcTy = CastExpr->getType(); 7487 7488 // If SrcTy is a VectorType, the total size must match to explicitly cast to 7489 // an ExtVectorType. 7490 // In OpenCL, casts between vectors of different types are not allowed. 7491 // (See OpenCL 6.2). 7492 if (SrcTy->isVectorType()) { 7493 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 7494 (getLangOpts().OpenCL && 7495 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 7496 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 7497 << DestTy << SrcTy << R; 7498 return ExprError(); 7499 } 7500 Kind = CK_BitCast; 7501 return CastExpr; 7502 } 7503 7504 // All non-pointer scalars can be cast to ExtVector type. The appropriate 7505 // conversion will take place first from scalar to elt type, and then 7506 // splat from elt type to vector. 7507 if (SrcTy->isPointerType()) 7508 return Diag(R.getBegin(), 7509 diag::err_invalid_conversion_between_vector_and_scalar) 7510 << DestTy << SrcTy << R; 7511 7512 Kind = CK_VectorSplat; 7513 return prepareVectorSplat(DestTy, CastExpr); 7514 } 7515 7516 ExprResult 7517 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 7518 Declarator &D, ParsedType &Ty, 7519 SourceLocation RParenLoc, Expr *CastExpr) { 7520 assert(!D.isInvalidType() && (CastExpr != nullptr) && 7521 "ActOnCastExpr(): missing type or expr"); 7522 7523 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 7524 if (D.isInvalidType()) 7525 return ExprError(); 7526 7527 if (getLangOpts().CPlusPlus) { 7528 // Check that there are no default arguments (C++ only). 7529 CheckExtraCXXDefaultArguments(D); 7530 } else { 7531 // Make sure any TypoExprs have been dealt with. 7532 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 7533 if (!Res.isUsable()) 7534 return ExprError(); 7535 CastExpr = Res.get(); 7536 } 7537 7538 checkUnusedDeclAttributes(D); 7539 7540 QualType castType = castTInfo->getType(); 7541 Ty = CreateParsedType(castType, castTInfo); 7542 7543 bool isVectorLiteral = false; 7544 7545 // Check for an altivec or OpenCL literal, 7546 // i.e. all the elements are integer constants. 7547 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 7548 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 7549 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 7550 && castType->isVectorType() && (PE || PLE)) { 7551 if (PLE && PLE->getNumExprs() == 0) { 7552 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 7553 return ExprError(); 7554 } 7555 if (PE || PLE->getNumExprs() == 1) { 7556 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 7557 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 7558 isVectorLiteral = true; 7559 } 7560 else 7561 isVectorLiteral = true; 7562 } 7563 7564 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 7565 // then handle it as such. 7566 if (isVectorLiteral) 7567 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 7568 7569 // If the Expr being casted is a ParenListExpr, handle it specially. 7570 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 7571 // sequence of BinOp comma operators. 7572 if (isa<ParenListExpr>(CastExpr)) { 7573 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 7574 if (Result.isInvalid()) return ExprError(); 7575 CastExpr = Result.get(); 7576 } 7577 7578 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 7579 !getSourceManager().isInSystemMacro(LParenLoc)) 7580 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 7581 7582 CheckTollFreeBridgeCast(castType, CastExpr); 7583 7584 CheckObjCBridgeRelatedCast(castType, CastExpr); 7585 7586 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 7587 7588 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 7589 } 7590 7591 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 7592 SourceLocation RParenLoc, Expr *E, 7593 TypeSourceInfo *TInfo) { 7594 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 7595 "Expected paren or paren list expression"); 7596 7597 Expr **exprs; 7598 unsigned numExprs; 7599 Expr *subExpr; 7600 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 7601 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 7602 LiteralLParenLoc = PE->getLParenLoc(); 7603 LiteralRParenLoc = PE->getRParenLoc(); 7604 exprs = PE->getExprs(); 7605 numExprs = PE->getNumExprs(); 7606 } else { // isa<ParenExpr> by assertion at function entrance 7607 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 7608 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 7609 subExpr = cast<ParenExpr>(E)->getSubExpr(); 7610 exprs = &subExpr; 7611 numExprs = 1; 7612 } 7613 7614 QualType Ty = TInfo->getType(); 7615 assert(Ty->isVectorType() && "Expected vector type"); 7616 7617 SmallVector<Expr *, 8> initExprs; 7618 const VectorType *VTy = Ty->castAs<VectorType>(); 7619 unsigned numElems = VTy->getNumElements(); 7620 7621 // '(...)' form of vector initialization in AltiVec: the number of 7622 // initializers must be one or must match the size of the vector. 7623 // If a single value is specified in the initializer then it will be 7624 // replicated to all the components of the vector 7625 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 7626 // The number of initializers must be one or must match the size of the 7627 // vector. If a single value is specified in the initializer then it will 7628 // be replicated to all the components of the vector 7629 if (numExprs == 1) { 7630 QualType ElemTy = VTy->getElementType(); 7631 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7632 if (Literal.isInvalid()) 7633 return ExprError(); 7634 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7635 PrepareScalarCast(Literal, ElemTy)); 7636 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7637 } 7638 else if (numExprs < numElems) { 7639 Diag(E->getExprLoc(), 7640 diag::err_incorrect_number_of_vector_initializers); 7641 return ExprError(); 7642 } 7643 else 7644 initExprs.append(exprs, exprs + numExprs); 7645 } 7646 else { 7647 // For OpenCL, when the number of initializers is a single value, 7648 // it will be replicated to all components of the vector. 7649 if (getLangOpts().OpenCL && 7650 VTy->getVectorKind() == VectorType::GenericVector && 7651 numExprs == 1) { 7652 QualType ElemTy = VTy->getElementType(); 7653 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 7654 if (Literal.isInvalid()) 7655 return ExprError(); 7656 Literal = ImpCastExprToType(Literal.get(), ElemTy, 7657 PrepareScalarCast(Literal, ElemTy)); 7658 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 7659 } 7660 7661 initExprs.append(exprs, exprs + numExprs); 7662 } 7663 // FIXME: This means that pretty-printing the final AST will produce curly 7664 // braces instead of the original commas. 7665 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 7666 initExprs, LiteralRParenLoc); 7667 initE->setType(Ty); 7668 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 7669 } 7670 7671 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7672 /// the ParenListExpr into a sequence of comma binary operators. 7673 ExprResult 7674 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 7675 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 7676 if (!E) 7677 return OrigExpr; 7678 7679 ExprResult Result(E->getExpr(0)); 7680 7681 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 7682 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 7683 E->getExpr(i)); 7684 7685 if (Result.isInvalid()) return ExprError(); 7686 7687 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 7688 } 7689 7690 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 7691 SourceLocation R, 7692 MultiExprArg Val) { 7693 return ParenListExpr::Create(Context, L, Val, R); 7694 } 7695 7696 /// Emit a specialized diagnostic when one expression is a null pointer 7697 /// constant and the other is not a pointer. Returns true if a diagnostic is 7698 /// emitted. 7699 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 7700 SourceLocation QuestionLoc) { 7701 Expr *NullExpr = LHSExpr; 7702 Expr *NonPointerExpr = RHSExpr; 7703 Expr::NullPointerConstantKind NullKind = 7704 NullExpr->isNullPointerConstant(Context, 7705 Expr::NPC_ValueDependentIsNotNull); 7706 7707 if (NullKind == Expr::NPCK_NotNull) { 7708 NullExpr = RHSExpr; 7709 NonPointerExpr = LHSExpr; 7710 NullKind = 7711 NullExpr->isNullPointerConstant(Context, 7712 Expr::NPC_ValueDependentIsNotNull); 7713 } 7714 7715 if (NullKind == Expr::NPCK_NotNull) 7716 return false; 7717 7718 if (NullKind == Expr::NPCK_ZeroExpression) 7719 return false; 7720 7721 if (NullKind == Expr::NPCK_ZeroLiteral) { 7722 // In this case, check to make sure that we got here from a "NULL" 7723 // string in the source code. 7724 NullExpr = NullExpr->IgnoreParenImpCasts(); 7725 SourceLocation loc = NullExpr->getExprLoc(); 7726 if (!findMacroSpelling(loc, "NULL")) 7727 return false; 7728 } 7729 7730 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 7731 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 7732 << NonPointerExpr->getType() << DiagType 7733 << NonPointerExpr->getSourceRange(); 7734 return true; 7735 } 7736 7737 /// Return false if the condition expression is valid, true otherwise. 7738 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 7739 QualType CondTy = Cond->getType(); 7740 7741 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 7742 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 7743 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 7744 << CondTy << Cond->getSourceRange(); 7745 return true; 7746 } 7747 7748 // C99 6.5.15p2 7749 if (CondTy->isScalarType()) return false; 7750 7751 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 7752 << CondTy << Cond->getSourceRange(); 7753 return true; 7754 } 7755 7756 /// Handle when one or both operands are void type. 7757 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 7758 ExprResult &RHS) { 7759 Expr *LHSExpr = LHS.get(); 7760 Expr *RHSExpr = RHS.get(); 7761 7762 if (!LHSExpr->getType()->isVoidType()) 7763 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7764 << RHSExpr->getSourceRange(); 7765 if (!RHSExpr->getType()->isVoidType()) 7766 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 7767 << LHSExpr->getSourceRange(); 7768 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 7769 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 7770 return S.Context.VoidTy; 7771 } 7772 7773 /// Return false if the NullExpr can be promoted to PointerTy, 7774 /// true otherwise. 7775 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 7776 QualType PointerTy) { 7777 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 7778 !NullExpr.get()->isNullPointerConstant(S.Context, 7779 Expr::NPC_ValueDependentIsNull)) 7780 return true; 7781 7782 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 7783 return false; 7784 } 7785 7786 /// Checks compatibility between two pointers and return the resulting 7787 /// type. 7788 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 7789 ExprResult &RHS, 7790 SourceLocation Loc) { 7791 QualType LHSTy = LHS.get()->getType(); 7792 QualType RHSTy = RHS.get()->getType(); 7793 7794 if (S.Context.hasSameType(LHSTy, RHSTy)) { 7795 // Two identical pointers types are always compatible. 7796 return LHSTy; 7797 } 7798 7799 QualType lhptee, rhptee; 7800 7801 // Get the pointee types. 7802 bool IsBlockPointer = false; 7803 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 7804 lhptee = LHSBTy->getPointeeType(); 7805 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 7806 IsBlockPointer = true; 7807 } else { 7808 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7809 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7810 } 7811 7812 // C99 6.5.15p6: If both operands are pointers to compatible types or to 7813 // differently qualified versions of compatible types, the result type is 7814 // a pointer to an appropriately qualified version of the composite 7815 // type. 7816 7817 // Only CVR-qualifiers exist in the standard, and the differently-qualified 7818 // clause doesn't make sense for our extensions. E.g. address space 2 should 7819 // be incompatible with address space 3: they may live on different devices or 7820 // anything. 7821 Qualifiers lhQual = lhptee.getQualifiers(); 7822 Qualifiers rhQual = rhptee.getQualifiers(); 7823 7824 LangAS ResultAddrSpace = LangAS::Default; 7825 LangAS LAddrSpace = lhQual.getAddressSpace(); 7826 LangAS RAddrSpace = rhQual.getAddressSpace(); 7827 7828 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 7829 // spaces is disallowed. 7830 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 7831 ResultAddrSpace = LAddrSpace; 7832 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 7833 ResultAddrSpace = RAddrSpace; 7834 else { 7835 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7836 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 7837 << RHS.get()->getSourceRange(); 7838 return QualType(); 7839 } 7840 7841 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 7842 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 7843 lhQual.removeCVRQualifiers(); 7844 rhQual.removeCVRQualifiers(); 7845 7846 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 7847 // (C99 6.7.3) for address spaces. We assume that the check should behave in 7848 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 7849 // qual types are compatible iff 7850 // * corresponded types are compatible 7851 // * CVR qualifiers are equal 7852 // * address spaces are equal 7853 // Thus for conditional operator we merge CVR and address space unqualified 7854 // pointees and if there is a composite type we return a pointer to it with 7855 // merged qualifiers. 7856 LHSCastKind = 7857 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7858 RHSCastKind = 7859 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 7860 lhQual.removeAddressSpace(); 7861 rhQual.removeAddressSpace(); 7862 7863 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 7864 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 7865 7866 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 7867 7868 if (CompositeTy.isNull()) { 7869 // In this situation, we assume void* type. No especially good 7870 // reason, but this is what gcc does, and we do have to pick 7871 // to get a consistent AST. 7872 QualType incompatTy; 7873 incompatTy = S.Context.getPointerType( 7874 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 7875 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 7876 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 7877 7878 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 7879 // for casts between types with incompatible address space qualifiers. 7880 // For the following code the compiler produces casts between global and 7881 // local address spaces of the corresponded innermost pointees: 7882 // local int *global *a; 7883 // global int *global *b; 7884 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 7885 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 7886 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7887 << RHS.get()->getSourceRange(); 7888 7889 return incompatTy; 7890 } 7891 7892 // The pointer types are compatible. 7893 // In case of OpenCL ResultTy should have the address space qualifier 7894 // which is a superset of address spaces of both the 2nd and the 3rd 7895 // operands of the conditional operator. 7896 QualType ResultTy = [&, ResultAddrSpace]() { 7897 if (S.getLangOpts().OpenCL) { 7898 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 7899 CompositeQuals.setAddressSpace(ResultAddrSpace); 7900 return S.Context 7901 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 7902 .withCVRQualifiers(MergedCVRQual); 7903 } 7904 return CompositeTy.withCVRQualifiers(MergedCVRQual); 7905 }(); 7906 if (IsBlockPointer) 7907 ResultTy = S.Context.getBlockPointerType(ResultTy); 7908 else 7909 ResultTy = S.Context.getPointerType(ResultTy); 7910 7911 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 7912 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 7913 return ResultTy; 7914 } 7915 7916 /// Return the resulting type when the operands are both block pointers. 7917 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 7918 ExprResult &LHS, 7919 ExprResult &RHS, 7920 SourceLocation Loc) { 7921 QualType LHSTy = LHS.get()->getType(); 7922 QualType RHSTy = RHS.get()->getType(); 7923 7924 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 7925 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 7926 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 7927 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7928 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7929 return destType; 7930 } 7931 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 7932 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7933 << RHS.get()->getSourceRange(); 7934 return QualType(); 7935 } 7936 7937 // We have 2 block pointer types. 7938 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7939 } 7940 7941 /// Return the resulting type when the operands are both pointers. 7942 static QualType 7943 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 7944 ExprResult &RHS, 7945 SourceLocation Loc) { 7946 // get the pointer types 7947 QualType LHSTy = LHS.get()->getType(); 7948 QualType RHSTy = RHS.get()->getType(); 7949 7950 // get the "pointed to" types 7951 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 7952 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 7953 7954 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 7955 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 7956 // Figure out necessary qualifiers (C99 6.5.15p6) 7957 QualType destPointee 7958 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7959 QualType destType = S.Context.getPointerType(destPointee); 7960 // Add qualifiers if necessary. 7961 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7962 // Promote to void*. 7963 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7964 return destType; 7965 } 7966 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 7967 QualType destPointee 7968 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7969 QualType destType = S.Context.getPointerType(destPointee); 7970 // Add qualifiers if necessary. 7971 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7972 // Promote to void*. 7973 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7974 return destType; 7975 } 7976 7977 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 7978 } 7979 7980 /// Return false if the first expression is not an integer and the second 7981 /// expression is not a pointer, true otherwise. 7982 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 7983 Expr* PointerExpr, SourceLocation Loc, 7984 bool IsIntFirstExpr) { 7985 if (!PointerExpr->getType()->isPointerType() || 7986 !Int.get()->getType()->isIntegerType()) 7987 return false; 7988 7989 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 7990 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 7991 7992 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 7993 << Expr1->getType() << Expr2->getType() 7994 << Expr1->getSourceRange() << Expr2->getSourceRange(); 7995 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 7996 CK_IntegralToPointer); 7997 return true; 7998 } 7999 8000 /// Simple conversion between integer and floating point types. 8001 /// 8002 /// Used when handling the OpenCL conditional operator where the 8003 /// condition is a vector while the other operands are scalar. 8004 /// 8005 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8006 /// types are either integer or floating type. Between the two 8007 /// operands, the type with the higher rank is defined as the "result 8008 /// type". The other operand needs to be promoted to the same type. No 8009 /// other type promotion is allowed. We cannot use 8010 /// UsualArithmeticConversions() for this purpose, since it always 8011 /// promotes promotable types. 8012 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8013 ExprResult &RHS, 8014 SourceLocation QuestionLoc) { 8015 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8016 if (LHS.isInvalid()) 8017 return QualType(); 8018 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8019 if (RHS.isInvalid()) 8020 return QualType(); 8021 8022 // For conversion purposes, we ignore any qualifiers. 8023 // For example, "const float" and "float" are equivalent. 8024 QualType LHSType = 8025 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8026 QualType RHSType = 8027 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8028 8029 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8030 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8031 << LHSType << LHS.get()->getSourceRange(); 8032 return QualType(); 8033 } 8034 8035 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8036 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8037 << RHSType << RHS.get()->getSourceRange(); 8038 return QualType(); 8039 } 8040 8041 // If both types are identical, no conversion is needed. 8042 if (LHSType == RHSType) 8043 return LHSType; 8044 8045 // Now handle "real" floating types (i.e. float, double, long double). 8046 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8047 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8048 /*IsCompAssign = */ false); 8049 8050 // Finally, we have two differing integer types. 8051 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8052 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8053 } 8054 8055 /// Convert scalar operands to a vector that matches the 8056 /// condition in length. 8057 /// 8058 /// Used when handling the OpenCL conditional operator where the 8059 /// condition is a vector while the other operands are scalar. 8060 /// 8061 /// We first compute the "result type" for the scalar operands 8062 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8063 /// into a vector of that type where the length matches the condition 8064 /// vector type. s6.11.6 requires that the element types of the result 8065 /// and the condition must have the same number of bits. 8066 static QualType 8067 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8068 QualType CondTy, SourceLocation QuestionLoc) { 8069 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8070 if (ResTy.isNull()) return QualType(); 8071 8072 const VectorType *CV = CondTy->getAs<VectorType>(); 8073 assert(CV); 8074 8075 // Determine the vector result type 8076 unsigned NumElements = CV->getNumElements(); 8077 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8078 8079 // Ensure that all types have the same number of bits 8080 if (S.Context.getTypeSize(CV->getElementType()) 8081 != S.Context.getTypeSize(ResTy)) { 8082 // Since VectorTy is created internally, it does not pretty print 8083 // with an OpenCL name. Instead, we just print a description. 8084 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8085 SmallString<64> Str; 8086 llvm::raw_svector_ostream OS(Str); 8087 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8088 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8089 << CondTy << OS.str(); 8090 return QualType(); 8091 } 8092 8093 // Convert operands to the vector result type 8094 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8095 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8096 8097 return VectorTy; 8098 } 8099 8100 /// Return false if this is a valid OpenCL condition vector 8101 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8102 SourceLocation QuestionLoc) { 8103 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8104 // integral type. 8105 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8106 assert(CondTy); 8107 QualType EleTy = CondTy->getElementType(); 8108 if (EleTy->isIntegerType()) return false; 8109 8110 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8111 << Cond->getType() << Cond->getSourceRange(); 8112 return true; 8113 } 8114 8115 /// Return false if the vector condition type and the vector 8116 /// result type are compatible. 8117 /// 8118 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8119 /// number of elements, and their element types have the same number 8120 /// of bits. 8121 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8122 SourceLocation QuestionLoc) { 8123 const VectorType *CV = CondTy->getAs<VectorType>(); 8124 const VectorType *RV = VecResTy->getAs<VectorType>(); 8125 assert(CV && RV); 8126 8127 if (CV->getNumElements() != RV->getNumElements()) { 8128 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8129 << CondTy << VecResTy; 8130 return true; 8131 } 8132 8133 QualType CVE = CV->getElementType(); 8134 QualType RVE = RV->getElementType(); 8135 8136 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8137 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8138 << CondTy << VecResTy; 8139 return true; 8140 } 8141 8142 return false; 8143 } 8144 8145 /// Return the resulting type for the conditional operator in 8146 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8147 /// s6.3.i) when the condition is a vector type. 8148 static QualType 8149 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8150 ExprResult &LHS, ExprResult &RHS, 8151 SourceLocation QuestionLoc) { 8152 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8153 if (Cond.isInvalid()) 8154 return QualType(); 8155 QualType CondTy = Cond.get()->getType(); 8156 8157 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8158 return QualType(); 8159 8160 // If either operand is a vector then find the vector type of the 8161 // result as specified in OpenCL v1.1 s6.3.i. 8162 if (LHS.get()->getType()->isVectorType() || 8163 RHS.get()->getType()->isVectorType()) { 8164 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8165 /*isCompAssign*/false, 8166 /*AllowBothBool*/true, 8167 /*AllowBoolConversions*/false); 8168 if (VecResTy.isNull()) return QualType(); 8169 // The result type must match the condition type as specified in 8170 // OpenCL v1.1 s6.11.6. 8171 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8172 return QualType(); 8173 return VecResTy; 8174 } 8175 8176 // Both operands are scalar. 8177 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8178 } 8179 8180 /// Return true if the Expr is block type 8181 static bool checkBlockType(Sema &S, const Expr *E) { 8182 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8183 QualType Ty = CE->getCallee()->getType(); 8184 if (Ty->isBlockPointerType()) { 8185 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8186 return true; 8187 } 8188 } 8189 return false; 8190 } 8191 8192 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8193 /// In that case, LHS = cond. 8194 /// C99 6.5.15 8195 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8196 ExprResult &RHS, ExprValueKind &VK, 8197 ExprObjectKind &OK, 8198 SourceLocation QuestionLoc) { 8199 8200 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8201 if (!LHSResult.isUsable()) return QualType(); 8202 LHS = LHSResult; 8203 8204 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8205 if (!RHSResult.isUsable()) return QualType(); 8206 RHS = RHSResult; 8207 8208 // C++ is sufficiently different to merit its own checker. 8209 if (getLangOpts().CPlusPlus) 8210 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8211 8212 VK = VK_RValue; 8213 OK = OK_Ordinary; 8214 8215 if (Context.isDependenceAllowed() && 8216 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8217 RHS.get()->isTypeDependent())) { 8218 assert(!getLangOpts().CPlusPlus); 8219 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8220 RHS.get()->containsErrors()) && 8221 "should only occur in error-recovery path."); 8222 return Context.DependentTy; 8223 } 8224 8225 // The OpenCL operator with a vector condition is sufficiently 8226 // different to merit its own checker. 8227 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8228 Cond.get()->getType()->isExtVectorType()) 8229 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8230 8231 // First, check the condition. 8232 Cond = UsualUnaryConversions(Cond.get()); 8233 if (Cond.isInvalid()) 8234 return QualType(); 8235 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8236 return QualType(); 8237 8238 // Now check the two expressions. 8239 if (LHS.get()->getType()->isVectorType() || 8240 RHS.get()->getType()->isVectorType()) 8241 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 8242 /*AllowBothBool*/true, 8243 /*AllowBoolConversions*/false); 8244 8245 QualType ResTy = 8246 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8247 if (LHS.isInvalid() || RHS.isInvalid()) 8248 return QualType(); 8249 8250 QualType LHSTy = LHS.get()->getType(); 8251 QualType RHSTy = RHS.get()->getType(); 8252 8253 // Diagnose attempts to convert between __float128 and long double where 8254 // such conversions currently can't be handled. 8255 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8256 Diag(QuestionLoc, 8257 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8258 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8259 return QualType(); 8260 } 8261 8262 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8263 // selection operator (?:). 8264 if (getLangOpts().OpenCL && 8265 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 8266 return QualType(); 8267 } 8268 8269 // If both operands have arithmetic type, do the usual arithmetic conversions 8270 // to find a common type: C99 6.5.15p3,5. 8271 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8272 // Disallow invalid arithmetic conversions, such as those between ExtInts of 8273 // different sizes, or between ExtInts and other types. 8274 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) { 8275 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8276 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8277 << RHS.get()->getSourceRange(); 8278 return QualType(); 8279 } 8280 8281 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8282 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8283 8284 return ResTy; 8285 } 8286 8287 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8288 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8289 return LHSTy; 8290 } 8291 8292 // If both operands are the same structure or union type, the result is that 8293 // type. 8294 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8295 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8296 if (LHSRT->getDecl() == RHSRT->getDecl()) 8297 // "If both the operands have structure or union type, the result has 8298 // that type." This implies that CV qualifiers are dropped. 8299 return LHSTy.getUnqualifiedType(); 8300 // FIXME: Type of conditional expression must be complete in C mode. 8301 } 8302 8303 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8304 // The following || allows only one side to be void (a GCC-ism). 8305 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8306 return checkConditionalVoidType(*this, LHS, RHS); 8307 } 8308 8309 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8310 // the type of the other operand." 8311 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8312 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8313 8314 // All objective-c pointer type analysis is done here. 8315 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8316 QuestionLoc); 8317 if (LHS.isInvalid() || RHS.isInvalid()) 8318 return QualType(); 8319 if (!compositeType.isNull()) 8320 return compositeType; 8321 8322 8323 // Handle block pointer types. 8324 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8325 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8326 QuestionLoc); 8327 8328 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8329 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8330 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8331 QuestionLoc); 8332 8333 // GCC compatibility: soften pointer/integer mismatch. Note that 8334 // null pointers have been filtered out by this point. 8335 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 8336 /*IsIntFirstExpr=*/true)) 8337 return RHSTy; 8338 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 8339 /*IsIntFirstExpr=*/false)) 8340 return LHSTy; 8341 8342 // Allow ?: operations in which both operands have the same 8343 // built-in sizeless type. 8344 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy) 8345 return LHSTy; 8346 8347 // Emit a better diagnostic if one of the expressions is a null pointer 8348 // constant and the other is not a pointer type. In this case, the user most 8349 // likely forgot to take the address of the other expression. 8350 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 8351 return QualType(); 8352 8353 // Otherwise, the operands are not compatible. 8354 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8355 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8356 << RHS.get()->getSourceRange(); 8357 return QualType(); 8358 } 8359 8360 /// FindCompositeObjCPointerType - Helper method to find composite type of 8361 /// two objective-c pointer types of the two input expressions. 8362 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8363 SourceLocation QuestionLoc) { 8364 QualType LHSTy = LHS.get()->getType(); 8365 QualType RHSTy = RHS.get()->getType(); 8366 8367 // Handle things like Class and struct objc_class*. Here we case the result 8368 // to the pseudo-builtin, because that will be implicitly cast back to the 8369 // redefinition type if an attempt is made to access its fields. 8370 if (LHSTy->isObjCClassType() && 8371 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 8372 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8373 return LHSTy; 8374 } 8375 if (RHSTy->isObjCClassType() && 8376 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 8377 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8378 return RHSTy; 8379 } 8380 // And the same for struct objc_object* / id 8381 if (LHSTy->isObjCIdType() && 8382 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 8383 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 8384 return LHSTy; 8385 } 8386 if (RHSTy->isObjCIdType() && 8387 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 8388 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 8389 return RHSTy; 8390 } 8391 // And the same for struct objc_selector* / SEL 8392 if (Context.isObjCSelType(LHSTy) && 8393 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 8394 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 8395 return LHSTy; 8396 } 8397 if (Context.isObjCSelType(RHSTy) && 8398 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 8399 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 8400 return RHSTy; 8401 } 8402 // Check constraints for Objective-C object pointers types. 8403 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 8404 8405 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 8406 // Two identical object pointer types are always compatible. 8407 return LHSTy; 8408 } 8409 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 8410 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 8411 QualType compositeType = LHSTy; 8412 8413 // If both operands are interfaces and either operand can be 8414 // assigned to the other, use that type as the composite 8415 // type. This allows 8416 // xxx ? (A*) a : (B*) b 8417 // where B is a subclass of A. 8418 // 8419 // Additionally, as for assignment, if either type is 'id' 8420 // allow silent coercion. Finally, if the types are 8421 // incompatible then make sure to use 'id' as the composite 8422 // type so the result is acceptable for sending messages to. 8423 8424 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 8425 // It could return the composite type. 8426 if (!(compositeType = 8427 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 8428 // Nothing more to do. 8429 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 8430 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 8431 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 8432 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 8433 } else if ((LHSOPT->isObjCQualifiedIdType() || 8434 RHSOPT->isObjCQualifiedIdType()) && 8435 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 8436 true)) { 8437 // Need to handle "id<xx>" explicitly. 8438 // GCC allows qualified id and any Objective-C type to devolve to 8439 // id. Currently localizing to here until clear this should be 8440 // part of ObjCQualifiedIdTypesAreCompatible. 8441 compositeType = Context.getObjCIdType(); 8442 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 8443 compositeType = Context.getObjCIdType(); 8444 } else { 8445 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 8446 << LHSTy << RHSTy 8447 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8448 QualType incompatTy = Context.getObjCIdType(); 8449 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 8450 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 8451 return incompatTy; 8452 } 8453 // The object pointer types are compatible. 8454 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 8455 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 8456 return compositeType; 8457 } 8458 // Check Objective-C object pointer types and 'void *' 8459 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 8460 if (getLangOpts().ObjCAutoRefCount) { 8461 // ARC forbids the implicit conversion of object pointers to 'void *', 8462 // so these types are not compatible. 8463 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8464 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8465 LHS = RHS = true; 8466 return QualType(); 8467 } 8468 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8469 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8470 QualType destPointee 8471 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8472 QualType destType = Context.getPointerType(destPointee); 8473 // Add qualifiers if necessary. 8474 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8475 // Promote to void*. 8476 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8477 return destType; 8478 } 8479 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 8480 if (getLangOpts().ObjCAutoRefCount) { 8481 // ARC forbids the implicit conversion of object pointers to 'void *', 8482 // so these types are not compatible. 8483 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 8484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8485 LHS = RHS = true; 8486 return QualType(); 8487 } 8488 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 8489 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8490 QualType destPointee 8491 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8492 QualType destType = Context.getPointerType(destPointee); 8493 // Add qualifiers if necessary. 8494 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8495 // Promote to void*. 8496 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8497 return destType; 8498 } 8499 return QualType(); 8500 } 8501 8502 /// SuggestParentheses - Emit a note with a fixit hint that wraps 8503 /// ParenRange in parentheses. 8504 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 8505 const PartialDiagnostic &Note, 8506 SourceRange ParenRange) { 8507 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 8508 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 8509 EndLoc.isValid()) { 8510 Self.Diag(Loc, Note) 8511 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 8512 << FixItHint::CreateInsertion(EndLoc, ")"); 8513 } else { 8514 // We can't display the parentheses, so just show the bare note. 8515 Self.Diag(Loc, Note) << ParenRange; 8516 } 8517 } 8518 8519 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 8520 return BinaryOperator::isAdditiveOp(Opc) || 8521 BinaryOperator::isMultiplicativeOp(Opc) || 8522 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 8523 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 8524 // not any of the logical operators. Bitwise-xor is commonly used as a 8525 // logical-xor because there is no logical-xor operator. The logical 8526 // operators, including uses of xor, have a high false positive rate for 8527 // precedence warnings. 8528 } 8529 8530 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 8531 /// expression, either using a built-in or overloaded operator, 8532 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 8533 /// expression. 8534 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 8535 Expr **RHSExprs) { 8536 // Don't strip parenthesis: we should not warn if E is in parenthesis. 8537 E = E->IgnoreImpCasts(); 8538 E = E->IgnoreConversionOperatorSingleStep(); 8539 E = E->IgnoreImpCasts(); 8540 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 8541 E = MTE->getSubExpr(); 8542 E = E->IgnoreImpCasts(); 8543 } 8544 8545 // Built-in binary operator. 8546 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 8547 if (IsArithmeticOp(OP->getOpcode())) { 8548 *Opcode = OP->getOpcode(); 8549 *RHSExprs = OP->getRHS(); 8550 return true; 8551 } 8552 } 8553 8554 // Overloaded operator. 8555 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 8556 if (Call->getNumArgs() != 2) 8557 return false; 8558 8559 // Make sure this is really a binary operator that is safe to pass into 8560 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 8561 OverloadedOperatorKind OO = Call->getOperator(); 8562 if (OO < OO_Plus || OO > OO_Arrow || 8563 OO == OO_PlusPlus || OO == OO_MinusMinus) 8564 return false; 8565 8566 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 8567 if (IsArithmeticOp(OpKind)) { 8568 *Opcode = OpKind; 8569 *RHSExprs = Call->getArg(1); 8570 return true; 8571 } 8572 } 8573 8574 return false; 8575 } 8576 8577 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 8578 /// or is a logical expression such as (x==y) which has int type, but is 8579 /// commonly interpreted as boolean. 8580 static bool ExprLooksBoolean(Expr *E) { 8581 E = E->IgnoreParenImpCasts(); 8582 8583 if (E->getType()->isBooleanType()) 8584 return true; 8585 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 8586 return OP->isComparisonOp() || OP->isLogicalOp(); 8587 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 8588 return OP->getOpcode() == UO_LNot; 8589 if (E->getType()->isPointerType()) 8590 return true; 8591 // FIXME: What about overloaded operator calls returning "unspecified boolean 8592 // type"s (commonly pointer-to-members)? 8593 8594 return false; 8595 } 8596 8597 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 8598 /// and binary operator are mixed in a way that suggests the programmer assumed 8599 /// the conditional operator has higher precedence, for example: 8600 /// "int x = a + someBinaryCondition ? 1 : 2". 8601 static void DiagnoseConditionalPrecedence(Sema &Self, 8602 SourceLocation OpLoc, 8603 Expr *Condition, 8604 Expr *LHSExpr, 8605 Expr *RHSExpr) { 8606 BinaryOperatorKind CondOpcode; 8607 Expr *CondRHS; 8608 8609 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 8610 return; 8611 if (!ExprLooksBoolean(CondRHS)) 8612 return; 8613 8614 // The condition is an arithmetic binary expression, with a right- 8615 // hand side that looks boolean, so warn. 8616 8617 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 8618 ? diag::warn_precedence_bitwise_conditional 8619 : diag::warn_precedence_conditional; 8620 8621 Self.Diag(OpLoc, DiagID) 8622 << Condition->getSourceRange() 8623 << BinaryOperator::getOpcodeStr(CondOpcode); 8624 8625 SuggestParentheses( 8626 Self, OpLoc, 8627 Self.PDiag(diag::note_precedence_silence) 8628 << BinaryOperator::getOpcodeStr(CondOpcode), 8629 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 8630 8631 SuggestParentheses(Self, OpLoc, 8632 Self.PDiag(diag::note_precedence_conditional_first), 8633 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 8634 } 8635 8636 /// Compute the nullability of a conditional expression. 8637 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 8638 QualType LHSTy, QualType RHSTy, 8639 ASTContext &Ctx) { 8640 if (!ResTy->isAnyPointerType()) 8641 return ResTy; 8642 8643 auto GetNullability = [&Ctx](QualType Ty) { 8644 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 8645 if (Kind) { 8646 // For our purposes, treat _Nullable_result as _Nullable. 8647 if (*Kind == NullabilityKind::NullableResult) 8648 return NullabilityKind::Nullable; 8649 return *Kind; 8650 } 8651 return NullabilityKind::Unspecified; 8652 }; 8653 8654 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 8655 NullabilityKind MergedKind; 8656 8657 // Compute nullability of a binary conditional expression. 8658 if (IsBin) { 8659 if (LHSKind == NullabilityKind::NonNull) 8660 MergedKind = NullabilityKind::NonNull; 8661 else 8662 MergedKind = RHSKind; 8663 // Compute nullability of a normal conditional expression. 8664 } else { 8665 if (LHSKind == NullabilityKind::Nullable || 8666 RHSKind == NullabilityKind::Nullable) 8667 MergedKind = NullabilityKind::Nullable; 8668 else if (LHSKind == NullabilityKind::NonNull) 8669 MergedKind = RHSKind; 8670 else if (RHSKind == NullabilityKind::NonNull) 8671 MergedKind = LHSKind; 8672 else 8673 MergedKind = NullabilityKind::Unspecified; 8674 } 8675 8676 // Return if ResTy already has the correct nullability. 8677 if (GetNullability(ResTy) == MergedKind) 8678 return ResTy; 8679 8680 // Strip all nullability from ResTy. 8681 while (ResTy->getNullability(Ctx)) 8682 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 8683 8684 // Create a new AttributedType with the new nullability kind. 8685 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 8686 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 8687 } 8688 8689 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 8690 /// in the case of a the GNU conditional expr extension. 8691 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 8692 SourceLocation ColonLoc, 8693 Expr *CondExpr, Expr *LHSExpr, 8694 Expr *RHSExpr) { 8695 if (!Context.isDependenceAllowed()) { 8696 // C cannot handle TypoExpr nodes in the condition because it 8697 // doesn't handle dependent types properly, so make sure any TypoExprs have 8698 // been dealt with before checking the operands. 8699 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 8700 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 8701 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 8702 8703 if (!CondResult.isUsable()) 8704 return ExprError(); 8705 8706 if (LHSExpr) { 8707 if (!LHSResult.isUsable()) 8708 return ExprError(); 8709 } 8710 8711 if (!RHSResult.isUsable()) 8712 return ExprError(); 8713 8714 CondExpr = CondResult.get(); 8715 LHSExpr = LHSResult.get(); 8716 RHSExpr = RHSResult.get(); 8717 } 8718 8719 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 8720 // was the condition. 8721 OpaqueValueExpr *opaqueValue = nullptr; 8722 Expr *commonExpr = nullptr; 8723 if (!LHSExpr) { 8724 commonExpr = CondExpr; 8725 // Lower out placeholder types first. This is important so that we don't 8726 // try to capture a placeholder. This happens in few cases in C++; such 8727 // as Objective-C++'s dictionary subscripting syntax. 8728 if (commonExpr->hasPlaceholderType()) { 8729 ExprResult result = CheckPlaceholderExpr(commonExpr); 8730 if (!result.isUsable()) return ExprError(); 8731 commonExpr = result.get(); 8732 } 8733 // We usually want to apply unary conversions *before* saving, except 8734 // in the special case of a C++ l-value conditional. 8735 if (!(getLangOpts().CPlusPlus 8736 && !commonExpr->isTypeDependent() 8737 && commonExpr->getValueKind() == RHSExpr->getValueKind() 8738 && commonExpr->isGLValue() 8739 && commonExpr->isOrdinaryOrBitFieldObject() 8740 && RHSExpr->isOrdinaryOrBitFieldObject() 8741 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 8742 ExprResult commonRes = UsualUnaryConversions(commonExpr); 8743 if (commonRes.isInvalid()) 8744 return ExprError(); 8745 commonExpr = commonRes.get(); 8746 } 8747 8748 // If the common expression is a class or array prvalue, materialize it 8749 // so that we can safely refer to it multiple times. 8750 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 8751 commonExpr->getType()->isArrayType())) { 8752 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 8753 if (MatExpr.isInvalid()) 8754 return ExprError(); 8755 commonExpr = MatExpr.get(); 8756 } 8757 8758 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 8759 commonExpr->getType(), 8760 commonExpr->getValueKind(), 8761 commonExpr->getObjectKind(), 8762 commonExpr); 8763 LHSExpr = CondExpr = opaqueValue; 8764 } 8765 8766 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 8767 ExprValueKind VK = VK_RValue; 8768 ExprObjectKind OK = OK_Ordinary; 8769 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 8770 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 8771 VK, OK, QuestionLoc); 8772 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 8773 RHS.isInvalid()) 8774 return ExprError(); 8775 8776 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 8777 RHS.get()); 8778 8779 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 8780 8781 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 8782 Context); 8783 8784 if (!commonExpr) 8785 return new (Context) 8786 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 8787 RHS.get(), result, VK, OK); 8788 8789 return new (Context) BinaryConditionalOperator( 8790 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 8791 ColonLoc, result, VK, OK); 8792 } 8793 8794 // Check if we have a conversion between incompatible cmse function pointer 8795 // types, that is, a conversion between a function pointer with the 8796 // cmse_nonsecure_call attribute and one without. 8797 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 8798 QualType ToType) { 8799 if (const auto *ToFn = 8800 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 8801 if (const auto *FromFn = 8802 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 8803 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 8804 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 8805 8806 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 8807 } 8808 } 8809 return false; 8810 } 8811 8812 // checkPointerTypesForAssignment - This is a very tricky routine (despite 8813 // being closely modeled after the C99 spec:-). The odd characteristic of this 8814 // routine is it effectively iqnores the qualifiers on the top level pointee. 8815 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 8816 // FIXME: add a couple examples in this comment. 8817 static Sema::AssignConvertType 8818 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 8819 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8820 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8821 8822 // get the "pointed to" type (ignoring qualifiers at the top level) 8823 const Type *lhptee, *rhptee; 8824 Qualifiers lhq, rhq; 8825 std::tie(lhptee, lhq) = 8826 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 8827 std::tie(rhptee, rhq) = 8828 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 8829 8830 Sema::AssignConvertType ConvTy = Sema::Compatible; 8831 8832 // C99 6.5.16.1p1: This following citation is common to constraints 8833 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 8834 // qualifiers of the type *pointed to* by the right; 8835 8836 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 8837 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 8838 lhq.compatiblyIncludesObjCLifetime(rhq)) { 8839 // Ignore lifetime for further calculation. 8840 lhq.removeObjCLifetime(); 8841 rhq.removeObjCLifetime(); 8842 } 8843 8844 if (!lhq.compatiblyIncludes(rhq)) { 8845 // Treat address-space mismatches as fatal. 8846 if (!lhq.isAddressSpaceSupersetOf(rhq)) 8847 return Sema::IncompatiblePointerDiscardsQualifiers; 8848 8849 // It's okay to add or remove GC or lifetime qualifiers when converting to 8850 // and from void*. 8851 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 8852 .compatiblyIncludes( 8853 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 8854 && (lhptee->isVoidType() || rhptee->isVoidType())) 8855 ; // keep old 8856 8857 // Treat lifetime mismatches as fatal. 8858 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 8859 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 8860 8861 // For GCC/MS compatibility, other qualifier mismatches are treated 8862 // as still compatible in C. 8863 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8864 } 8865 8866 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 8867 // incomplete type and the other is a pointer to a qualified or unqualified 8868 // version of void... 8869 if (lhptee->isVoidType()) { 8870 if (rhptee->isIncompleteOrObjectType()) 8871 return ConvTy; 8872 8873 // As an extension, we allow cast to/from void* to function pointer. 8874 assert(rhptee->isFunctionType()); 8875 return Sema::FunctionVoidPointer; 8876 } 8877 8878 if (rhptee->isVoidType()) { 8879 if (lhptee->isIncompleteOrObjectType()) 8880 return ConvTy; 8881 8882 // As an extension, we allow cast to/from void* to function pointer. 8883 assert(lhptee->isFunctionType()); 8884 return Sema::FunctionVoidPointer; 8885 } 8886 8887 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 8888 // unqualified versions of compatible types, ... 8889 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 8890 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 8891 // Check if the pointee types are compatible ignoring the sign. 8892 // We explicitly check for char so that we catch "char" vs 8893 // "unsigned char" on systems where "char" is unsigned. 8894 if (lhptee->isCharType()) 8895 ltrans = S.Context.UnsignedCharTy; 8896 else if (lhptee->hasSignedIntegerRepresentation()) 8897 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 8898 8899 if (rhptee->isCharType()) 8900 rtrans = S.Context.UnsignedCharTy; 8901 else if (rhptee->hasSignedIntegerRepresentation()) 8902 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 8903 8904 if (ltrans == rtrans) { 8905 // Types are compatible ignoring the sign. Qualifier incompatibility 8906 // takes priority over sign incompatibility because the sign 8907 // warning can be disabled. 8908 if (ConvTy != Sema::Compatible) 8909 return ConvTy; 8910 8911 return Sema::IncompatiblePointerSign; 8912 } 8913 8914 // If we are a multi-level pointer, it's possible that our issue is simply 8915 // one of qualification - e.g. char ** -> const char ** is not allowed. If 8916 // the eventual target type is the same and the pointers have the same 8917 // level of indirection, this must be the issue. 8918 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 8919 do { 8920 std::tie(lhptee, lhq) = 8921 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 8922 std::tie(rhptee, rhq) = 8923 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 8924 8925 // Inconsistent address spaces at this point is invalid, even if the 8926 // address spaces would be compatible. 8927 // FIXME: This doesn't catch address space mismatches for pointers of 8928 // different nesting levels, like: 8929 // __local int *** a; 8930 // int ** b = a; 8931 // It's not clear how to actually determine when such pointers are 8932 // invalidly incompatible. 8933 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 8934 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 8935 8936 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 8937 8938 if (lhptee == rhptee) 8939 return Sema::IncompatibleNestedPointerQualifiers; 8940 } 8941 8942 // General pointer incompatibility takes priority over qualifiers. 8943 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 8944 return Sema::IncompatibleFunctionPointer; 8945 return Sema::IncompatiblePointer; 8946 } 8947 if (!S.getLangOpts().CPlusPlus && 8948 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 8949 return Sema::IncompatibleFunctionPointer; 8950 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 8951 return Sema::IncompatibleFunctionPointer; 8952 return ConvTy; 8953 } 8954 8955 /// checkBlockPointerTypesForAssignment - This routine determines whether two 8956 /// block pointer types are compatible or whether a block and normal pointer 8957 /// are compatible. It is more restrict than comparing two function pointer 8958 // types. 8959 static Sema::AssignConvertType 8960 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 8961 QualType RHSType) { 8962 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 8963 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 8964 8965 QualType lhptee, rhptee; 8966 8967 // get the "pointed to" type (ignoring qualifiers at the top level) 8968 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 8969 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 8970 8971 // In C++, the types have to match exactly. 8972 if (S.getLangOpts().CPlusPlus) 8973 return Sema::IncompatibleBlockPointer; 8974 8975 Sema::AssignConvertType ConvTy = Sema::Compatible; 8976 8977 // For blocks we enforce that qualifiers are identical. 8978 Qualifiers LQuals = lhptee.getLocalQualifiers(); 8979 Qualifiers RQuals = rhptee.getLocalQualifiers(); 8980 if (S.getLangOpts().OpenCL) { 8981 LQuals.removeAddressSpace(); 8982 RQuals.removeAddressSpace(); 8983 } 8984 if (LQuals != RQuals) 8985 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 8986 8987 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 8988 // assignment. 8989 // The current behavior is similar to C++ lambdas. A block might be 8990 // assigned to a variable iff its return type and parameters are compatible 8991 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 8992 // an assignment. Presumably it should behave in way that a function pointer 8993 // assignment does in C, so for each parameter and return type: 8994 // * CVR and address space of LHS should be a superset of CVR and address 8995 // space of RHS. 8996 // * unqualified types should be compatible. 8997 if (S.getLangOpts().OpenCL) { 8998 if (!S.Context.typesAreBlockPointerCompatible( 8999 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9000 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9001 return Sema::IncompatibleBlockPointer; 9002 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9003 return Sema::IncompatibleBlockPointer; 9004 9005 return ConvTy; 9006 } 9007 9008 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9009 /// for assignment compatibility. 9010 static Sema::AssignConvertType 9011 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9012 QualType RHSType) { 9013 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9014 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9015 9016 if (LHSType->isObjCBuiltinType()) { 9017 // Class is not compatible with ObjC object pointers. 9018 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9019 !RHSType->isObjCQualifiedClassType()) 9020 return Sema::IncompatiblePointer; 9021 return Sema::Compatible; 9022 } 9023 if (RHSType->isObjCBuiltinType()) { 9024 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9025 !LHSType->isObjCQualifiedClassType()) 9026 return Sema::IncompatiblePointer; 9027 return Sema::Compatible; 9028 } 9029 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9030 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9031 9032 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9033 // make an exception for id<P> 9034 !LHSType->isObjCQualifiedIdType()) 9035 return Sema::CompatiblePointerDiscardsQualifiers; 9036 9037 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9038 return Sema::Compatible; 9039 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9040 return Sema::IncompatibleObjCQualifiedId; 9041 return Sema::IncompatiblePointer; 9042 } 9043 9044 Sema::AssignConvertType 9045 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9046 QualType LHSType, QualType RHSType) { 9047 // Fake up an opaque expression. We don't actually care about what 9048 // cast operations are required, so if CheckAssignmentConstraints 9049 // adds casts to this they'll be wasted, but fortunately that doesn't 9050 // usually happen on valid code. 9051 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 9052 ExprResult RHSPtr = &RHSExpr; 9053 CastKind K; 9054 9055 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9056 } 9057 9058 /// This helper function returns true if QT is a vector type that has element 9059 /// type ElementType. 9060 static bool isVector(QualType QT, QualType ElementType) { 9061 if (const VectorType *VT = QT->getAs<VectorType>()) 9062 return VT->getElementType().getCanonicalType() == ElementType; 9063 return false; 9064 } 9065 9066 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9067 /// has code to accommodate several GCC extensions when type checking 9068 /// pointers. Here are some objectionable examples that GCC considers warnings: 9069 /// 9070 /// int a, *pint; 9071 /// short *pshort; 9072 /// struct foo *pfoo; 9073 /// 9074 /// pint = pshort; // warning: assignment from incompatible pointer type 9075 /// a = pint; // warning: assignment makes integer from pointer without a cast 9076 /// pint = a; // warning: assignment makes pointer from integer without a cast 9077 /// pint = pfoo; // warning: assignment from incompatible pointer type 9078 /// 9079 /// As a result, the code for dealing with pointers is more complex than the 9080 /// C99 spec dictates. 9081 /// 9082 /// Sets 'Kind' for any result kind except Incompatible. 9083 Sema::AssignConvertType 9084 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9085 CastKind &Kind, bool ConvertRHS) { 9086 QualType RHSType = RHS.get()->getType(); 9087 QualType OrigLHSType = LHSType; 9088 9089 // Get canonical types. We're not formatting these types, just comparing 9090 // them. 9091 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9092 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9093 9094 // Common case: no conversion required. 9095 if (LHSType == RHSType) { 9096 Kind = CK_NoOp; 9097 return Compatible; 9098 } 9099 9100 // If we have an atomic type, try a non-atomic assignment, then just add an 9101 // atomic qualification step. 9102 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9103 Sema::AssignConvertType result = 9104 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9105 if (result != Compatible) 9106 return result; 9107 if (Kind != CK_NoOp && ConvertRHS) 9108 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9109 Kind = CK_NonAtomicToAtomic; 9110 return Compatible; 9111 } 9112 9113 // If the left-hand side is a reference type, then we are in a 9114 // (rare!) case where we've allowed the use of references in C, 9115 // e.g., as a parameter type in a built-in function. In this case, 9116 // just make sure that the type referenced is compatible with the 9117 // right-hand side type. The caller is responsible for adjusting 9118 // LHSType so that the resulting expression does not have reference 9119 // type. 9120 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9121 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9122 Kind = CK_LValueBitCast; 9123 return Compatible; 9124 } 9125 return Incompatible; 9126 } 9127 9128 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9129 // to the same ExtVector type. 9130 if (LHSType->isExtVectorType()) { 9131 if (RHSType->isExtVectorType()) 9132 return Incompatible; 9133 if (RHSType->isArithmeticType()) { 9134 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9135 if (ConvertRHS) 9136 RHS = prepareVectorSplat(LHSType, RHS.get()); 9137 Kind = CK_VectorSplat; 9138 return Compatible; 9139 } 9140 } 9141 9142 // Conversions to or from vector type. 9143 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9144 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9145 // Allow assignments of an AltiVec vector type to an equivalent GCC 9146 // vector type and vice versa 9147 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9148 Kind = CK_BitCast; 9149 return Compatible; 9150 } 9151 9152 // If we are allowing lax vector conversions, and LHS and RHS are both 9153 // vectors, the total size only needs to be the same. This is a bitcast; 9154 // no bits are changed but the result type is different. 9155 if (isLaxVectorConversion(RHSType, LHSType)) { 9156 Kind = CK_BitCast; 9157 return IncompatibleVectors; 9158 } 9159 } 9160 9161 // When the RHS comes from another lax conversion (e.g. binops between 9162 // scalars and vectors) the result is canonicalized as a vector. When the 9163 // LHS is also a vector, the lax is allowed by the condition above. Handle 9164 // the case where LHS is a scalar. 9165 if (LHSType->isScalarType()) { 9166 const VectorType *VecType = RHSType->getAs<VectorType>(); 9167 if (VecType && VecType->getNumElements() == 1 && 9168 isLaxVectorConversion(RHSType, LHSType)) { 9169 ExprResult *VecExpr = &RHS; 9170 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9171 Kind = CK_BitCast; 9172 return Compatible; 9173 } 9174 } 9175 9176 // Allow assignments between fixed-length and sizeless SVE vectors. 9177 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9178 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9179 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9180 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9181 Kind = CK_BitCast; 9182 return Compatible; 9183 } 9184 9185 return Incompatible; 9186 } 9187 9188 // Diagnose attempts to convert between __float128 and long double where 9189 // such conversions currently can't be handled. 9190 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9191 return Incompatible; 9192 9193 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9194 // discards the imaginary part. 9195 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9196 !LHSType->getAs<ComplexType>()) 9197 return Incompatible; 9198 9199 // Arithmetic conversions. 9200 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9201 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9202 if (ConvertRHS) 9203 Kind = PrepareScalarCast(RHS, LHSType); 9204 return Compatible; 9205 } 9206 9207 // Conversions to normal pointers. 9208 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9209 // U* -> T* 9210 if (isa<PointerType>(RHSType)) { 9211 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9212 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9213 if (AddrSpaceL != AddrSpaceR) 9214 Kind = CK_AddressSpaceConversion; 9215 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9216 Kind = CK_NoOp; 9217 else 9218 Kind = CK_BitCast; 9219 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 9220 } 9221 9222 // int -> T* 9223 if (RHSType->isIntegerType()) { 9224 Kind = CK_IntegralToPointer; // FIXME: null? 9225 return IntToPointer; 9226 } 9227 9228 // C pointers are not compatible with ObjC object pointers, 9229 // with two exceptions: 9230 if (isa<ObjCObjectPointerType>(RHSType)) { 9231 // - conversions to void* 9232 if (LHSPointer->getPointeeType()->isVoidType()) { 9233 Kind = CK_BitCast; 9234 return Compatible; 9235 } 9236 9237 // - conversions from 'Class' to the redefinition type 9238 if (RHSType->isObjCClassType() && 9239 Context.hasSameType(LHSType, 9240 Context.getObjCClassRedefinitionType())) { 9241 Kind = CK_BitCast; 9242 return Compatible; 9243 } 9244 9245 Kind = CK_BitCast; 9246 return IncompatiblePointer; 9247 } 9248 9249 // U^ -> void* 9250 if (RHSType->getAs<BlockPointerType>()) { 9251 if (LHSPointer->getPointeeType()->isVoidType()) { 9252 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9253 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9254 ->getPointeeType() 9255 .getAddressSpace(); 9256 Kind = 9257 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9258 return Compatible; 9259 } 9260 } 9261 9262 return Incompatible; 9263 } 9264 9265 // Conversions to block pointers. 9266 if (isa<BlockPointerType>(LHSType)) { 9267 // U^ -> T^ 9268 if (RHSType->isBlockPointerType()) { 9269 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9270 ->getPointeeType() 9271 .getAddressSpace(); 9272 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9273 ->getPointeeType() 9274 .getAddressSpace(); 9275 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9276 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9277 } 9278 9279 // int or null -> T^ 9280 if (RHSType->isIntegerType()) { 9281 Kind = CK_IntegralToPointer; // FIXME: null 9282 return IntToBlockPointer; 9283 } 9284 9285 // id -> T^ 9286 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9287 Kind = CK_AnyPointerToBlockPointerCast; 9288 return Compatible; 9289 } 9290 9291 // void* -> T^ 9292 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9293 if (RHSPT->getPointeeType()->isVoidType()) { 9294 Kind = CK_AnyPointerToBlockPointerCast; 9295 return Compatible; 9296 } 9297 9298 return Incompatible; 9299 } 9300 9301 // Conversions to Objective-C pointers. 9302 if (isa<ObjCObjectPointerType>(LHSType)) { 9303 // A* -> B* 9304 if (RHSType->isObjCObjectPointerType()) { 9305 Kind = CK_BitCast; 9306 Sema::AssignConvertType result = 9307 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 9308 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9309 result == Compatible && 9310 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 9311 result = IncompatibleObjCWeakRef; 9312 return result; 9313 } 9314 9315 // int or null -> A* 9316 if (RHSType->isIntegerType()) { 9317 Kind = CK_IntegralToPointer; // FIXME: null 9318 return IntToPointer; 9319 } 9320 9321 // In general, C pointers are not compatible with ObjC object pointers, 9322 // with two exceptions: 9323 if (isa<PointerType>(RHSType)) { 9324 Kind = CK_CPointerToObjCPointerCast; 9325 9326 // - conversions from 'void*' 9327 if (RHSType->isVoidPointerType()) { 9328 return Compatible; 9329 } 9330 9331 // - conversions to 'Class' from its redefinition type 9332 if (LHSType->isObjCClassType() && 9333 Context.hasSameType(RHSType, 9334 Context.getObjCClassRedefinitionType())) { 9335 return Compatible; 9336 } 9337 9338 return IncompatiblePointer; 9339 } 9340 9341 // Only under strict condition T^ is compatible with an Objective-C pointer. 9342 if (RHSType->isBlockPointerType() && 9343 LHSType->isBlockCompatibleObjCPointerType(Context)) { 9344 if (ConvertRHS) 9345 maybeExtendBlockObject(RHS); 9346 Kind = CK_BlockPointerToObjCPointerCast; 9347 return Compatible; 9348 } 9349 9350 return Incompatible; 9351 } 9352 9353 // Conversions from pointers that are not covered by the above. 9354 if (isa<PointerType>(RHSType)) { 9355 // T* -> _Bool 9356 if (LHSType == Context.BoolTy) { 9357 Kind = CK_PointerToBoolean; 9358 return Compatible; 9359 } 9360 9361 // T* -> int 9362 if (LHSType->isIntegerType()) { 9363 Kind = CK_PointerToIntegral; 9364 return PointerToInt; 9365 } 9366 9367 return Incompatible; 9368 } 9369 9370 // Conversions from Objective-C pointers that are not covered by the above. 9371 if (isa<ObjCObjectPointerType>(RHSType)) { 9372 // T* -> _Bool 9373 if (LHSType == Context.BoolTy) { 9374 Kind = CK_PointerToBoolean; 9375 return Compatible; 9376 } 9377 9378 // T* -> int 9379 if (LHSType->isIntegerType()) { 9380 Kind = CK_PointerToIntegral; 9381 return PointerToInt; 9382 } 9383 9384 return Incompatible; 9385 } 9386 9387 // struct A -> struct B 9388 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 9389 if (Context.typesAreCompatible(LHSType, RHSType)) { 9390 Kind = CK_NoOp; 9391 return Compatible; 9392 } 9393 } 9394 9395 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 9396 Kind = CK_IntToOCLSampler; 9397 return Compatible; 9398 } 9399 9400 return Incompatible; 9401 } 9402 9403 /// Constructs a transparent union from an expression that is 9404 /// used to initialize the transparent union. 9405 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 9406 ExprResult &EResult, QualType UnionType, 9407 FieldDecl *Field) { 9408 // Build an initializer list that designates the appropriate member 9409 // of the transparent union. 9410 Expr *E = EResult.get(); 9411 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 9412 E, SourceLocation()); 9413 Initializer->setType(UnionType); 9414 Initializer->setInitializedFieldInUnion(Field); 9415 9416 // Build a compound literal constructing a value of the transparent 9417 // union type from this initializer list. 9418 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 9419 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 9420 VK_RValue, Initializer, false); 9421 } 9422 9423 Sema::AssignConvertType 9424 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 9425 ExprResult &RHS) { 9426 QualType RHSType = RHS.get()->getType(); 9427 9428 // If the ArgType is a Union type, we want to handle a potential 9429 // transparent_union GCC extension. 9430 const RecordType *UT = ArgType->getAsUnionType(); 9431 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 9432 return Incompatible; 9433 9434 // The field to initialize within the transparent union. 9435 RecordDecl *UD = UT->getDecl(); 9436 FieldDecl *InitField = nullptr; 9437 // It's compatible if the expression matches any of the fields. 9438 for (auto *it : UD->fields()) { 9439 if (it->getType()->isPointerType()) { 9440 // If the transparent union contains a pointer type, we allow: 9441 // 1) void pointer 9442 // 2) null pointer constant 9443 if (RHSType->isPointerType()) 9444 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 9445 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 9446 InitField = it; 9447 break; 9448 } 9449 9450 if (RHS.get()->isNullPointerConstant(Context, 9451 Expr::NPC_ValueDependentIsNull)) { 9452 RHS = ImpCastExprToType(RHS.get(), it->getType(), 9453 CK_NullToPointer); 9454 InitField = it; 9455 break; 9456 } 9457 } 9458 9459 CastKind Kind; 9460 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 9461 == Compatible) { 9462 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 9463 InitField = it; 9464 break; 9465 } 9466 } 9467 9468 if (!InitField) 9469 return Incompatible; 9470 9471 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 9472 return Compatible; 9473 } 9474 9475 Sema::AssignConvertType 9476 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 9477 bool Diagnose, 9478 bool DiagnoseCFAudited, 9479 bool ConvertRHS) { 9480 // We need to be able to tell the caller whether we diagnosed a problem, if 9481 // they ask us to issue diagnostics. 9482 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 9483 9484 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 9485 // we can't avoid *all* modifications at the moment, so we need some somewhere 9486 // to put the updated value. 9487 ExprResult LocalRHS = CallerRHS; 9488 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 9489 9490 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 9491 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 9492 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 9493 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 9494 Diag(RHS.get()->getExprLoc(), 9495 diag::warn_noderef_to_dereferenceable_pointer) 9496 << RHS.get()->getSourceRange(); 9497 } 9498 } 9499 } 9500 9501 if (getLangOpts().CPlusPlus) { 9502 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 9503 // C++ 5.17p3: If the left operand is not of class type, the 9504 // expression is implicitly converted (C++ 4) to the 9505 // cv-unqualified type of the left operand. 9506 QualType RHSType = RHS.get()->getType(); 9507 if (Diagnose) { 9508 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9509 AA_Assigning); 9510 } else { 9511 ImplicitConversionSequence ICS = 9512 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9513 /*SuppressUserConversions=*/false, 9514 AllowedExplicit::None, 9515 /*InOverloadResolution=*/false, 9516 /*CStyle=*/false, 9517 /*AllowObjCWritebackConversion=*/false); 9518 if (ICS.isFailure()) 9519 return Incompatible; 9520 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 9521 ICS, AA_Assigning); 9522 } 9523 if (RHS.isInvalid()) 9524 return Incompatible; 9525 Sema::AssignConvertType result = Compatible; 9526 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9527 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 9528 result = IncompatibleObjCWeakRef; 9529 return result; 9530 } 9531 9532 // FIXME: Currently, we fall through and treat C++ classes like C 9533 // structures. 9534 // FIXME: We also fall through for atomics; not sure what should 9535 // happen there, though. 9536 } else if (RHS.get()->getType() == Context.OverloadTy) { 9537 // As a set of extensions to C, we support overloading on functions. These 9538 // functions need to be resolved here. 9539 DeclAccessPair DAP; 9540 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 9541 RHS.get(), LHSType, /*Complain=*/false, DAP)) 9542 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 9543 else 9544 return Incompatible; 9545 } 9546 9547 // C99 6.5.16.1p1: the left operand is a pointer and the right is 9548 // a null pointer constant. 9549 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 9550 LHSType->isBlockPointerType()) && 9551 RHS.get()->isNullPointerConstant(Context, 9552 Expr::NPC_ValueDependentIsNull)) { 9553 if (Diagnose || ConvertRHS) { 9554 CastKind Kind; 9555 CXXCastPath Path; 9556 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 9557 /*IgnoreBaseAccess=*/false, Diagnose); 9558 if (ConvertRHS) 9559 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 9560 } 9561 return Compatible; 9562 } 9563 9564 // OpenCL queue_t type assignment. 9565 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 9566 Context, Expr::NPC_ValueDependentIsNull)) { 9567 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9568 return Compatible; 9569 } 9570 9571 // This check seems unnatural, however it is necessary to ensure the proper 9572 // conversion of functions/arrays. If the conversion were done for all 9573 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 9574 // expressions that suppress this implicit conversion (&, sizeof). 9575 // 9576 // Suppress this for references: C++ 8.5.3p5. 9577 if (!LHSType->isReferenceType()) { 9578 // FIXME: We potentially allocate here even if ConvertRHS is false. 9579 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 9580 if (RHS.isInvalid()) 9581 return Incompatible; 9582 } 9583 CastKind Kind; 9584 Sema::AssignConvertType result = 9585 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 9586 9587 // C99 6.5.16.1p2: The value of the right operand is converted to the 9588 // type of the assignment expression. 9589 // CheckAssignmentConstraints allows the left-hand side to be a reference, 9590 // so that we can use references in built-in functions even in C. 9591 // The getNonReferenceType() call makes sure that the resulting expression 9592 // does not have reference type. 9593 if (result != Incompatible && RHS.get()->getType() != LHSType) { 9594 QualType Ty = LHSType.getNonLValueExprType(Context); 9595 Expr *E = RHS.get(); 9596 9597 // Check for various Objective-C errors. If we are not reporting 9598 // diagnostics and just checking for errors, e.g., during overload 9599 // resolution, return Incompatible to indicate the failure. 9600 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 9601 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 9602 Diagnose, DiagnoseCFAudited) != ACR_okay) { 9603 if (!Diagnose) 9604 return Incompatible; 9605 } 9606 if (getLangOpts().ObjC && 9607 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 9608 E->getType(), E, Diagnose) || 9609 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 9610 if (!Diagnose) 9611 return Incompatible; 9612 // Replace the expression with a corrected version and continue so we 9613 // can find further errors. 9614 RHS = E; 9615 return Compatible; 9616 } 9617 9618 if (ConvertRHS) 9619 RHS = ImpCastExprToType(E, Ty, Kind); 9620 } 9621 9622 return result; 9623 } 9624 9625 namespace { 9626 /// The original operand to an operator, prior to the application of the usual 9627 /// arithmetic conversions and converting the arguments of a builtin operator 9628 /// candidate. 9629 struct OriginalOperand { 9630 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 9631 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 9632 Op = MTE->getSubExpr(); 9633 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 9634 Op = BTE->getSubExpr(); 9635 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 9636 Orig = ICE->getSubExprAsWritten(); 9637 Conversion = ICE->getConversionFunction(); 9638 } 9639 } 9640 9641 QualType getType() const { return Orig->getType(); } 9642 9643 Expr *Orig; 9644 NamedDecl *Conversion; 9645 }; 9646 } 9647 9648 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 9649 ExprResult &RHS) { 9650 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 9651 9652 Diag(Loc, diag::err_typecheck_invalid_operands) 9653 << OrigLHS.getType() << OrigRHS.getType() 9654 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9655 9656 // If a user-defined conversion was applied to either of the operands prior 9657 // to applying the built-in operator rules, tell the user about it. 9658 if (OrigLHS.Conversion) { 9659 Diag(OrigLHS.Conversion->getLocation(), 9660 diag::note_typecheck_invalid_operands_converted) 9661 << 0 << LHS.get()->getType(); 9662 } 9663 if (OrigRHS.Conversion) { 9664 Diag(OrigRHS.Conversion->getLocation(), 9665 diag::note_typecheck_invalid_operands_converted) 9666 << 1 << RHS.get()->getType(); 9667 } 9668 9669 return QualType(); 9670 } 9671 9672 // Diagnose cases where a scalar was implicitly converted to a vector and 9673 // diagnose the underlying types. Otherwise, diagnose the error 9674 // as invalid vector logical operands for non-C++ cases. 9675 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 9676 ExprResult &RHS) { 9677 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 9678 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 9679 9680 bool LHSNatVec = LHSType->isVectorType(); 9681 bool RHSNatVec = RHSType->isVectorType(); 9682 9683 if (!(LHSNatVec && RHSNatVec)) { 9684 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 9685 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 9686 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9687 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 9688 << Vector->getSourceRange(); 9689 return QualType(); 9690 } 9691 9692 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 9693 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 9694 << RHS.get()->getSourceRange(); 9695 9696 return QualType(); 9697 } 9698 9699 /// Try to convert a value of non-vector type to a vector type by converting 9700 /// the type to the element type of the vector and then performing a splat. 9701 /// If the language is OpenCL, we only use conversions that promote scalar 9702 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 9703 /// for float->int. 9704 /// 9705 /// OpenCL V2.0 6.2.6.p2: 9706 /// An error shall occur if any scalar operand type has greater rank 9707 /// than the type of the vector element. 9708 /// 9709 /// \param scalar - if non-null, actually perform the conversions 9710 /// \return true if the operation fails (but without diagnosing the failure) 9711 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 9712 QualType scalarTy, 9713 QualType vectorEltTy, 9714 QualType vectorTy, 9715 unsigned &DiagID) { 9716 // The conversion to apply to the scalar before splatting it, 9717 // if necessary. 9718 CastKind scalarCast = CK_NoOp; 9719 9720 if (vectorEltTy->isIntegralType(S.Context)) { 9721 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 9722 (scalarTy->isIntegerType() && 9723 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 9724 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9725 return true; 9726 } 9727 if (!scalarTy->isIntegralType(S.Context)) 9728 return true; 9729 scalarCast = CK_IntegralCast; 9730 } else if (vectorEltTy->isRealFloatingType()) { 9731 if (scalarTy->isRealFloatingType()) { 9732 if (S.getLangOpts().OpenCL && 9733 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 9734 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 9735 return true; 9736 } 9737 scalarCast = CK_FloatingCast; 9738 } 9739 else if (scalarTy->isIntegralType(S.Context)) 9740 scalarCast = CK_IntegralToFloating; 9741 else 9742 return true; 9743 } else { 9744 return true; 9745 } 9746 9747 // Adjust scalar if desired. 9748 if (scalar) { 9749 if (scalarCast != CK_NoOp) 9750 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 9751 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 9752 } 9753 return false; 9754 } 9755 9756 /// Convert vector E to a vector with the same number of elements but different 9757 /// element type. 9758 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 9759 const auto *VecTy = E->getType()->getAs<VectorType>(); 9760 assert(VecTy && "Expression E must be a vector"); 9761 QualType NewVecTy = S.Context.getVectorType(ElementType, 9762 VecTy->getNumElements(), 9763 VecTy->getVectorKind()); 9764 9765 // Look through the implicit cast. Return the subexpression if its type is 9766 // NewVecTy. 9767 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9768 if (ICE->getSubExpr()->getType() == NewVecTy) 9769 return ICE->getSubExpr(); 9770 9771 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 9772 return S.ImpCastExprToType(E, NewVecTy, Cast); 9773 } 9774 9775 /// Test if a (constant) integer Int can be casted to another integer type 9776 /// IntTy without losing precision. 9777 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 9778 QualType OtherIntTy) { 9779 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9780 9781 // Reject cases where the value of the Int is unknown as that would 9782 // possibly cause truncation, but accept cases where the scalar can be 9783 // demoted without loss of precision. 9784 Expr::EvalResult EVResult; 9785 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9786 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 9787 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 9788 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 9789 9790 if (CstInt) { 9791 // If the scalar is constant and is of a higher order and has more active 9792 // bits that the vector element type, reject it. 9793 llvm::APSInt Result = EVResult.Val.getInt(); 9794 unsigned NumBits = IntSigned 9795 ? (Result.isNegative() ? Result.getMinSignedBits() 9796 : Result.getActiveBits()) 9797 : Result.getActiveBits(); 9798 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 9799 return true; 9800 9801 // If the signedness of the scalar type and the vector element type 9802 // differs and the number of bits is greater than that of the vector 9803 // element reject it. 9804 return (IntSigned != OtherIntSigned && 9805 NumBits > S.Context.getIntWidth(OtherIntTy)); 9806 } 9807 9808 // Reject cases where the value of the scalar is not constant and it's 9809 // order is greater than that of the vector element type. 9810 return (Order < 0); 9811 } 9812 9813 /// Test if a (constant) integer Int can be casted to floating point type 9814 /// FloatTy without losing precision. 9815 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 9816 QualType FloatTy) { 9817 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 9818 9819 // Determine if the integer constant can be expressed as a floating point 9820 // number of the appropriate type. 9821 Expr::EvalResult EVResult; 9822 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 9823 9824 uint64_t Bits = 0; 9825 if (CstInt) { 9826 // Reject constants that would be truncated if they were converted to 9827 // the floating point type. Test by simple to/from conversion. 9828 // FIXME: Ideally the conversion to an APFloat and from an APFloat 9829 // could be avoided if there was a convertFromAPInt method 9830 // which could signal back if implicit truncation occurred. 9831 llvm::APSInt Result = EVResult.Val.getInt(); 9832 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 9833 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 9834 llvm::APFloat::rmTowardZero); 9835 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 9836 !IntTy->hasSignedIntegerRepresentation()); 9837 bool Ignored = false; 9838 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 9839 &Ignored); 9840 if (Result != ConvertBack) 9841 return true; 9842 } else { 9843 // Reject types that cannot be fully encoded into the mantissa of 9844 // the float. 9845 Bits = S.Context.getTypeSize(IntTy); 9846 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 9847 S.Context.getFloatTypeSemantics(FloatTy)); 9848 if (Bits > FloatPrec) 9849 return true; 9850 } 9851 9852 return false; 9853 } 9854 9855 /// Attempt to convert and splat Scalar into a vector whose types matches 9856 /// Vector following GCC conversion rules. The rule is that implicit 9857 /// conversion can occur when Scalar can be casted to match Vector's element 9858 /// type without causing truncation of Scalar. 9859 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 9860 ExprResult *Vector) { 9861 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 9862 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 9863 const VectorType *VT = VectorTy->getAs<VectorType>(); 9864 9865 assert(!isa<ExtVectorType>(VT) && 9866 "ExtVectorTypes should not be handled here!"); 9867 9868 QualType VectorEltTy = VT->getElementType(); 9869 9870 // Reject cases where the vector element type or the scalar element type are 9871 // not integral or floating point types. 9872 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 9873 return true; 9874 9875 // The conversion to apply to the scalar before splatting it, 9876 // if necessary. 9877 CastKind ScalarCast = CK_NoOp; 9878 9879 // Accept cases where the vector elements are integers and the scalar is 9880 // an integer. 9881 // FIXME: Notionally if the scalar was a floating point value with a precise 9882 // integral representation, we could cast it to an appropriate integer 9883 // type and then perform the rest of the checks here. GCC will perform 9884 // this conversion in some cases as determined by the input language. 9885 // We should accept it on a language independent basis. 9886 if (VectorEltTy->isIntegralType(S.Context) && 9887 ScalarTy->isIntegralType(S.Context) && 9888 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 9889 9890 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 9891 return true; 9892 9893 ScalarCast = CK_IntegralCast; 9894 } else if (VectorEltTy->isIntegralType(S.Context) && 9895 ScalarTy->isRealFloatingType()) { 9896 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 9897 ScalarCast = CK_FloatingToIntegral; 9898 else 9899 return true; 9900 } else if (VectorEltTy->isRealFloatingType()) { 9901 if (ScalarTy->isRealFloatingType()) { 9902 9903 // Reject cases where the scalar type is not a constant and has a higher 9904 // Order than the vector element type. 9905 llvm::APFloat Result(0.0); 9906 9907 // Determine whether this is a constant scalar. In the event that the 9908 // value is dependent (and thus cannot be evaluated by the constant 9909 // evaluator), skip the evaluation. This will then diagnose once the 9910 // expression is instantiated. 9911 bool CstScalar = Scalar->get()->isValueDependent() || 9912 Scalar->get()->EvaluateAsFloat(Result, S.Context); 9913 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 9914 if (!CstScalar && Order < 0) 9915 return true; 9916 9917 // If the scalar cannot be safely casted to the vector element type, 9918 // reject it. 9919 if (CstScalar) { 9920 bool Truncated = false; 9921 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 9922 llvm::APFloat::rmNearestTiesToEven, &Truncated); 9923 if (Truncated) 9924 return true; 9925 } 9926 9927 ScalarCast = CK_FloatingCast; 9928 } else if (ScalarTy->isIntegralType(S.Context)) { 9929 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 9930 return true; 9931 9932 ScalarCast = CK_IntegralToFloating; 9933 } else 9934 return true; 9935 } else if (ScalarTy->isEnumeralType()) 9936 return true; 9937 9938 // Adjust scalar if desired. 9939 if (Scalar) { 9940 if (ScalarCast != CK_NoOp) 9941 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 9942 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 9943 } 9944 return false; 9945 } 9946 9947 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 9948 SourceLocation Loc, bool IsCompAssign, 9949 bool AllowBothBool, 9950 bool AllowBoolConversions) { 9951 if (!IsCompAssign) { 9952 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 9953 if (LHS.isInvalid()) 9954 return QualType(); 9955 } 9956 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 9957 if (RHS.isInvalid()) 9958 return QualType(); 9959 9960 // For conversion purposes, we ignore any qualifiers. 9961 // For example, "const float" and "float" are equivalent. 9962 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 9963 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 9964 9965 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 9966 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 9967 assert(LHSVecType || RHSVecType); 9968 9969 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 9970 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 9971 return InvalidOperands(Loc, LHS, RHS); 9972 9973 // AltiVec-style "vector bool op vector bool" combinations are allowed 9974 // for some operators but not others. 9975 if (!AllowBothBool && 9976 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 9977 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9978 return InvalidOperands(Loc, LHS, RHS); 9979 9980 // If the vector types are identical, return. 9981 if (Context.hasSameType(LHSType, RHSType)) 9982 return LHSType; 9983 9984 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 9985 if (LHSVecType && RHSVecType && 9986 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9987 if (isa<ExtVectorType>(LHSVecType)) { 9988 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9989 return LHSType; 9990 } 9991 9992 if (!IsCompAssign) 9993 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9994 return RHSType; 9995 } 9996 9997 // AllowBoolConversions says that bool and non-bool AltiVec vectors 9998 // can be mixed, with the result being the non-bool type. The non-bool 9999 // operand must have integer element type. 10000 if (AllowBoolConversions && LHSVecType && RHSVecType && 10001 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10002 (Context.getTypeSize(LHSVecType->getElementType()) == 10003 Context.getTypeSize(RHSVecType->getElementType()))) { 10004 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10005 LHSVecType->getElementType()->isIntegerType() && 10006 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10007 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10008 return LHSType; 10009 } 10010 if (!IsCompAssign && 10011 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10012 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10013 RHSVecType->getElementType()->isIntegerType()) { 10014 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10015 return RHSType; 10016 } 10017 } 10018 10019 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10020 // since the ambiguity can affect the ABI. 10021 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10022 const VectorType *VecType = SecondType->getAs<VectorType>(); 10023 return FirstType->isSizelessBuiltinType() && VecType && 10024 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10025 VecType->getVectorKind() == 10026 VectorType::SveFixedLengthPredicateVector); 10027 }; 10028 10029 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10030 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10031 return QualType(); 10032 } 10033 10034 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10035 // since the ambiguity can affect the ABI. 10036 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10037 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10038 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10039 10040 if (FirstVecType && SecondVecType) 10041 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10042 (SecondVecType->getVectorKind() == 10043 VectorType::SveFixedLengthDataVector || 10044 SecondVecType->getVectorKind() == 10045 VectorType::SveFixedLengthPredicateVector); 10046 10047 return FirstType->isSizelessBuiltinType() && SecondVecType && 10048 SecondVecType->getVectorKind() == VectorType::GenericVector; 10049 }; 10050 10051 if (IsSveGnuConversion(LHSType, RHSType) || 10052 IsSveGnuConversion(RHSType, LHSType)) { 10053 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10054 return QualType(); 10055 } 10056 10057 // If there's a vector type and a scalar, try to convert the scalar to 10058 // the vector element type and splat. 10059 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10060 if (!RHSVecType) { 10061 if (isa<ExtVectorType>(LHSVecType)) { 10062 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10063 LHSVecType->getElementType(), LHSType, 10064 DiagID)) 10065 return LHSType; 10066 } else { 10067 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10068 return LHSType; 10069 } 10070 } 10071 if (!LHSVecType) { 10072 if (isa<ExtVectorType>(RHSVecType)) { 10073 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10074 LHSType, RHSVecType->getElementType(), 10075 RHSType, DiagID)) 10076 return RHSType; 10077 } else { 10078 if (LHS.get()->getValueKind() == VK_LValue || 10079 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10080 return RHSType; 10081 } 10082 } 10083 10084 // FIXME: The code below also handles conversion between vectors and 10085 // non-scalars, we should break this down into fine grained specific checks 10086 // and emit proper diagnostics. 10087 QualType VecType = LHSVecType ? LHSType : RHSType; 10088 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10089 QualType OtherType = LHSVecType ? RHSType : LHSType; 10090 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10091 if (isLaxVectorConversion(OtherType, VecType)) { 10092 // If we're allowing lax vector conversions, only the total (data) size 10093 // needs to be the same. For non compound assignment, if one of the types is 10094 // scalar, the result is always the vector type. 10095 if (!IsCompAssign) { 10096 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10097 return VecType; 10098 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10099 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10100 // type. Note that this is already done by non-compound assignments in 10101 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10102 // <1 x T> -> T. The result is also a vector type. 10103 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10104 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10105 ExprResult *RHSExpr = &RHS; 10106 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10107 return VecType; 10108 } 10109 } 10110 10111 // Okay, the expression is invalid. 10112 10113 // If there's a non-vector, non-real operand, diagnose that. 10114 if ((!RHSVecType && !RHSType->isRealType()) || 10115 (!LHSVecType && !LHSType->isRealType())) { 10116 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10117 << LHSType << RHSType 10118 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10119 return QualType(); 10120 } 10121 10122 // OpenCL V1.1 6.2.6.p1: 10123 // If the operands are of more than one vector type, then an error shall 10124 // occur. Implicit conversions between vector types are not permitted, per 10125 // section 6.2.1. 10126 if (getLangOpts().OpenCL && 10127 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10128 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10129 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10130 << RHSType; 10131 return QualType(); 10132 } 10133 10134 10135 // If there is a vector type that is not a ExtVector and a scalar, we reach 10136 // this point if scalar could not be converted to the vector's element type 10137 // without truncation. 10138 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10139 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10140 QualType Scalar = LHSVecType ? RHSType : LHSType; 10141 QualType Vector = LHSVecType ? LHSType : RHSType; 10142 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10143 Diag(Loc, 10144 diag::err_typecheck_vector_not_convertable_implict_truncation) 10145 << ScalarOrVector << Scalar << Vector; 10146 10147 return QualType(); 10148 } 10149 10150 // Otherwise, use the generic diagnostic. 10151 Diag(Loc, DiagID) 10152 << LHSType << RHSType 10153 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10154 return QualType(); 10155 } 10156 10157 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10158 // expression. These are mainly cases where the null pointer is used as an 10159 // integer instead of a pointer. 10160 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10161 SourceLocation Loc, bool IsCompare) { 10162 // The canonical way to check for a GNU null is with isNullPointerConstant, 10163 // but we use a bit of a hack here for speed; this is a relatively 10164 // hot path, and isNullPointerConstant is slow. 10165 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10166 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10167 10168 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10169 10170 // Avoid analyzing cases where the result will either be invalid (and 10171 // diagnosed as such) or entirely valid and not something to warn about. 10172 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10173 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10174 return; 10175 10176 // Comparison operations would not make sense with a null pointer no matter 10177 // what the other expression is. 10178 if (!IsCompare) { 10179 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10180 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10181 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10182 return; 10183 } 10184 10185 // The rest of the operations only make sense with a null pointer 10186 // if the other expression is a pointer. 10187 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10188 NonNullType->canDecayToPointerType()) 10189 return; 10190 10191 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10192 << LHSNull /* LHS is NULL */ << NonNullType 10193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10194 } 10195 10196 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10197 SourceLocation Loc) { 10198 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10199 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10200 if (!LUE || !RUE) 10201 return; 10202 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10203 RUE->getKind() != UETT_SizeOf) 10204 return; 10205 10206 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 10207 QualType LHSTy = LHSArg->getType(); 10208 QualType RHSTy; 10209 10210 if (RUE->isArgumentType()) 10211 RHSTy = RUE->getArgumentType().getNonReferenceType(); 10212 else 10213 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 10214 10215 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 10216 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 10217 return; 10218 10219 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 10220 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10221 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10222 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 10223 << LHSArgDecl; 10224 } 10225 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 10226 QualType ArrayElemTy = ArrayTy->getElementType(); 10227 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 10228 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 10229 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 10230 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 10231 return; 10232 S.Diag(Loc, diag::warn_division_sizeof_array) 10233 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 10234 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 10235 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 10236 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 10237 << LHSArgDecl; 10238 } 10239 10240 S.Diag(Loc, diag::note_precedence_silence) << RHS; 10241 } 10242 } 10243 10244 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 10245 ExprResult &RHS, 10246 SourceLocation Loc, bool IsDiv) { 10247 // Check for division/remainder by zero. 10248 Expr::EvalResult RHSValue; 10249 if (!RHS.get()->isValueDependent() && 10250 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 10251 RHSValue.Val.getInt() == 0) 10252 S.DiagRuntimeBehavior(Loc, RHS.get(), 10253 S.PDiag(diag::warn_remainder_division_by_zero) 10254 << IsDiv << RHS.get()->getSourceRange()); 10255 } 10256 10257 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 10258 SourceLocation Loc, 10259 bool IsCompAssign, bool IsDiv) { 10260 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10261 10262 QualType LHSTy = LHS.get()->getType(); 10263 QualType RHSTy = RHS.get()->getType(); 10264 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 10265 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10266 /*AllowBothBool*/getLangOpts().AltiVec, 10267 /*AllowBoolConversions*/false); 10268 if (!IsDiv && 10269 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 10270 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 10271 // For division, only matrix-by-scalar is supported. Other combinations with 10272 // matrix types are invalid. 10273 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 10274 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 10275 10276 QualType compType = UsualArithmeticConversions( 10277 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10278 if (LHS.isInvalid() || RHS.isInvalid()) 10279 return QualType(); 10280 10281 10282 if (compType.isNull() || !compType->isArithmeticType()) 10283 return InvalidOperands(Loc, LHS, RHS); 10284 if (IsDiv) { 10285 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 10286 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 10287 } 10288 return compType; 10289 } 10290 10291 QualType Sema::CheckRemainderOperands( 10292 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 10293 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10294 10295 if (LHS.get()->getType()->isVectorType() || 10296 RHS.get()->getType()->isVectorType()) { 10297 if (LHS.get()->getType()->hasIntegerRepresentation() && 10298 RHS.get()->getType()->hasIntegerRepresentation()) 10299 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10300 /*AllowBothBool*/getLangOpts().AltiVec, 10301 /*AllowBoolConversions*/false); 10302 return InvalidOperands(Loc, LHS, RHS); 10303 } 10304 10305 QualType compType = UsualArithmeticConversions( 10306 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 10307 if (LHS.isInvalid() || RHS.isInvalid()) 10308 return QualType(); 10309 10310 if (compType.isNull() || !compType->isIntegerType()) 10311 return InvalidOperands(Loc, LHS, RHS); 10312 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 10313 return compType; 10314 } 10315 10316 /// Diagnose invalid arithmetic on two void pointers. 10317 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 10318 Expr *LHSExpr, Expr *RHSExpr) { 10319 S.Diag(Loc, S.getLangOpts().CPlusPlus 10320 ? diag::err_typecheck_pointer_arith_void_type 10321 : diag::ext_gnu_void_ptr) 10322 << 1 /* two pointers */ << LHSExpr->getSourceRange() 10323 << RHSExpr->getSourceRange(); 10324 } 10325 10326 /// Diagnose invalid arithmetic on a void pointer. 10327 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 10328 Expr *Pointer) { 10329 S.Diag(Loc, S.getLangOpts().CPlusPlus 10330 ? diag::err_typecheck_pointer_arith_void_type 10331 : diag::ext_gnu_void_ptr) 10332 << 0 /* one pointer */ << Pointer->getSourceRange(); 10333 } 10334 10335 /// Diagnose invalid arithmetic on a null pointer. 10336 /// 10337 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 10338 /// idiom, which we recognize as a GNU extension. 10339 /// 10340 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 10341 Expr *Pointer, bool IsGNUIdiom) { 10342 if (IsGNUIdiom) 10343 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 10344 << Pointer->getSourceRange(); 10345 else 10346 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 10347 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 10348 } 10349 10350 /// Diagnose invalid arithmetic on two function pointers. 10351 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 10352 Expr *LHS, Expr *RHS) { 10353 assert(LHS->getType()->isAnyPointerType()); 10354 assert(RHS->getType()->isAnyPointerType()); 10355 S.Diag(Loc, S.getLangOpts().CPlusPlus 10356 ? diag::err_typecheck_pointer_arith_function_type 10357 : diag::ext_gnu_ptr_func_arith) 10358 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 10359 // We only show the second type if it differs from the first. 10360 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 10361 RHS->getType()) 10362 << RHS->getType()->getPointeeType() 10363 << LHS->getSourceRange() << RHS->getSourceRange(); 10364 } 10365 10366 /// Diagnose invalid arithmetic on a function pointer. 10367 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 10368 Expr *Pointer) { 10369 assert(Pointer->getType()->isAnyPointerType()); 10370 S.Diag(Loc, S.getLangOpts().CPlusPlus 10371 ? diag::err_typecheck_pointer_arith_function_type 10372 : diag::ext_gnu_ptr_func_arith) 10373 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 10374 << 0 /* one pointer, so only one type */ 10375 << Pointer->getSourceRange(); 10376 } 10377 10378 /// Emit error if Operand is incomplete pointer type 10379 /// 10380 /// \returns True if pointer has incomplete type 10381 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 10382 Expr *Operand) { 10383 QualType ResType = Operand->getType(); 10384 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10385 ResType = ResAtomicType->getValueType(); 10386 10387 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 10388 QualType PointeeTy = ResType->getPointeeType(); 10389 return S.RequireCompleteSizedType( 10390 Loc, PointeeTy, 10391 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 10392 Operand->getSourceRange()); 10393 } 10394 10395 /// Check the validity of an arithmetic pointer operand. 10396 /// 10397 /// If the operand has pointer type, this code will check for pointer types 10398 /// which are invalid in arithmetic operations. These will be diagnosed 10399 /// appropriately, including whether or not the use is supported as an 10400 /// extension. 10401 /// 10402 /// \returns True when the operand is valid to use (even if as an extension). 10403 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 10404 Expr *Operand) { 10405 QualType ResType = Operand->getType(); 10406 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 10407 ResType = ResAtomicType->getValueType(); 10408 10409 if (!ResType->isAnyPointerType()) return true; 10410 10411 QualType PointeeTy = ResType->getPointeeType(); 10412 if (PointeeTy->isVoidType()) { 10413 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 10414 return !S.getLangOpts().CPlusPlus; 10415 } 10416 if (PointeeTy->isFunctionType()) { 10417 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 10418 return !S.getLangOpts().CPlusPlus; 10419 } 10420 10421 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 10422 10423 return true; 10424 } 10425 10426 /// Check the validity of a binary arithmetic operation w.r.t. pointer 10427 /// operands. 10428 /// 10429 /// This routine will diagnose any invalid arithmetic on pointer operands much 10430 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 10431 /// for emitting a single diagnostic even for operations where both LHS and RHS 10432 /// are (potentially problematic) pointers. 10433 /// 10434 /// \returns True when the operand is valid to use (even if as an extension). 10435 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 10436 Expr *LHSExpr, Expr *RHSExpr) { 10437 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 10438 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 10439 if (!isLHSPointer && !isRHSPointer) return true; 10440 10441 QualType LHSPointeeTy, RHSPointeeTy; 10442 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 10443 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 10444 10445 // if both are pointers check if operation is valid wrt address spaces 10446 if (isLHSPointer && isRHSPointer) { 10447 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 10448 S.Diag(Loc, 10449 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10450 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 10451 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10452 return false; 10453 } 10454 } 10455 10456 // Check for arithmetic on pointers to incomplete types. 10457 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 10458 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 10459 if (isLHSVoidPtr || isRHSVoidPtr) { 10460 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 10461 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 10462 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 10463 10464 return !S.getLangOpts().CPlusPlus; 10465 } 10466 10467 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 10468 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 10469 if (isLHSFuncPtr || isRHSFuncPtr) { 10470 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 10471 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 10472 RHSExpr); 10473 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 10474 10475 return !S.getLangOpts().CPlusPlus; 10476 } 10477 10478 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 10479 return false; 10480 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 10481 return false; 10482 10483 return true; 10484 } 10485 10486 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 10487 /// literal. 10488 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 10489 Expr *LHSExpr, Expr *RHSExpr) { 10490 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 10491 Expr* IndexExpr = RHSExpr; 10492 if (!StrExpr) { 10493 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 10494 IndexExpr = LHSExpr; 10495 } 10496 10497 bool IsStringPlusInt = StrExpr && 10498 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 10499 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 10500 return; 10501 10502 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10503 Self.Diag(OpLoc, diag::warn_string_plus_int) 10504 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 10505 10506 // Only print a fixit for "str" + int, not for int + "str". 10507 if (IndexExpr == RHSExpr) { 10508 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10509 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10510 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10511 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10512 << FixItHint::CreateInsertion(EndLoc, "]"); 10513 } else 10514 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10515 } 10516 10517 /// Emit a warning when adding a char literal to a string. 10518 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 10519 Expr *LHSExpr, Expr *RHSExpr) { 10520 const Expr *StringRefExpr = LHSExpr; 10521 const CharacterLiteral *CharExpr = 10522 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 10523 10524 if (!CharExpr) { 10525 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 10526 StringRefExpr = RHSExpr; 10527 } 10528 10529 if (!CharExpr || !StringRefExpr) 10530 return; 10531 10532 const QualType StringType = StringRefExpr->getType(); 10533 10534 // Return if not a PointerType. 10535 if (!StringType->isAnyPointerType()) 10536 return; 10537 10538 // Return if not a CharacterType. 10539 if (!StringType->getPointeeType()->isAnyCharacterType()) 10540 return; 10541 10542 ASTContext &Ctx = Self.getASTContext(); 10543 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 10544 10545 const QualType CharType = CharExpr->getType(); 10546 if (!CharType->isAnyCharacterType() && 10547 CharType->isIntegerType() && 10548 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 10549 Self.Diag(OpLoc, diag::warn_string_plus_char) 10550 << DiagRange << Ctx.CharTy; 10551 } else { 10552 Self.Diag(OpLoc, diag::warn_string_plus_char) 10553 << DiagRange << CharExpr->getType(); 10554 } 10555 10556 // Only print a fixit for str + char, not for char + str. 10557 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 10558 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 10559 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 10560 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 10561 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 10562 << FixItHint::CreateInsertion(EndLoc, "]"); 10563 } else { 10564 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 10565 } 10566 } 10567 10568 /// Emit error when two pointers are incompatible. 10569 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 10570 Expr *LHSExpr, Expr *RHSExpr) { 10571 assert(LHSExpr->getType()->isAnyPointerType()); 10572 assert(RHSExpr->getType()->isAnyPointerType()); 10573 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 10574 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 10575 << RHSExpr->getSourceRange(); 10576 } 10577 10578 // C99 6.5.6 10579 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 10580 SourceLocation Loc, BinaryOperatorKind Opc, 10581 QualType* CompLHSTy) { 10582 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10583 10584 if (LHS.get()->getType()->isVectorType() || 10585 RHS.get()->getType()->isVectorType()) { 10586 QualType compType = CheckVectorOperands( 10587 LHS, RHS, Loc, CompLHSTy, 10588 /*AllowBothBool*/getLangOpts().AltiVec, 10589 /*AllowBoolConversions*/getLangOpts().ZVector); 10590 if (CompLHSTy) *CompLHSTy = compType; 10591 return compType; 10592 } 10593 10594 if (LHS.get()->getType()->isConstantMatrixType() || 10595 RHS.get()->getType()->isConstantMatrixType()) { 10596 QualType compType = 10597 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10598 if (CompLHSTy) 10599 *CompLHSTy = compType; 10600 return compType; 10601 } 10602 10603 QualType compType = UsualArithmeticConversions( 10604 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10605 if (LHS.isInvalid() || RHS.isInvalid()) 10606 return QualType(); 10607 10608 // Diagnose "string literal" '+' int and string '+' "char literal". 10609 if (Opc == BO_Add) { 10610 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 10611 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 10612 } 10613 10614 // handle the common case first (both operands are arithmetic). 10615 if (!compType.isNull() && compType->isArithmeticType()) { 10616 if (CompLHSTy) *CompLHSTy = compType; 10617 return compType; 10618 } 10619 10620 // Type-checking. Ultimately the pointer's going to be in PExp; 10621 // note that we bias towards the LHS being the pointer. 10622 Expr *PExp = LHS.get(), *IExp = RHS.get(); 10623 10624 bool isObjCPointer; 10625 if (PExp->getType()->isPointerType()) { 10626 isObjCPointer = false; 10627 } else if (PExp->getType()->isObjCObjectPointerType()) { 10628 isObjCPointer = true; 10629 } else { 10630 std::swap(PExp, IExp); 10631 if (PExp->getType()->isPointerType()) { 10632 isObjCPointer = false; 10633 } else if (PExp->getType()->isObjCObjectPointerType()) { 10634 isObjCPointer = true; 10635 } else { 10636 return InvalidOperands(Loc, LHS, RHS); 10637 } 10638 } 10639 assert(PExp->getType()->isAnyPointerType()); 10640 10641 if (!IExp->getType()->isIntegerType()) 10642 return InvalidOperands(Loc, LHS, RHS); 10643 10644 // Adding to a null pointer results in undefined behavior. 10645 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 10646 Context, Expr::NPC_ValueDependentIsNotNull)) { 10647 // In C++ adding zero to a null pointer is defined. 10648 Expr::EvalResult KnownVal; 10649 if (!getLangOpts().CPlusPlus || 10650 (!IExp->isValueDependent() && 10651 (!IExp->EvaluateAsInt(KnownVal, Context) || 10652 KnownVal.Val.getInt() != 0))) { 10653 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 10654 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 10655 Context, BO_Add, PExp, IExp); 10656 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 10657 } 10658 } 10659 10660 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 10661 return QualType(); 10662 10663 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 10664 return QualType(); 10665 10666 // Check array bounds for pointer arithemtic 10667 CheckArrayAccess(PExp, IExp); 10668 10669 if (CompLHSTy) { 10670 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 10671 if (LHSTy.isNull()) { 10672 LHSTy = LHS.get()->getType(); 10673 if (LHSTy->isPromotableIntegerType()) 10674 LHSTy = Context.getPromotedIntegerType(LHSTy); 10675 } 10676 *CompLHSTy = LHSTy; 10677 } 10678 10679 return PExp->getType(); 10680 } 10681 10682 // C99 6.5.6 10683 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 10684 SourceLocation Loc, 10685 QualType* CompLHSTy) { 10686 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10687 10688 if (LHS.get()->getType()->isVectorType() || 10689 RHS.get()->getType()->isVectorType()) { 10690 QualType compType = CheckVectorOperands( 10691 LHS, RHS, Loc, CompLHSTy, 10692 /*AllowBothBool*/getLangOpts().AltiVec, 10693 /*AllowBoolConversions*/getLangOpts().ZVector); 10694 if (CompLHSTy) *CompLHSTy = compType; 10695 return compType; 10696 } 10697 10698 if (LHS.get()->getType()->isConstantMatrixType() || 10699 RHS.get()->getType()->isConstantMatrixType()) { 10700 QualType compType = 10701 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 10702 if (CompLHSTy) 10703 *CompLHSTy = compType; 10704 return compType; 10705 } 10706 10707 QualType compType = UsualArithmeticConversions( 10708 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 10709 if (LHS.isInvalid() || RHS.isInvalid()) 10710 return QualType(); 10711 10712 // Enforce type constraints: C99 6.5.6p3. 10713 10714 // Handle the common case first (both operands are arithmetic). 10715 if (!compType.isNull() && compType->isArithmeticType()) { 10716 if (CompLHSTy) *CompLHSTy = compType; 10717 return compType; 10718 } 10719 10720 // Either ptr - int or ptr - ptr. 10721 if (LHS.get()->getType()->isAnyPointerType()) { 10722 QualType lpointee = LHS.get()->getType()->getPointeeType(); 10723 10724 // Diagnose bad cases where we step over interface counts. 10725 if (LHS.get()->getType()->isObjCObjectPointerType() && 10726 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 10727 return QualType(); 10728 10729 // The result type of a pointer-int computation is the pointer type. 10730 if (RHS.get()->getType()->isIntegerType()) { 10731 // Subtracting from a null pointer should produce a warning. 10732 // The last argument to the diagnose call says this doesn't match the 10733 // GNU int-to-pointer idiom. 10734 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 10735 Expr::NPC_ValueDependentIsNotNull)) { 10736 // In C++ adding zero to a null pointer is defined. 10737 Expr::EvalResult KnownVal; 10738 if (!getLangOpts().CPlusPlus || 10739 (!RHS.get()->isValueDependent() && 10740 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 10741 KnownVal.Val.getInt() != 0))) { 10742 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 10743 } 10744 } 10745 10746 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 10747 return QualType(); 10748 10749 // Check array bounds for pointer arithemtic 10750 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 10751 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 10752 10753 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10754 return LHS.get()->getType(); 10755 } 10756 10757 // Handle pointer-pointer subtractions. 10758 if (const PointerType *RHSPTy 10759 = RHS.get()->getType()->getAs<PointerType>()) { 10760 QualType rpointee = RHSPTy->getPointeeType(); 10761 10762 if (getLangOpts().CPlusPlus) { 10763 // Pointee types must be the same: C++ [expr.add] 10764 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 10765 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10766 } 10767 } else { 10768 // Pointee types must be compatible C99 6.5.6p3 10769 if (!Context.typesAreCompatible( 10770 Context.getCanonicalType(lpointee).getUnqualifiedType(), 10771 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 10772 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 10773 return QualType(); 10774 } 10775 } 10776 10777 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 10778 LHS.get(), RHS.get())) 10779 return QualType(); 10780 10781 // FIXME: Add warnings for nullptr - ptr. 10782 10783 // The pointee type may have zero size. As an extension, a structure or 10784 // union may have zero size or an array may have zero length. In this 10785 // case subtraction does not make sense. 10786 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 10787 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 10788 if (ElementSize.isZero()) { 10789 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 10790 << rpointee.getUnqualifiedType() 10791 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10792 } 10793 } 10794 10795 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 10796 return Context.getPointerDiffType(); 10797 } 10798 } 10799 10800 return InvalidOperands(Loc, LHS, RHS); 10801 } 10802 10803 static bool isScopedEnumerationType(QualType T) { 10804 if (const EnumType *ET = T->getAs<EnumType>()) 10805 return ET->getDecl()->isScoped(); 10806 return false; 10807 } 10808 10809 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 10810 SourceLocation Loc, BinaryOperatorKind Opc, 10811 QualType LHSType) { 10812 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 10813 // so skip remaining warnings as we don't want to modify values within Sema. 10814 if (S.getLangOpts().OpenCL) 10815 return; 10816 10817 // Check right/shifter operand 10818 Expr::EvalResult RHSResult; 10819 if (RHS.get()->isValueDependent() || 10820 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 10821 return; 10822 llvm::APSInt Right = RHSResult.Val.getInt(); 10823 10824 if (Right.isNegative()) { 10825 S.DiagRuntimeBehavior(Loc, RHS.get(), 10826 S.PDiag(diag::warn_shift_negative) 10827 << RHS.get()->getSourceRange()); 10828 return; 10829 } 10830 10831 QualType LHSExprType = LHS.get()->getType(); 10832 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 10833 if (LHSExprType->isExtIntType()) 10834 LeftSize = S.Context.getIntWidth(LHSExprType); 10835 else if (LHSExprType->isFixedPointType()) { 10836 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 10837 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 10838 } 10839 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 10840 if (Right.uge(LeftBits)) { 10841 S.DiagRuntimeBehavior(Loc, RHS.get(), 10842 S.PDiag(diag::warn_shift_gt_typewidth) 10843 << RHS.get()->getSourceRange()); 10844 return; 10845 } 10846 10847 // FIXME: We probably need to handle fixed point types specially here. 10848 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 10849 return; 10850 10851 // When left shifting an ICE which is signed, we can check for overflow which 10852 // according to C++ standards prior to C++2a has undefined behavior 10853 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 10854 // more than the maximum value representable in the result type, so never 10855 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 10856 // expression is still probably a bug.) 10857 Expr::EvalResult LHSResult; 10858 if (LHS.get()->isValueDependent() || 10859 LHSType->hasUnsignedIntegerRepresentation() || 10860 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 10861 return; 10862 llvm::APSInt Left = LHSResult.Val.getInt(); 10863 10864 // If LHS does not have a signed type and non-negative value 10865 // then, the behavior is undefined before C++2a. Warn about it. 10866 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() && 10867 !S.getLangOpts().CPlusPlus20) { 10868 S.DiagRuntimeBehavior(Loc, LHS.get(), 10869 S.PDiag(diag::warn_shift_lhs_negative) 10870 << LHS.get()->getSourceRange()); 10871 return; 10872 } 10873 10874 llvm::APInt ResultBits = 10875 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 10876 if (LeftBits.uge(ResultBits)) 10877 return; 10878 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 10879 Result = Result.shl(Right); 10880 10881 // Print the bit representation of the signed integer as an unsigned 10882 // hexadecimal number. 10883 SmallString<40> HexResult; 10884 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 10885 10886 // If we are only missing a sign bit, this is less likely to result in actual 10887 // bugs -- if the result is cast back to an unsigned type, it will have the 10888 // expected value. Thus we place this behind a different warning that can be 10889 // turned off separately if needed. 10890 if (LeftBits == ResultBits - 1) { 10891 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 10892 << HexResult << LHSType 10893 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10894 return; 10895 } 10896 10897 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 10898 << HexResult.str() << Result.getMinSignedBits() << LHSType 10899 << Left.getBitWidth() << LHS.get()->getSourceRange() 10900 << RHS.get()->getSourceRange(); 10901 } 10902 10903 /// Return the resulting type when a vector is shifted 10904 /// by a scalar or vector shift amount. 10905 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 10906 SourceLocation Loc, bool IsCompAssign) { 10907 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 10908 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 10909 !LHS.get()->getType()->isVectorType()) { 10910 S.Diag(Loc, diag::err_shift_rhs_only_vector) 10911 << RHS.get()->getType() << LHS.get()->getType() 10912 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10913 return QualType(); 10914 } 10915 10916 if (!IsCompAssign) { 10917 LHS = S.UsualUnaryConversions(LHS.get()); 10918 if (LHS.isInvalid()) return QualType(); 10919 } 10920 10921 RHS = S.UsualUnaryConversions(RHS.get()); 10922 if (RHS.isInvalid()) return QualType(); 10923 10924 QualType LHSType = LHS.get()->getType(); 10925 // Note that LHS might be a scalar because the routine calls not only in 10926 // OpenCL case. 10927 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 10928 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 10929 10930 // Note that RHS might not be a vector. 10931 QualType RHSType = RHS.get()->getType(); 10932 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 10933 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 10934 10935 // The operands need to be integers. 10936 if (!LHSEleType->isIntegerType()) { 10937 S.Diag(Loc, diag::err_typecheck_expect_int) 10938 << LHS.get()->getType() << LHS.get()->getSourceRange(); 10939 return QualType(); 10940 } 10941 10942 if (!RHSEleType->isIntegerType()) { 10943 S.Diag(Loc, diag::err_typecheck_expect_int) 10944 << RHS.get()->getType() << RHS.get()->getSourceRange(); 10945 return QualType(); 10946 } 10947 10948 if (!LHSVecTy) { 10949 assert(RHSVecTy); 10950 if (IsCompAssign) 10951 return RHSType; 10952 if (LHSEleType != RHSEleType) { 10953 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 10954 LHSEleType = RHSEleType; 10955 } 10956 QualType VecTy = 10957 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 10958 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 10959 LHSType = VecTy; 10960 } else if (RHSVecTy) { 10961 // OpenCL v1.1 s6.3.j says that for vector types, the operators 10962 // are applied component-wise. So if RHS is a vector, then ensure 10963 // that the number of elements is the same as LHS... 10964 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 10965 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10966 << LHS.get()->getType() << RHS.get()->getType() 10967 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10968 return QualType(); 10969 } 10970 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 10971 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 10972 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 10973 if (LHSBT != RHSBT && 10974 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 10975 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 10976 << LHS.get()->getType() << RHS.get()->getType() 10977 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10978 } 10979 } 10980 } else { 10981 // ...else expand RHS to match the number of elements in LHS. 10982 QualType VecTy = 10983 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 10984 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 10985 } 10986 10987 return LHSType; 10988 } 10989 10990 // C99 6.5.7 10991 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 10992 SourceLocation Loc, BinaryOperatorKind Opc, 10993 bool IsCompAssign) { 10994 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 10995 10996 // Vector shifts promote their scalar inputs to vector type. 10997 if (LHS.get()->getType()->isVectorType() || 10998 RHS.get()->getType()->isVectorType()) { 10999 if (LangOpts.ZVector) { 11000 // The shift operators for the z vector extensions work basically 11001 // like general shifts, except that neither the LHS nor the RHS is 11002 // allowed to be a "vector bool". 11003 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11004 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11005 return InvalidOperands(Loc, LHS, RHS); 11006 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11007 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11008 return InvalidOperands(Loc, LHS, RHS); 11009 } 11010 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11011 } 11012 11013 // Shifts don't perform usual arithmetic conversions, they just do integer 11014 // promotions on each operand. C99 6.5.7p3 11015 11016 // For the LHS, do usual unary conversions, but then reset them away 11017 // if this is a compound assignment. 11018 ExprResult OldLHS = LHS; 11019 LHS = UsualUnaryConversions(LHS.get()); 11020 if (LHS.isInvalid()) 11021 return QualType(); 11022 QualType LHSType = LHS.get()->getType(); 11023 if (IsCompAssign) LHS = OldLHS; 11024 11025 // The RHS is simpler. 11026 RHS = UsualUnaryConversions(RHS.get()); 11027 if (RHS.isInvalid()) 11028 return QualType(); 11029 QualType RHSType = RHS.get()->getType(); 11030 11031 // C99 6.5.7p2: Each of the operands shall have integer type. 11032 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 11033 if ((!LHSType->isFixedPointOrIntegerType() && 11034 !LHSType->hasIntegerRepresentation()) || 11035 !RHSType->hasIntegerRepresentation()) 11036 return InvalidOperands(Loc, LHS, RHS); 11037 11038 // C++0x: Don't allow scoped enums. FIXME: Use something better than 11039 // hasIntegerRepresentation() above instead of this. 11040 if (isScopedEnumerationType(LHSType) || 11041 isScopedEnumerationType(RHSType)) { 11042 return InvalidOperands(Loc, LHS, RHS); 11043 } 11044 // Sanity-check shift operands 11045 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 11046 11047 // "The type of the result is that of the promoted left operand." 11048 return LHSType; 11049 } 11050 11051 /// Diagnose bad pointer comparisons. 11052 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 11053 ExprResult &LHS, ExprResult &RHS, 11054 bool IsError) { 11055 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 11056 : diag::ext_typecheck_comparison_of_distinct_pointers) 11057 << LHS.get()->getType() << RHS.get()->getType() 11058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11059 } 11060 11061 /// Returns false if the pointers are converted to a composite type, 11062 /// true otherwise. 11063 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 11064 ExprResult &LHS, ExprResult &RHS) { 11065 // C++ [expr.rel]p2: 11066 // [...] Pointer conversions (4.10) and qualification 11067 // conversions (4.4) are performed on pointer operands (or on 11068 // a pointer operand and a null pointer constant) to bring 11069 // them to their composite pointer type. [...] 11070 // 11071 // C++ [expr.eq]p1 uses the same notion for (in)equality 11072 // comparisons of pointers. 11073 11074 QualType LHSType = LHS.get()->getType(); 11075 QualType RHSType = RHS.get()->getType(); 11076 assert(LHSType->isPointerType() || RHSType->isPointerType() || 11077 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 11078 11079 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 11080 if (T.isNull()) { 11081 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 11082 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 11083 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 11084 else 11085 S.InvalidOperands(Loc, LHS, RHS); 11086 return true; 11087 } 11088 11089 return false; 11090 } 11091 11092 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 11093 ExprResult &LHS, 11094 ExprResult &RHS, 11095 bool IsError) { 11096 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 11097 : diag::ext_typecheck_comparison_of_fptr_to_void) 11098 << LHS.get()->getType() << RHS.get()->getType() 11099 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11100 } 11101 11102 static bool isObjCObjectLiteral(ExprResult &E) { 11103 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 11104 case Stmt::ObjCArrayLiteralClass: 11105 case Stmt::ObjCDictionaryLiteralClass: 11106 case Stmt::ObjCStringLiteralClass: 11107 case Stmt::ObjCBoxedExprClass: 11108 return true; 11109 default: 11110 // Note that ObjCBoolLiteral is NOT an object literal! 11111 return false; 11112 } 11113 } 11114 11115 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 11116 const ObjCObjectPointerType *Type = 11117 LHS->getType()->getAs<ObjCObjectPointerType>(); 11118 11119 // If this is not actually an Objective-C object, bail out. 11120 if (!Type) 11121 return false; 11122 11123 // Get the LHS object's interface type. 11124 QualType InterfaceType = Type->getPointeeType(); 11125 11126 // If the RHS isn't an Objective-C object, bail out. 11127 if (!RHS->getType()->isObjCObjectPointerType()) 11128 return false; 11129 11130 // Try to find the -isEqual: method. 11131 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 11132 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 11133 InterfaceType, 11134 /*IsInstance=*/true); 11135 if (!Method) { 11136 if (Type->isObjCIdType()) { 11137 // For 'id', just check the global pool. 11138 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 11139 /*receiverId=*/true); 11140 } else { 11141 // Check protocols. 11142 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 11143 /*IsInstance=*/true); 11144 } 11145 } 11146 11147 if (!Method) 11148 return false; 11149 11150 QualType T = Method->parameters()[0]->getType(); 11151 if (!T->isObjCObjectPointerType()) 11152 return false; 11153 11154 QualType R = Method->getReturnType(); 11155 if (!R->isScalarType()) 11156 return false; 11157 11158 return true; 11159 } 11160 11161 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 11162 FromE = FromE->IgnoreParenImpCasts(); 11163 switch (FromE->getStmtClass()) { 11164 default: 11165 break; 11166 case Stmt::ObjCStringLiteralClass: 11167 // "string literal" 11168 return LK_String; 11169 case Stmt::ObjCArrayLiteralClass: 11170 // "array literal" 11171 return LK_Array; 11172 case Stmt::ObjCDictionaryLiteralClass: 11173 // "dictionary literal" 11174 return LK_Dictionary; 11175 case Stmt::BlockExprClass: 11176 return LK_Block; 11177 case Stmt::ObjCBoxedExprClass: { 11178 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 11179 switch (Inner->getStmtClass()) { 11180 case Stmt::IntegerLiteralClass: 11181 case Stmt::FloatingLiteralClass: 11182 case Stmt::CharacterLiteralClass: 11183 case Stmt::ObjCBoolLiteralExprClass: 11184 case Stmt::CXXBoolLiteralExprClass: 11185 // "numeric literal" 11186 return LK_Numeric; 11187 case Stmt::ImplicitCastExprClass: { 11188 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 11189 // Boolean literals can be represented by implicit casts. 11190 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 11191 return LK_Numeric; 11192 break; 11193 } 11194 default: 11195 break; 11196 } 11197 return LK_Boxed; 11198 } 11199 } 11200 return LK_None; 11201 } 11202 11203 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 11204 ExprResult &LHS, ExprResult &RHS, 11205 BinaryOperator::Opcode Opc){ 11206 Expr *Literal; 11207 Expr *Other; 11208 if (isObjCObjectLiteral(LHS)) { 11209 Literal = LHS.get(); 11210 Other = RHS.get(); 11211 } else { 11212 Literal = RHS.get(); 11213 Other = LHS.get(); 11214 } 11215 11216 // Don't warn on comparisons against nil. 11217 Other = Other->IgnoreParenCasts(); 11218 if (Other->isNullPointerConstant(S.getASTContext(), 11219 Expr::NPC_ValueDependentIsNotNull)) 11220 return; 11221 11222 // This should be kept in sync with warn_objc_literal_comparison. 11223 // LK_String should always be after the other literals, since it has its own 11224 // warning flag. 11225 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 11226 assert(LiteralKind != Sema::LK_Block); 11227 if (LiteralKind == Sema::LK_None) { 11228 llvm_unreachable("Unknown Objective-C object literal kind"); 11229 } 11230 11231 if (LiteralKind == Sema::LK_String) 11232 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 11233 << Literal->getSourceRange(); 11234 else 11235 S.Diag(Loc, diag::warn_objc_literal_comparison) 11236 << LiteralKind << Literal->getSourceRange(); 11237 11238 if (BinaryOperator::isEqualityOp(Opc) && 11239 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 11240 SourceLocation Start = LHS.get()->getBeginLoc(); 11241 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 11242 CharSourceRange OpRange = 11243 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 11244 11245 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 11246 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 11247 << FixItHint::CreateReplacement(OpRange, " isEqual:") 11248 << FixItHint::CreateInsertion(End, "]"); 11249 } 11250 } 11251 11252 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 11253 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 11254 ExprResult &RHS, SourceLocation Loc, 11255 BinaryOperatorKind Opc) { 11256 // Check that left hand side is !something. 11257 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 11258 if (!UO || UO->getOpcode() != UO_LNot) return; 11259 11260 // Only check if the right hand side is non-bool arithmetic type. 11261 if (RHS.get()->isKnownToHaveBooleanValue()) return; 11262 11263 // Make sure that the something in !something is not bool. 11264 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 11265 if (SubExpr->isKnownToHaveBooleanValue()) return; 11266 11267 // Emit warning. 11268 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 11269 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 11270 << Loc << IsBitwiseOp; 11271 11272 // First note suggest !(x < y) 11273 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 11274 SourceLocation FirstClose = RHS.get()->getEndLoc(); 11275 FirstClose = S.getLocForEndOfToken(FirstClose); 11276 if (FirstClose.isInvalid()) 11277 FirstOpen = SourceLocation(); 11278 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 11279 << IsBitwiseOp 11280 << FixItHint::CreateInsertion(FirstOpen, "(") 11281 << FixItHint::CreateInsertion(FirstClose, ")"); 11282 11283 // Second note suggests (!x) < y 11284 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 11285 SourceLocation SecondClose = LHS.get()->getEndLoc(); 11286 SecondClose = S.getLocForEndOfToken(SecondClose); 11287 if (SecondClose.isInvalid()) 11288 SecondOpen = SourceLocation(); 11289 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 11290 << FixItHint::CreateInsertion(SecondOpen, "(") 11291 << FixItHint::CreateInsertion(SecondClose, ")"); 11292 } 11293 11294 // Returns true if E refers to a non-weak array. 11295 static bool checkForArray(const Expr *E) { 11296 const ValueDecl *D = nullptr; 11297 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 11298 D = DR->getDecl(); 11299 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 11300 if (Mem->isImplicitAccess()) 11301 D = Mem->getMemberDecl(); 11302 } 11303 if (!D) 11304 return false; 11305 return D->getType()->isArrayType() && !D->isWeak(); 11306 } 11307 11308 /// Diagnose some forms of syntactically-obvious tautological comparison. 11309 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 11310 Expr *LHS, Expr *RHS, 11311 BinaryOperatorKind Opc) { 11312 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 11313 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 11314 11315 QualType LHSType = LHS->getType(); 11316 QualType RHSType = RHS->getType(); 11317 if (LHSType->hasFloatingRepresentation() || 11318 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 11319 S.inTemplateInstantiation()) 11320 return; 11321 11322 // Comparisons between two array types are ill-formed for operator<=>, so 11323 // we shouldn't emit any additional warnings about it. 11324 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 11325 return; 11326 11327 // For non-floating point types, check for self-comparisons of the form 11328 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 11329 // often indicate logic errors in the program. 11330 // 11331 // NOTE: Don't warn about comparison expressions resulting from macro 11332 // expansion. Also don't warn about comparisons which are only self 11333 // comparisons within a template instantiation. The warnings should catch 11334 // obvious cases in the definition of the template anyways. The idea is to 11335 // warn when the typed comparison operator will always evaluate to the same 11336 // result. 11337 11338 // Used for indexing into %select in warn_comparison_always 11339 enum { 11340 AlwaysConstant, 11341 AlwaysTrue, 11342 AlwaysFalse, 11343 AlwaysEqual, // std::strong_ordering::equal from operator<=> 11344 }; 11345 11346 // C++2a [depr.array.comp]: 11347 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 11348 // operands of array type are deprecated. 11349 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 11350 RHSStripped->getType()->isArrayType()) { 11351 S.Diag(Loc, diag::warn_depr_array_comparison) 11352 << LHS->getSourceRange() << RHS->getSourceRange() 11353 << LHSStripped->getType() << RHSStripped->getType(); 11354 // Carry on to produce the tautological comparison warning, if this 11355 // expression is potentially-evaluated, we can resolve the array to a 11356 // non-weak declaration, and so on. 11357 } 11358 11359 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 11360 if (Expr::isSameComparisonOperand(LHS, RHS)) { 11361 unsigned Result; 11362 switch (Opc) { 11363 case BO_EQ: 11364 case BO_LE: 11365 case BO_GE: 11366 Result = AlwaysTrue; 11367 break; 11368 case BO_NE: 11369 case BO_LT: 11370 case BO_GT: 11371 Result = AlwaysFalse; 11372 break; 11373 case BO_Cmp: 11374 Result = AlwaysEqual; 11375 break; 11376 default: 11377 Result = AlwaysConstant; 11378 break; 11379 } 11380 S.DiagRuntimeBehavior(Loc, nullptr, 11381 S.PDiag(diag::warn_comparison_always) 11382 << 0 /*self-comparison*/ 11383 << Result); 11384 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 11385 // What is it always going to evaluate to? 11386 unsigned Result; 11387 switch (Opc) { 11388 case BO_EQ: // e.g. array1 == array2 11389 Result = AlwaysFalse; 11390 break; 11391 case BO_NE: // e.g. array1 != array2 11392 Result = AlwaysTrue; 11393 break; 11394 default: // e.g. array1 <= array2 11395 // The best we can say is 'a constant' 11396 Result = AlwaysConstant; 11397 break; 11398 } 11399 S.DiagRuntimeBehavior(Loc, nullptr, 11400 S.PDiag(diag::warn_comparison_always) 11401 << 1 /*array comparison*/ 11402 << Result); 11403 } 11404 } 11405 11406 if (isa<CastExpr>(LHSStripped)) 11407 LHSStripped = LHSStripped->IgnoreParenCasts(); 11408 if (isa<CastExpr>(RHSStripped)) 11409 RHSStripped = RHSStripped->IgnoreParenCasts(); 11410 11411 // Warn about comparisons against a string constant (unless the other 11412 // operand is null); the user probably wants string comparison function. 11413 Expr *LiteralString = nullptr; 11414 Expr *LiteralStringStripped = nullptr; 11415 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 11416 !RHSStripped->isNullPointerConstant(S.Context, 11417 Expr::NPC_ValueDependentIsNull)) { 11418 LiteralString = LHS; 11419 LiteralStringStripped = LHSStripped; 11420 } else if ((isa<StringLiteral>(RHSStripped) || 11421 isa<ObjCEncodeExpr>(RHSStripped)) && 11422 !LHSStripped->isNullPointerConstant(S.Context, 11423 Expr::NPC_ValueDependentIsNull)) { 11424 LiteralString = RHS; 11425 LiteralStringStripped = RHSStripped; 11426 } 11427 11428 if (LiteralString) { 11429 S.DiagRuntimeBehavior(Loc, nullptr, 11430 S.PDiag(diag::warn_stringcompare) 11431 << isa<ObjCEncodeExpr>(LiteralStringStripped) 11432 << LiteralString->getSourceRange()); 11433 } 11434 } 11435 11436 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 11437 switch (CK) { 11438 default: { 11439 #ifndef NDEBUG 11440 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 11441 << "\n"; 11442 #endif 11443 llvm_unreachable("unhandled cast kind"); 11444 } 11445 case CK_UserDefinedConversion: 11446 return ICK_Identity; 11447 case CK_LValueToRValue: 11448 return ICK_Lvalue_To_Rvalue; 11449 case CK_ArrayToPointerDecay: 11450 return ICK_Array_To_Pointer; 11451 case CK_FunctionToPointerDecay: 11452 return ICK_Function_To_Pointer; 11453 case CK_IntegralCast: 11454 return ICK_Integral_Conversion; 11455 case CK_FloatingCast: 11456 return ICK_Floating_Conversion; 11457 case CK_IntegralToFloating: 11458 case CK_FloatingToIntegral: 11459 return ICK_Floating_Integral; 11460 case CK_IntegralComplexCast: 11461 case CK_FloatingComplexCast: 11462 case CK_FloatingComplexToIntegralComplex: 11463 case CK_IntegralComplexToFloatingComplex: 11464 return ICK_Complex_Conversion; 11465 case CK_FloatingComplexToReal: 11466 case CK_FloatingRealToComplex: 11467 case CK_IntegralComplexToReal: 11468 case CK_IntegralRealToComplex: 11469 return ICK_Complex_Real; 11470 } 11471 } 11472 11473 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 11474 QualType FromType, 11475 SourceLocation Loc) { 11476 // Check for a narrowing implicit conversion. 11477 StandardConversionSequence SCS; 11478 SCS.setAsIdentityConversion(); 11479 SCS.setToType(0, FromType); 11480 SCS.setToType(1, ToType); 11481 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 11482 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 11483 11484 APValue PreNarrowingValue; 11485 QualType PreNarrowingType; 11486 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 11487 PreNarrowingType, 11488 /*IgnoreFloatToIntegralConversion*/ true)) { 11489 case NK_Dependent_Narrowing: 11490 // Implicit conversion to a narrower type, but the expression is 11491 // value-dependent so we can't tell whether it's actually narrowing. 11492 case NK_Not_Narrowing: 11493 return false; 11494 11495 case NK_Constant_Narrowing: 11496 // Implicit conversion to a narrower type, and the value is not a constant 11497 // expression. 11498 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11499 << /*Constant*/ 1 11500 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 11501 return true; 11502 11503 case NK_Variable_Narrowing: 11504 // Implicit conversion to a narrower type, and the value is not a constant 11505 // expression. 11506 case NK_Type_Narrowing: 11507 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 11508 << /*Constant*/ 0 << FromType << ToType; 11509 // TODO: It's not a constant expression, but what if the user intended it 11510 // to be? Can we produce notes to help them figure out why it isn't? 11511 return true; 11512 } 11513 llvm_unreachable("unhandled case in switch"); 11514 } 11515 11516 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 11517 ExprResult &LHS, 11518 ExprResult &RHS, 11519 SourceLocation Loc) { 11520 QualType LHSType = LHS.get()->getType(); 11521 QualType RHSType = RHS.get()->getType(); 11522 // Dig out the original argument type and expression before implicit casts 11523 // were applied. These are the types/expressions we need to check the 11524 // [expr.spaceship] requirements against. 11525 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 11526 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 11527 QualType LHSStrippedType = LHSStripped.get()->getType(); 11528 QualType RHSStrippedType = RHSStripped.get()->getType(); 11529 11530 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 11531 // other is not, the program is ill-formed. 11532 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 11533 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11534 return QualType(); 11535 } 11536 11537 // FIXME: Consider combining this with checkEnumArithmeticConversions. 11538 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 11539 RHSStrippedType->isEnumeralType(); 11540 if (NumEnumArgs == 1) { 11541 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 11542 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 11543 if (OtherTy->hasFloatingRepresentation()) { 11544 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 11545 return QualType(); 11546 } 11547 } 11548 if (NumEnumArgs == 2) { 11549 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 11550 // type E, the operator yields the result of converting the operands 11551 // to the underlying type of E and applying <=> to the converted operands. 11552 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 11553 S.InvalidOperands(Loc, LHS, RHS); 11554 return QualType(); 11555 } 11556 QualType IntType = 11557 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 11558 assert(IntType->isArithmeticType()); 11559 11560 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 11561 // promote the boolean type, and all other promotable integer types, to 11562 // avoid this. 11563 if (IntType->isPromotableIntegerType()) 11564 IntType = S.Context.getPromotedIntegerType(IntType); 11565 11566 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 11567 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 11568 LHSType = RHSType = IntType; 11569 } 11570 11571 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 11572 // usual arithmetic conversions are applied to the operands. 11573 QualType Type = 11574 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11575 if (LHS.isInvalid() || RHS.isInvalid()) 11576 return QualType(); 11577 if (Type.isNull()) 11578 return S.InvalidOperands(Loc, LHS, RHS); 11579 11580 Optional<ComparisonCategoryType> CCT = 11581 getComparisonCategoryForBuiltinCmp(Type); 11582 if (!CCT) 11583 return S.InvalidOperands(Loc, LHS, RHS); 11584 11585 bool HasNarrowing = checkThreeWayNarrowingConversion( 11586 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 11587 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 11588 RHS.get()->getBeginLoc()); 11589 if (HasNarrowing) 11590 return QualType(); 11591 11592 assert(!Type.isNull() && "composite type for <=> has not been set"); 11593 11594 return S.CheckComparisonCategoryType( 11595 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 11596 } 11597 11598 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 11599 ExprResult &RHS, 11600 SourceLocation Loc, 11601 BinaryOperatorKind Opc) { 11602 if (Opc == BO_Cmp) 11603 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 11604 11605 // C99 6.5.8p3 / C99 6.5.9p4 11606 QualType Type = 11607 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 11608 if (LHS.isInvalid() || RHS.isInvalid()) 11609 return QualType(); 11610 if (Type.isNull()) 11611 return S.InvalidOperands(Loc, LHS, RHS); 11612 assert(Type->isArithmeticType() || Type->isEnumeralType()); 11613 11614 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 11615 return S.InvalidOperands(Loc, LHS, RHS); 11616 11617 // Check for comparisons of floating point operands using != and ==. 11618 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 11619 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 11620 11621 // The result of comparisons is 'bool' in C++, 'int' in C. 11622 return S.Context.getLogicalOperationType(); 11623 } 11624 11625 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 11626 if (!NullE.get()->getType()->isAnyPointerType()) 11627 return; 11628 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 11629 if (!E.get()->getType()->isAnyPointerType() && 11630 E.get()->isNullPointerConstant(Context, 11631 Expr::NPC_ValueDependentIsNotNull) == 11632 Expr::NPCK_ZeroExpression) { 11633 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 11634 if (CL->getValue() == 0) 11635 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11636 << NullValue 11637 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11638 NullValue ? "NULL" : "(void *)0"); 11639 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 11640 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 11641 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 11642 if (T == Context.CharTy) 11643 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 11644 << NullValue 11645 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 11646 NullValue ? "NULL" : "(void *)0"); 11647 } 11648 } 11649 } 11650 11651 // C99 6.5.8, C++ [expr.rel] 11652 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 11653 SourceLocation Loc, 11654 BinaryOperatorKind Opc) { 11655 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 11656 bool IsThreeWay = Opc == BO_Cmp; 11657 bool IsOrdered = IsRelational || IsThreeWay; 11658 auto IsAnyPointerType = [](ExprResult E) { 11659 QualType Ty = E.get()->getType(); 11660 return Ty->isPointerType() || Ty->isMemberPointerType(); 11661 }; 11662 11663 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 11664 // type, array-to-pointer, ..., conversions are performed on both operands to 11665 // bring them to their composite type. 11666 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 11667 // any type-related checks. 11668 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 11669 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 11670 if (LHS.isInvalid()) 11671 return QualType(); 11672 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 11673 if (RHS.isInvalid()) 11674 return QualType(); 11675 } else { 11676 LHS = DefaultLvalueConversion(LHS.get()); 11677 if (LHS.isInvalid()) 11678 return QualType(); 11679 RHS = DefaultLvalueConversion(RHS.get()); 11680 if (RHS.isInvalid()) 11681 return QualType(); 11682 } 11683 11684 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 11685 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 11686 CheckPtrComparisonWithNullChar(LHS, RHS); 11687 CheckPtrComparisonWithNullChar(RHS, LHS); 11688 } 11689 11690 // Handle vector comparisons separately. 11691 if (LHS.get()->getType()->isVectorType() || 11692 RHS.get()->getType()->isVectorType()) 11693 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 11694 11695 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 11696 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 11697 11698 QualType LHSType = LHS.get()->getType(); 11699 QualType RHSType = RHS.get()->getType(); 11700 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 11701 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 11702 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 11703 11704 const Expr::NullPointerConstantKind LHSNullKind = 11705 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11706 const Expr::NullPointerConstantKind RHSNullKind = 11707 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 11708 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 11709 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 11710 11711 auto computeResultTy = [&]() { 11712 if (Opc != BO_Cmp) 11713 return Context.getLogicalOperationType(); 11714 assert(getLangOpts().CPlusPlus); 11715 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 11716 11717 QualType CompositeTy = LHS.get()->getType(); 11718 assert(!CompositeTy->isReferenceType()); 11719 11720 Optional<ComparisonCategoryType> CCT = 11721 getComparisonCategoryForBuiltinCmp(CompositeTy); 11722 if (!CCT) 11723 return InvalidOperands(Loc, LHS, RHS); 11724 11725 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 11726 // P0946R0: Comparisons between a null pointer constant and an object 11727 // pointer result in std::strong_equality, which is ill-formed under 11728 // P1959R0. 11729 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 11730 << (LHSIsNull ? LHS.get()->getSourceRange() 11731 : RHS.get()->getSourceRange()); 11732 return QualType(); 11733 } 11734 11735 return CheckComparisonCategoryType( 11736 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 11737 }; 11738 11739 if (!IsOrdered && LHSIsNull != RHSIsNull) { 11740 bool IsEquality = Opc == BO_EQ; 11741 if (RHSIsNull) 11742 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 11743 RHS.get()->getSourceRange()); 11744 else 11745 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 11746 LHS.get()->getSourceRange()); 11747 } 11748 11749 if ((LHSType->isIntegerType() && !LHSIsNull) || 11750 (RHSType->isIntegerType() && !RHSIsNull)) { 11751 // Skip normal pointer conversion checks in this case; we have better 11752 // diagnostics for this below. 11753 } else if (getLangOpts().CPlusPlus) { 11754 // Equality comparison of a function pointer to a void pointer is invalid, 11755 // but we allow it as an extension. 11756 // FIXME: If we really want to allow this, should it be part of composite 11757 // pointer type computation so it works in conditionals too? 11758 if (!IsOrdered && 11759 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 11760 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 11761 // This is a gcc extension compatibility comparison. 11762 // In a SFINAE context, we treat this as a hard error to maintain 11763 // conformance with the C++ standard. 11764 diagnoseFunctionPointerToVoidComparison( 11765 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 11766 11767 if (isSFINAEContext()) 11768 return QualType(); 11769 11770 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11771 return computeResultTy(); 11772 } 11773 11774 // C++ [expr.eq]p2: 11775 // If at least one operand is a pointer [...] bring them to their 11776 // composite pointer type. 11777 // C++ [expr.spaceship]p6 11778 // If at least one of the operands is of pointer type, [...] bring them 11779 // to their composite pointer type. 11780 // C++ [expr.rel]p2: 11781 // If both operands are pointers, [...] bring them to their composite 11782 // pointer type. 11783 // For <=>, the only valid non-pointer types are arrays and functions, and 11784 // we already decayed those, so this is really the same as the relational 11785 // comparison rule. 11786 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 11787 (IsOrdered ? 2 : 1) && 11788 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 11789 RHSType->isObjCObjectPointerType()))) { 11790 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11791 return QualType(); 11792 return computeResultTy(); 11793 } 11794 } else if (LHSType->isPointerType() && 11795 RHSType->isPointerType()) { // C99 6.5.8p2 11796 // All of the following pointer-related warnings are GCC extensions, except 11797 // when handling null pointer constants. 11798 QualType LCanPointeeTy = 11799 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11800 QualType RCanPointeeTy = 11801 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 11802 11803 // C99 6.5.9p2 and C99 6.5.8p2 11804 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 11805 RCanPointeeTy.getUnqualifiedType())) { 11806 if (IsRelational) { 11807 // Pointers both need to point to complete or incomplete types 11808 if ((LCanPointeeTy->isIncompleteType() != 11809 RCanPointeeTy->isIncompleteType()) && 11810 !getLangOpts().C11) { 11811 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 11812 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 11813 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 11814 << RCanPointeeTy->isIncompleteType(); 11815 } 11816 if (LCanPointeeTy->isFunctionType()) { 11817 // Valid unless a relational comparison of function pointers 11818 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 11819 << LHSType << RHSType << LHS.get()->getSourceRange() 11820 << RHS.get()->getSourceRange(); 11821 } 11822 } 11823 } else if (!IsRelational && 11824 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 11825 // Valid unless comparison between non-null pointer and function pointer 11826 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 11827 && !LHSIsNull && !RHSIsNull) 11828 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 11829 /*isError*/false); 11830 } else { 11831 // Invalid 11832 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 11833 } 11834 if (LCanPointeeTy != RCanPointeeTy) { 11835 // Treat NULL constant as a special case in OpenCL. 11836 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 11837 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 11838 Diag(Loc, 11839 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11840 << LHSType << RHSType << 0 /* comparison */ 11841 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11842 } 11843 } 11844 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 11845 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 11846 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 11847 : CK_BitCast; 11848 if (LHSIsNull && !RHSIsNull) 11849 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 11850 else 11851 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 11852 } 11853 return computeResultTy(); 11854 } 11855 11856 if (getLangOpts().CPlusPlus) { 11857 // C++ [expr.eq]p4: 11858 // Two operands of type std::nullptr_t or one operand of type 11859 // std::nullptr_t and the other a null pointer constant compare equal. 11860 if (!IsOrdered && LHSIsNull && RHSIsNull) { 11861 if (LHSType->isNullPtrType()) { 11862 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11863 return computeResultTy(); 11864 } 11865 if (RHSType->isNullPtrType()) { 11866 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11867 return computeResultTy(); 11868 } 11869 } 11870 11871 // Comparison of Objective-C pointers and block pointers against nullptr_t. 11872 // These aren't covered by the composite pointer type rules. 11873 if (!IsOrdered && RHSType->isNullPtrType() && 11874 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 11875 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11876 return computeResultTy(); 11877 } 11878 if (!IsOrdered && LHSType->isNullPtrType() && 11879 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 11880 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11881 return computeResultTy(); 11882 } 11883 11884 if (IsRelational && 11885 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 11886 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 11887 // HACK: Relational comparison of nullptr_t against a pointer type is 11888 // invalid per DR583, but we allow it within std::less<> and friends, 11889 // since otherwise common uses of it break. 11890 // FIXME: Consider removing this hack once LWG fixes std::less<> and 11891 // friends to have std::nullptr_t overload candidates. 11892 DeclContext *DC = CurContext; 11893 if (isa<FunctionDecl>(DC)) 11894 DC = DC->getParent(); 11895 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 11896 if (CTSD->isInStdNamespace() && 11897 llvm::StringSwitch<bool>(CTSD->getName()) 11898 .Cases("less", "less_equal", "greater", "greater_equal", true) 11899 .Default(false)) { 11900 if (RHSType->isNullPtrType()) 11901 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 11902 else 11903 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 11904 return computeResultTy(); 11905 } 11906 } 11907 } 11908 11909 // C++ [expr.eq]p2: 11910 // If at least one operand is a pointer to member, [...] bring them to 11911 // their composite pointer type. 11912 if (!IsOrdered && 11913 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 11914 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 11915 return QualType(); 11916 else 11917 return computeResultTy(); 11918 } 11919 } 11920 11921 // Handle block pointer types. 11922 if (!IsOrdered && LHSType->isBlockPointerType() && 11923 RHSType->isBlockPointerType()) { 11924 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 11925 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 11926 11927 if (!LHSIsNull && !RHSIsNull && 11928 !Context.typesAreCompatible(lpointee, rpointee)) { 11929 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11930 << LHSType << RHSType << LHS.get()->getSourceRange() 11931 << RHS.get()->getSourceRange(); 11932 } 11933 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 11934 return computeResultTy(); 11935 } 11936 11937 // Allow block pointers to be compared with null pointer constants. 11938 if (!IsOrdered 11939 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 11940 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 11941 if (!LHSIsNull && !RHSIsNull) { 11942 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 11943 ->getPointeeType()->isVoidType()) 11944 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 11945 ->getPointeeType()->isVoidType()))) 11946 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 11947 << LHSType << RHSType << LHS.get()->getSourceRange() 11948 << RHS.get()->getSourceRange(); 11949 } 11950 if (LHSIsNull && !RHSIsNull) 11951 LHS = ImpCastExprToType(LHS.get(), RHSType, 11952 RHSType->isPointerType() ? CK_BitCast 11953 : CK_AnyPointerToBlockPointerCast); 11954 else 11955 RHS = ImpCastExprToType(RHS.get(), LHSType, 11956 LHSType->isPointerType() ? CK_BitCast 11957 : CK_AnyPointerToBlockPointerCast); 11958 return computeResultTy(); 11959 } 11960 11961 if (LHSType->isObjCObjectPointerType() || 11962 RHSType->isObjCObjectPointerType()) { 11963 const PointerType *LPT = LHSType->getAs<PointerType>(); 11964 const PointerType *RPT = RHSType->getAs<PointerType>(); 11965 if (LPT || RPT) { 11966 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 11967 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 11968 11969 if (!LPtrToVoid && !RPtrToVoid && 11970 !Context.typesAreCompatible(LHSType, RHSType)) { 11971 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 11972 /*isError*/false); 11973 } 11974 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 11975 // the RHS, but we have test coverage for this behavior. 11976 // FIXME: Consider using convertPointersToCompositeType in C++. 11977 if (LHSIsNull && !RHSIsNull) { 11978 Expr *E = LHS.get(); 11979 if (getLangOpts().ObjCAutoRefCount) 11980 CheckObjCConversion(SourceRange(), RHSType, E, 11981 CCK_ImplicitConversion); 11982 LHS = ImpCastExprToType(E, RHSType, 11983 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11984 } 11985 else { 11986 Expr *E = RHS.get(); 11987 if (getLangOpts().ObjCAutoRefCount) 11988 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 11989 /*Diagnose=*/true, 11990 /*DiagnoseCFAudited=*/false, Opc); 11991 RHS = ImpCastExprToType(E, LHSType, 11992 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 11993 } 11994 return computeResultTy(); 11995 } 11996 if (LHSType->isObjCObjectPointerType() && 11997 RHSType->isObjCObjectPointerType()) { 11998 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 11999 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12000 /*isError*/false); 12001 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 12002 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 12003 12004 if (LHSIsNull && !RHSIsNull) 12005 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 12006 else 12007 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12008 return computeResultTy(); 12009 } 12010 12011 if (!IsOrdered && LHSType->isBlockPointerType() && 12012 RHSType->isBlockCompatibleObjCPointerType(Context)) { 12013 LHS = ImpCastExprToType(LHS.get(), RHSType, 12014 CK_BlockPointerToObjCPointerCast); 12015 return computeResultTy(); 12016 } else if (!IsOrdered && 12017 LHSType->isBlockCompatibleObjCPointerType(Context) && 12018 RHSType->isBlockPointerType()) { 12019 RHS = ImpCastExprToType(RHS.get(), LHSType, 12020 CK_BlockPointerToObjCPointerCast); 12021 return computeResultTy(); 12022 } 12023 } 12024 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 12025 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 12026 unsigned DiagID = 0; 12027 bool isError = false; 12028 if (LangOpts.DebuggerSupport) { 12029 // Under a debugger, allow the comparison of pointers to integers, 12030 // since users tend to want to compare addresses. 12031 } else if ((LHSIsNull && LHSType->isIntegerType()) || 12032 (RHSIsNull && RHSType->isIntegerType())) { 12033 if (IsOrdered) { 12034 isError = getLangOpts().CPlusPlus; 12035 DiagID = 12036 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 12037 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 12038 } 12039 } else if (getLangOpts().CPlusPlus) { 12040 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 12041 isError = true; 12042 } else if (IsOrdered) 12043 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 12044 else 12045 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 12046 12047 if (DiagID) { 12048 Diag(Loc, DiagID) 12049 << LHSType << RHSType << LHS.get()->getSourceRange() 12050 << RHS.get()->getSourceRange(); 12051 if (isError) 12052 return QualType(); 12053 } 12054 12055 if (LHSType->isIntegerType()) 12056 LHS = ImpCastExprToType(LHS.get(), RHSType, 12057 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12058 else 12059 RHS = ImpCastExprToType(RHS.get(), LHSType, 12060 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 12061 return computeResultTy(); 12062 } 12063 12064 // Handle block pointers. 12065 if (!IsOrdered && RHSIsNull 12066 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 12067 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12068 return computeResultTy(); 12069 } 12070 if (!IsOrdered && LHSIsNull 12071 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 12072 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12073 return computeResultTy(); 12074 } 12075 12076 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 12077 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 12078 return computeResultTy(); 12079 } 12080 12081 if (LHSType->isQueueT() && RHSType->isQueueT()) { 12082 return computeResultTy(); 12083 } 12084 12085 if (LHSIsNull && RHSType->isQueueT()) { 12086 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12087 return computeResultTy(); 12088 } 12089 12090 if (LHSType->isQueueT() && RHSIsNull) { 12091 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12092 return computeResultTy(); 12093 } 12094 } 12095 12096 return InvalidOperands(Loc, LHS, RHS); 12097 } 12098 12099 // Return a signed ext_vector_type that is of identical size and number of 12100 // elements. For floating point vectors, return an integer type of identical 12101 // size and number of elements. In the non ext_vector_type case, search from 12102 // the largest type to the smallest type to avoid cases where long long == long, 12103 // where long gets picked over long long. 12104 QualType Sema::GetSignedVectorType(QualType V) { 12105 const VectorType *VTy = V->castAs<VectorType>(); 12106 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 12107 12108 if (isa<ExtVectorType>(VTy)) { 12109 if (TypeSize == Context.getTypeSize(Context.CharTy)) 12110 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 12111 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12112 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 12113 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12114 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 12115 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12116 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 12117 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 12118 "Unhandled vector element size in vector compare"); 12119 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 12120 } 12121 12122 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 12123 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 12124 VectorType::GenericVector); 12125 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 12126 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 12127 VectorType::GenericVector); 12128 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 12129 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 12130 VectorType::GenericVector); 12131 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 12132 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 12133 VectorType::GenericVector); 12134 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 12135 "Unhandled vector element size in vector compare"); 12136 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 12137 VectorType::GenericVector); 12138 } 12139 12140 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 12141 /// operates on extended vector types. Instead of producing an IntTy result, 12142 /// like a scalar comparison, a vector comparison produces a vector of integer 12143 /// types. 12144 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 12145 SourceLocation Loc, 12146 BinaryOperatorKind Opc) { 12147 if (Opc == BO_Cmp) { 12148 Diag(Loc, diag::err_three_way_vector_comparison); 12149 return QualType(); 12150 } 12151 12152 // Check to make sure we're operating on vectors of the same type and width, 12153 // Allowing one side to be a scalar of element type. 12154 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 12155 /*AllowBothBool*/true, 12156 /*AllowBoolConversions*/getLangOpts().ZVector); 12157 if (vType.isNull()) 12158 return vType; 12159 12160 QualType LHSType = LHS.get()->getType(); 12161 12162 // If AltiVec, the comparison results in a numeric type, i.e. 12163 // bool for C++, int for C 12164 if (getLangOpts().AltiVec && 12165 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 12166 return Context.getLogicalOperationType(); 12167 12168 // For non-floating point types, check for self-comparisons of the form 12169 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12170 // often indicate logic errors in the program. 12171 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12172 12173 // Check for comparisons of floating point operands using != and ==. 12174 if (BinaryOperator::isEqualityOp(Opc) && 12175 LHSType->hasFloatingRepresentation()) { 12176 assert(RHS.get()->getType()->hasFloatingRepresentation()); 12177 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 12178 } 12179 12180 // Return a signed type for the vector. 12181 return GetSignedVectorType(vType); 12182 } 12183 12184 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 12185 const ExprResult &XorRHS, 12186 const SourceLocation Loc) { 12187 // Do not diagnose macros. 12188 if (Loc.isMacroID()) 12189 return; 12190 12191 // Do not diagnose if both LHS and RHS are macros. 12192 if (XorLHS.get()->getExprLoc().isMacroID() && 12193 XorRHS.get()->getExprLoc().isMacroID()) 12194 return; 12195 12196 bool Negative = false; 12197 bool ExplicitPlus = false; 12198 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 12199 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 12200 12201 if (!LHSInt) 12202 return; 12203 if (!RHSInt) { 12204 // Check negative literals. 12205 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 12206 UnaryOperatorKind Opc = UO->getOpcode(); 12207 if (Opc != UO_Minus && Opc != UO_Plus) 12208 return; 12209 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12210 if (!RHSInt) 12211 return; 12212 Negative = (Opc == UO_Minus); 12213 ExplicitPlus = !Negative; 12214 } else { 12215 return; 12216 } 12217 } 12218 12219 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 12220 llvm::APInt RightSideValue = RHSInt->getValue(); 12221 if (LeftSideValue != 2 && LeftSideValue != 10) 12222 return; 12223 12224 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 12225 return; 12226 12227 CharSourceRange ExprRange = CharSourceRange::getCharRange( 12228 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 12229 llvm::StringRef ExprStr = 12230 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 12231 12232 CharSourceRange XorRange = 12233 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12234 llvm::StringRef XorStr = 12235 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 12236 // Do not diagnose if xor keyword/macro is used. 12237 if (XorStr == "xor") 12238 return; 12239 12240 std::string LHSStr = std::string(Lexer::getSourceText( 12241 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 12242 S.getSourceManager(), S.getLangOpts())); 12243 std::string RHSStr = std::string(Lexer::getSourceText( 12244 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 12245 S.getSourceManager(), S.getLangOpts())); 12246 12247 if (Negative) { 12248 RightSideValue = -RightSideValue; 12249 RHSStr = "-" + RHSStr; 12250 } else if (ExplicitPlus) { 12251 RHSStr = "+" + RHSStr; 12252 } 12253 12254 StringRef LHSStrRef = LHSStr; 12255 StringRef RHSStrRef = RHSStr; 12256 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 12257 // literals. 12258 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 12259 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 12260 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 12261 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 12262 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 12263 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 12264 LHSStrRef.find('\'') != StringRef::npos || 12265 RHSStrRef.find('\'') != StringRef::npos) 12266 return; 12267 12268 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 12269 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 12270 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 12271 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 12272 std::string SuggestedExpr = "1 << " + RHSStr; 12273 bool Overflow = false; 12274 llvm::APInt One = (LeftSideValue - 1); 12275 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 12276 if (Overflow) { 12277 if (RightSideIntValue < 64) 12278 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12279 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr) 12280 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 12281 else if (RightSideIntValue == 64) 12282 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true); 12283 else 12284 return; 12285 } else { 12286 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 12287 << ExprStr << XorValue.toString(10, true) << SuggestedExpr 12288 << PowValue.toString(10, true) 12289 << FixItHint::CreateReplacement( 12290 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 12291 } 12292 12293 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor; 12294 } else if (LeftSideValue == 10) { 12295 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 12296 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 12297 << ExprStr << XorValue.toString(10, true) << SuggestedValue 12298 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 12299 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor; 12300 } 12301 } 12302 12303 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12304 SourceLocation Loc) { 12305 // Ensure that either both operands are of the same vector type, or 12306 // one operand is of a vector type and the other is of its element type. 12307 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 12308 /*AllowBothBool*/true, 12309 /*AllowBoolConversions*/false); 12310 if (vType.isNull()) 12311 return InvalidOperands(Loc, LHS, RHS); 12312 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 12313 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation()) 12314 return InvalidOperands(Loc, LHS, RHS); 12315 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 12316 // usage of the logical operators && and || with vectors in C. This 12317 // check could be notionally dropped. 12318 if (!getLangOpts().CPlusPlus && 12319 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 12320 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 12321 12322 return GetSignedVectorType(LHS.get()->getType()); 12323 } 12324 12325 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 12326 SourceLocation Loc, 12327 bool IsCompAssign) { 12328 if (!IsCompAssign) { 12329 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12330 if (LHS.isInvalid()) 12331 return QualType(); 12332 } 12333 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12334 if (RHS.isInvalid()) 12335 return QualType(); 12336 12337 // For conversion purposes, we ignore any qualifiers. 12338 // For example, "const float" and "float" are equivalent. 12339 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 12340 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 12341 12342 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 12343 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 12344 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12345 12346 if (Context.hasSameType(LHSType, RHSType)) 12347 return LHSType; 12348 12349 // Type conversion may change LHS/RHS. Keep copies to the original results, in 12350 // case we have to return InvalidOperands. 12351 ExprResult OriginalLHS = LHS; 12352 ExprResult OriginalRHS = RHS; 12353 if (LHSMatType && !RHSMatType) { 12354 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 12355 if (!RHS.isInvalid()) 12356 return LHSType; 12357 12358 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12359 } 12360 12361 if (!LHSMatType && RHSMatType) { 12362 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 12363 if (!LHS.isInvalid()) 12364 return RHSType; 12365 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 12366 } 12367 12368 return InvalidOperands(Loc, LHS, RHS); 12369 } 12370 12371 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 12372 SourceLocation Loc, 12373 bool IsCompAssign) { 12374 if (!IsCompAssign) { 12375 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12376 if (LHS.isInvalid()) 12377 return QualType(); 12378 } 12379 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12380 if (RHS.isInvalid()) 12381 return QualType(); 12382 12383 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 12384 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 12385 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 12386 12387 if (LHSMatType && RHSMatType) { 12388 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 12389 return InvalidOperands(Loc, LHS, RHS); 12390 12391 if (!Context.hasSameType(LHSMatType->getElementType(), 12392 RHSMatType->getElementType())) 12393 return InvalidOperands(Loc, LHS, RHS); 12394 12395 return Context.getConstantMatrixType(LHSMatType->getElementType(), 12396 LHSMatType->getNumRows(), 12397 RHSMatType->getNumColumns()); 12398 } 12399 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 12400 } 12401 12402 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 12403 SourceLocation Loc, 12404 BinaryOperatorKind Opc) { 12405 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 12406 12407 bool IsCompAssign = 12408 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 12409 12410 if (LHS.get()->getType()->isVectorType() || 12411 RHS.get()->getType()->isVectorType()) { 12412 if (LHS.get()->getType()->hasIntegerRepresentation() && 12413 RHS.get()->getType()->hasIntegerRepresentation()) 12414 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 12415 /*AllowBothBool*/true, 12416 /*AllowBoolConversions*/getLangOpts().ZVector); 12417 return InvalidOperands(Loc, LHS, RHS); 12418 } 12419 12420 if (Opc == BO_And) 12421 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12422 12423 if (LHS.get()->getType()->hasFloatingRepresentation() || 12424 RHS.get()->getType()->hasFloatingRepresentation()) 12425 return InvalidOperands(Loc, LHS, RHS); 12426 12427 ExprResult LHSResult = LHS, RHSResult = RHS; 12428 QualType compType = UsualArithmeticConversions( 12429 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 12430 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 12431 return QualType(); 12432 LHS = LHSResult.get(); 12433 RHS = RHSResult.get(); 12434 12435 if (Opc == BO_Xor) 12436 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 12437 12438 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 12439 return compType; 12440 return InvalidOperands(Loc, LHS, RHS); 12441 } 12442 12443 // C99 6.5.[13,14] 12444 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 12445 SourceLocation Loc, 12446 BinaryOperatorKind Opc) { 12447 // Check vector operands differently. 12448 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 12449 return CheckVectorLogicalOperands(LHS, RHS, Loc); 12450 12451 bool EnumConstantInBoolContext = false; 12452 for (const ExprResult &HS : {LHS, RHS}) { 12453 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 12454 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 12455 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 12456 EnumConstantInBoolContext = true; 12457 } 12458 } 12459 12460 if (EnumConstantInBoolContext) 12461 Diag(Loc, diag::warn_enum_constant_in_bool_context); 12462 12463 // Diagnose cases where the user write a logical and/or but probably meant a 12464 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 12465 // is a constant. 12466 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 12467 !LHS.get()->getType()->isBooleanType() && 12468 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 12469 // Don't warn in macros or template instantiations. 12470 !Loc.isMacroID() && !inTemplateInstantiation()) { 12471 // If the RHS can be constant folded, and if it constant folds to something 12472 // that isn't 0 or 1 (which indicate a potential logical operation that 12473 // happened to fold to true/false) then warn. 12474 // Parens on the RHS are ignored. 12475 Expr::EvalResult EVResult; 12476 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 12477 llvm::APSInt Result = EVResult.Val.getInt(); 12478 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 12479 !RHS.get()->getExprLoc().isMacroID()) || 12480 (Result != 0 && Result != 1)) { 12481 Diag(Loc, diag::warn_logical_instead_of_bitwise) 12482 << RHS.get()->getSourceRange() 12483 << (Opc == BO_LAnd ? "&&" : "||"); 12484 // Suggest replacing the logical operator with the bitwise version 12485 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 12486 << (Opc == BO_LAnd ? "&" : "|") 12487 << FixItHint::CreateReplacement(SourceRange( 12488 Loc, getLocForEndOfToken(Loc)), 12489 Opc == BO_LAnd ? "&" : "|"); 12490 if (Opc == BO_LAnd) 12491 // Suggest replacing "Foo() && kNonZero" with "Foo()" 12492 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 12493 << FixItHint::CreateRemoval( 12494 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 12495 RHS.get()->getEndLoc())); 12496 } 12497 } 12498 } 12499 12500 if (!Context.getLangOpts().CPlusPlus) { 12501 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 12502 // not operate on the built-in scalar and vector float types. 12503 if (Context.getLangOpts().OpenCL && 12504 Context.getLangOpts().OpenCLVersion < 120) { 12505 if (LHS.get()->getType()->isFloatingType() || 12506 RHS.get()->getType()->isFloatingType()) 12507 return InvalidOperands(Loc, LHS, RHS); 12508 } 12509 12510 LHS = UsualUnaryConversions(LHS.get()); 12511 if (LHS.isInvalid()) 12512 return QualType(); 12513 12514 RHS = UsualUnaryConversions(RHS.get()); 12515 if (RHS.isInvalid()) 12516 return QualType(); 12517 12518 if (!LHS.get()->getType()->isScalarType() || 12519 !RHS.get()->getType()->isScalarType()) 12520 return InvalidOperands(Loc, LHS, RHS); 12521 12522 return Context.IntTy; 12523 } 12524 12525 // The following is safe because we only use this method for 12526 // non-overloadable operands. 12527 12528 // C++ [expr.log.and]p1 12529 // C++ [expr.log.or]p1 12530 // The operands are both contextually converted to type bool. 12531 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 12532 if (LHSRes.isInvalid()) 12533 return InvalidOperands(Loc, LHS, RHS); 12534 LHS = LHSRes; 12535 12536 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 12537 if (RHSRes.isInvalid()) 12538 return InvalidOperands(Loc, LHS, RHS); 12539 RHS = RHSRes; 12540 12541 // C++ [expr.log.and]p2 12542 // C++ [expr.log.or]p2 12543 // The result is a bool. 12544 return Context.BoolTy; 12545 } 12546 12547 static bool IsReadonlyMessage(Expr *E, Sema &S) { 12548 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12549 if (!ME) return false; 12550 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 12551 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 12552 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 12553 if (!Base) return false; 12554 return Base->getMethodDecl() != nullptr; 12555 } 12556 12557 /// Is the given expression (which must be 'const') a reference to a 12558 /// variable which was originally non-const, but which has become 12559 /// 'const' due to being captured within a block? 12560 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 12561 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 12562 assert(E->isLValue() && E->getType().isConstQualified()); 12563 E = E->IgnoreParens(); 12564 12565 // Must be a reference to a declaration from an enclosing scope. 12566 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 12567 if (!DRE) return NCCK_None; 12568 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 12569 12570 // The declaration must be a variable which is not declared 'const'. 12571 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 12572 if (!var) return NCCK_None; 12573 if (var->getType().isConstQualified()) return NCCK_None; 12574 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 12575 12576 // Decide whether the first capture was for a block or a lambda. 12577 DeclContext *DC = S.CurContext, *Prev = nullptr; 12578 // Decide whether the first capture was for a block or a lambda. 12579 while (DC) { 12580 // For init-capture, it is possible that the variable belongs to the 12581 // template pattern of the current context. 12582 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 12583 if (var->isInitCapture() && 12584 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 12585 break; 12586 if (DC == var->getDeclContext()) 12587 break; 12588 Prev = DC; 12589 DC = DC->getParent(); 12590 } 12591 // Unless we have an init-capture, we've gone one step too far. 12592 if (!var->isInitCapture()) 12593 DC = Prev; 12594 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 12595 } 12596 12597 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 12598 Ty = Ty.getNonReferenceType(); 12599 if (IsDereference && Ty->isPointerType()) 12600 Ty = Ty->getPointeeType(); 12601 return !Ty.isConstQualified(); 12602 } 12603 12604 // Update err_typecheck_assign_const and note_typecheck_assign_const 12605 // when this enum is changed. 12606 enum { 12607 ConstFunction, 12608 ConstVariable, 12609 ConstMember, 12610 ConstMethod, 12611 NestedConstMember, 12612 ConstUnknown, // Keep as last element 12613 }; 12614 12615 /// Emit the "read-only variable not assignable" error and print notes to give 12616 /// more information about why the variable is not assignable, such as pointing 12617 /// to the declaration of a const variable, showing that a method is const, or 12618 /// that the function is returning a const reference. 12619 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 12620 SourceLocation Loc) { 12621 SourceRange ExprRange = E->getSourceRange(); 12622 12623 // Only emit one error on the first const found. All other consts will emit 12624 // a note to the error. 12625 bool DiagnosticEmitted = false; 12626 12627 // Track if the current expression is the result of a dereference, and if the 12628 // next checked expression is the result of a dereference. 12629 bool IsDereference = false; 12630 bool NextIsDereference = false; 12631 12632 // Loop to process MemberExpr chains. 12633 while (true) { 12634 IsDereference = NextIsDereference; 12635 12636 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 12637 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12638 NextIsDereference = ME->isArrow(); 12639 const ValueDecl *VD = ME->getMemberDecl(); 12640 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 12641 // Mutable fields can be modified even if the class is const. 12642 if (Field->isMutable()) { 12643 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 12644 break; 12645 } 12646 12647 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 12648 if (!DiagnosticEmitted) { 12649 S.Diag(Loc, diag::err_typecheck_assign_const) 12650 << ExprRange << ConstMember << false /*static*/ << Field 12651 << Field->getType(); 12652 DiagnosticEmitted = true; 12653 } 12654 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12655 << ConstMember << false /*static*/ << Field << Field->getType() 12656 << Field->getSourceRange(); 12657 } 12658 E = ME->getBase(); 12659 continue; 12660 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 12661 if (VDecl->getType().isConstQualified()) { 12662 if (!DiagnosticEmitted) { 12663 S.Diag(Loc, diag::err_typecheck_assign_const) 12664 << ExprRange << ConstMember << true /*static*/ << VDecl 12665 << VDecl->getType(); 12666 DiagnosticEmitted = true; 12667 } 12668 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12669 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 12670 << VDecl->getSourceRange(); 12671 } 12672 // Static fields do not inherit constness from parents. 12673 break; 12674 } 12675 break; // End MemberExpr 12676 } else if (const ArraySubscriptExpr *ASE = 12677 dyn_cast<ArraySubscriptExpr>(E)) { 12678 E = ASE->getBase()->IgnoreParenImpCasts(); 12679 continue; 12680 } else if (const ExtVectorElementExpr *EVE = 12681 dyn_cast<ExtVectorElementExpr>(E)) { 12682 E = EVE->getBase()->IgnoreParenImpCasts(); 12683 continue; 12684 } 12685 break; 12686 } 12687 12688 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 12689 // Function calls 12690 const FunctionDecl *FD = CE->getDirectCallee(); 12691 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 12692 if (!DiagnosticEmitted) { 12693 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12694 << ConstFunction << FD; 12695 DiagnosticEmitted = true; 12696 } 12697 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 12698 diag::note_typecheck_assign_const) 12699 << ConstFunction << FD << FD->getReturnType() 12700 << FD->getReturnTypeSourceRange(); 12701 } 12702 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12703 // Point to variable declaration. 12704 if (const ValueDecl *VD = DRE->getDecl()) { 12705 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 12706 if (!DiagnosticEmitted) { 12707 S.Diag(Loc, diag::err_typecheck_assign_const) 12708 << ExprRange << ConstVariable << VD << VD->getType(); 12709 DiagnosticEmitted = true; 12710 } 12711 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 12712 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 12713 } 12714 } 12715 } else if (isa<CXXThisExpr>(E)) { 12716 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 12717 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 12718 if (MD->isConst()) { 12719 if (!DiagnosticEmitted) { 12720 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 12721 << ConstMethod << MD; 12722 DiagnosticEmitted = true; 12723 } 12724 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 12725 << ConstMethod << MD << MD->getSourceRange(); 12726 } 12727 } 12728 } 12729 } 12730 12731 if (DiagnosticEmitted) 12732 return; 12733 12734 // Can't determine a more specific message, so display the generic error. 12735 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 12736 } 12737 12738 enum OriginalExprKind { 12739 OEK_Variable, 12740 OEK_Member, 12741 OEK_LValue 12742 }; 12743 12744 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 12745 const RecordType *Ty, 12746 SourceLocation Loc, SourceRange Range, 12747 OriginalExprKind OEK, 12748 bool &DiagnosticEmitted) { 12749 std::vector<const RecordType *> RecordTypeList; 12750 RecordTypeList.push_back(Ty); 12751 unsigned NextToCheckIndex = 0; 12752 // We walk the record hierarchy breadth-first to ensure that we print 12753 // diagnostics in field nesting order. 12754 while (RecordTypeList.size() > NextToCheckIndex) { 12755 bool IsNested = NextToCheckIndex > 0; 12756 for (const FieldDecl *Field : 12757 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 12758 // First, check every field for constness. 12759 QualType FieldTy = Field->getType(); 12760 if (FieldTy.isConstQualified()) { 12761 if (!DiagnosticEmitted) { 12762 S.Diag(Loc, diag::err_typecheck_assign_const) 12763 << Range << NestedConstMember << OEK << VD 12764 << IsNested << Field; 12765 DiagnosticEmitted = true; 12766 } 12767 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 12768 << NestedConstMember << IsNested << Field 12769 << FieldTy << Field->getSourceRange(); 12770 } 12771 12772 // Then we append it to the list to check next in order. 12773 FieldTy = FieldTy.getCanonicalType(); 12774 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 12775 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 12776 RecordTypeList.push_back(FieldRecTy); 12777 } 12778 } 12779 ++NextToCheckIndex; 12780 } 12781 } 12782 12783 /// Emit an error for the case where a record we are trying to assign to has a 12784 /// const-qualified field somewhere in its hierarchy. 12785 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 12786 SourceLocation Loc) { 12787 QualType Ty = E->getType(); 12788 assert(Ty->isRecordType() && "lvalue was not record?"); 12789 SourceRange Range = E->getSourceRange(); 12790 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 12791 bool DiagEmitted = false; 12792 12793 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 12794 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 12795 Range, OEK_Member, DiagEmitted); 12796 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12797 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 12798 Range, OEK_Variable, DiagEmitted); 12799 else 12800 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 12801 Range, OEK_LValue, DiagEmitted); 12802 if (!DiagEmitted) 12803 DiagnoseConstAssignment(S, E, Loc); 12804 } 12805 12806 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 12807 /// emit an error and return true. If so, return false. 12808 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 12809 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 12810 12811 S.CheckShadowingDeclModification(E, Loc); 12812 12813 SourceLocation OrigLoc = Loc; 12814 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 12815 &Loc); 12816 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 12817 IsLV = Expr::MLV_InvalidMessageExpression; 12818 if (IsLV == Expr::MLV_Valid) 12819 return false; 12820 12821 unsigned DiagID = 0; 12822 bool NeedType = false; 12823 switch (IsLV) { // C99 6.5.16p2 12824 case Expr::MLV_ConstQualified: 12825 // Use a specialized diagnostic when we're assigning to an object 12826 // from an enclosing function or block. 12827 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 12828 if (NCCK == NCCK_Block) 12829 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 12830 else 12831 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 12832 break; 12833 } 12834 12835 // In ARC, use some specialized diagnostics for occasions where we 12836 // infer 'const'. These are always pseudo-strong variables. 12837 if (S.getLangOpts().ObjCAutoRefCount) { 12838 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 12839 if (declRef && isa<VarDecl>(declRef->getDecl())) { 12840 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 12841 12842 // Use the normal diagnostic if it's pseudo-__strong but the 12843 // user actually wrote 'const'. 12844 if (var->isARCPseudoStrong() && 12845 (!var->getTypeSourceInfo() || 12846 !var->getTypeSourceInfo()->getType().isConstQualified())) { 12847 // There are three pseudo-strong cases: 12848 // - self 12849 ObjCMethodDecl *method = S.getCurMethodDecl(); 12850 if (method && var == method->getSelfDecl()) { 12851 DiagID = method->isClassMethod() 12852 ? diag::err_typecheck_arc_assign_self_class_method 12853 : diag::err_typecheck_arc_assign_self; 12854 12855 // - Objective-C externally_retained attribute. 12856 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 12857 isa<ParmVarDecl>(var)) { 12858 DiagID = diag::err_typecheck_arc_assign_externally_retained; 12859 12860 // - fast enumeration variables 12861 } else { 12862 DiagID = diag::err_typecheck_arr_assign_enumeration; 12863 } 12864 12865 SourceRange Assign; 12866 if (Loc != OrigLoc) 12867 Assign = SourceRange(OrigLoc, OrigLoc); 12868 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12869 // We need to preserve the AST regardless, so migration tool 12870 // can do its job. 12871 return false; 12872 } 12873 } 12874 } 12875 12876 // If none of the special cases above are triggered, then this is a 12877 // simple const assignment. 12878 if (DiagID == 0) { 12879 DiagnoseConstAssignment(S, E, Loc); 12880 return true; 12881 } 12882 12883 break; 12884 case Expr::MLV_ConstAddrSpace: 12885 DiagnoseConstAssignment(S, E, Loc); 12886 return true; 12887 case Expr::MLV_ConstQualifiedField: 12888 DiagnoseRecursiveConstFields(S, E, Loc); 12889 return true; 12890 case Expr::MLV_ArrayType: 12891 case Expr::MLV_ArrayTemporary: 12892 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 12893 NeedType = true; 12894 break; 12895 case Expr::MLV_NotObjectType: 12896 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 12897 NeedType = true; 12898 break; 12899 case Expr::MLV_LValueCast: 12900 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 12901 break; 12902 case Expr::MLV_Valid: 12903 llvm_unreachable("did not take early return for MLV_Valid"); 12904 case Expr::MLV_InvalidExpression: 12905 case Expr::MLV_MemberFunction: 12906 case Expr::MLV_ClassTemporary: 12907 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 12908 break; 12909 case Expr::MLV_IncompleteType: 12910 case Expr::MLV_IncompleteVoidType: 12911 return S.RequireCompleteType(Loc, E->getType(), 12912 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 12913 case Expr::MLV_DuplicateVectorComponents: 12914 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 12915 break; 12916 case Expr::MLV_NoSetterProperty: 12917 llvm_unreachable("readonly properties should be processed differently"); 12918 case Expr::MLV_InvalidMessageExpression: 12919 DiagID = diag::err_readonly_message_assignment; 12920 break; 12921 case Expr::MLV_SubObjCPropertySetting: 12922 DiagID = diag::err_no_subobject_property_setting; 12923 break; 12924 } 12925 12926 SourceRange Assign; 12927 if (Loc != OrigLoc) 12928 Assign = SourceRange(OrigLoc, OrigLoc); 12929 if (NeedType) 12930 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 12931 else 12932 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 12933 return true; 12934 } 12935 12936 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 12937 SourceLocation Loc, 12938 Sema &Sema) { 12939 if (Sema.inTemplateInstantiation()) 12940 return; 12941 if (Sema.isUnevaluatedContext()) 12942 return; 12943 if (Loc.isInvalid() || Loc.isMacroID()) 12944 return; 12945 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 12946 return; 12947 12948 // C / C++ fields 12949 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 12950 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 12951 if (ML && MR) { 12952 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 12953 return; 12954 const ValueDecl *LHSDecl = 12955 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 12956 const ValueDecl *RHSDecl = 12957 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 12958 if (LHSDecl != RHSDecl) 12959 return; 12960 if (LHSDecl->getType().isVolatileQualified()) 12961 return; 12962 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12963 if (RefTy->getPointeeType().isVolatileQualified()) 12964 return; 12965 12966 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 12967 } 12968 12969 // Objective-C instance variables 12970 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 12971 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 12972 if (OL && OR && OL->getDecl() == OR->getDecl()) { 12973 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 12974 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 12975 if (RL && RR && RL->getDecl() == RR->getDecl()) 12976 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 12977 } 12978 } 12979 12980 // C99 6.5.16.1 12981 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 12982 SourceLocation Loc, 12983 QualType CompoundType) { 12984 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 12985 12986 // Verify that LHS is a modifiable lvalue, and emit error if not. 12987 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 12988 return QualType(); 12989 12990 QualType LHSType = LHSExpr->getType(); 12991 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 12992 CompoundType; 12993 // OpenCL v1.2 s6.1.1.1 p2: 12994 // The half data type can only be used to declare a pointer to a buffer that 12995 // contains half values 12996 if (getLangOpts().OpenCL && 12997 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 12998 LHSType->isHalfType()) { 12999 Diag(Loc, diag::err_opencl_half_load_store) << 1 13000 << LHSType.getUnqualifiedType(); 13001 return QualType(); 13002 } 13003 13004 AssignConvertType ConvTy; 13005 if (CompoundType.isNull()) { 13006 Expr *RHSCheck = RHS.get(); 13007 13008 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 13009 13010 QualType LHSTy(LHSType); 13011 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 13012 if (RHS.isInvalid()) 13013 return QualType(); 13014 // Special case of NSObject attributes on c-style pointer types. 13015 if (ConvTy == IncompatiblePointer && 13016 ((Context.isObjCNSObjectType(LHSType) && 13017 RHSType->isObjCObjectPointerType()) || 13018 (Context.isObjCNSObjectType(RHSType) && 13019 LHSType->isObjCObjectPointerType()))) 13020 ConvTy = Compatible; 13021 13022 if (ConvTy == Compatible && 13023 LHSType->isObjCObjectType()) 13024 Diag(Loc, diag::err_objc_object_assignment) 13025 << LHSType; 13026 13027 // If the RHS is a unary plus or minus, check to see if they = and + are 13028 // right next to each other. If so, the user may have typo'd "x =+ 4" 13029 // instead of "x += 4". 13030 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 13031 RHSCheck = ICE->getSubExpr(); 13032 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 13033 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 13034 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 13035 // Only if the two operators are exactly adjacent. 13036 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 13037 // And there is a space or other character before the subexpr of the 13038 // unary +/-. We don't want to warn on "x=-1". 13039 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 13040 UO->getSubExpr()->getBeginLoc().isFileID()) { 13041 Diag(Loc, diag::warn_not_compound_assign) 13042 << (UO->getOpcode() == UO_Plus ? "+" : "-") 13043 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 13044 } 13045 } 13046 13047 if (ConvTy == Compatible) { 13048 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 13049 // Warn about retain cycles where a block captures the LHS, but 13050 // not if the LHS is a simple variable into which the block is 13051 // being stored...unless that variable can be captured by reference! 13052 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 13053 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 13054 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 13055 checkRetainCycles(LHSExpr, RHS.get()); 13056 } 13057 13058 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 13059 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 13060 // It is safe to assign a weak reference into a strong variable. 13061 // Although this code can still have problems: 13062 // id x = self.weakProp; 13063 // id y = self.weakProp; 13064 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13065 // paths through the function. This should be revisited if 13066 // -Wrepeated-use-of-weak is made flow-sensitive. 13067 // For ObjCWeak only, we do not warn if the assign is to a non-weak 13068 // variable, which will be valid for the current autorelease scope. 13069 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13070 RHS.get()->getBeginLoc())) 13071 getCurFunction()->markSafeWeakUse(RHS.get()); 13072 13073 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 13074 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 13075 } 13076 } 13077 } else { 13078 // Compound assignment "x += y" 13079 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 13080 } 13081 13082 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 13083 RHS.get(), AA_Assigning)) 13084 return QualType(); 13085 13086 CheckForNullPointerDereference(*this, LHSExpr); 13087 13088 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 13089 if (CompoundType.isNull()) { 13090 // C++2a [expr.ass]p5: 13091 // A simple-assignment whose left operand is of a volatile-qualified 13092 // type is deprecated unless the assignment is either a discarded-value 13093 // expression or an unevaluated operand 13094 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 13095 } else { 13096 // C++2a [expr.ass]p6: 13097 // [Compound-assignment] expressions are deprecated if E1 has 13098 // volatile-qualified type 13099 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType; 13100 } 13101 } 13102 13103 // C99 6.5.16p3: The type of an assignment expression is the type of the 13104 // left operand unless the left operand has qualified type, in which case 13105 // it is the unqualified version of the type of the left operand. 13106 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 13107 // is converted to the type of the assignment expression (above). 13108 // C++ 5.17p1: the type of the assignment expression is that of its left 13109 // operand. 13110 return (getLangOpts().CPlusPlus 13111 ? LHSType : LHSType.getUnqualifiedType()); 13112 } 13113 13114 // Only ignore explicit casts to void. 13115 static bool IgnoreCommaOperand(const Expr *E) { 13116 E = E->IgnoreParens(); 13117 13118 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 13119 if (CE->getCastKind() == CK_ToVoid) { 13120 return true; 13121 } 13122 13123 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 13124 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 13125 CE->getSubExpr()->getType()->isDependentType()) { 13126 return true; 13127 } 13128 } 13129 13130 return false; 13131 } 13132 13133 // Look for instances where it is likely the comma operator is confused with 13134 // another operator. There is an explicit list of acceptable expressions for 13135 // the left hand side of the comma operator, otherwise emit a warning. 13136 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 13137 // No warnings in macros 13138 if (Loc.isMacroID()) 13139 return; 13140 13141 // Don't warn in template instantiations. 13142 if (inTemplateInstantiation()) 13143 return; 13144 13145 // Scope isn't fine-grained enough to explicitly list the specific cases, so 13146 // instead, skip more than needed, then call back into here with the 13147 // CommaVisitor in SemaStmt.cpp. 13148 // The listed locations are the initialization and increment portions 13149 // of a for loop. The additional checks are on the condition of 13150 // if statements, do/while loops, and for loops. 13151 // Differences in scope flags for C89 mode requires the extra logic. 13152 const unsigned ForIncrementFlags = 13153 getLangOpts().C99 || getLangOpts().CPlusPlus 13154 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 13155 : Scope::ContinueScope | Scope::BreakScope; 13156 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 13157 const unsigned ScopeFlags = getCurScope()->getFlags(); 13158 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 13159 (ScopeFlags & ForInitFlags) == ForInitFlags) 13160 return; 13161 13162 // If there are multiple comma operators used together, get the RHS of the 13163 // of the comma operator as the LHS. 13164 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 13165 if (BO->getOpcode() != BO_Comma) 13166 break; 13167 LHS = BO->getRHS(); 13168 } 13169 13170 // Only allow some expressions on LHS to not warn. 13171 if (IgnoreCommaOperand(LHS)) 13172 return; 13173 13174 Diag(Loc, diag::warn_comma_operator); 13175 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 13176 << LHS->getSourceRange() 13177 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 13178 LangOpts.CPlusPlus ? "static_cast<void>(" 13179 : "(void)(") 13180 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 13181 ")"); 13182 } 13183 13184 // C99 6.5.17 13185 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 13186 SourceLocation Loc) { 13187 LHS = S.CheckPlaceholderExpr(LHS.get()); 13188 RHS = S.CheckPlaceholderExpr(RHS.get()); 13189 if (LHS.isInvalid() || RHS.isInvalid()) 13190 return QualType(); 13191 13192 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 13193 // operands, but not unary promotions. 13194 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 13195 13196 // So we treat the LHS as a ignored value, and in C++ we allow the 13197 // containing site to determine what should be done with the RHS. 13198 LHS = S.IgnoredValueConversions(LHS.get()); 13199 if (LHS.isInvalid()) 13200 return QualType(); 13201 13202 S.DiagnoseUnusedExprResult(LHS.get()); 13203 13204 if (!S.getLangOpts().CPlusPlus) { 13205 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 13206 if (RHS.isInvalid()) 13207 return QualType(); 13208 if (!RHS.get()->getType()->isVoidType()) 13209 S.RequireCompleteType(Loc, RHS.get()->getType(), 13210 diag::err_incomplete_type); 13211 } 13212 13213 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 13214 S.DiagnoseCommaOperator(LHS.get(), Loc); 13215 13216 return RHS.get()->getType(); 13217 } 13218 13219 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 13220 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 13221 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 13222 ExprValueKind &VK, 13223 ExprObjectKind &OK, 13224 SourceLocation OpLoc, 13225 bool IsInc, bool IsPrefix) { 13226 if (Op->isTypeDependent()) 13227 return S.Context.DependentTy; 13228 13229 QualType ResType = Op->getType(); 13230 // Atomic types can be used for increment / decrement where the non-atomic 13231 // versions can, so ignore the _Atomic() specifier for the purpose of 13232 // checking. 13233 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 13234 ResType = ResAtomicType->getValueType(); 13235 13236 assert(!ResType.isNull() && "no type for increment/decrement expression"); 13237 13238 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 13239 // Decrement of bool is not allowed. 13240 if (!IsInc) { 13241 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 13242 return QualType(); 13243 } 13244 // Increment of bool sets it to true, but is deprecated. 13245 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 13246 : diag::warn_increment_bool) 13247 << Op->getSourceRange(); 13248 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 13249 // Error on enum increments and decrements in C++ mode 13250 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 13251 return QualType(); 13252 } else if (ResType->isRealType()) { 13253 // OK! 13254 } else if (ResType->isPointerType()) { 13255 // C99 6.5.2.4p2, 6.5.6p2 13256 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 13257 return QualType(); 13258 } else if (ResType->isObjCObjectPointerType()) { 13259 // On modern runtimes, ObjC pointer arithmetic is forbidden. 13260 // Otherwise, we just need a complete type. 13261 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 13262 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 13263 return QualType(); 13264 } else if (ResType->isAnyComplexType()) { 13265 // C99 does not support ++/-- on complex types, we allow as an extension. 13266 S.Diag(OpLoc, diag::ext_integer_increment_complex) 13267 << ResType << Op->getSourceRange(); 13268 } else if (ResType->isPlaceholderType()) { 13269 ExprResult PR = S.CheckPlaceholderExpr(Op); 13270 if (PR.isInvalid()) return QualType(); 13271 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 13272 IsInc, IsPrefix); 13273 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 13274 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 13275 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 13276 (ResType->castAs<VectorType>()->getVectorKind() != 13277 VectorType::AltiVecBool)) { 13278 // The z vector extensions allow ++ and -- for non-bool vectors. 13279 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 13280 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 13281 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 13282 } else { 13283 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 13284 << ResType << int(IsInc) << Op->getSourceRange(); 13285 return QualType(); 13286 } 13287 // At this point, we know we have a real, complex or pointer type. 13288 // Now make sure the operand is a modifiable lvalue. 13289 if (CheckForModifiableLvalue(Op, OpLoc, S)) 13290 return QualType(); 13291 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 13292 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 13293 // An operand with volatile-qualified type is deprecated 13294 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 13295 << IsInc << ResType; 13296 } 13297 // In C++, a prefix increment is the same type as the operand. Otherwise 13298 // (in C or with postfix), the increment is the unqualified type of the 13299 // operand. 13300 if (IsPrefix && S.getLangOpts().CPlusPlus) { 13301 VK = VK_LValue; 13302 OK = Op->getObjectKind(); 13303 return ResType; 13304 } else { 13305 VK = VK_RValue; 13306 return ResType.getUnqualifiedType(); 13307 } 13308 } 13309 13310 13311 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 13312 /// This routine allows us to typecheck complex/recursive expressions 13313 /// where the declaration is needed for type checking. We only need to 13314 /// handle cases when the expression references a function designator 13315 /// or is an lvalue. Here are some examples: 13316 /// - &(x) => x 13317 /// - &*****f => f for f a function designator. 13318 /// - &s.xx => s 13319 /// - &s.zz[1].yy -> s, if zz is an array 13320 /// - *(x + 1) -> x, if x is an array 13321 /// - &"123"[2] -> 0 13322 /// - & __real__ x -> x 13323 /// 13324 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 13325 /// members. 13326 static ValueDecl *getPrimaryDecl(Expr *E) { 13327 switch (E->getStmtClass()) { 13328 case Stmt::DeclRefExprClass: 13329 return cast<DeclRefExpr>(E)->getDecl(); 13330 case Stmt::MemberExprClass: 13331 // If this is an arrow operator, the address is an offset from 13332 // the base's value, so the object the base refers to is 13333 // irrelevant. 13334 if (cast<MemberExpr>(E)->isArrow()) 13335 return nullptr; 13336 // Otherwise, the expression refers to a part of the base 13337 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 13338 case Stmt::ArraySubscriptExprClass: { 13339 // FIXME: This code shouldn't be necessary! We should catch the implicit 13340 // promotion of register arrays earlier. 13341 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 13342 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 13343 if (ICE->getSubExpr()->getType()->isArrayType()) 13344 return getPrimaryDecl(ICE->getSubExpr()); 13345 } 13346 return nullptr; 13347 } 13348 case Stmt::UnaryOperatorClass: { 13349 UnaryOperator *UO = cast<UnaryOperator>(E); 13350 13351 switch(UO->getOpcode()) { 13352 case UO_Real: 13353 case UO_Imag: 13354 case UO_Extension: 13355 return getPrimaryDecl(UO->getSubExpr()); 13356 default: 13357 return nullptr; 13358 } 13359 } 13360 case Stmt::ParenExprClass: 13361 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 13362 case Stmt::ImplicitCastExprClass: 13363 // If the result of an implicit cast is an l-value, we care about 13364 // the sub-expression; otherwise, the result here doesn't matter. 13365 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 13366 case Stmt::CXXUuidofExprClass: 13367 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 13368 default: 13369 return nullptr; 13370 } 13371 } 13372 13373 namespace { 13374 enum { 13375 AO_Bit_Field = 0, 13376 AO_Vector_Element = 1, 13377 AO_Property_Expansion = 2, 13378 AO_Register_Variable = 3, 13379 AO_Matrix_Element = 4, 13380 AO_No_Error = 5 13381 }; 13382 } 13383 /// Diagnose invalid operand for address of operations. 13384 /// 13385 /// \param Type The type of operand which cannot have its address taken. 13386 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 13387 Expr *E, unsigned Type) { 13388 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 13389 } 13390 13391 /// CheckAddressOfOperand - The operand of & must be either a function 13392 /// designator or an lvalue designating an object. If it is an lvalue, the 13393 /// object cannot be declared with storage class register or be a bit field. 13394 /// Note: The usual conversions are *not* applied to the operand of the & 13395 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 13396 /// In C++, the operand might be an overloaded function name, in which case 13397 /// we allow the '&' but retain the overloaded-function type. 13398 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 13399 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 13400 if (PTy->getKind() == BuiltinType::Overload) { 13401 Expr *E = OrigOp.get()->IgnoreParens(); 13402 if (!isa<OverloadExpr>(E)) { 13403 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 13404 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 13405 << OrigOp.get()->getSourceRange(); 13406 return QualType(); 13407 } 13408 13409 OverloadExpr *Ovl = cast<OverloadExpr>(E); 13410 if (isa<UnresolvedMemberExpr>(Ovl)) 13411 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 13412 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13413 << OrigOp.get()->getSourceRange(); 13414 return QualType(); 13415 } 13416 13417 return Context.OverloadTy; 13418 } 13419 13420 if (PTy->getKind() == BuiltinType::UnknownAny) 13421 return Context.UnknownAnyTy; 13422 13423 if (PTy->getKind() == BuiltinType::BoundMember) { 13424 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13425 << OrigOp.get()->getSourceRange(); 13426 return QualType(); 13427 } 13428 13429 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 13430 if (OrigOp.isInvalid()) return QualType(); 13431 } 13432 13433 if (OrigOp.get()->isTypeDependent()) 13434 return Context.DependentTy; 13435 13436 assert(!OrigOp.get()->getType()->isPlaceholderType()); 13437 13438 // Make sure to ignore parentheses in subsequent checks 13439 Expr *op = OrigOp.get()->IgnoreParens(); 13440 13441 // In OpenCL captures for blocks called as lambda functions 13442 // are located in the private address space. Blocks used in 13443 // enqueue_kernel can be located in a different address space 13444 // depending on a vendor implementation. Thus preventing 13445 // taking an address of the capture to avoid invalid AS casts. 13446 if (LangOpts.OpenCL) { 13447 auto* VarRef = dyn_cast<DeclRefExpr>(op); 13448 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 13449 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 13450 return QualType(); 13451 } 13452 } 13453 13454 if (getLangOpts().C99) { 13455 // Implement C99-only parts of addressof rules. 13456 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 13457 if (uOp->getOpcode() == UO_Deref) 13458 // Per C99 6.5.3.2, the address of a deref always returns a valid result 13459 // (assuming the deref expression is valid). 13460 return uOp->getSubExpr()->getType(); 13461 } 13462 // Technically, there should be a check for array subscript 13463 // expressions here, but the result of one is always an lvalue anyway. 13464 } 13465 ValueDecl *dcl = getPrimaryDecl(op); 13466 13467 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 13468 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 13469 op->getBeginLoc())) 13470 return QualType(); 13471 13472 Expr::LValueClassification lval = op->ClassifyLValue(Context); 13473 unsigned AddressOfError = AO_No_Error; 13474 13475 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 13476 bool sfinae = (bool)isSFINAEContext(); 13477 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 13478 : diag::ext_typecheck_addrof_temporary) 13479 << op->getType() << op->getSourceRange(); 13480 if (sfinae) 13481 return QualType(); 13482 // Materialize the temporary as an lvalue so that we can take its address. 13483 OrigOp = op = 13484 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 13485 } else if (isa<ObjCSelectorExpr>(op)) { 13486 return Context.getPointerType(op->getType()); 13487 } else if (lval == Expr::LV_MemberFunction) { 13488 // If it's an instance method, make a member pointer. 13489 // The expression must have exactly the form &A::foo. 13490 13491 // If the underlying expression isn't a decl ref, give up. 13492 if (!isa<DeclRefExpr>(op)) { 13493 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 13494 << OrigOp.get()->getSourceRange(); 13495 return QualType(); 13496 } 13497 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 13498 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 13499 13500 // The id-expression was parenthesized. 13501 if (OrigOp.get() != DRE) { 13502 Diag(OpLoc, diag::err_parens_pointer_member_function) 13503 << OrigOp.get()->getSourceRange(); 13504 13505 // The method was named without a qualifier. 13506 } else if (!DRE->getQualifier()) { 13507 if (MD->getParent()->getName().empty()) 13508 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13509 << op->getSourceRange(); 13510 else { 13511 SmallString<32> Str; 13512 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 13513 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 13514 << op->getSourceRange() 13515 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 13516 } 13517 } 13518 13519 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 13520 if (isa<CXXDestructorDecl>(MD)) 13521 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 13522 13523 QualType MPTy = Context.getMemberPointerType( 13524 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 13525 // Under the MS ABI, lock down the inheritance model now. 13526 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13527 (void)isCompleteType(OpLoc, MPTy); 13528 return MPTy; 13529 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 13530 // C99 6.5.3.2p1 13531 // The operand must be either an l-value or a function designator 13532 if (!op->getType()->isFunctionType()) { 13533 // Use a special diagnostic for loads from property references. 13534 if (isa<PseudoObjectExpr>(op)) { 13535 AddressOfError = AO_Property_Expansion; 13536 } else { 13537 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 13538 << op->getType() << op->getSourceRange(); 13539 return QualType(); 13540 } 13541 } 13542 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 13543 // The operand cannot be a bit-field 13544 AddressOfError = AO_Bit_Field; 13545 } else if (op->getObjectKind() == OK_VectorComponent) { 13546 // The operand cannot be an element of a vector 13547 AddressOfError = AO_Vector_Element; 13548 } else if (op->getObjectKind() == OK_MatrixComponent) { 13549 // The operand cannot be an element of a matrix. 13550 AddressOfError = AO_Matrix_Element; 13551 } else if (dcl) { // C99 6.5.3.2p1 13552 // We have an lvalue with a decl. Make sure the decl is not declared 13553 // with the register storage-class specifier. 13554 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 13555 // in C++ it is not error to take address of a register 13556 // variable (c++03 7.1.1P3) 13557 if (vd->getStorageClass() == SC_Register && 13558 !getLangOpts().CPlusPlus) { 13559 AddressOfError = AO_Register_Variable; 13560 } 13561 } else if (isa<MSPropertyDecl>(dcl)) { 13562 AddressOfError = AO_Property_Expansion; 13563 } else if (isa<FunctionTemplateDecl>(dcl)) { 13564 return Context.OverloadTy; 13565 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 13566 // Okay: we can take the address of a field. 13567 // Could be a pointer to member, though, if there is an explicit 13568 // scope qualifier for the class. 13569 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 13570 DeclContext *Ctx = dcl->getDeclContext(); 13571 if (Ctx && Ctx->isRecord()) { 13572 if (dcl->getType()->isReferenceType()) { 13573 Diag(OpLoc, 13574 diag::err_cannot_form_pointer_to_member_of_reference_type) 13575 << dcl->getDeclName() << dcl->getType(); 13576 return QualType(); 13577 } 13578 13579 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 13580 Ctx = Ctx->getParent(); 13581 13582 QualType MPTy = Context.getMemberPointerType( 13583 op->getType(), 13584 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 13585 // Under the MS ABI, lock down the inheritance model now. 13586 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13587 (void)isCompleteType(OpLoc, MPTy); 13588 return MPTy; 13589 } 13590 } 13591 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 13592 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl)) 13593 llvm_unreachable("Unknown/unexpected decl type"); 13594 } 13595 13596 if (AddressOfError != AO_No_Error) { 13597 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 13598 return QualType(); 13599 } 13600 13601 if (lval == Expr::LV_IncompleteVoidType) { 13602 // Taking the address of a void variable is technically illegal, but we 13603 // allow it in cases which are otherwise valid. 13604 // Example: "extern void x; void* y = &x;". 13605 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 13606 } 13607 13608 // If the operand has type "type", the result has type "pointer to type". 13609 if (op->getType()->isObjCObjectType()) 13610 return Context.getObjCObjectPointerType(op->getType()); 13611 13612 CheckAddressOfPackedMember(op); 13613 13614 return Context.getPointerType(op->getType()); 13615 } 13616 13617 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 13618 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 13619 if (!DRE) 13620 return; 13621 const Decl *D = DRE->getDecl(); 13622 if (!D) 13623 return; 13624 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 13625 if (!Param) 13626 return; 13627 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 13628 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 13629 return; 13630 if (FunctionScopeInfo *FD = S.getCurFunction()) 13631 if (!FD->ModifiedNonNullParams.count(Param)) 13632 FD->ModifiedNonNullParams.insert(Param); 13633 } 13634 13635 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 13636 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 13637 SourceLocation OpLoc) { 13638 if (Op->isTypeDependent()) 13639 return S.Context.DependentTy; 13640 13641 ExprResult ConvResult = S.UsualUnaryConversions(Op); 13642 if (ConvResult.isInvalid()) 13643 return QualType(); 13644 Op = ConvResult.get(); 13645 QualType OpTy = Op->getType(); 13646 QualType Result; 13647 13648 if (isa<CXXReinterpretCastExpr>(Op)) { 13649 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 13650 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 13651 Op->getSourceRange()); 13652 } 13653 13654 if (const PointerType *PT = OpTy->getAs<PointerType>()) 13655 { 13656 Result = PT->getPointeeType(); 13657 } 13658 else if (const ObjCObjectPointerType *OPT = 13659 OpTy->getAs<ObjCObjectPointerType>()) 13660 Result = OPT->getPointeeType(); 13661 else { 13662 ExprResult PR = S.CheckPlaceholderExpr(Op); 13663 if (PR.isInvalid()) return QualType(); 13664 if (PR.get() != Op) 13665 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 13666 } 13667 13668 if (Result.isNull()) { 13669 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 13670 << OpTy << Op->getSourceRange(); 13671 return QualType(); 13672 } 13673 13674 // Note that per both C89 and C99, indirection is always legal, even if Result 13675 // is an incomplete type or void. It would be possible to warn about 13676 // dereferencing a void pointer, but it's completely well-defined, and such a 13677 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 13678 // for pointers to 'void' but is fine for any other pointer type: 13679 // 13680 // C++ [expr.unary.op]p1: 13681 // [...] the expression to which [the unary * operator] is applied shall 13682 // be a pointer to an object type, or a pointer to a function type 13683 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 13684 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 13685 << OpTy << Op->getSourceRange(); 13686 13687 // Dereferences are usually l-values... 13688 VK = VK_LValue; 13689 13690 // ...except that certain expressions are never l-values in C. 13691 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 13692 VK = VK_RValue; 13693 13694 return Result; 13695 } 13696 13697 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 13698 BinaryOperatorKind Opc; 13699 switch (Kind) { 13700 default: llvm_unreachable("Unknown binop!"); 13701 case tok::periodstar: Opc = BO_PtrMemD; break; 13702 case tok::arrowstar: Opc = BO_PtrMemI; break; 13703 case tok::star: Opc = BO_Mul; break; 13704 case tok::slash: Opc = BO_Div; break; 13705 case tok::percent: Opc = BO_Rem; break; 13706 case tok::plus: Opc = BO_Add; break; 13707 case tok::minus: Opc = BO_Sub; break; 13708 case tok::lessless: Opc = BO_Shl; break; 13709 case tok::greatergreater: Opc = BO_Shr; break; 13710 case tok::lessequal: Opc = BO_LE; break; 13711 case tok::less: Opc = BO_LT; break; 13712 case tok::greaterequal: Opc = BO_GE; break; 13713 case tok::greater: Opc = BO_GT; break; 13714 case tok::exclaimequal: Opc = BO_NE; break; 13715 case tok::equalequal: Opc = BO_EQ; break; 13716 case tok::spaceship: Opc = BO_Cmp; break; 13717 case tok::amp: Opc = BO_And; break; 13718 case tok::caret: Opc = BO_Xor; break; 13719 case tok::pipe: Opc = BO_Or; break; 13720 case tok::ampamp: Opc = BO_LAnd; break; 13721 case tok::pipepipe: Opc = BO_LOr; break; 13722 case tok::equal: Opc = BO_Assign; break; 13723 case tok::starequal: Opc = BO_MulAssign; break; 13724 case tok::slashequal: Opc = BO_DivAssign; break; 13725 case tok::percentequal: Opc = BO_RemAssign; break; 13726 case tok::plusequal: Opc = BO_AddAssign; break; 13727 case tok::minusequal: Opc = BO_SubAssign; break; 13728 case tok::lesslessequal: Opc = BO_ShlAssign; break; 13729 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 13730 case tok::ampequal: Opc = BO_AndAssign; break; 13731 case tok::caretequal: Opc = BO_XorAssign; break; 13732 case tok::pipeequal: Opc = BO_OrAssign; break; 13733 case tok::comma: Opc = BO_Comma; break; 13734 } 13735 return Opc; 13736 } 13737 13738 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 13739 tok::TokenKind Kind) { 13740 UnaryOperatorKind Opc; 13741 switch (Kind) { 13742 default: llvm_unreachable("Unknown unary op!"); 13743 case tok::plusplus: Opc = UO_PreInc; break; 13744 case tok::minusminus: Opc = UO_PreDec; break; 13745 case tok::amp: Opc = UO_AddrOf; break; 13746 case tok::star: Opc = UO_Deref; break; 13747 case tok::plus: Opc = UO_Plus; break; 13748 case tok::minus: Opc = UO_Minus; break; 13749 case tok::tilde: Opc = UO_Not; break; 13750 case tok::exclaim: Opc = UO_LNot; break; 13751 case tok::kw___real: Opc = UO_Real; break; 13752 case tok::kw___imag: Opc = UO_Imag; break; 13753 case tok::kw___extension__: Opc = UO_Extension; break; 13754 } 13755 return Opc; 13756 } 13757 13758 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 13759 /// This warning suppressed in the event of macro expansions. 13760 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 13761 SourceLocation OpLoc, bool IsBuiltin) { 13762 if (S.inTemplateInstantiation()) 13763 return; 13764 if (S.isUnevaluatedContext()) 13765 return; 13766 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 13767 return; 13768 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13769 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13770 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13771 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13772 if (!LHSDeclRef || !RHSDeclRef || 13773 LHSDeclRef->getLocation().isMacroID() || 13774 RHSDeclRef->getLocation().isMacroID()) 13775 return; 13776 const ValueDecl *LHSDecl = 13777 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 13778 const ValueDecl *RHSDecl = 13779 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 13780 if (LHSDecl != RHSDecl) 13781 return; 13782 if (LHSDecl->getType().isVolatileQualified()) 13783 return; 13784 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 13785 if (RefTy->getPointeeType().isVolatileQualified()) 13786 return; 13787 13788 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 13789 : diag::warn_self_assignment_overloaded) 13790 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 13791 << RHSExpr->getSourceRange(); 13792 } 13793 13794 /// Check if a bitwise-& is performed on an Objective-C pointer. This 13795 /// is usually indicative of introspection within the Objective-C pointer. 13796 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 13797 SourceLocation OpLoc) { 13798 if (!S.getLangOpts().ObjC) 13799 return; 13800 13801 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 13802 const Expr *LHS = L.get(); 13803 const Expr *RHS = R.get(); 13804 13805 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13806 ObjCPointerExpr = LHS; 13807 OtherExpr = RHS; 13808 } 13809 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 13810 ObjCPointerExpr = RHS; 13811 OtherExpr = LHS; 13812 } 13813 13814 // This warning is deliberately made very specific to reduce false 13815 // positives with logic that uses '&' for hashing. This logic mainly 13816 // looks for code trying to introspect into tagged pointers, which 13817 // code should generally never do. 13818 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 13819 unsigned Diag = diag::warn_objc_pointer_masking; 13820 // Determine if we are introspecting the result of performSelectorXXX. 13821 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 13822 // Special case messages to -performSelector and friends, which 13823 // can return non-pointer values boxed in a pointer value. 13824 // Some clients may wish to silence warnings in this subcase. 13825 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 13826 Selector S = ME->getSelector(); 13827 StringRef SelArg0 = S.getNameForSlot(0); 13828 if (SelArg0.startswith("performSelector")) 13829 Diag = diag::warn_objc_pointer_masking_performSelector; 13830 } 13831 13832 S.Diag(OpLoc, Diag) 13833 << ObjCPointerExpr->getSourceRange(); 13834 } 13835 } 13836 13837 static NamedDecl *getDeclFromExpr(Expr *E) { 13838 if (!E) 13839 return nullptr; 13840 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 13841 return DRE->getDecl(); 13842 if (auto *ME = dyn_cast<MemberExpr>(E)) 13843 return ME->getMemberDecl(); 13844 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 13845 return IRE->getDecl(); 13846 return nullptr; 13847 } 13848 13849 // This helper function promotes a binary operator's operands (which are of a 13850 // half vector type) to a vector of floats and then truncates the result to 13851 // a vector of either half or short. 13852 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 13853 BinaryOperatorKind Opc, QualType ResultTy, 13854 ExprValueKind VK, ExprObjectKind OK, 13855 bool IsCompAssign, SourceLocation OpLoc, 13856 FPOptionsOverride FPFeatures) { 13857 auto &Context = S.getASTContext(); 13858 assert((isVector(ResultTy, Context.HalfTy) || 13859 isVector(ResultTy, Context.ShortTy)) && 13860 "Result must be a vector of half or short"); 13861 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 13862 isVector(RHS.get()->getType(), Context.HalfTy) && 13863 "both operands expected to be a half vector"); 13864 13865 RHS = convertVector(RHS.get(), Context.FloatTy, S); 13866 QualType BinOpResTy = RHS.get()->getType(); 13867 13868 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 13869 // change BinOpResTy to a vector of ints. 13870 if (isVector(ResultTy, Context.ShortTy)) 13871 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 13872 13873 if (IsCompAssign) 13874 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13875 ResultTy, VK, OK, OpLoc, FPFeatures, 13876 BinOpResTy, BinOpResTy); 13877 13878 LHS = convertVector(LHS.get(), Context.FloatTy, S); 13879 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 13880 BinOpResTy, VK, OK, OpLoc, FPFeatures); 13881 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 13882 } 13883 13884 static std::pair<ExprResult, ExprResult> 13885 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 13886 Expr *RHSExpr) { 13887 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13888 if (!S.Context.isDependenceAllowed()) { 13889 // C cannot handle TypoExpr nodes on either side of a binop because it 13890 // doesn't handle dependent types properly, so make sure any TypoExprs have 13891 // been dealt with before checking the operands. 13892 LHS = S.CorrectDelayedTyposInExpr(LHS); 13893 RHS = S.CorrectDelayedTyposInExpr( 13894 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 13895 [Opc, LHS](Expr *E) { 13896 if (Opc != BO_Assign) 13897 return ExprResult(E); 13898 // Avoid correcting the RHS to the same Expr as the LHS. 13899 Decl *D = getDeclFromExpr(E); 13900 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 13901 }); 13902 } 13903 return std::make_pair(LHS, RHS); 13904 } 13905 13906 /// Returns true if conversion between vectors of halfs and vectors of floats 13907 /// is needed. 13908 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 13909 Expr *E0, Expr *E1 = nullptr) { 13910 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 13911 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 13912 return false; 13913 13914 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 13915 QualType Ty = E->IgnoreImplicit()->getType(); 13916 13917 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 13918 // to vectors of floats. Although the element type of the vectors is __fp16, 13919 // the vectors shouldn't be treated as storage-only types. See the 13920 // discussion here: https://reviews.llvm.org/rG825235c140e7 13921 if (const VectorType *VT = Ty->getAs<VectorType>()) { 13922 if (VT->getVectorKind() == VectorType::NeonVector) 13923 return false; 13924 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 13925 } 13926 return false; 13927 }; 13928 13929 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 13930 } 13931 13932 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 13933 /// operator @p Opc at location @c TokLoc. This routine only supports 13934 /// built-in operations; ActOnBinOp handles overloaded operators. 13935 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 13936 BinaryOperatorKind Opc, 13937 Expr *LHSExpr, Expr *RHSExpr) { 13938 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 13939 // The syntax only allows initializer lists on the RHS of assignment, 13940 // so we don't need to worry about accepting invalid code for 13941 // non-assignment operators. 13942 // C++11 5.17p9: 13943 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 13944 // of x = {} is x = T(). 13945 InitializationKind Kind = InitializationKind::CreateDirectList( 13946 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13947 InitializedEntity Entity = 13948 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 13949 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 13950 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 13951 if (Init.isInvalid()) 13952 return Init; 13953 RHSExpr = Init.get(); 13954 } 13955 13956 ExprResult LHS = LHSExpr, RHS = RHSExpr; 13957 QualType ResultTy; // Result type of the binary operator. 13958 // The following two variables are used for compound assignment operators 13959 QualType CompLHSTy; // Type of LHS after promotions for computation 13960 QualType CompResultTy; // Type of computation result 13961 ExprValueKind VK = VK_RValue; 13962 ExprObjectKind OK = OK_Ordinary; 13963 bool ConvertHalfVec = false; 13964 13965 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 13966 if (!LHS.isUsable() || !RHS.isUsable()) 13967 return ExprError(); 13968 13969 if (getLangOpts().OpenCL) { 13970 QualType LHSTy = LHSExpr->getType(); 13971 QualType RHSTy = RHSExpr->getType(); 13972 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 13973 // the ATOMIC_VAR_INIT macro. 13974 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 13975 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 13976 if (BO_Assign == Opc) 13977 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 13978 else 13979 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13980 return ExprError(); 13981 } 13982 13983 // OpenCL special types - image, sampler, pipe, and blocks are to be used 13984 // only with a builtin functions and therefore should be disallowed here. 13985 if (LHSTy->isImageType() || RHSTy->isImageType() || 13986 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 13987 LHSTy->isPipeType() || RHSTy->isPipeType() || 13988 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 13989 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 13990 return ExprError(); 13991 } 13992 } 13993 13994 switch (Opc) { 13995 case BO_Assign: 13996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 13997 if (getLangOpts().CPlusPlus && 13998 LHS.get()->getObjectKind() != OK_ObjCProperty) { 13999 VK = LHS.get()->getValueKind(); 14000 OK = LHS.get()->getObjectKind(); 14001 } 14002 if (!ResultTy.isNull()) { 14003 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14004 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 14005 14006 // Avoid copying a block to the heap if the block is assigned to a local 14007 // auto variable that is declared in the same scope as the block. This 14008 // optimization is unsafe if the local variable is declared in an outer 14009 // scope. For example: 14010 // 14011 // BlockTy b; 14012 // { 14013 // b = ^{...}; 14014 // } 14015 // // It is unsafe to invoke the block here if it wasn't copied to the 14016 // // heap. 14017 // b(); 14018 14019 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 14020 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 14021 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 14022 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 14023 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 14024 14025 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14026 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 14027 NTCUC_Assignment, NTCUK_Copy); 14028 } 14029 RecordModifiableNonNullParam(*this, LHS.get()); 14030 break; 14031 case BO_PtrMemD: 14032 case BO_PtrMemI: 14033 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 14034 Opc == BO_PtrMemI); 14035 break; 14036 case BO_Mul: 14037 case BO_Div: 14038 ConvertHalfVec = true; 14039 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 14040 Opc == BO_Div); 14041 break; 14042 case BO_Rem: 14043 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 14044 break; 14045 case BO_Add: 14046 ConvertHalfVec = true; 14047 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 14048 break; 14049 case BO_Sub: 14050 ConvertHalfVec = true; 14051 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 14052 break; 14053 case BO_Shl: 14054 case BO_Shr: 14055 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 14056 break; 14057 case BO_LE: 14058 case BO_LT: 14059 case BO_GE: 14060 case BO_GT: 14061 ConvertHalfVec = true; 14062 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14063 break; 14064 case BO_EQ: 14065 case BO_NE: 14066 ConvertHalfVec = true; 14067 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14068 break; 14069 case BO_Cmp: 14070 ConvertHalfVec = true; 14071 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 14072 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 14073 break; 14074 case BO_And: 14075 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 14076 LLVM_FALLTHROUGH; 14077 case BO_Xor: 14078 case BO_Or: 14079 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14080 break; 14081 case BO_LAnd: 14082 case BO_LOr: 14083 ConvertHalfVec = true; 14084 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 14085 break; 14086 case BO_MulAssign: 14087 case BO_DivAssign: 14088 ConvertHalfVec = true; 14089 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 14090 Opc == BO_DivAssign); 14091 CompLHSTy = CompResultTy; 14092 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14093 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14094 break; 14095 case BO_RemAssign: 14096 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 14097 CompLHSTy = CompResultTy; 14098 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14099 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14100 break; 14101 case BO_AddAssign: 14102 ConvertHalfVec = true; 14103 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 14104 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14105 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14106 break; 14107 case BO_SubAssign: 14108 ConvertHalfVec = true; 14109 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 14110 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14111 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14112 break; 14113 case BO_ShlAssign: 14114 case BO_ShrAssign: 14115 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 14116 CompLHSTy = CompResultTy; 14117 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14118 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14119 break; 14120 case BO_AndAssign: 14121 case BO_OrAssign: // fallthrough 14122 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 14123 LLVM_FALLTHROUGH; 14124 case BO_XorAssign: 14125 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 14126 CompLHSTy = CompResultTy; 14127 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 14128 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 14129 break; 14130 case BO_Comma: 14131 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 14132 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 14133 VK = RHS.get()->getValueKind(); 14134 OK = RHS.get()->getObjectKind(); 14135 } 14136 break; 14137 } 14138 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 14139 return ExprError(); 14140 14141 // Some of the binary operations require promoting operands of half vector to 14142 // float vectors and truncating the result back to half vector. For now, we do 14143 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 14144 // arm64). 14145 assert( 14146 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 14147 isVector(LHS.get()->getType(), Context.HalfTy)) && 14148 "both sides are half vectors or neither sides are"); 14149 ConvertHalfVec = 14150 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 14151 14152 // Check for array bounds violations for both sides of the BinaryOperator 14153 CheckArrayAccess(LHS.get()); 14154 CheckArrayAccess(RHS.get()); 14155 14156 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 14157 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 14158 &Context.Idents.get("object_setClass"), 14159 SourceLocation(), LookupOrdinaryName); 14160 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 14161 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 14162 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 14163 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 14164 "object_setClass(") 14165 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 14166 ",") 14167 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 14168 } 14169 else 14170 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 14171 } 14172 else if (const ObjCIvarRefExpr *OIRE = 14173 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 14174 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 14175 14176 // Opc is not a compound assignment if CompResultTy is null. 14177 if (CompResultTy.isNull()) { 14178 if (ConvertHalfVec) 14179 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 14180 OpLoc, CurFPFeatureOverrides()); 14181 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 14182 VK, OK, OpLoc, CurFPFeatureOverrides()); 14183 } 14184 14185 // Handle compound assignments. 14186 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 14187 OK_ObjCProperty) { 14188 VK = VK_LValue; 14189 OK = LHS.get()->getObjectKind(); 14190 } 14191 14192 // The LHS is not converted to the result type for fixed-point compound 14193 // assignment as the common type is computed on demand. Reset the CompLHSTy 14194 // to the LHS type we would have gotten after unary conversions. 14195 if (CompResultTy->isFixedPointType()) 14196 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 14197 14198 if (ConvertHalfVec) 14199 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 14200 OpLoc, CurFPFeatureOverrides()); 14201 14202 return CompoundAssignOperator::Create( 14203 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 14204 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 14205 } 14206 14207 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 14208 /// operators are mixed in a way that suggests that the programmer forgot that 14209 /// comparison operators have higher precedence. The most typical example of 14210 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 14211 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 14212 SourceLocation OpLoc, Expr *LHSExpr, 14213 Expr *RHSExpr) { 14214 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 14215 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 14216 14217 // Check that one of the sides is a comparison operator and the other isn't. 14218 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 14219 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 14220 if (isLeftComp == isRightComp) 14221 return; 14222 14223 // Bitwise operations are sometimes used as eager logical ops. 14224 // Don't diagnose this. 14225 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 14226 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 14227 if (isLeftBitwise || isRightBitwise) 14228 return; 14229 14230 SourceRange DiagRange = isLeftComp 14231 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 14232 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 14233 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 14234 SourceRange ParensRange = 14235 isLeftComp 14236 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 14237 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 14238 14239 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 14240 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 14241 SuggestParentheses(Self, OpLoc, 14242 Self.PDiag(diag::note_precedence_silence) << OpStr, 14243 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 14244 SuggestParentheses(Self, OpLoc, 14245 Self.PDiag(diag::note_precedence_bitwise_first) 14246 << BinaryOperator::getOpcodeStr(Opc), 14247 ParensRange); 14248 } 14249 14250 /// It accepts a '&&' expr that is inside a '||' one. 14251 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 14252 /// in parentheses. 14253 static void 14254 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 14255 BinaryOperator *Bop) { 14256 assert(Bop->getOpcode() == BO_LAnd); 14257 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 14258 << Bop->getSourceRange() << OpLoc; 14259 SuggestParentheses(Self, Bop->getOperatorLoc(), 14260 Self.PDiag(diag::note_precedence_silence) 14261 << Bop->getOpcodeStr(), 14262 Bop->getSourceRange()); 14263 } 14264 14265 /// Returns true if the given expression can be evaluated as a constant 14266 /// 'true'. 14267 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 14268 bool Res; 14269 return !E->isValueDependent() && 14270 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 14271 } 14272 14273 /// Returns true if the given expression can be evaluated as a constant 14274 /// 'false'. 14275 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 14276 bool Res; 14277 return !E->isValueDependent() && 14278 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 14279 } 14280 14281 /// Look for '&&' in the left hand of a '||' expr. 14282 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 14283 Expr *LHSExpr, Expr *RHSExpr) { 14284 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 14285 if (Bop->getOpcode() == BO_LAnd) { 14286 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 14287 if (EvaluatesAsFalse(S, RHSExpr)) 14288 return; 14289 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 14290 if (!EvaluatesAsTrue(S, Bop->getLHS())) 14291 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14292 } else if (Bop->getOpcode() == BO_LOr) { 14293 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 14294 // If it's "a || b && 1 || c" we didn't warn earlier for 14295 // "a || b && 1", but warn now. 14296 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 14297 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 14298 } 14299 } 14300 } 14301 } 14302 14303 /// Look for '&&' in the right hand of a '||' expr. 14304 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 14305 Expr *LHSExpr, Expr *RHSExpr) { 14306 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 14307 if (Bop->getOpcode() == BO_LAnd) { 14308 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 14309 if (EvaluatesAsFalse(S, LHSExpr)) 14310 return; 14311 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 14312 if (!EvaluatesAsTrue(S, Bop->getRHS())) 14313 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 14314 } 14315 } 14316 } 14317 14318 /// Look for bitwise op in the left or right hand of a bitwise op with 14319 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 14320 /// the '&' expression in parentheses. 14321 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 14322 SourceLocation OpLoc, Expr *SubExpr) { 14323 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14324 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 14325 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 14326 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 14327 << Bop->getSourceRange() << OpLoc; 14328 SuggestParentheses(S, Bop->getOperatorLoc(), 14329 S.PDiag(diag::note_precedence_silence) 14330 << Bop->getOpcodeStr(), 14331 Bop->getSourceRange()); 14332 } 14333 } 14334 } 14335 14336 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 14337 Expr *SubExpr, StringRef Shift) { 14338 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 14339 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 14340 StringRef Op = Bop->getOpcodeStr(); 14341 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 14342 << Bop->getSourceRange() << OpLoc << Shift << Op; 14343 SuggestParentheses(S, Bop->getOperatorLoc(), 14344 S.PDiag(diag::note_precedence_silence) << Op, 14345 Bop->getSourceRange()); 14346 } 14347 } 14348 } 14349 14350 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 14351 Expr *LHSExpr, Expr *RHSExpr) { 14352 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 14353 if (!OCE) 14354 return; 14355 14356 FunctionDecl *FD = OCE->getDirectCallee(); 14357 if (!FD || !FD->isOverloadedOperator()) 14358 return; 14359 14360 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 14361 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 14362 return; 14363 14364 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 14365 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 14366 << (Kind == OO_LessLess); 14367 SuggestParentheses(S, OCE->getOperatorLoc(), 14368 S.PDiag(diag::note_precedence_silence) 14369 << (Kind == OO_LessLess ? "<<" : ">>"), 14370 OCE->getSourceRange()); 14371 SuggestParentheses( 14372 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 14373 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 14374 } 14375 14376 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 14377 /// precedence. 14378 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 14379 SourceLocation OpLoc, Expr *LHSExpr, 14380 Expr *RHSExpr){ 14381 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 14382 if (BinaryOperator::isBitwiseOp(Opc)) 14383 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 14384 14385 // Diagnose "arg1 & arg2 | arg3" 14386 if ((Opc == BO_Or || Opc == BO_Xor) && 14387 !OpLoc.isMacroID()/* Don't warn in macros. */) { 14388 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 14389 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 14390 } 14391 14392 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 14393 // We don't warn for 'assert(a || b && "bad")' since this is safe. 14394 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 14395 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 14396 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 14397 } 14398 14399 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 14400 || Opc == BO_Shr) { 14401 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 14402 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 14403 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 14404 } 14405 14406 // Warn on overloaded shift operators and comparisons, such as: 14407 // cout << 5 == 4; 14408 if (BinaryOperator::isComparisonOp(Opc)) 14409 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 14410 } 14411 14412 // Binary Operators. 'Tok' is the token for the operator. 14413 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 14414 tok::TokenKind Kind, 14415 Expr *LHSExpr, Expr *RHSExpr) { 14416 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 14417 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 14418 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 14419 14420 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 14421 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 14422 14423 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 14424 } 14425 14426 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 14427 UnresolvedSetImpl &Functions) { 14428 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 14429 if (OverOp != OO_None && OverOp != OO_Equal) 14430 LookupOverloadedOperatorName(OverOp, S, Functions); 14431 14432 // In C++20 onwards, we may have a second operator to look up. 14433 if (getLangOpts().CPlusPlus20) { 14434 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 14435 LookupOverloadedOperatorName(ExtraOp, S, Functions); 14436 } 14437 } 14438 14439 /// Build an overloaded binary operator expression in the given scope. 14440 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 14441 BinaryOperatorKind Opc, 14442 Expr *LHS, Expr *RHS) { 14443 switch (Opc) { 14444 case BO_Assign: 14445 case BO_DivAssign: 14446 case BO_RemAssign: 14447 case BO_SubAssign: 14448 case BO_AndAssign: 14449 case BO_OrAssign: 14450 case BO_XorAssign: 14451 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 14452 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 14453 break; 14454 default: 14455 break; 14456 } 14457 14458 // Find all of the overloaded operators visible from this point. 14459 UnresolvedSet<16> Functions; 14460 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 14461 14462 // Build the (potentially-overloaded, potentially-dependent) 14463 // binary operation. 14464 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 14465 } 14466 14467 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 14468 BinaryOperatorKind Opc, 14469 Expr *LHSExpr, Expr *RHSExpr) { 14470 ExprResult LHS, RHS; 14471 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 14472 if (!LHS.isUsable() || !RHS.isUsable()) 14473 return ExprError(); 14474 LHSExpr = LHS.get(); 14475 RHSExpr = RHS.get(); 14476 14477 // We want to end up calling one of checkPseudoObjectAssignment 14478 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 14479 // both expressions are overloadable or either is type-dependent), 14480 // or CreateBuiltinBinOp (in any other case). We also want to get 14481 // any placeholder types out of the way. 14482 14483 // Handle pseudo-objects in the LHS. 14484 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 14485 // Assignments with a pseudo-object l-value need special analysis. 14486 if (pty->getKind() == BuiltinType::PseudoObject && 14487 BinaryOperator::isAssignmentOp(Opc)) 14488 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 14489 14490 // Don't resolve overloads if the other type is overloadable. 14491 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 14492 // We can't actually test that if we still have a placeholder, 14493 // though. Fortunately, none of the exceptions we see in that 14494 // code below are valid when the LHS is an overload set. Note 14495 // that an overload set can be dependently-typed, but it never 14496 // instantiates to having an overloadable type. 14497 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14498 if (resolvedRHS.isInvalid()) return ExprError(); 14499 RHSExpr = resolvedRHS.get(); 14500 14501 if (RHSExpr->isTypeDependent() || 14502 RHSExpr->getType()->isOverloadableType()) 14503 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14504 } 14505 14506 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 14507 // template, diagnose the missing 'template' keyword instead of diagnosing 14508 // an invalid use of a bound member function. 14509 // 14510 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 14511 // to C++1z [over.over]/1.4, but we already checked for that case above. 14512 if (Opc == BO_LT && inTemplateInstantiation() && 14513 (pty->getKind() == BuiltinType::BoundMember || 14514 pty->getKind() == BuiltinType::Overload)) { 14515 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 14516 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 14517 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 14518 return isa<FunctionTemplateDecl>(ND); 14519 })) { 14520 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 14521 : OE->getNameLoc(), 14522 diag::err_template_kw_missing) 14523 << OE->getName().getAsString() << ""; 14524 return ExprError(); 14525 } 14526 } 14527 14528 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 14529 if (LHS.isInvalid()) return ExprError(); 14530 LHSExpr = LHS.get(); 14531 } 14532 14533 // Handle pseudo-objects in the RHS. 14534 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 14535 // An overload in the RHS can potentially be resolved by the type 14536 // being assigned to. 14537 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 14538 if (getLangOpts().CPlusPlus && 14539 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 14540 LHSExpr->getType()->isOverloadableType())) 14541 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14542 14543 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14544 } 14545 14546 // Don't resolve overloads if the other type is overloadable. 14547 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 14548 LHSExpr->getType()->isOverloadableType()) 14549 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14550 14551 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 14552 if (!resolvedRHS.isUsable()) return ExprError(); 14553 RHSExpr = resolvedRHS.get(); 14554 } 14555 14556 if (getLangOpts().CPlusPlus) { 14557 // If either expression is type-dependent, always build an 14558 // overloaded op. 14559 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 14560 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14561 14562 // Otherwise, build an overloaded op if either expression has an 14563 // overloadable type. 14564 if (LHSExpr->getType()->isOverloadableType() || 14565 RHSExpr->getType()->isOverloadableType()) 14566 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 14567 } 14568 14569 if (getLangOpts().RecoveryAST && 14570 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 14571 assert(!getLangOpts().CPlusPlus); 14572 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 14573 "Should only occur in error-recovery path."); 14574 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 14575 // C [6.15.16] p3: 14576 // An assignment expression has the value of the left operand after the 14577 // assignment, but is not an lvalue. 14578 return CompoundAssignOperator::Create( 14579 Context, LHSExpr, RHSExpr, Opc, 14580 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary, 14581 OpLoc, CurFPFeatureOverrides()); 14582 QualType ResultType; 14583 switch (Opc) { 14584 case BO_Assign: 14585 ResultType = LHSExpr->getType().getUnqualifiedType(); 14586 break; 14587 case BO_LT: 14588 case BO_GT: 14589 case BO_LE: 14590 case BO_GE: 14591 case BO_EQ: 14592 case BO_NE: 14593 case BO_LAnd: 14594 case BO_LOr: 14595 // These operators have a fixed result type regardless of operands. 14596 ResultType = Context.IntTy; 14597 break; 14598 case BO_Comma: 14599 ResultType = RHSExpr->getType(); 14600 break; 14601 default: 14602 ResultType = Context.DependentTy; 14603 break; 14604 } 14605 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 14606 VK_RValue, OK_Ordinary, OpLoc, 14607 CurFPFeatureOverrides()); 14608 } 14609 14610 // Build a built-in binary operation. 14611 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 14612 } 14613 14614 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 14615 if (T.isNull() || T->isDependentType()) 14616 return false; 14617 14618 if (!T->isPromotableIntegerType()) 14619 return true; 14620 14621 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 14622 } 14623 14624 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 14625 UnaryOperatorKind Opc, 14626 Expr *InputExpr) { 14627 ExprResult Input = InputExpr; 14628 ExprValueKind VK = VK_RValue; 14629 ExprObjectKind OK = OK_Ordinary; 14630 QualType resultType; 14631 bool CanOverflow = false; 14632 14633 bool ConvertHalfVec = false; 14634 if (getLangOpts().OpenCL) { 14635 QualType Ty = InputExpr->getType(); 14636 // The only legal unary operation for atomics is '&'. 14637 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 14638 // OpenCL special types - image, sampler, pipe, and blocks are to be used 14639 // only with a builtin functions and therefore should be disallowed here. 14640 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 14641 || Ty->isBlockPointerType())) { 14642 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14643 << InputExpr->getType() 14644 << Input.get()->getSourceRange()); 14645 } 14646 } 14647 14648 switch (Opc) { 14649 case UO_PreInc: 14650 case UO_PreDec: 14651 case UO_PostInc: 14652 case UO_PostDec: 14653 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 14654 OpLoc, 14655 Opc == UO_PreInc || 14656 Opc == UO_PostInc, 14657 Opc == UO_PreInc || 14658 Opc == UO_PreDec); 14659 CanOverflow = isOverflowingIntegerType(Context, resultType); 14660 break; 14661 case UO_AddrOf: 14662 resultType = CheckAddressOfOperand(Input, OpLoc); 14663 CheckAddressOfNoDeref(InputExpr); 14664 RecordModifiableNonNullParam(*this, InputExpr); 14665 break; 14666 case UO_Deref: { 14667 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14668 if (Input.isInvalid()) return ExprError(); 14669 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 14670 break; 14671 } 14672 case UO_Plus: 14673 case UO_Minus: 14674 CanOverflow = Opc == UO_Minus && 14675 isOverflowingIntegerType(Context, Input.get()->getType()); 14676 Input = UsualUnaryConversions(Input.get()); 14677 if (Input.isInvalid()) return ExprError(); 14678 // Unary plus and minus require promoting an operand of half vector to a 14679 // float vector and truncating the result back to a half vector. For now, we 14680 // do this only when HalfArgsAndReturns is set (that is, when the target is 14681 // arm or arm64). 14682 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 14683 14684 // If the operand is a half vector, promote it to a float vector. 14685 if (ConvertHalfVec) 14686 Input = convertVector(Input.get(), Context.FloatTy, *this); 14687 resultType = Input.get()->getType(); 14688 if (resultType->isDependentType()) 14689 break; 14690 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 14691 break; 14692 else if (resultType->isVectorType() && 14693 // The z vector extensions don't allow + or - with bool vectors. 14694 (!Context.getLangOpts().ZVector || 14695 resultType->castAs<VectorType>()->getVectorKind() != 14696 VectorType::AltiVecBool)) 14697 break; 14698 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 14699 Opc == UO_Plus && 14700 resultType->isPointerType()) 14701 break; 14702 14703 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14704 << resultType << Input.get()->getSourceRange()); 14705 14706 case UO_Not: // bitwise complement 14707 Input = UsualUnaryConversions(Input.get()); 14708 if (Input.isInvalid()) 14709 return ExprError(); 14710 resultType = Input.get()->getType(); 14711 if (resultType->isDependentType()) 14712 break; 14713 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 14714 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 14715 // C99 does not support '~' for complex conjugation. 14716 Diag(OpLoc, diag::ext_integer_complement_complex) 14717 << resultType << Input.get()->getSourceRange(); 14718 else if (resultType->hasIntegerRepresentation()) 14719 break; 14720 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 14721 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 14722 // on vector float types. 14723 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14724 if (!T->isIntegerType()) 14725 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14726 << resultType << Input.get()->getSourceRange()); 14727 } else { 14728 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14729 << resultType << Input.get()->getSourceRange()); 14730 } 14731 break; 14732 14733 case UO_LNot: // logical negation 14734 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 14735 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 14736 if (Input.isInvalid()) return ExprError(); 14737 resultType = Input.get()->getType(); 14738 14739 // Though we still have to promote half FP to float... 14740 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 14741 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 14742 resultType = Context.FloatTy; 14743 } 14744 14745 if (resultType->isDependentType()) 14746 break; 14747 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 14748 // C99 6.5.3.3p1: ok, fallthrough; 14749 if (Context.getLangOpts().CPlusPlus) { 14750 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 14751 // operand contextually converted to bool. 14752 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 14753 ScalarTypeToBooleanCastKind(resultType)); 14754 } else if (Context.getLangOpts().OpenCL && 14755 Context.getLangOpts().OpenCLVersion < 120) { 14756 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14757 // operate on scalar float types. 14758 if (!resultType->isIntegerType() && !resultType->isPointerType()) 14759 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14760 << resultType << Input.get()->getSourceRange()); 14761 } 14762 } else if (resultType->isExtVectorType()) { 14763 if (Context.getLangOpts().OpenCL && 14764 Context.getLangOpts().OpenCLVersion < 120 && 14765 !Context.getLangOpts().OpenCLCPlusPlus) { 14766 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 14767 // operate on vector float types. 14768 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 14769 if (!T->isIntegerType()) 14770 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14771 << resultType << Input.get()->getSourceRange()); 14772 } 14773 // Vector logical not returns the signed variant of the operand type. 14774 resultType = GetSignedVectorType(resultType); 14775 break; 14776 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 14777 const VectorType *VTy = resultType->castAs<VectorType>(); 14778 if (VTy->getVectorKind() != VectorType::GenericVector) 14779 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14780 << resultType << Input.get()->getSourceRange()); 14781 14782 // Vector logical not returns the signed variant of the operand type. 14783 resultType = GetSignedVectorType(resultType); 14784 break; 14785 } else { 14786 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 14787 << resultType << Input.get()->getSourceRange()); 14788 } 14789 14790 // LNot always has type int. C99 6.5.3.3p5. 14791 // In C++, it's bool. C++ 5.3.1p8 14792 resultType = Context.getLogicalOperationType(); 14793 break; 14794 case UO_Real: 14795 case UO_Imag: 14796 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 14797 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 14798 // complex l-values to ordinary l-values and all other values to r-values. 14799 if (Input.isInvalid()) return ExprError(); 14800 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 14801 if (Input.get()->getValueKind() != VK_RValue && 14802 Input.get()->getObjectKind() == OK_Ordinary) 14803 VK = Input.get()->getValueKind(); 14804 } else if (!getLangOpts().CPlusPlus) { 14805 // In C, a volatile scalar is read by __imag. In C++, it is not. 14806 Input = DefaultLvalueConversion(Input.get()); 14807 } 14808 break; 14809 case UO_Extension: 14810 resultType = Input.get()->getType(); 14811 VK = Input.get()->getValueKind(); 14812 OK = Input.get()->getObjectKind(); 14813 break; 14814 case UO_Coawait: 14815 // It's unnecessary to represent the pass-through operator co_await in the 14816 // AST; just return the input expression instead. 14817 assert(!Input.get()->getType()->isDependentType() && 14818 "the co_await expression must be non-dependant before " 14819 "building operator co_await"); 14820 return Input; 14821 } 14822 if (resultType.isNull() || Input.isInvalid()) 14823 return ExprError(); 14824 14825 // Check for array bounds violations in the operand of the UnaryOperator, 14826 // except for the '*' and '&' operators that have to be handled specially 14827 // by CheckArrayAccess (as there are special cases like &array[arraysize] 14828 // that are explicitly defined as valid by the standard). 14829 if (Opc != UO_AddrOf && Opc != UO_Deref) 14830 CheckArrayAccess(Input.get()); 14831 14832 auto *UO = 14833 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 14834 OpLoc, CanOverflow, CurFPFeatureOverrides()); 14835 14836 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 14837 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 14838 !isUnevaluatedContext()) 14839 ExprEvalContexts.back().PossibleDerefs.insert(UO); 14840 14841 // Convert the result back to a half vector. 14842 if (ConvertHalfVec) 14843 return convertVector(UO, Context.HalfTy, *this); 14844 return UO; 14845 } 14846 14847 /// Determine whether the given expression is a qualified member 14848 /// access expression, of a form that could be turned into a pointer to member 14849 /// with the address-of operator. 14850 bool Sema::isQualifiedMemberAccess(Expr *E) { 14851 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 14852 if (!DRE->getQualifier()) 14853 return false; 14854 14855 ValueDecl *VD = DRE->getDecl(); 14856 if (!VD->isCXXClassMember()) 14857 return false; 14858 14859 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 14860 return true; 14861 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 14862 return Method->isInstance(); 14863 14864 return false; 14865 } 14866 14867 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 14868 if (!ULE->getQualifier()) 14869 return false; 14870 14871 for (NamedDecl *D : ULE->decls()) { 14872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 14873 if (Method->isInstance()) 14874 return true; 14875 } else { 14876 // Overload set does not contain methods. 14877 break; 14878 } 14879 } 14880 14881 return false; 14882 } 14883 14884 return false; 14885 } 14886 14887 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 14888 UnaryOperatorKind Opc, Expr *Input) { 14889 // First things first: handle placeholders so that the 14890 // overloaded-operator check considers the right type. 14891 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 14892 // Increment and decrement of pseudo-object references. 14893 if (pty->getKind() == BuiltinType::PseudoObject && 14894 UnaryOperator::isIncrementDecrementOp(Opc)) 14895 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 14896 14897 // extension is always a builtin operator. 14898 if (Opc == UO_Extension) 14899 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14900 14901 // & gets special logic for several kinds of placeholder. 14902 // The builtin code knows what to do. 14903 if (Opc == UO_AddrOf && 14904 (pty->getKind() == BuiltinType::Overload || 14905 pty->getKind() == BuiltinType::UnknownAny || 14906 pty->getKind() == BuiltinType::BoundMember)) 14907 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14908 14909 // Anything else needs to be handled now. 14910 ExprResult Result = CheckPlaceholderExpr(Input); 14911 if (Result.isInvalid()) return ExprError(); 14912 Input = Result.get(); 14913 } 14914 14915 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 14916 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 14917 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 14918 // Find all of the overloaded operators visible from this point. 14919 UnresolvedSet<16> Functions; 14920 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 14921 if (S && OverOp != OO_None) 14922 LookupOverloadedOperatorName(OverOp, S, Functions); 14923 14924 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 14925 } 14926 14927 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 14928 } 14929 14930 // Unary Operators. 'Tok' is the token for the operator. 14931 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 14932 tok::TokenKind Op, Expr *Input) { 14933 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 14934 } 14935 14936 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 14937 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 14938 LabelDecl *TheDecl) { 14939 TheDecl->markUsed(Context); 14940 // Create the AST node. The address of a label always has type 'void*'. 14941 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 14942 Context.getPointerType(Context.VoidTy)); 14943 } 14944 14945 void Sema::ActOnStartStmtExpr() { 14946 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14947 } 14948 14949 void Sema::ActOnStmtExprError() { 14950 // Note that function is also called by TreeTransform when leaving a 14951 // StmtExpr scope without rebuilding anything. 14952 14953 DiscardCleanupsInEvaluationContext(); 14954 PopExpressionEvaluationContext(); 14955 } 14956 14957 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 14958 SourceLocation RPLoc) { 14959 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 14960 } 14961 14962 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 14963 SourceLocation RPLoc, unsigned TemplateDepth) { 14964 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 14965 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 14966 14967 if (hasAnyUnrecoverableErrorsInThisFunction()) 14968 DiscardCleanupsInEvaluationContext(); 14969 assert(!Cleanup.exprNeedsCleanups() && 14970 "cleanups within StmtExpr not correctly bound!"); 14971 PopExpressionEvaluationContext(); 14972 14973 // FIXME: there are a variety of strange constraints to enforce here, for 14974 // example, it is not possible to goto into a stmt expression apparently. 14975 // More semantic analysis is needed. 14976 14977 // If there are sub-stmts in the compound stmt, take the type of the last one 14978 // as the type of the stmtexpr. 14979 QualType Ty = Context.VoidTy; 14980 bool StmtExprMayBindToTemp = false; 14981 if (!Compound->body_empty()) { 14982 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 14983 if (const auto *LastStmt = 14984 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 14985 if (const Expr *Value = LastStmt->getExprStmt()) { 14986 StmtExprMayBindToTemp = true; 14987 Ty = Value->getType(); 14988 } 14989 } 14990 } 14991 14992 // FIXME: Check that expression type is complete/non-abstract; statement 14993 // expressions are not lvalues. 14994 Expr *ResStmtExpr = 14995 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 14996 if (StmtExprMayBindToTemp) 14997 return MaybeBindToTemporary(ResStmtExpr); 14998 return ResStmtExpr; 14999 } 15000 15001 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 15002 if (ER.isInvalid()) 15003 return ExprError(); 15004 15005 // Do function/array conversion on the last expression, but not 15006 // lvalue-to-rvalue. However, initialize an unqualified type. 15007 ER = DefaultFunctionArrayConversion(ER.get()); 15008 if (ER.isInvalid()) 15009 return ExprError(); 15010 Expr *E = ER.get(); 15011 15012 if (E->isTypeDependent()) 15013 return E; 15014 15015 // In ARC, if the final expression ends in a consume, splice 15016 // the consume out and bind it later. In the alternate case 15017 // (when dealing with a retainable type), the result 15018 // initialization will create a produce. In both cases the 15019 // result will be +1, and we'll need to balance that out with 15020 // a bind. 15021 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 15022 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 15023 return Cast->getSubExpr(); 15024 15025 // FIXME: Provide a better location for the initialization. 15026 return PerformCopyInitialization( 15027 InitializedEntity::InitializeStmtExprResult( 15028 E->getBeginLoc(), E->getType().getUnqualifiedType()), 15029 SourceLocation(), E); 15030 } 15031 15032 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 15033 TypeSourceInfo *TInfo, 15034 ArrayRef<OffsetOfComponent> Components, 15035 SourceLocation RParenLoc) { 15036 QualType ArgTy = TInfo->getType(); 15037 bool Dependent = ArgTy->isDependentType(); 15038 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 15039 15040 // We must have at least one component that refers to the type, and the first 15041 // one is known to be a field designator. Verify that the ArgTy represents 15042 // a struct/union/class. 15043 if (!Dependent && !ArgTy->isRecordType()) 15044 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 15045 << ArgTy << TypeRange); 15046 15047 // Type must be complete per C99 7.17p3 because a declaring a variable 15048 // with an incomplete type would be ill-formed. 15049 if (!Dependent 15050 && RequireCompleteType(BuiltinLoc, ArgTy, 15051 diag::err_offsetof_incomplete_type, TypeRange)) 15052 return ExprError(); 15053 15054 bool DidWarnAboutNonPOD = false; 15055 QualType CurrentType = ArgTy; 15056 SmallVector<OffsetOfNode, 4> Comps; 15057 SmallVector<Expr*, 4> Exprs; 15058 for (const OffsetOfComponent &OC : Components) { 15059 if (OC.isBrackets) { 15060 // Offset of an array sub-field. TODO: Should we allow vector elements? 15061 if (!CurrentType->isDependentType()) { 15062 const ArrayType *AT = Context.getAsArrayType(CurrentType); 15063 if(!AT) 15064 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 15065 << CurrentType); 15066 CurrentType = AT->getElementType(); 15067 } else 15068 CurrentType = Context.DependentTy; 15069 15070 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 15071 if (IdxRval.isInvalid()) 15072 return ExprError(); 15073 Expr *Idx = IdxRval.get(); 15074 15075 // The expression must be an integral expression. 15076 // FIXME: An integral constant expression? 15077 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 15078 !Idx->getType()->isIntegerType()) 15079 return ExprError( 15080 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 15081 << Idx->getSourceRange()); 15082 15083 // Record this array index. 15084 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 15085 Exprs.push_back(Idx); 15086 continue; 15087 } 15088 15089 // Offset of a field. 15090 if (CurrentType->isDependentType()) { 15091 // We have the offset of a field, but we can't look into the dependent 15092 // type. Just record the identifier of the field. 15093 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 15094 CurrentType = Context.DependentTy; 15095 continue; 15096 } 15097 15098 // We need to have a complete type to look into. 15099 if (RequireCompleteType(OC.LocStart, CurrentType, 15100 diag::err_offsetof_incomplete_type)) 15101 return ExprError(); 15102 15103 // Look for the designated field. 15104 const RecordType *RC = CurrentType->getAs<RecordType>(); 15105 if (!RC) 15106 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 15107 << CurrentType); 15108 RecordDecl *RD = RC->getDecl(); 15109 15110 // C++ [lib.support.types]p5: 15111 // The macro offsetof accepts a restricted set of type arguments in this 15112 // International Standard. type shall be a POD structure or a POD union 15113 // (clause 9). 15114 // C++11 [support.types]p4: 15115 // If type is not a standard-layout class (Clause 9), the results are 15116 // undefined. 15117 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15118 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 15119 unsigned DiagID = 15120 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 15121 : diag::ext_offsetof_non_pod_type; 15122 15123 if (!IsSafe && !DidWarnAboutNonPOD && 15124 DiagRuntimeBehavior(BuiltinLoc, nullptr, 15125 PDiag(DiagID) 15126 << SourceRange(Components[0].LocStart, OC.LocEnd) 15127 << CurrentType)) 15128 DidWarnAboutNonPOD = true; 15129 } 15130 15131 // Look for the field. 15132 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 15133 LookupQualifiedName(R, RD); 15134 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 15135 IndirectFieldDecl *IndirectMemberDecl = nullptr; 15136 if (!MemberDecl) { 15137 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 15138 MemberDecl = IndirectMemberDecl->getAnonField(); 15139 } 15140 15141 if (!MemberDecl) 15142 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 15143 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 15144 OC.LocEnd)); 15145 15146 // C99 7.17p3: 15147 // (If the specified member is a bit-field, the behavior is undefined.) 15148 // 15149 // We diagnose this as an error. 15150 if (MemberDecl->isBitField()) { 15151 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 15152 << MemberDecl->getDeclName() 15153 << SourceRange(BuiltinLoc, RParenLoc); 15154 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 15155 return ExprError(); 15156 } 15157 15158 RecordDecl *Parent = MemberDecl->getParent(); 15159 if (IndirectMemberDecl) 15160 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 15161 15162 // If the member was found in a base class, introduce OffsetOfNodes for 15163 // the base class indirections. 15164 CXXBasePaths Paths; 15165 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 15166 Paths)) { 15167 if (Paths.getDetectedVirtual()) { 15168 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 15169 << MemberDecl->getDeclName() 15170 << SourceRange(BuiltinLoc, RParenLoc); 15171 return ExprError(); 15172 } 15173 15174 CXXBasePath &Path = Paths.front(); 15175 for (const CXXBasePathElement &B : Path) 15176 Comps.push_back(OffsetOfNode(B.Base)); 15177 } 15178 15179 if (IndirectMemberDecl) { 15180 for (auto *FI : IndirectMemberDecl->chain()) { 15181 assert(isa<FieldDecl>(FI)); 15182 Comps.push_back(OffsetOfNode(OC.LocStart, 15183 cast<FieldDecl>(FI), OC.LocEnd)); 15184 } 15185 } else 15186 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 15187 15188 CurrentType = MemberDecl->getType().getNonReferenceType(); 15189 } 15190 15191 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 15192 Comps, Exprs, RParenLoc); 15193 } 15194 15195 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 15196 SourceLocation BuiltinLoc, 15197 SourceLocation TypeLoc, 15198 ParsedType ParsedArgTy, 15199 ArrayRef<OffsetOfComponent> Components, 15200 SourceLocation RParenLoc) { 15201 15202 TypeSourceInfo *ArgTInfo; 15203 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 15204 if (ArgTy.isNull()) 15205 return ExprError(); 15206 15207 if (!ArgTInfo) 15208 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 15209 15210 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 15211 } 15212 15213 15214 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 15215 Expr *CondExpr, 15216 Expr *LHSExpr, Expr *RHSExpr, 15217 SourceLocation RPLoc) { 15218 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 15219 15220 ExprValueKind VK = VK_RValue; 15221 ExprObjectKind OK = OK_Ordinary; 15222 QualType resType; 15223 bool CondIsTrue = false; 15224 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 15225 resType = Context.DependentTy; 15226 } else { 15227 // The conditional expression is required to be a constant expression. 15228 llvm::APSInt condEval(32); 15229 ExprResult CondICE = VerifyIntegerConstantExpression( 15230 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 15231 if (CondICE.isInvalid()) 15232 return ExprError(); 15233 CondExpr = CondICE.get(); 15234 CondIsTrue = condEval.getZExtValue(); 15235 15236 // If the condition is > zero, then the AST type is the same as the LHSExpr. 15237 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 15238 15239 resType = ActiveExpr->getType(); 15240 VK = ActiveExpr->getValueKind(); 15241 OK = ActiveExpr->getObjectKind(); 15242 } 15243 15244 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 15245 resType, VK, OK, RPLoc, CondIsTrue); 15246 } 15247 15248 //===----------------------------------------------------------------------===// 15249 // Clang Extensions. 15250 //===----------------------------------------------------------------------===// 15251 15252 /// ActOnBlockStart - This callback is invoked when a block literal is started. 15253 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 15254 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 15255 15256 if (LangOpts.CPlusPlus) { 15257 MangleNumberingContext *MCtx; 15258 Decl *ManglingContextDecl; 15259 std::tie(MCtx, ManglingContextDecl) = 15260 getCurrentMangleNumberContext(Block->getDeclContext()); 15261 if (MCtx) { 15262 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 15263 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 15264 } 15265 } 15266 15267 PushBlockScope(CurScope, Block); 15268 CurContext->addDecl(Block); 15269 if (CurScope) 15270 PushDeclContext(CurScope, Block); 15271 else 15272 CurContext = Block; 15273 15274 getCurBlock()->HasImplicitReturnType = true; 15275 15276 // Enter a new evaluation context to insulate the block from any 15277 // cleanups from the enclosing full-expression. 15278 PushExpressionEvaluationContext( 15279 ExpressionEvaluationContext::PotentiallyEvaluated); 15280 } 15281 15282 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 15283 Scope *CurScope) { 15284 assert(ParamInfo.getIdentifier() == nullptr && 15285 "block-id should have no identifier!"); 15286 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 15287 BlockScopeInfo *CurBlock = getCurBlock(); 15288 15289 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 15290 QualType T = Sig->getType(); 15291 15292 // FIXME: We should allow unexpanded parameter packs here, but that would, 15293 // in turn, make the block expression contain unexpanded parameter packs. 15294 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 15295 // Drop the parameters. 15296 FunctionProtoType::ExtProtoInfo EPI; 15297 EPI.HasTrailingReturn = false; 15298 EPI.TypeQuals.addConst(); 15299 T = Context.getFunctionType(Context.DependentTy, None, EPI); 15300 Sig = Context.getTrivialTypeSourceInfo(T); 15301 } 15302 15303 // GetTypeForDeclarator always produces a function type for a block 15304 // literal signature. Furthermore, it is always a FunctionProtoType 15305 // unless the function was written with a typedef. 15306 assert(T->isFunctionType() && 15307 "GetTypeForDeclarator made a non-function block signature"); 15308 15309 // Look for an explicit signature in that function type. 15310 FunctionProtoTypeLoc ExplicitSignature; 15311 15312 if ((ExplicitSignature = Sig->getTypeLoc() 15313 .getAsAdjusted<FunctionProtoTypeLoc>())) { 15314 15315 // Check whether that explicit signature was synthesized by 15316 // GetTypeForDeclarator. If so, don't save that as part of the 15317 // written signature. 15318 if (ExplicitSignature.getLocalRangeBegin() == 15319 ExplicitSignature.getLocalRangeEnd()) { 15320 // This would be much cheaper if we stored TypeLocs instead of 15321 // TypeSourceInfos. 15322 TypeLoc Result = ExplicitSignature.getReturnLoc(); 15323 unsigned Size = Result.getFullDataSize(); 15324 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 15325 Sig->getTypeLoc().initializeFullCopy(Result, Size); 15326 15327 ExplicitSignature = FunctionProtoTypeLoc(); 15328 } 15329 } 15330 15331 CurBlock->TheDecl->setSignatureAsWritten(Sig); 15332 CurBlock->FunctionType = T; 15333 15334 const auto *Fn = T->castAs<FunctionType>(); 15335 QualType RetTy = Fn->getReturnType(); 15336 bool isVariadic = 15337 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 15338 15339 CurBlock->TheDecl->setIsVariadic(isVariadic); 15340 15341 // Context.DependentTy is used as a placeholder for a missing block 15342 // return type. TODO: what should we do with declarators like: 15343 // ^ * { ... } 15344 // If the answer is "apply template argument deduction".... 15345 if (RetTy != Context.DependentTy) { 15346 CurBlock->ReturnType = RetTy; 15347 CurBlock->TheDecl->setBlockMissingReturnType(false); 15348 CurBlock->HasImplicitReturnType = false; 15349 } 15350 15351 // Push block parameters from the declarator if we had them. 15352 SmallVector<ParmVarDecl*, 8> Params; 15353 if (ExplicitSignature) { 15354 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 15355 ParmVarDecl *Param = ExplicitSignature.getParam(I); 15356 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 15357 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 15358 // Diagnose this as an extension in C17 and earlier. 15359 if (!getLangOpts().C2x) 15360 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15361 } 15362 Params.push_back(Param); 15363 } 15364 15365 // Fake up parameter variables if we have a typedef, like 15366 // ^ fntype { ... } 15367 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 15368 for (const auto &I : Fn->param_types()) { 15369 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 15370 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 15371 Params.push_back(Param); 15372 } 15373 } 15374 15375 // Set the parameters on the block decl. 15376 if (!Params.empty()) { 15377 CurBlock->TheDecl->setParams(Params); 15378 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 15379 /*CheckParameterNames=*/false); 15380 } 15381 15382 // Finally we can process decl attributes. 15383 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 15384 15385 // Put the parameter variables in scope. 15386 for (auto AI : CurBlock->TheDecl->parameters()) { 15387 AI->setOwningFunction(CurBlock->TheDecl); 15388 15389 // If this has an identifier, add it to the scope stack. 15390 if (AI->getIdentifier()) { 15391 CheckShadow(CurBlock->TheScope, AI); 15392 15393 PushOnScopeChains(AI, CurBlock->TheScope); 15394 } 15395 } 15396 } 15397 15398 /// ActOnBlockError - If there is an error parsing a block, this callback 15399 /// is invoked to pop the information about the block from the action impl. 15400 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 15401 // Leave the expression-evaluation context. 15402 DiscardCleanupsInEvaluationContext(); 15403 PopExpressionEvaluationContext(); 15404 15405 // Pop off CurBlock, handle nested blocks. 15406 PopDeclContext(); 15407 PopFunctionScopeInfo(); 15408 } 15409 15410 /// ActOnBlockStmtExpr - This is called when the body of a block statement 15411 /// literal was successfully completed. ^(int x){...} 15412 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 15413 Stmt *Body, Scope *CurScope) { 15414 // If blocks are disabled, emit an error. 15415 if (!LangOpts.Blocks) 15416 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 15417 15418 // Leave the expression-evaluation context. 15419 if (hasAnyUnrecoverableErrorsInThisFunction()) 15420 DiscardCleanupsInEvaluationContext(); 15421 assert(!Cleanup.exprNeedsCleanups() && 15422 "cleanups within block not correctly bound!"); 15423 PopExpressionEvaluationContext(); 15424 15425 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 15426 BlockDecl *BD = BSI->TheDecl; 15427 15428 if (BSI->HasImplicitReturnType) 15429 deduceClosureReturnType(*BSI); 15430 15431 QualType RetTy = Context.VoidTy; 15432 if (!BSI->ReturnType.isNull()) 15433 RetTy = BSI->ReturnType; 15434 15435 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 15436 QualType BlockTy; 15437 15438 // If the user wrote a function type in some form, try to use that. 15439 if (!BSI->FunctionType.isNull()) { 15440 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 15441 15442 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 15443 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 15444 15445 // Turn protoless block types into nullary block types. 15446 if (isa<FunctionNoProtoType>(FTy)) { 15447 FunctionProtoType::ExtProtoInfo EPI; 15448 EPI.ExtInfo = Ext; 15449 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15450 15451 // Otherwise, if we don't need to change anything about the function type, 15452 // preserve its sugar structure. 15453 } else if (FTy->getReturnType() == RetTy && 15454 (!NoReturn || FTy->getNoReturnAttr())) { 15455 BlockTy = BSI->FunctionType; 15456 15457 // Otherwise, make the minimal modifications to the function type. 15458 } else { 15459 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 15460 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 15461 EPI.TypeQuals = Qualifiers(); 15462 EPI.ExtInfo = Ext; 15463 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 15464 } 15465 15466 // If we don't have a function type, just build one from nothing. 15467 } else { 15468 FunctionProtoType::ExtProtoInfo EPI; 15469 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 15470 BlockTy = Context.getFunctionType(RetTy, None, EPI); 15471 } 15472 15473 DiagnoseUnusedParameters(BD->parameters()); 15474 BlockTy = Context.getBlockPointerType(BlockTy); 15475 15476 // If needed, diagnose invalid gotos and switches in the block. 15477 if (getCurFunction()->NeedsScopeChecking() && 15478 !PP.isCodeCompletionEnabled()) 15479 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 15480 15481 BD->setBody(cast<CompoundStmt>(Body)); 15482 15483 // wait to diagnose unused but set parameters until after setBody 15484 DiagnoseUnusedButSetParameters(BD->parameters()); 15485 15486 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 15487 DiagnoseUnguardedAvailabilityViolations(BD); 15488 15489 // Try to apply the named return value optimization. We have to check again 15490 // if we can do this, though, because blocks keep return statements around 15491 // to deduce an implicit return type. 15492 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 15493 !BD->isDependentContext()) 15494 computeNRVO(Body, BSI); 15495 15496 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 15497 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 15498 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 15499 NTCUK_Destruct|NTCUK_Copy); 15500 15501 PopDeclContext(); 15502 15503 // Set the captured variables on the block. 15504 SmallVector<BlockDecl::Capture, 4> Captures; 15505 for (Capture &Cap : BSI->Captures) { 15506 if (Cap.isInvalid() || Cap.isThisCapture()) 15507 continue; 15508 15509 VarDecl *Var = Cap.getVariable(); 15510 Expr *CopyExpr = nullptr; 15511 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 15512 if (const RecordType *Record = 15513 Cap.getCaptureType()->getAs<RecordType>()) { 15514 // The capture logic needs the destructor, so make sure we mark it. 15515 // Usually this is unnecessary because most local variables have 15516 // their destructors marked at declaration time, but parameters are 15517 // an exception because it's technically only the call site that 15518 // actually requires the destructor. 15519 if (isa<ParmVarDecl>(Var)) 15520 FinalizeVarWithDestructor(Var, Record); 15521 15522 // Enter a separate potentially-evaluated context while building block 15523 // initializers to isolate their cleanups from those of the block 15524 // itself. 15525 // FIXME: Is this appropriate even when the block itself occurs in an 15526 // unevaluated operand? 15527 EnterExpressionEvaluationContext EvalContext( 15528 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15529 15530 SourceLocation Loc = Cap.getLocation(); 15531 15532 ExprResult Result = BuildDeclarationNameExpr( 15533 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 15534 15535 // According to the blocks spec, the capture of a variable from 15536 // the stack requires a const copy constructor. This is not true 15537 // of the copy/move done to move a __block variable to the heap. 15538 if (!Result.isInvalid() && 15539 !Result.get()->getType().isConstQualified()) { 15540 Result = ImpCastExprToType(Result.get(), 15541 Result.get()->getType().withConst(), 15542 CK_NoOp, VK_LValue); 15543 } 15544 15545 if (!Result.isInvalid()) { 15546 Result = PerformCopyInitialization( 15547 InitializedEntity::InitializeBlock(Var->getLocation(), 15548 Cap.getCaptureType(), false), 15549 Loc, Result.get()); 15550 } 15551 15552 // Build a full-expression copy expression if initialization 15553 // succeeded and used a non-trivial constructor. Recover from 15554 // errors by pretending that the copy isn't necessary. 15555 if (!Result.isInvalid() && 15556 !cast<CXXConstructExpr>(Result.get())->getConstructor() 15557 ->isTrivial()) { 15558 Result = MaybeCreateExprWithCleanups(Result); 15559 CopyExpr = Result.get(); 15560 } 15561 } 15562 } 15563 15564 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 15565 CopyExpr); 15566 Captures.push_back(NewCap); 15567 } 15568 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 15569 15570 // Pop the block scope now but keep it alive to the end of this function. 15571 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15572 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 15573 15574 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 15575 15576 // If the block isn't obviously global, i.e. it captures anything at 15577 // all, then we need to do a few things in the surrounding context: 15578 if (Result->getBlockDecl()->hasCaptures()) { 15579 // First, this expression has a new cleanup object. 15580 ExprCleanupObjects.push_back(Result->getBlockDecl()); 15581 Cleanup.setExprNeedsCleanups(true); 15582 15583 // It also gets a branch-protected scope if any of the captured 15584 // variables needs destruction. 15585 for (const auto &CI : Result->getBlockDecl()->captures()) { 15586 const VarDecl *var = CI.getVariable(); 15587 if (var->getType().isDestructedType() != QualType::DK_none) { 15588 setFunctionHasBranchProtectedScope(); 15589 break; 15590 } 15591 } 15592 } 15593 15594 if (getCurFunction()) 15595 getCurFunction()->addBlock(BD); 15596 15597 return Result; 15598 } 15599 15600 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 15601 SourceLocation RPLoc) { 15602 TypeSourceInfo *TInfo; 15603 GetTypeFromParser(Ty, &TInfo); 15604 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 15605 } 15606 15607 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 15608 Expr *E, TypeSourceInfo *TInfo, 15609 SourceLocation RPLoc) { 15610 Expr *OrigExpr = E; 15611 bool IsMS = false; 15612 15613 // CUDA device code does not support varargs. 15614 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 15615 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 15616 CUDAFunctionTarget T = IdentifyCUDATarget(F); 15617 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 15618 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 15619 } 15620 } 15621 15622 // NVPTX does not support va_arg expression. 15623 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 15624 Context.getTargetInfo().getTriple().isNVPTX()) 15625 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 15626 15627 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 15628 // as Microsoft ABI on an actual Microsoft platform, where 15629 // __builtin_ms_va_list and __builtin_va_list are the same.) 15630 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 15631 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 15632 QualType MSVaListType = Context.getBuiltinMSVaListType(); 15633 if (Context.hasSameType(MSVaListType, E->getType())) { 15634 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15635 return ExprError(); 15636 IsMS = true; 15637 } 15638 } 15639 15640 // Get the va_list type 15641 QualType VaListType = Context.getBuiltinVaListType(); 15642 if (!IsMS) { 15643 if (VaListType->isArrayType()) { 15644 // Deal with implicit array decay; for example, on x86-64, 15645 // va_list is an array, but it's supposed to decay to 15646 // a pointer for va_arg. 15647 VaListType = Context.getArrayDecayedType(VaListType); 15648 // Make sure the input expression also decays appropriately. 15649 ExprResult Result = UsualUnaryConversions(E); 15650 if (Result.isInvalid()) 15651 return ExprError(); 15652 E = Result.get(); 15653 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 15654 // If va_list is a record type and we are compiling in C++ mode, 15655 // check the argument using reference binding. 15656 InitializedEntity Entity = InitializedEntity::InitializeParameter( 15657 Context, Context.getLValueReferenceType(VaListType), false); 15658 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 15659 if (Init.isInvalid()) 15660 return ExprError(); 15661 E = Init.getAs<Expr>(); 15662 } else { 15663 // Otherwise, the va_list argument must be an l-value because 15664 // it is modified by va_arg. 15665 if (!E->isTypeDependent() && 15666 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 15667 return ExprError(); 15668 } 15669 } 15670 15671 if (!IsMS && !E->isTypeDependent() && 15672 !Context.hasSameType(VaListType, E->getType())) 15673 return ExprError( 15674 Diag(E->getBeginLoc(), 15675 diag::err_first_argument_to_va_arg_not_of_type_va_list) 15676 << OrigExpr->getType() << E->getSourceRange()); 15677 15678 if (!TInfo->getType()->isDependentType()) { 15679 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 15680 diag::err_second_parameter_to_va_arg_incomplete, 15681 TInfo->getTypeLoc())) 15682 return ExprError(); 15683 15684 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 15685 TInfo->getType(), 15686 diag::err_second_parameter_to_va_arg_abstract, 15687 TInfo->getTypeLoc())) 15688 return ExprError(); 15689 15690 if (!TInfo->getType().isPODType(Context)) { 15691 Diag(TInfo->getTypeLoc().getBeginLoc(), 15692 TInfo->getType()->isObjCLifetimeType() 15693 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 15694 : diag::warn_second_parameter_to_va_arg_not_pod) 15695 << TInfo->getType() 15696 << TInfo->getTypeLoc().getSourceRange(); 15697 } 15698 15699 // Check for va_arg where arguments of the given type will be promoted 15700 // (i.e. this va_arg is guaranteed to have undefined behavior). 15701 QualType PromoteType; 15702 if (TInfo->getType()->isPromotableIntegerType()) { 15703 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 15704 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 15705 PromoteType = QualType(); 15706 } 15707 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 15708 PromoteType = Context.DoubleTy; 15709 if (!PromoteType.isNull()) 15710 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 15711 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 15712 << TInfo->getType() 15713 << PromoteType 15714 << TInfo->getTypeLoc().getSourceRange()); 15715 } 15716 15717 QualType T = TInfo->getType().getNonLValueExprType(Context); 15718 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 15719 } 15720 15721 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 15722 // The type of __null will be int or long, depending on the size of 15723 // pointers on the target. 15724 QualType Ty; 15725 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 15726 if (pw == Context.getTargetInfo().getIntWidth()) 15727 Ty = Context.IntTy; 15728 else if (pw == Context.getTargetInfo().getLongWidth()) 15729 Ty = Context.LongTy; 15730 else if (pw == Context.getTargetInfo().getLongLongWidth()) 15731 Ty = Context.LongLongTy; 15732 else { 15733 llvm_unreachable("I don't know size of pointer!"); 15734 } 15735 15736 return new (Context) GNUNullExpr(Ty, TokenLoc); 15737 } 15738 15739 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 15740 SourceLocation BuiltinLoc, 15741 SourceLocation RPLoc) { 15742 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext); 15743 } 15744 15745 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 15746 SourceLocation BuiltinLoc, 15747 SourceLocation RPLoc, 15748 DeclContext *ParentContext) { 15749 return new (Context) 15750 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext); 15751 } 15752 15753 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 15754 bool Diagnose) { 15755 if (!getLangOpts().ObjC) 15756 return false; 15757 15758 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 15759 if (!PT) 15760 return false; 15761 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 15762 15763 // Ignore any parens, implicit casts (should only be 15764 // array-to-pointer decays), and not-so-opaque values. The last is 15765 // important for making this trigger for property assignments. 15766 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 15767 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 15768 if (OV->getSourceExpr()) 15769 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 15770 15771 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 15772 if (!PT->isObjCIdType() && 15773 !(ID && ID->getIdentifier()->isStr("NSString"))) 15774 return false; 15775 if (!SL->isAscii()) 15776 return false; 15777 15778 if (Diagnose) { 15779 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 15780 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 15781 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 15782 } 15783 return true; 15784 } 15785 15786 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 15787 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 15788 isa<CXXBoolLiteralExpr>(SrcExpr)) && 15789 !SrcExpr->isNullPointerConstant( 15790 getASTContext(), Expr::NPC_NeverValueDependent)) { 15791 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 15792 return false; 15793 if (Diagnose) { 15794 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 15795 << /*number*/1 15796 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 15797 Expr *NumLit = 15798 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 15799 if (NumLit) 15800 Exp = NumLit; 15801 } 15802 return true; 15803 } 15804 15805 return false; 15806 } 15807 15808 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 15809 const Expr *SrcExpr) { 15810 if (!DstType->isFunctionPointerType() || 15811 !SrcExpr->getType()->isFunctionType()) 15812 return false; 15813 15814 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 15815 if (!DRE) 15816 return false; 15817 15818 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 15819 if (!FD) 15820 return false; 15821 15822 return !S.checkAddressOfFunctionIsAvailable(FD, 15823 /*Complain=*/true, 15824 SrcExpr->getBeginLoc()); 15825 } 15826 15827 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 15828 SourceLocation Loc, 15829 QualType DstType, QualType SrcType, 15830 Expr *SrcExpr, AssignmentAction Action, 15831 bool *Complained) { 15832 if (Complained) 15833 *Complained = false; 15834 15835 // Decode the result (notice that AST's are still created for extensions). 15836 bool CheckInferredResultType = false; 15837 bool isInvalid = false; 15838 unsigned DiagKind = 0; 15839 ConversionFixItGenerator ConvHints; 15840 bool MayHaveConvFixit = false; 15841 bool MayHaveFunctionDiff = false; 15842 const ObjCInterfaceDecl *IFace = nullptr; 15843 const ObjCProtocolDecl *PDecl = nullptr; 15844 15845 switch (ConvTy) { 15846 case Compatible: 15847 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 15848 return false; 15849 15850 case PointerToInt: 15851 if (getLangOpts().CPlusPlus) { 15852 DiagKind = diag::err_typecheck_convert_pointer_int; 15853 isInvalid = true; 15854 } else { 15855 DiagKind = diag::ext_typecheck_convert_pointer_int; 15856 } 15857 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15858 MayHaveConvFixit = true; 15859 break; 15860 case IntToPointer: 15861 if (getLangOpts().CPlusPlus) { 15862 DiagKind = diag::err_typecheck_convert_int_pointer; 15863 isInvalid = true; 15864 } else { 15865 DiagKind = diag::ext_typecheck_convert_int_pointer; 15866 } 15867 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15868 MayHaveConvFixit = true; 15869 break; 15870 case IncompatibleFunctionPointer: 15871 if (getLangOpts().CPlusPlus) { 15872 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 15873 isInvalid = true; 15874 } else { 15875 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 15876 } 15877 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15878 MayHaveConvFixit = true; 15879 break; 15880 case IncompatiblePointer: 15881 if (Action == AA_Passing_CFAudited) { 15882 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 15883 } else if (getLangOpts().CPlusPlus) { 15884 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 15885 isInvalid = true; 15886 } else { 15887 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 15888 } 15889 CheckInferredResultType = DstType->isObjCObjectPointerType() && 15890 SrcType->isObjCObjectPointerType(); 15891 if (!CheckInferredResultType) { 15892 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 15893 } else if (CheckInferredResultType) { 15894 SrcType = SrcType.getUnqualifiedType(); 15895 DstType = DstType.getUnqualifiedType(); 15896 } 15897 MayHaveConvFixit = true; 15898 break; 15899 case IncompatiblePointerSign: 15900 if (getLangOpts().CPlusPlus) { 15901 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 15902 isInvalid = true; 15903 } else { 15904 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 15905 } 15906 break; 15907 case FunctionVoidPointer: 15908 if (getLangOpts().CPlusPlus) { 15909 DiagKind = diag::err_typecheck_convert_pointer_void_func; 15910 isInvalid = true; 15911 } else { 15912 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 15913 } 15914 break; 15915 case IncompatiblePointerDiscardsQualifiers: { 15916 // Perform array-to-pointer decay if necessary. 15917 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 15918 15919 isInvalid = true; 15920 15921 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 15922 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 15923 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 15924 DiagKind = diag::err_typecheck_incompatible_address_space; 15925 break; 15926 15927 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 15928 DiagKind = diag::err_typecheck_incompatible_ownership; 15929 break; 15930 } 15931 15932 llvm_unreachable("unknown error case for discarding qualifiers!"); 15933 // fallthrough 15934 } 15935 case CompatiblePointerDiscardsQualifiers: 15936 // If the qualifiers lost were because we were applying the 15937 // (deprecated) C++ conversion from a string literal to a char* 15938 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 15939 // Ideally, this check would be performed in 15940 // checkPointerTypesForAssignment. However, that would require a 15941 // bit of refactoring (so that the second argument is an 15942 // expression, rather than a type), which should be done as part 15943 // of a larger effort to fix checkPointerTypesForAssignment for 15944 // C++ semantics. 15945 if (getLangOpts().CPlusPlus && 15946 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 15947 return false; 15948 if (getLangOpts().CPlusPlus) { 15949 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 15950 isInvalid = true; 15951 } else { 15952 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 15953 } 15954 15955 break; 15956 case IncompatibleNestedPointerQualifiers: 15957 if (getLangOpts().CPlusPlus) { 15958 isInvalid = true; 15959 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 15960 } else { 15961 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 15962 } 15963 break; 15964 case IncompatibleNestedPointerAddressSpaceMismatch: 15965 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 15966 isInvalid = true; 15967 break; 15968 case IntToBlockPointer: 15969 DiagKind = diag::err_int_to_block_pointer; 15970 isInvalid = true; 15971 break; 15972 case IncompatibleBlockPointer: 15973 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 15974 isInvalid = true; 15975 break; 15976 case IncompatibleObjCQualifiedId: { 15977 if (SrcType->isObjCQualifiedIdType()) { 15978 const ObjCObjectPointerType *srcOPT = 15979 SrcType->castAs<ObjCObjectPointerType>(); 15980 for (auto *srcProto : srcOPT->quals()) { 15981 PDecl = srcProto; 15982 break; 15983 } 15984 if (const ObjCInterfaceType *IFaceT = 15985 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15986 IFace = IFaceT->getDecl(); 15987 } 15988 else if (DstType->isObjCQualifiedIdType()) { 15989 const ObjCObjectPointerType *dstOPT = 15990 DstType->castAs<ObjCObjectPointerType>(); 15991 for (auto *dstProto : dstOPT->quals()) { 15992 PDecl = dstProto; 15993 break; 15994 } 15995 if (const ObjCInterfaceType *IFaceT = 15996 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 15997 IFace = IFaceT->getDecl(); 15998 } 15999 if (getLangOpts().CPlusPlus) { 16000 DiagKind = diag::err_incompatible_qualified_id; 16001 isInvalid = true; 16002 } else { 16003 DiagKind = diag::warn_incompatible_qualified_id; 16004 } 16005 break; 16006 } 16007 case IncompatibleVectors: 16008 if (getLangOpts().CPlusPlus) { 16009 DiagKind = diag::err_incompatible_vectors; 16010 isInvalid = true; 16011 } else { 16012 DiagKind = diag::warn_incompatible_vectors; 16013 } 16014 break; 16015 case IncompatibleObjCWeakRef: 16016 DiagKind = diag::err_arc_weak_unavailable_assign; 16017 isInvalid = true; 16018 break; 16019 case Incompatible: 16020 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 16021 if (Complained) 16022 *Complained = true; 16023 return true; 16024 } 16025 16026 DiagKind = diag::err_typecheck_convert_incompatible; 16027 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 16028 MayHaveConvFixit = true; 16029 isInvalid = true; 16030 MayHaveFunctionDiff = true; 16031 break; 16032 } 16033 16034 QualType FirstType, SecondType; 16035 switch (Action) { 16036 case AA_Assigning: 16037 case AA_Initializing: 16038 // The destination type comes first. 16039 FirstType = DstType; 16040 SecondType = SrcType; 16041 break; 16042 16043 case AA_Returning: 16044 case AA_Passing: 16045 case AA_Passing_CFAudited: 16046 case AA_Converting: 16047 case AA_Sending: 16048 case AA_Casting: 16049 // The source type comes first. 16050 FirstType = SrcType; 16051 SecondType = DstType; 16052 break; 16053 } 16054 16055 PartialDiagnostic FDiag = PDiag(DiagKind); 16056 if (Action == AA_Passing_CFAudited) 16057 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 16058 else 16059 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 16060 16061 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 16062 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 16063 auto isPlainChar = [](const clang::Type *Type) { 16064 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 16065 Type->isSpecificBuiltinType(BuiltinType::Char_U); 16066 }; 16067 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 16068 isPlainChar(SecondType->getPointeeOrArrayElementType())); 16069 } 16070 16071 // If we can fix the conversion, suggest the FixIts. 16072 if (!ConvHints.isNull()) { 16073 for (FixItHint &H : ConvHints.Hints) 16074 FDiag << H; 16075 } 16076 16077 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 16078 16079 if (MayHaveFunctionDiff) 16080 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 16081 16082 Diag(Loc, FDiag); 16083 if ((DiagKind == diag::warn_incompatible_qualified_id || 16084 DiagKind == diag::err_incompatible_qualified_id) && 16085 PDecl && IFace && !IFace->hasDefinition()) 16086 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 16087 << IFace << PDecl; 16088 16089 if (SecondType == Context.OverloadTy) 16090 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 16091 FirstType, /*TakingAddress=*/true); 16092 16093 if (CheckInferredResultType) 16094 EmitRelatedResultTypeNote(SrcExpr); 16095 16096 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 16097 EmitRelatedResultTypeNoteForReturn(DstType); 16098 16099 if (Complained) 16100 *Complained = true; 16101 return isInvalid; 16102 } 16103 16104 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16105 llvm::APSInt *Result, 16106 AllowFoldKind CanFold) { 16107 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 16108 public: 16109 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 16110 QualType T) override { 16111 return S.Diag(Loc, diag::err_ice_not_integral) 16112 << T << S.LangOpts.CPlusPlus; 16113 } 16114 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16115 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 16116 } 16117 } Diagnoser; 16118 16119 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16120 } 16121 16122 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 16123 llvm::APSInt *Result, 16124 unsigned DiagID, 16125 AllowFoldKind CanFold) { 16126 class IDDiagnoser : public VerifyICEDiagnoser { 16127 unsigned DiagID; 16128 16129 public: 16130 IDDiagnoser(unsigned DiagID) 16131 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 16132 16133 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 16134 return S.Diag(Loc, DiagID); 16135 } 16136 } Diagnoser(DiagID); 16137 16138 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 16139 } 16140 16141 Sema::SemaDiagnosticBuilder 16142 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 16143 QualType T) { 16144 return diagnoseNotICE(S, Loc); 16145 } 16146 16147 Sema::SemaDiagnosticBuilder 16148 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 16149 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 16150 } 16151 16152 ExprResult 16153 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 16154 VerifyICEDiagnoser &Diagnoser, 16155 AllowFoldKind CanFold) { 16156 SourceLocation DiagLoc = E->getBeginLoc(); 16157 16158 if (getLangOpts().CPlusPlus11) { 16159 // C++11 [expr.const]p5: 16160 // If an expression of literal class type is used in a context where an 16161 // integral constant expression is required, then that class type shall 16162 // have a single non-explicit conversion function to an integral or 16163 // unscoped enumeration type 16164 ExprResult Converted; 16165 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 16166 VerifyICEDiagnoser &BaseDiagnoser; 16167 public: 16168 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 16169 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 16170 BaseDiagnoser.Suppress, true), 16171 BaseDiagnoser(BaseDiagnoser) {} 16172 16173 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 16174 QualType T) override { 16175 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 16176 } 16177 16178 SemaDiagnosticBuilder diagnoseIncomplete( 16179 Sema &S, SourceLocation Loc, QualType T) override { 16180 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 16181 } 16182 16183 SemaDiagnosticBuilder diagnoseExplicitConv( 16184 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16185 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 16186 } 16187 16188 SemaDiagnosticBuilder noteExplicitConv( 16189 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16190 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16191 << ConvTy->isEnumeralType() << ConvTy; 16192 } 16193 16194 SemaDiagnosticBuilder diagnoseAmbiguous( 16195 Sema &S, SourceLocation Loc, QualType T) override { 16196 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 16197 } 16198 16199 SemaDiagnosticBuilder noteAmbiguous( 16200 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 16201 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 16202 << ConvTy->isEnumeralType() << ConvTy; 16203 } 16204 16205 SemaDiagnosticBuilder diagnoseConversion( 16206 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 16207 llvm_unreachable("conversion functions are permitted"); 16208 } 16209 } ConvertDiagnoser(Diagnoser); 16210 16211 Converted = PerformContextualImplicitConversion(DiagLoc, E, 16212 ConvertDiagnoser); 16213 if (Converted.isInvalid()) 16214 return Converted; 16215 E = Converted.get(); 16216 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 16217 return ExprError(); 16218 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 16219 // An ICE must be of integral or unscoped enumeration type. 16220 if (!Diagnoser.Suppress) 16221 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 16222 << E->getSourceRange(); 16223 return ExprError(); 16224 } 16225 16226 ExprResult RValueExpr = DefaultLvalueConversion(E); 16227 if (RValueExpr.isInvalid()) 16228 return ExprError(); 16229 16230 E = RValueExpr.get(); 16231 16232 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 16233 // in the non-ICE case. 16234 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 16235 if (Result) 16236 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 16237 if (!isa<ConstantExpr>(E)) 16238 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 16239 : ConstantExpr::Create(Context, E); 16240 return E; 16241 } 16242 16243 Expr::EvalResult EvalResult; 16244 SmallVector<PartialDiagnosticAt, 8> Notes; 16245 EvalResult.Diag = &Notes; 16246 16247 // Try to evaluate the expression, and produce diagnostics explaining why it's 16248 // not a constant expression as a side-effect. 16249 bool Folded = 16250 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 16251 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 16252 16253 if (!isa<ConstantExpr>(E)) 16254 E = ConstantExpr::Create(Context, E, EvalResult.Val); 16255 16256 // In C++11, we can rely on diagnostics being produced for any expression 16257 // which is not a constant expression. If no diagnostics were produced, then 16258 // this is a constant expression. 16259 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 16260 if (Result) 16261 *Result = EvalResult.Val.getInt(); 16262 return E; 16263 } 16264 16265 // If our only note is the usual "invalid subexpression" note, just point 16266 // the caret at its location rather than producing an essentially 16267 // redundant note. 16268 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 16269 diag::note_invalid_subexpr_in_const_expr) { 16270 DiagLoc = Notes[0].first; 16271 Notes.clear(); 16272 } 16273 16274 if (!Folded || !CanFold) { 16275 if (!Diagnoser.Suppress) { 16276 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 16277 for (const PartialDiagnosticAt &Note : Notes) 16278 Diag(Note.first, Note.second); 16279 } 16280 16281 return ExprError(); 16282 } 16283 16284 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 16285 for (const PartialDiagnosticAt &Note : Notes) 16286 Diag(Note.first, Note.second); 16287 16288 if (Result) 16289 *Result = EvalResult.Val.getInt(); 16290 return E; 16291 } 16292 16293 namespace { 16294 // Handle the case where we conclude a expression which we speculatively 16295 // considered to be unevaluated is actually evaluated. 16296 class TransformToPE : public TreeTransform<TransformToPE> { 16297 typedef TreeTransform<TransformToPE> BaseTransform; 16298 16299 public: 16300 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 16301 16302 // Make sure we redo semantic analysis 16303 bool AlwaysRebuild() { return true; } 16304 bool ReplacingOriginal() { return true; } 16305 16306 // We need to special-case DeclRefExprs referring to FieldDecls which 16307 // are not part of a member pointer formation; normal TreeTransforming 16308 // doesn't catch this case because of the way we represent them in the AST. 16309 // FIXME: This is a bit ugly; is it really the best way to handle this 16310 // case? 16311 // 16312 // Error on DeclRefExprs referring to FieldDecls. 16313 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16314 if (isa<FieldDecl>(E->getDecl()) && 16315 !SemaRef.isUnevaluatedContext()) 16316 return SemaRef.Diag(E->getLocation(), 16317 diag::err_invalid_non_static_member_use) 16318 << E->getDecl() << E->getSourceRange(); 16319 16320 return BaseTransform::TransformDeclRefExpr(E); 16321 } 16322 16323 // Exception: filter out member pointer formation 16324 ExprResult TransformUnaryOperator(UnaryOperator *E) { 16325 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 16326 return E; 16327 16328 return BaseTransform::TransformUnaryOperator(E); 16329 } 16330 16331 // The body of a lambda-expression is in a separate expression evaluation 16332 // context so never needs to be transformed. 16333 // FIXME: Ideally we wouldn't transform the closure type either, and would 16334 // just recreate the capture expressions and lambda expression. 16335 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 16336 return SkipLambdaBody(E, Body); 16337 } 16338 }; 16339 } 16340 16341 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 16342 assert(isUnevaluatedContext() && 16343 "Should only transform unevaluated expressions"); 16344 ExprEvalContexts.back().Context = 16345 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 16346 if (isUnevaluatedContext()) 16347 return E; 16348 return TransformToPE(*this).TransformExpr(E); 16349 } 16350 16351 void 16352 Sema::PushExpressionEvaluationContext( 16353 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 16354 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16355 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 16356 LambdaContextDecl, ExprContext); 16357 Cleanup.reset(); 16358 if (!MaybeODRUseExprs.empty()) 16359 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 16360 } 16361 16362 void 16363 Sema::PushExpressionEvaluationContext( 16364 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 16365 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 16366 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 16367 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 16368 } 16369 16370 namespace { 16371 16372 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 16373 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 16374 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 16375 if (E->getOpcode() == UO_Deref) 16376 return CheckPossibleDeref(S, E->getSubExpr()); 16377 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 16378 return CheckPossibleDeref(S, E->getBase()); 16379 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 16380 return CheckPossibleDeref(S, E->getBase()); 16381 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 16382 QualType Inner; 16383 QualType Ty = E->getType(); 16384 if (const auto *Ptr = Ty->getAs<PointerType>()) 16385 Inner = Ptr->getPointeeType(); 16386 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 16387 Inner = Arr->getElementType(); 16388 else 16389 return nullptr; 16390 16391 if (Inner->hasAttr(attr::NoDeref)) 16392 return E; 16393 } 16394 return nullptr; 16395 } 16396 16397 } // namespace 16398 16399 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 16400 for (const Expr *E : Rec.PossibleDerefs) { 16401 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 16402 if (DeclRef) { 16403 const ValueDecl *Decl = DeclRef->getDecl(); 16404 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 16405 << Decl->getName() << E->getSourceRange(); 16406 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 16407 } else { 16408 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 16409 << E->getSourceRange(); 16410 } 16411 } 16412 Rec.PossibleDerefs.clear(); 16413 } 16414 16415 /// Check whether E, which is either a discarded-value expression or an 16416 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 16417 /// and if so, remove it from the list of volatile-qualified assignments that 16418 /// we are going to warn are deprecated. 16419 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 16420 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 16421 return; 16422 16423 // Note: ignoring parens here is not justified by the standard rules, but 16424 // ignoring parentheses seems like a more reasonable approach, and this only 16425 // drives a deprecation warning so doesn't affect conformance. 16426 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 16427 if (BO->getOpcode() == BO_Assign) { 16428 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 16429 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()), 16430 LHSs.end()); 16431 } 16432 } 16433 } 16434 16435 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 16436 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() || 16437 RebuildingImmediateInvocation) 16438 return E; 16439 16440 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 16441 /// It's OK if this fails; we'll also remove this in 16442 /// HandleImmediateInvocations, but catching it here allows us to avoid 16443 /// walking the AST looking for it in simple cases. 16444 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 16445 if (auto *DeclRef = 16446 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 16447 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 16448 16449 E = MaybeCreateExprWithCleanups(E); 16450 16451 ConstantExpr *Res = ConstantExpr::Create( 16452 getASTContext(), E.get(), 16453 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 16454 getASTContext()), 16455 /*IsImmediateInvocation*/ true); 16456 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 16457 return Res; 16458 } 16459 16460 static void EvaluateAndDiagnoseImmediateInvocation( 16461 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 16462 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 16463 Expr::EvalResult Eval; 16464 Eval.Diag = &Notes; 16465 ConstantExpr *CE = Candidate.getPointer(); 16466 bool Result = CE->EvaluateAsConstantExpr( 16467 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 16468 if (!Result || !Notes.empty()) { 16469 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 16470 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 16471 InnerExpr = FunctionalCast->getSubExpr(); 16472 FunctionDecl *FD = nullptr; 16473 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 16474 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 16475 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 16476 FD = Call->getConstructor(); 16477 else 16478 llvm_unreachable("unhandled decl kind"); 16479 assert(FD->isConsteval()); 16480 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 16481 for (auto &Note : Notes) 16482 SemaRef.Diag(Note.first, Note.second); 16483 return; 16484 } 16485 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 16486 } 16487 16488 static void RemoveNestedImmediateInvocation( 16489 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 16490 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 16491 struct ComplexRemove : TreeTransform<ComplexRemove> { 16492 using Base = TreeTransform<ComplexRemove>; 16493 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16494 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 16495 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 16496 CurrentII; 16497 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 16498 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 16499 SmallVector<Sema::ImmediateInvocationCandidate, 16500 4>::reverse_iterator Current) 16501 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 16502 void RemoveImmediateInvocation(ConstantExpr* E) { 16503 auto It = std::find_if(CurrentII, IISet.rend(), 16504 [E](Sema::ImmediateInvocationCandidate Elem) { 16505 return Elem.getPointer() == E; 16506 }); 16507 assert(It != IISet.rend() && 16508 "ConstantExpr marked IsImmediateInvocation should " 16509 "be present"); 16510 It->setInt(1); // Mark as deleted 16511 } 16512 ExprResult TransformConstantExpr(ConstantExpr *E) { 16513 if (!E->isImmediateInvocation()) 16514 return Base::TransformConstantExpr(E); 16515 RemoveImmediateInvocation(E); 16516 return Base::TransformExpr(E->getSubExpr()); 16517 } 16518 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 16519 /// we need to remove its DeclRefExpr from the DRSet. 16520 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 16521 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 16522 return Base::TransformCXXOperatorCallExpr(E); 16523 } 16524 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 16525 /// here. 16526 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 16527 if (!Init) 16528 return Init; 16529 /// ConstantExpr are the first layer of implicit node to be removed so if 16530 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 16531 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 16532 if (CE->isImmediateInvocation()) 16533 RemoveImmediateInvocation(CE); 16534 return Base::TransformInitializer(Init, NotCopyInit); 16535 } 16536 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 16537 DRSet.erase(E); 16538 return E; 16539 } 16540 bool AlwaysRebuild() { return false; } 16541 bool ReplacingOriginal() { return true; } 16542 bool AllowSkippingCXXConstructExpr() { 16543 bool Res = AllowSkippingFirstCXXConstructExpr; 16544 AllowSkippingFirstCXXConstructExpr = true; 16545 return Res; 16546 } 16547 bool AllowSkippingFirstCXXConstructExpr = true; 16548 } Transformer(SemaRef, Rec.ReferenceToConsteval, 16549 Rec.ImmediateInvocationCandidates, It); 16550 16551 /// CXXConstructExpr with a single argument are getting skipped by 16552 /// TreeTransform in some situtation because they could be implicit. This 16553 /// can only occur for the top-level CXXConstructExpr because it is used 16554 /// nowhere in the expression being transformed therefore will not be rebuilt. 16555 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 16556 /// skipping the first CXXConstructExpr. 16557 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 16558 Transformer.AllowSkippingFirstCXXConstructExpr = false; 16559 16560 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 16561 assert(Res.isUsable()); 16562 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 16563 It->getPointer()->setSubExpr(Res.get()); 16564 } 16565 16566 static void 16567 HandleImmediateInvocations(Sema &SemaRef, 16568 Sema::ExpressionEvaluationContextRecord &Rec) { 16569 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 16570 Rec.ReferenceToConsteval.size() == 0) || 16571 SemaRef.RebuildingImmediateInvocation) 16572 return; 16573 16574 /// When we have more then 1 ImmediateInvocationCandidates we need to check 16575 /// for nested ImmediateInvocationCandidates. when we have only 1 we only 16576 /// need to remove ReferenceToConsteval in the immediate invocation. 16577 if (Rec.ImmediateInvocationCandidates.size() > 1) { 16578 16579 /// Prevent sema calls during the tree transform from adding pointers that 16580 /// are already in the sets. 16581 llvm::SaveAndRestore<bool> DisableIITracking( 16582 SemaRef.RebuildingImmediateInvocation, true); 16583 16584 /// Prevent diagnostic during tree transfrom as they are duplicates 16585 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 16586 16587 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 16588 It != Rec.ImmediateInvocationCandidates.rend(); It++) 16589 if (!It->getInt()) 16590 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 16591 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 16592 Rec.ReferenceToConsteval.size()) { 16593 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 16594 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 16595 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 16596 bool VisitDeclRefExpr(DeclRefExpr *E) { 16597 DRSet.erase(E); 16598 return DRSet.size(); 16599 } 16600 } Visitor(Rec.ReferenceToConsteval); 16601 Visitor.TraverseStmt( 16602 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 16603 } 16604 for (auto CE : Rec.ImmediateInvocationCandidates) 16605 if (!CE.getInt()) 16606 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 16607 for (auto DR : Rec.ReferenceToConsteval) { 16608 auto *FD = cast<FunctionDecl>(DR->getDecl()); 16609 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 16610 << FD; 16611 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 16612 } 16613 } 16614 16615 void Sema::PopExpressionEvaluationContext() { 16616 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 16617 unsigned NumTypos = Rec.NumTypos; 16618 16619 if (!Rec.Lambdas.empty()) { 16620 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 16621 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 16622 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 16623 unsigned D; 16624 if (Rec.isUnevaluated()) { 16625 // C++11 [expr.prim.lambda]p2: 16626 // A lambda-expression shall not appear in an unevaluated operand 16627 // (Clause 5). 16628 D = diag::err_lambda_unevaluated_operand; 16629 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 16630 // C++1y [expr.const]p2: 16631 // A conditional-expression e is a core constant expression unless the 16632 // evaluation of e, following the rules of the abstract machine, would 16633 // evaluate [...] a lambda-expression. 16634 D = diag::err_lambda_in_constant_expression; 16635 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 16636 // C++17 [expr.prim.lamda]p2: 16637 // A lambda-expression shall not appear [...] in a template-argument. 16638 D = diag::err_lambda_in_invalid_context; 16639 } else 16640 llvm_unreachable("Couldn't infer lambda error message."); 16641 16642 for (const auto *L : Rec.Lambdas) 16643 Diag(L->getBeginLoc(), D); 16644 } 16645 } 16646 16647 WarnOnPendingNoDerefs(Rec); 16648 HandleImmediateInvocations(*this, Rec); 16649 16650 // Warn on any volatile-qualified simple-assignments that are not discarded- 16651 // value expressions nor unevaluated operands (those cases get removed from 16652 // this list by CheckUnusedVolatileAssignment). 16653 for (auto *BO : Rec.VolatileAssignmentLHSs) 16654 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 16655 << BO->getType(); 16656 16657 // When are coming out of an unevaluated context, clear out any 16658 // temporaries that we may have created as part of the evaluation of 16659 // the expression in that context: they aren't relevant because they 16660 // will never be constructed. 16661 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 16662 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 16663 ExprCleanupObjects.end()); 16664 Cleanup = Rec.ParentCleanup; 16665 CleanupVarDeclMarking(); 16666 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 16667 // Otherwise, merge the contexts together. 16668 } else { 16669 Cleanup.mergeFrom(Rec.ParentCleanup); 16670 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 16671 Rec.SavedMaybeODRUseExprs.end()); 16672 } 16673 16674 // Pop the current expression evaluation context off the stack. 16675 ExprEvalContexts.pop_back(); 16676 16677 // The global expression evaluation context record is never popped. 16678 ExprEvalContexts.back().NumTypos += NumTypos; 16679 } 16680 16681 void Sema::DiscardCleanupsInEvaluationContext() { 16682 ExprCleanupObjects.erase( 16683 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 16684 ExprCleanupObjects.end()); 16685 Cleanup.reset(); 16686 MaybeODRUseExprs.clear(); 16687 } 16688 16689 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 16690 ExprResult Result = CheckPlaceholderExpr(E); 16691 if (Result.isInvalid()) 16692 return ExprError(); 16693 E = Result.get(); 16694 if (!E->getType()->isVariablyModifiedType()) 16695 return E; 16696 return TransformToPotentiallyEvaluated(E); 16697 } 16698 16699 /// Are we in a context that is potentially constant evaluated per C++20 16700 /// [expr.const]p12? 16701 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 16702 /// C++2a [expr.const]p12: 16703 // An expression or conversion is potentially constant evaluated if it is 16704 switch (SemaRef.ExprEvalContexts.back().Context) { 16705 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16706 // -- a manifestly constant-evaluated expression, 16707 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16708 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16709 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16710 // -- a potentially-evaluated expression, 16711 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16712 // -- an immediate subexpression of a braced-init-list, 16713 16714 // -- [FIXME] an expression of the form & cast-expression that occurs 16715 // within a templated entity 16716 // -- a subexpression of one of the above that is not a subexpression of 16717 // a nested unevaluated operand. 16718 return true; 16719 16720 case Sema::ExpressionEvaluationContext::Unevaluated: 16721 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16722 // Expressions in this context are never evaluated. 16723 return false; 16724 } 16725 llvm_unreachable("Invalid context"); 16726 } 16727 16728 /// Return true if this function has a calling convention that requires mangling 16729 /// in the size of the parameter pack. 16730 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 16731 // These manglings don't do anything on non-Windows or non-x86 platforms, so 16732 // we don't need parameter type sizes. 16733 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 16734 if (!TT.isOSWindows() || !TT.isX86()) 16735 return false; 16736 16737 // If this is C++ and this isn't an extern "C" function, parameters do not 16738 // need to be complete. In this case, C++ mangling will apply, which doesn't 16739 // use the size of the parameters. 16740 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 16741 return false; 16742 16743 // Stdcall, fastcall, and vectorcall need this special treatment. 16744 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16745 switch (CC) { 16746 case CC_X86StdCall: 16747 case CC_X86FastCall: 16748 case CC_X86VectorCall: 16749 return true; 16750 default: 16751 break; 16752 } 16753 return false; 16754 } 16755 16756 /// Require that all of the parameter types of function be complete. Normally, 16757 /// parameter types are only required to be complete when a function is called 16758 /// or defined, but to mangle functions with certain calling conventions, the 16759 /// mangler needs to know the size of the parameter list. In this situation, 16760 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 16761 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 16762 /// result in a linker error. Clang doesn't implement this behavior, and instead 16763 /// attempts to error at compile time. 16764 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 16765 SourceLocation Loc) { 16766 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 16767 FunctionDecl *FD; 16768 ParmVarDecl *Param; 16769 16770 public: 16771 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 16772 : FD(FD), Param(Param) {} 16773 16774 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 16775 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 16776 StringRef CCName; 16777 switch (CC) { 16778 case CC_X86StdCall: 16779 CCName = "stdcall"; 16780 break; 16781 case CC_X86FastCall: 16782 CCName = "fastcall"; 16783 break; 16784 case CC_X86VectorCall: 16785 CCName = "vectorcall"; 16786 break; 16787 default: 16788 llvm_unreachable("CC does not need mangling"); 16789 } 16790 16791 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 16792 << Param->getDeclName() << FD->getDeclName() << CCName; 16793 } 16794 }; 16795 16796 for (ParmVarDecl *Param : FD->parameters()) { 16797 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 16798 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 16799 } 16800 } 16801 16802 namespace { 16803 enum class OdrUseContext { 16804 /// Declarations in this context are not odr-used. 16805 None, 16806 /// Declarations in this context are formally odr-used, but this is a 16807 /// dependent context. 16808 Dependent, 16809 /// Declarations in this context are odr-used but not actually used (yet). 16810 FormallyOdrUsed, 16811 /// Declarations in this context are used. 16812 Used 16813 }; 16814 } 16815 16816 /// Are we within a context in which references to resolved functions or to 16817 /// variables result in odr-use? 16818 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 16819 OdrUseContext Result; 16820 16821 switch (SemaRef.ExprEvalContexts.back().Context) { 16822 case Sema::ExpressionEvaluationContext::Unevaluated: 16823 case Sema::ExpressionEvaluationContext::UnevaluatedList: 16824 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 16825 return OdrUseContext::None; 16826 16827 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 16828 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 16829 Result = OdrUseContext::Used; 16830 break; 16831 16832 case Sema::ExpressionEvaluationContext::DiscardedStatement: 16833 Result = OdrUseContext::FormallyOdrUsed; 16834 break; 16835 16836 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 16837 // A default argument formally results in odr-use, but doesn't actually 16838 // result in a use in any real sense until it itself is used. 16839 Result = OdrUseContext::FormallyOdrUsed; 16840 break; 16841 } 16842 16843 if (SemaRef.CurContext->isDependentContext()) 16844 return OdrUseContext::Dependent; 16845 16846 return Result; 16847 } 16848 16849 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 16850 if (!Func->isConstexpr()) 16851 return false; 16852 16853 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 16854 return true; 16855 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 16856 return CCD && CCD->getInheritedConstructor(); 16857 } 16858 16859 /// Mark a function referenced, and check whether it is odr-used 16860 /// (C++ [basic.def.odr]p2, C99 6.9p3) 16861 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 16862 bool MightBeOdrUse) { 16863 assert(Func && "No function?"); 16864 16865 Func->setReferenced(); 16866 16867 // Recursive functions aren't really used until they're used from some other 16868 // context. 16869 bool IsRecursiveCall = CurContext == Func; 16870 16871 // C++11 [basic.def.odr]p3: 16872 // A function whose name appears as a potentially-evaluated expression is 16873 // odr-used if it is the unique lookup result or the selected member of a 16874 // set of overloaded functions [...]. 16875 // 16876 // We (incorrectly) mark overload resolution as an unevaluated context, so we 16877 // can just check that here. 16878 OdrUseContext OdrUse = 16879 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 16880 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 16881 OdrUse = OdrUseContext::FormallyOdrUsed; 16882 16883 // Trivial default constructors and destructors are never actually used. 16884 // FIXME: What about other special members? 16885 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 16886 OdrUse == OdrUseContext::Used) { 16887 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 16888 if (Constructor->isDefaultConstructor()) 16889 OdrUse = OdrUseContext::FormallyOdrUsed; 16890 if (isa<CXXDestructorDecl>(Func)) 16891 OdrUse = OdrUseContext::FormallyOdrUsed; 16892 } 16893 16894 // C++20 [expr.const]p12: 16895 // A function [...] is needed for constant evaluation if it is [...] a 16896 // constexpr function that is named by an expression that is potentially 16897 // constant evaluated 16898 bool NeededForConstantEvaluation = 16899 isPotentiallyConstantEvaluatedContext(*this) && 16900 isImplicitlyDefinableConstexprFunction(Func); 16901 16902 // Determine whether we require a function definition to exist, per 16903 // C++11 [temp.inst]p3: 16904 // Unless a function template specialization has been explicitly 16905 // instantiated or explicitly specialized, the function template 16906 // specialization is implicitly instantiated when the specialization is 16907 // referenced in a context that requires a function definition to exist. 16908 // C++20 [temp.inst]p7: 16909 // The existence of a definition of a [...] function is considered to 16910 // affect the semantics of the program if the [...] function is needed for 16911 // constant evaluation by an expression 16912 // C++20 [basic.def.odr]p10: 16913 // Every program shall contain exactly one definition of every non-inline 16914 // function or variable that is odr-used in that program outside of a 16915 // discarded statement 16916 // C++20 [special]p1: 16917 // The implementation will implicitly define [defaulted special members] 16918 // if they are odr-used or needed for constant evaluation. 16919 // 16920 // Note that we skip the implicit instantiation of templates that are only 16921 // used in unused default arguments or by recursive calls to themselves. 16922 // This is formally non-conforming, but seems reasonable in practice. 16923 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 16924 NeededForConstantEvaluation); 16925 16926 // C++14 [temp.expl.spec]p6: 16927 // If a template [...] is explicitly specialized then that specialization 16928 // shall be declared before the first use of that specialization that would 16929 // cause an implicit instantiation to take place, in every translation unit 16930 // in which such a use occurs 16931 if (NeedDefinition && 16932 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 16933 Func->getMemberSpecializationInfo())) 16934 checkSpecializationVisibility(Loc, Func); 16935 16936 if (getLangOpts().CUDA) 16937 CheckCUDACall(Loc, Func); 16938 16939 if (getLangOpts().SYCLIsDevice) 16940 checkSYCLDeviceFunction(Loc, Func); 16941 16942 // If we need a definition, try to create one. 16943 if (NeedDefinition && !Func->getBody()) { 16944 runWithSufficientStackSpace(Loc, [&] { 16945 if (CXXConstructorDecl *Constructor = 16946 dyn_cast<CXXConstructorDecl>(Func)) { 16947 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 16948 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 16949 if (Constructor->isDefaultConstructor()) { 16950 if (Constructor->isTrivial() && 16951 !Constructor->hasAttr<DLLExportAttr>()) 16952 return; 16953 DefineImplicitDefaultConstructor(Loc, Constructor); 16954 } else if (Constructor->isCopyConstructor()) { 16955 DefineImplicitCopyConstructor(Loc, Constructor); 16956 } else if (Constructor->isMoveConstructor()) { 16957 DefineImplicitMoveConstructor(Loc, Constructor); 16958 } 16959 } else if (Constructor->getInheritedConstructor()) { 16960 DefineInheritingConstructor(Loc, Constructor); 16961 } 16962 } else if (CXXDestructorDecl *Destructor = 16963 dyn_cast<CXXDestructorDecl>(Func)) { 16964 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 16965 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 16966 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 16967 return; 16968 DefineImplicitDestructor(Loc, Destructor); 16969 } 16970 if (Destructor->isVirtual() && getLangOpts().AppleKext) 16971 MarkVTableUsed(Loc, Destructor->getParent()); 16972 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 16973 if (MethodDecl->isOverloadedOperator() && 16974 MethodDecl->getOverloadedOperator() == OO_Equal) { 16975 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 16976 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 16977 if (MethodDecl->isCopyAssignmentOperator()) 16978 DefineImplicitCopyAssignment(Loc, MethodDecl); 16979 else if (MethodDecl->isMoveAssignmentOperator()) 16980 DefineImplicitMoveAssignment(Loc, MethodDecl); 16981 } 16982 } else if (isa<CXXConversionDecl>(MethodDecl) && 16983 MethodDecl->getParent()->isLambda()) { 16984 CXXConversionDecl *Conversion = 16985 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 16986 if (Conversion->isLambdaToBlockPointerConversion()) 16987 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 16988 else 16989 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 16990 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 16991 MarkVTableUsed(Loc, MethodDecl->getParent()); 16992 } 16993 16994 if (Func->isDefaulted() && !Func->isDeleted()) { 16995 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 16996 if (DCK != DefaultedComparisonKind::None) 16997 DefineDefaultedComparison(Loc, Func, DCK); 16998 } 16999 17000 // Implicit instantiation of function templates and member functions of 17001 // class templates. 17002 if (Func->isImplicitlyInstantiable()) { 17003 TemplateSpecializationKind TSK = 17004 Func->getTemplateSpecializationKindForInstantiation(); 17005 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 17006 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 17007 if (FirstInstantiation) { 17008 PointOfInstantiation = Loc; 17009 if (auto *MSI = Func->getMemberSpecializationInfo()) 17010 MSI->setPointOfInstantiation(Loc); 17011 // FIXME: Notify listener. 17012 else 17013 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 17014 } else if (TSK != TSK_ImplicitInstantiation) { 17015 // Use the point of use as the point of instantiation, instead of the 17016 // point of explicit instantiation (which we track as the actual point 17017 // of instantiation). This gives better backtraces in diagnostics. 17018 PointOfInstantiation = Loc; 17019 } 17020 17021 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 17022 Func->isConstexpr()) { 17023 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 17024 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 17025 CodeSynthesisContexts.size()) 17026 PendingLocalImplicitInstantiations.push_back( 17027 std::make_pair(Func, PointOfInstantiation)); 17028 else if (Func->isConstexpr()) 17029 // Do not defer instantiations of constexpr functions, to avoid the 17030 // expression evaluator needing to call back into Sema if it sees a 17031 // call to such a function. 17032 InstantiateFunctionDefinition(PointOfInstantiation, Func); 17033 else { 17034 Func->setInstantiationIsPending(true); 17035 PendingInstantiations.push_back( 17036 std::make_pair(Func, PointOfInstantiation)); 17037 // Notify the consumer that a function was implicitly instantiated. 17038 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 17039 } 17040 } 17041 } else { 17042 // Walk redefinitions, as some of them may be instantiable. 17043 for (auto i : Func->redecls()) { 17044 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 17045 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 17046 } 17047 } 17048 }); 17049 } 17050 17051 // C++14 [except.spec]p17: 17052 // An exception-specification is considered to be needed when: 17053 // - the function is odr-used or, if it appears in an unevaluated operand, 17054 // would be odr-used if the expression were potentially-evaluated; 17055 // 17056 // Note, we do this even if MightBeOdrUse is false. That indicates that the 17057 // function is a pure virtual function we're calling, and in that case the 17058 // function was selected by overload resolution and we need to resolve its 17059 // exception specification for a different reason. 17060 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 17061 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 17062 ResolveExceptionSpec(Loc, FPT); 17063 17064 // If this is the first "real" use, act on that. 17065 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 17066 // Keep track of used but undefined functions. 17067 if (!Func->isDefined()) { 17068 if (mightHaveNonExternalLinkage(Func)) 17069 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17070 else if (Func->getMostRecentDecl()->isInlined() && 17071 !LangOpts.GNUInline && 17072 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 17073 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17074 else if (isExternalWithNoLinkageType(Func)) 17075 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 17076 } 17077 17078 // Some x86 Windows calling conventions mangle the size of the parameter 17079 // pack into the name. Computing the size of the parameters requires the 17080 // parameter types to be complete. Check that now. 17081 if (funcHasParameterSizeMangling(*this, Func)) 17082 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 17083 17084 // In the MS C++ ABI, the compiler emits destructor variants where they are 17085 // used. If the destructor is used here but defined elsewhere, mark the 17086 // virtual base destructors referenced. If those virtual base destructors 17087 // are inline, this will ensure they are defined when emitting the complete 17088 // destructor variant. This checking may be redundant if the destructor is 17089 // provided later in this TU. 17090 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17091 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 17092 CXXRecordDecl *Parent = Dtor->getParent(); 17093 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 17094 CheckCompleteDestructorVariant(Loc, Dtor); 17095 } 17096 } 17097 17098 Func->markUsed(Context); 17099 } 17100 } 17101 17102 /// Directly mark a variable odr-used. Given a choice, prefer to use 17103 /// MarkVariableReferenced since it does additional checks and then 17104 /// calls MarkVarDeclODRUsed. 17105 /// If the variable must be captured: 17106 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 17107 /// - else capture it in the DeclContext that maps to the 17108 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 17109 static void 17110 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, 17111 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 17112 // Keep track of used but undefined variables. 17113 // FIXME: We shouldn't suppress this warning for static data members. 17114 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 17115 (!Var->isExternallyVisible() || Var->isInline() || 17116 SemaRef.isExternalWithNoLinkageType(Var)) && 17117 !(Var->isStaticDataMember() && Var->hasInit())) { 17118 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 17119 if (old.isInvalid()) 17120 old = Loc; 17121 } 17122 QualType CaptureType, DeclRefType; 17123 if (SemaRef.LangOpts.OpenMP) 17124 SemaRef.tryCaptureOpenMPLambdas(Var); 17125 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 17126 /*EllipsisLoc*/ SourceLocation(), 17127 /*BuildAndDiagnose*/ true, 17128 CaptureType, DeclRefType, 17129 FunctionScopeIndexToStopAt); 17130 17131 // Diagnose ODR-use of host global variables in device functions. Reference 17132 // of device global variables in host functions is allowed through shadow 17133 // variables therefore it is not diagnosed. 17134 if (SemaRef.LangOpts.CUDA && SemaRef.LangOpts.CUDAIsDevice) { 17135 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 17136 auto Target = SemaRef.IdentifyCUDATarget(FD); 17137 auto IsEmittedOnDeviceSide = [](VarDecl *Var) { 17138 if (Var->hasAttr<CUDADeviceAttr>() || Var->hasAttr<CUDAConstantAttr>() || 17139 Var->hasAttr<CUDASharedAttr>() || 17140 Var->getType()->isCUDADeviceBuiltinSurfaceType() || 17141 Var->getType()->isCUDADeviceBuiltinTextureType()) 17142 return true; 17143 // Function-scope static variable in device functions or kernels are 17144 // emitted on device side. 17145 if (auto *FD = dyn_cast<FunctionDecl>(Var->getDeclContext())) { 17146 return FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>(); 17147 } 17148 return false; 17149 }; 17150 if (Var && Var->hasGlobalStorage() && !IsEmittedOnDeviceSide(Var)) { 17151 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 17152 << /*host*/ 2 << /*variable*/ 1 << Var << Target; 17153 } 17154 } 17155 17156 Var->markUsed(SemaRef.Context); 17157 } 17158 17159 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture, 17160 SourceLocation Loc, 17161 unsigned CapturingScopeIndex) { 17162 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 17163 } 17164 17165 static void 17166 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 17167 ValueDecl *var, DeclContext *DC) { 17168 DeclContext *VarDC = var->getDeclContext(); 17169 17170 // If the parameter still belongs to the translation unit, then 17171 // we're actually just using one parameter in the declaration of 17172 // the next. 17173 if (isa<ParmVarDecl>(var) && 17174 isa<TranslationUnitDecl>(VarDC)) 17175 return; 17176 17177 // For C code, don't diagnose about capture if we're not actually in code 17178 // right now; it's impossible to write a non-constant expression outside of 17179 // function context, so we'll get other (more useful) diagnostics later. 17180 // 17181 // For C++, things get a bit more nasty... it would be nice to suppress this 17182 // diagnostic for certain cases like using a local variable in an array bound 17183 // for a member of a local class, but the correct predicate is not obvious. 17184 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 17185 return; 17186 17187 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 17188 unsigned ContextKind = 3; // unknown 17189 if (isa<CXXMethodDecl>(VarDC) && 17190 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 17191 ContextKind = 2; 17192 } else if (isa<FunctionDecl>(VarDC)) { 17193 ContextKind = 0; 17194 } else if (isa<BlockDecl>(VarDC)) { 17195 ContextKind = 1; 17196 } 17197 17198 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 17199 << var << ValueKind << ContextKind << VarDC; 17200 S.Diag(var->getLocation(), diag::note_entity_declared_at) 17201 << var; 17202 17203 // FIXME: Add additional diagnostic info about class etc. which prevents 17204 // capture. 17205 } 17206 17207 17208 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 17209 bool &SubCapturesAreNested, 17210 QualType &CaptureType, 17211 QualType &DeclRefType) { 17212 // Check whether we've already captured it. 17213 if (CSI->CaptureMap.count(Var)) { 17214 // If we found a capture, any subcaptures are nested. 17215 SubCapturesAreNested = true; 17216 17217 // Retrieve the capture type for this variable. 17218 CaptureType = CSI->getCapture(Var).getCaptureType(); 17219 17220 // Compute the type of an expression that refers to this variable. 17221 DeclRefType = CaptureType.getNonReferenceType(); 17222 17223 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 17224 // are mutable in the sense that user can change their value - they are 17225 // private instances of the captured declarations. 17226 const Capture &Cap = CSI->getCapture(Var); 17227 if (Cap.isCopyCapture() && 17228 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 17229 !(isa<CapturedRegionScopeInfo>(CSI) && 17230 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 17231 DeclRefType.addConst(); 17232 return true; 17233 } 17234 return false; 17235 } 17236 17237 // Only block literals, captured statements, and lambda expressions can 17238 // capture; other scopes don't work. 17239 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 17240 SourceLocation Loc, 17241 const bool Diagnose, Sema &S) { 17242 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 17243 return getLambdaAwareParentOfDeclContext(DC); 17244 else if (Var->hasLocalStorage()) { 17245 if (Diagnose) 17246 diagnoseUncapturableValueReference(S, Loc, Var, DC); 17247 } 17248 return nullptr; 17249 } 17250 17251 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17252 // certain types of variables (unnamed, variably modified types etc.) 17253 // so check for eligibility. 17254 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 17255 SourceLocation Loc, 17256 const bool Diagnose, Sema &S) { 17257 17258 bool IsBlock = isa<BlockScopeInfo>(CSI); 17259 bool IsLambda = isa<LambdaScopeInfo>(CSI); 17260 17261 // Lambdas are not allowed to capture unnamed variables 17262 // (e.g. anonymous unions). 17263 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 17264 // assuming that's the intent. 17265 if (IsLambda && !Var->getDeclName()) { 17266 if (Diagnose) { 17267 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 17268 S.Diag(Var->getLocation(), diag::note_declared_at); 17269 } 17270 return false; 17271 } 17272 17273 // Prohibit variably-modified types in blocks; they're difficult to deal with. 17274 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 17275 if (Diagnose) { 17276 S.Diag(Loc, diag::err_ref_vm_type); 17277 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17278 } 17279 return false; 17280 } 17281 // Prohibit structs with flexible array members too. 17282 // We cannot capture what is in the tail end of the struct. 17283 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 17284 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 17285 if (Diagnose) { 17286 if (IsBlock) 17287 S.Diag(Loc, diag::err_ref_flexarray_type); 17288 else 17289 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 17290 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17291 } 17292 return false; 17293 } 17294 } 17295 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17296 // Lambdas and captured statements are not allowed to capture __block 17297 // variables; they don't support the expected semantics. 17298 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 17299 if (Diagnose) { 17300 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 17301 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17302 } 17303 return false; 17304 } 17305 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 17306 if (S.getLangOpts().OpenCL && IsBlock && 17307 Var->getType()->isBlockPointerType()) { 17308 if (Diagnose) 17309 S.Diag(Loc, diag::err_opencl_block_ref_block); 17310 return false; 17311 } 17312 17313 return true; 17314 } 17315 17316 // Returns true if the capture by block was successful. 17317 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 17318 SourceLocation Loc, 17319 const bool BuildAndDiagnose, 17320 QualType &CaptureType, 17321 QualType &DeclRefType, 17322 const bool Nested, 17323 Sema &S, bool Invalid) { 17324 bool ByRef = false; 17325 17326 // Blocks are not allowed to capture arrays, excepting OpenCL. 17327 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 17328 // (decayed to pointers). 17329 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 17330 if (BuildAndDiagnose) { 17331 S.Diag(Loc, diag::err_ref_array_type); 17332 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17333 Invalid = true; 17334 } else { 17335 return false; 17336 } 17337 } 17338 17339 // Forbid the block-capture of autoreleasing variables. 17340 if (!Invalid && 17341 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17342 if (BuildAndDiagnose) { 17343 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 17344 << /*block*/ 0; 17345 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17346 Invalid = true; 17347 } else { 17348 return false; 17349 } 17350 } 17351 17352 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 17353 if (const auto *PT = CaptureType->getAs<PointerType>()) { 17354 QualType PointeeTy = PT->getPointeeType(); 17355 17356 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 17357 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 17358 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 17359 if (BuildAndDiagnose) { 17360 SourceLocation VarLoc = Var->getLocation(); 17361 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 17362 S.Diag(VarLoc, diag::note_declare_parameter_strong); 17363 } 17364 } 17365 } 17366 17367 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 17368 if (HasBlocksAttr || CaptureType->isReferenceType() || 17369 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 17370 // Block capture by reference does not change the capture or 17371 // declaration reference types. 17372 ByRef = true; 17373 } else { 17374 // Block capture by copy introduces 'const'. 17375 CaptureType = CaptureType.getNonReferenceType().withConst(); 17376 DeclRefType = CaptureType; 17377 } 17378 17379 // Actually capture the variable. 17380 if (BuildAndDiagnose) 17381 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 17382 CaptureType, Invalid); 17383 17384 return !Invalid; 17385 } 17386 17387 17388 /// Capture the given variable in the captured region. 17389 static bool captureInCapturedRegion( 17390 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc, 17391 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 17392 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 17393 bool IsTopScope, Sema &S, bool Invalid) { 17394 // By default, capture variables by reference. 17395 bool ByRef = true; 17396 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17397 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17398 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 17399 // Using an LValue reference type is consistent with Lambdas (see below). 17400 if (S.isOpenMPCapturedDecl(Var)) { 17401 bool HasConst = DeclRefType.isConstQualified(); 17402 DeclRefType = DeclRefType.getUnqualifiedType(); 17403 // Don't lose diagnostics about assignments to const. 17404 if (HasConst) 17405 DeclRefType.addConst(); 17406 } 17407 // Do not capture firstprivates in tasks. 17408 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 17409 OMPC_unknown) 17410 return true; 17411 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 17412 RSI->OpenMPCaptureLevel); 17413 } 17414 17415 if (ByRef) 17416 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17417 else 17418 CaptureType = DeclRefType; 17419 17420 // Actually capture the variable. 17421 if (BuildAndDiagnose) 17422 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 17423 Loc, SourceLocation(), CaptureType, Invalid); 17424 17425 return !Invalid; 17426 } 17427 17428 /// Capture the given variable in the lambda. 17429 static bool captureInLambda(LambdaScopeInfo *LSI, 17430 VarDecl *Var, 17431 SourceLocation Loc, 17432 const bool BuildAndDiagnose, 17433 QualType &CaptureType, 17434 QualType &DeclRefType, 17435 const bool RefersToCapturedVariable, 17436 const Sema::TryCaptureKind Kind, 17437 SourceLocation EllipsisLoc, 17438 const bool IsTopScope, 17439 Sema &S, bool Invalid) { 17440 // Determine whether we are capturing by reference or by value. 17441 bool ByRef = false; 17442 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 17443 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 17444 } else { 17445 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 17446 } 17447 17448 // Compute the type of the field that will capture this variable. 17449 if (ByRef) { 17450 // C++11 [expr.prim.lambda]p15: 17451 // An entity is captured by reference if it is implicitly or 17452 // explicitly captured but not captured by copy. It is 17453 // unspecified whether additional unnamed non-static data 17454 // members are declared in the closure type for entities 17455 // captured by reference. 17456 // 17457 // FIXME: It is not clear whether we want to build an lvalue reference 17458 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 17459 // to do the former, while EDG does the latter. Core issue 1249 will 17460 // clarify, but for now we follow GCC because it's a more permissive and 17461 // easily defensible position. 17462 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 17463 } else { 17464 // C++11 [expr.prim.lambda]p14: 17465 // For each entity captured by copy, an unnamed non-static 17466 // data member is declared in the closure type. The 17467 // declaration order of these members is unspecified. The type 17468 // of such a data member is the type of the corresponding 17469 // captured entity if the entity is not a reference to an 17470 // object, or the referenced type otherwise. [Note: If the 17471 // captured entity is a reference to a function, the 17472 // corresponding data member is also a reference to a 17473 // function. - end note ] 17474 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 17475 if (!RefType->getPointeeType()->isFunctionType()) 17476 CaptureType = RefType->getPointeeType(); 17477 } 17478 17479 // Forbid the lambda copy-capture of autoreleasing variables. 17480 if (!Invalid && 17481 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 17482 if (BuildAndDiagnose) { 17483 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 17484 S.Diag(Var->getLocation(), diag::note_previous_decl) 17485 << Var->getDeclName(); 17486 Invalid = true; 17487 } else { 17488 return false; 17489 } 17490 } 17491 17492 // Make sure that by-copy captures are of a complete and non-abstract type. 17493 if (!Invalid && BuildAndDiagnose) { 17494 if (!CaptureType->isDependentType() && 17495 S.RequireCompleteSizedType( 17496 Loc, CaptureType, 17497 diag::err_capture_of_incomplete_or_sizeless_type, 17498 Var->getDeclName())) 17499 Invalid = true; 17500 else if (S.RequireNonAbstractType(Loc, CaptureType, 17501 diag::err_capture_of_abstract_type)) 17502 Invalid = true; 17503 } 17504 } 17505 17506 // Compute the type of a reference to this captured variable. 17507 if (ByRef) 17508 DeclRefType = CaptureType.getNonReferenceType(); 17509 else { 17510 // C++ [expr.prim.lambda]p5: 17511 // The closure type for a lambda-expression has a public inline 17512 // function call operator [...]. This function call operator is 17513 // declared const (9.3.1) if and only if the lambda-expression's 17514 // parameter-declaration-clause is not followed by mutable. 17515 DeclRefType = CaptureType.getNonReferenceType(); 17516 if (!LSI->Mutable && !CaptureType->isReferenceType()) 17517 DeclRefType.addConst(); 17518 } 17519 17520 // Add the capture. 17521 if (BuildAndDiagnose) 17522 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 17523 Loc, EllipsisLoc, CaptureType, Invalid); 17524 17525 return !Invalid; 17526 } 17527 17528 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) { 17529 // Offer a Copy fix even if the type is dependent. 17530 if (Var->getType()->isDependentType()) 17531 return true; 17532 QualType T = Var->getType().getNonReferenceType(); 17533 if (T.isTriviallyCopyableType(Context)) 17534 return true; 17535 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 17536 17537 if (!(RD = RD->getDefinition())) 17538 return false; 17539 if (RD->hasSimpleCopyConstructor()) 17540 return true; 17541 if (RD->hasUserDeclaredCopyConstructor()) 17542 for (CXXConstructorDecl *Ctor : RD->ctors()) 17543 if (Ctor->isCopyConstructor()) 17544 return !Ctor->isDeleted(); 17545 } 17546 return false; 17547 } 17548 17549 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 17550 /// default capture. Fixes may be omitted if they aren't allowed by the 17551 /// standard, for example we can't emit a default copy capture fix-it if we 17552 /// already explicitly copy capture capture another variable. 17553 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 17554 VarDecl *Var) { 17555 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 17556 // Don't offer Capture by copy of default capture by copy fixes if Var is 17557 // known not to be copy constructible. 17558 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 17559 17560 SmallString<32> FixBuffer; 17561 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 17562 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 17563 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 17564 if (ShouldOfferCopyFix) { 17565 // Offer fixes to insert an explicit capture for the variable. 17566 // [] -> [VarName] 17567 // [OtherCapture] -> [OtherCapture, VarName] 17568 FixBuffer.assign({Separator, Var->getName()}); 17569 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17570 << Var << /*value*/ 0 17571 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17572 } 17573 // As above but capture by reference. 17574 FixBuffer.assign({Separator, "&", Var->getName()}); 17575 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 17576 << Var << /*reference*/ 1 17577 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 17578 } 17579 17580 // Only try to offer default capture if there are no captures excluding this 17581 // and init captures. 17582 // [this]: OK. 17583 // [X = Y]: OK. 17584 // [&A, &B]: Don't offer. 17585 // [A, B]: Don't offer. 17586 if (llvm::any_of(LSI->Captures, [](Capture &C) { 17587 return !C.isThisCapture() && !C.isInitCapture(); 17588 })) 17589 return; 17590 17591 // The default capture specifiers, '=' or '&', must appear first in the 17592 // capture body. 17593 SourceLocation DefaultInsertLoc = 17594 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 17595 17596 if (ShouldOfferCopyFix) { 17597 bool CanDefaultCopyCapture = true; 17598 // [=, *this] OK since c++17 17599 // [=, this] OK since c++20 17600 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 17601 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 17602 ? LSI->getCXXThisCapture().isCopyCapture() 17603 : false; 17604 // We can't use default capture by copy if any captures already specified 17605 // capture by copy. 17606 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 17607 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 17608 })) { 17609 FixBuffer.assign({"=", Separator}); 17610 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17611 << /*value*/ 0 17612 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17613 } 17614 } 17615 17616 // We can't use default capture by reference if any captures already specified 17617 // capture by reference. 17618 if (llvm::none_of(LSI->Captures, [](Capture &C) { 17619 return !C.isInitCapture() && C.isReferenceCapture() && 17620 !C.isThisCapture(); 17621 })) { 17622 FixBuffer.assign({"&", Separator}); 17623 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 17624 << /*reference*/ 1 17625 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 17626 } 17627 } 17628 17629 bool Sema::tryCaptureVariable( 17630 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 17631 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 17632 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 17633 // An init-capture is notionally from the context surrounding its 17634 // declaration, but its parent DC is the lambda class. 17635 DeclContext *VarDC = Var->getDeclContext(); 17636 if (Var->isInitCapture()) 17637 VarDC = VarDC->getParent(); 17638 17639 DeclContext *DC = CurContext; 17640 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 17641 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 17642 // We need to sync up the Declaration Context with the 17643 // FunctionScopeIndexToStopAt 17644 if (FunctionScopeIndexToStopAt) { 17645 unsigned FSIndex = FunctionScopes.size() - 1; 17646 while (FSIndex != MaxFunctionScopesIndex) { 17647 DC = getLambdaAwareParentOfDeclContext(DC); 17648 --FSIndex; 17649 } 17650 } 17651 17652 17653 // If the variable is declared in the current context, there is no need to 17654 // capture it. 17655 if (VarDC == DC) return true; 17656 17657 // Capture global variables if it is required to use private copy of this 17658 // variable. 17659 bool IsGlobal = !Var->hasLocalStorage(); 17660 if (IsGlobal && 17661 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 17662 MaxFunctionScopesIndex))) 17663 return true; 17664 Var = Var->getCanonicalDecl(); 17665 17666 // Walk up the stack to determine whether we can capture the variable, 17667 // performing the "simple" checks that don't depend on type. We stop when 17668 // we've either hit the declared scope of the variable or find an existing 17669 // capture of that variable. We start from the innermost capturing-entity 17670 // (the DC) and ensure that all intervening capturing-entities 17671 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 17672 // declcontext can either capture the variable or have already captured 17673 // the variable. 17674 CaptureType = Var->getType(); 17675 DeclRefType = CaptureType.getNonReferenceType(); 17676 bool Nested = false; 17677 bool Explicit = (Kind != TryCapture_Implicit); 17678 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 17679 do { 17680 // Only block literals, captured statements, and lambda expressions can 17681 // capture; other scopes don't work. 17682 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 17683 ExprLoc, 17684 BuildAndDiagnose, 17685 *this); 17686 // We need to check for the parent *first* because, if we *have* 17687 // private-captured a global variable, we need to recursively capture it in 17688 // intermediate blocks, lambdas, etc. 17689 if (!ParentDC) { 17690 if (IsGlobal) { 17691 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 17692 break; 17693 } 17694 return true; 17695 } 17696 17697 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 17698 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 17699 17700 17701 // Check whether we've already captured it. 17702 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 17703 DeclRefType)) { 17704 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 17705 break; 17706 } 17707 // If we are instantiating a generic lambda call operator body, 17708 // we do not want to capture new variables. What was captured 17709 // during either a lambdas transformation or initial parsing 17710 // should be used. 17711 if (isGenericLambdaCallOperatorSpecialization(DC)) { 17712 if (BuildAndDiagnose) { 17713 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17714 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 17715 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17716 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17717 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17718 buildLambdaCaptureFixit(*this, LSI, Var); 17719 } else 17720 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 17721 } 17722 return true; 17723 } 17724 17725 // Try to capture variable-length arrays types. 17726 if (Var->getType()->isVariablyModifiedType()) { 17727 // We're going to walk down into the type and look for VLA 17728 // expressions. 17729 QualType QTy = Var->getType(); 17730 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17731 QTy = PVD->getOriginalType(); 17732 captureVariablyModifiedType(Context, QTy, CSI); 17733 } 17734 17735 if (getLangOpts().OpenMP) { 17736 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17737 // OpenMP private variables should not be captured in outer scope, so 17738 // just break here. Similarly, global variables that are captured in a 17739 // target region should not be captured outside the scope of the region. 17740 if (RSI->CapRegionKind == CR_OpenMP) { 17741 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 17742 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 17743 // If the variable is private (i.e. not captured) and has variably 17744 // modified type, we still need to capture the type for correct 17745 // codegen in all regions, associated with the construct. Currently, 17746 // it is captured in the innermost captured region only. 17747 if (IsOpenMPPrivateDecl != OMPC_unknown && 17748 Var->getType()->isVariablyModifiedType()) { 17749 QualType QTy = Var->getType(); 17750 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 17751 QTy = PVD->getOriginalType(); 17752 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 17753 I < E; ++I) { 17754 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 17755 FunctionScopes[FunctionScopesIndex - I]); 17756 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 17757 "Wrong number of captured regions associated with the " 17758 "OpenMP construct."); 17759 captureVariablyModifiedType(Context, QTy, OuterRSI); 17760 } 17761 } 17762 bool IsTargetCap = 17763 IsOpenMPPrivateDecl != OMPC_private && 17764 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 17765 RSI->OpenMPCaptureLevel); 17766 // Do not capture global if it is not privatized in outer regions. 17767 bool IsGlobalCap = 17768 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 17769 RSI->OpenMPCaptureLevel); 17770 17771 // When we detect target captures we are looking from inside the 17772 // target region, therefore we need to propagate the capture from the 17773 // enclosing region. Therefore, the capture is not initially nested. 17774 if (IsTargetCap) 17775 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 17776 17777 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 17778 (IsGlobal && !IsGlobalCap)) { 17779 Nested = !IsTargetCap; 17780 bool HasConst = DeclRefType.isConstQualified(); 17781 DeclRefType = DeclRefType.getUnqualifiedType(); 17782 // Don't lose diagnostics about assignments to const. 17783 if (HasConst) 17784 DeclRefType.addConst(); 17785 CaptureType = Context.getLValueReferenceType(DeclRefType); 17786 break; 17787 } 17788 } 17789 } 17790 } 17791 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 17792 // No capture-default, and this is not an explicit capture 17793 // so cannot capture this variable. 17794 if (BuildAndDiagnose) { 17795 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 17796 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 17797 auto *LSI = cast<LambdaScopeInfo>(CSI); 17798 if (LSI->Lambda) { 17799 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 17800 buildLambdaCaptureFixit(*this, LSI, Var); 17801 } 17802 // FIXME: If we error out because an outer lambda can not implicitly 17803 // capture a variable that an inner lambda explicitly captures, we 17804 // should have the inner lambda do the explicit capture - because 17805 // it makes for cleaner diagnostics later. This would purely be done 17806 // so that the diagnostic does not misleadingly claim that a variable 17807 // can not be captured by a lambda implicitly even though it is captured 17808 // explicitly. Suggestion: 17809 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 17810 // at the function head 17811 // - cache the StartingDeclContext - this must be a lambda 17812 // - captureInLambda in the innermost lambda the variable. 17813 } 17814 return true; 17815 } 17816 17817 FunctionScopesIndex--; 17818 DC = ParentDC; 17819 Explicit = false; 17820 } while (!VarDC->Equals(DC)); 17821 17822 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 17823 // computing the type of the capture at each step, checking type-specific 17824 // requirements, and adding captures if requested. 17825 // If the variable had already been captured previously, we start capturing 17826 // at the lambda nested within that one. 17827 bool Invalid = false; 17828 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 17829 ++I) { 17830 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 17831 17832 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 17833 // certain types of variables (unnamed, variably modified types etc.) 17834 // so check for eligibility. 17835 if (!Invalid) 17836 Invalid = 17837 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 17838 17839 // After encountering an error, if we're actually supposed to capture, keep 17840 // capturing in nested contexts to suppress any follow-on diagnostics. 17841 if (Invalid && !BuildAndDiagnose) 17842 return true; 17843 17844 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 17845 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17846 DeclRefType, Nested, *this, Invalid); 17847 Nested = true; 17848 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 17849 Invalid = !captureInCapturedRegion( 17850 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 17851 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 17852 Nested = true; 17853 } else { 17854 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 17855 Invalid = 17856 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 17857 DeclRefType, Nested, Kind, EllipsisLoc, 17858 /*IsTopScope*/ I == N - 1, *this, Invalid); 17859 Nested = true; 17860 } 17861 17862 if (Invalid && !BuildAndDiagnose) 17863 return true; 17864 } 17865 return Invalid; 17866 } 17867 17868 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 17869 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 17870 QualType CaptureType; 17871 QualType DeclRefType; 17872 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 17873 /*BuildAndDiagnose=*/true, CaptureType, 17874 DeclRefType, nullptr); 17875 } 17876 17877 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 17878 QualType CaptureType; 17879 QualType DeclRefType; 17880 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17881 /*BuildAndDiagnose=*/false, CaptureType, 17882 DeclRefType, nullptr); 17883 } 17884 17885 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 17886 QualType CaptureType; 17887 QualType DeclRefType; 17888 17889 // Determine whether we can capture this variable. 17890 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 17891 /*BuildAndDiagnose=*/false, CaptureType, 17892 DeclRefType, nullptr)) 17893 return QualType(); 17894 17895 return DeclRefType; 17896 } 17897 17898 namespace { 17899 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 17900 // The produced TemplateArgumentListInfo* points to data stored within this 17901 // object, so should only be used in contexts where the pointer will not be 17902 // used after the CopiedTemplateArgs object is destroyed. 17903 class CopiedTemplateArgs { 17904 bool HasArgs; 17905 TemplateArgumentListInfo TemplateArgStorage; 17906 public: 17907 template<typename RefExpr> 17908 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 17909 if (HasArgs) 17910 E->copyTemplateArgumentsInto(TemplateArgStorage); 17911 } 17912 operator TemplateArgumentListInfo*() 17913 #ifdef __has_cpp_attribute 17914 #if __has_cpp_attribute(clang::lifetimebound) 17915 [[clang::lifetimebound]] 17916 #endif 17917 #endif 17918 { 17919 return HasArgs ? &TemplateArgStorage : nullptr; 17920 } 17921 }; 17922 } 17923 17924 /// Walk the set of potential results of an expression and mark them all as 17925 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 17926 /// 17927 /// \return A new expression if we found any potential results, ExprEmpty() if 17928 /// not, and ExprError() if we diagnosed an error. 17929 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 17930 NonOdrUseReason NOUR) { 17931 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 17932 // an object that satisfies the requirements for appearing in a 17933 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 17934 // is immediately applied." This function handles the lvalue-to-rvalue 17935 // conversion part. 17936 // 17937 // If we encounter a node that claims to be an odr-use but shouldn't be, we 17938 // transform it into the relevant kind of non-odr-use node and rebuild the 17939 // tree of nodes leading to it. 17940 // 17941 // This is a mini-TreeTransform that only transforms a restricted subset of 17942 // nodes (and only certain operands of them). 17943 17944 // Rebuild a subexpression. 17945 auto Rebuild = [&](Expr *Sub) { 17946 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 17947 }; 17948 17949 // Check whether a potential result satisfies the requirements of NOUR. 17950 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 17951 // Any entity other than a VarDecl is always odr-used whenever it's named 17952 // in a potentially-evaluated expression. 17953 auto *VD = dyn_cast<VarDecl>(D); 17954 if (!VD) 17955 return true; 17956 17957 // C++2a [basic.def.odr]p4: 17958 // A variable x whose name appears as a potentially-evalauted expression 17959 // e is odr-used by e unless 17960 // -- x is a reference that is usable in constant expressions, or 17961 // -- x is a variable of non-reference type that is usable in constant 17962 // expressions and has no mutable subobjects, and e is an element of 17963 // the set of potential results of an expression of 17964 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 17965 // conversion is applied, or 17966 // -- x is a variable of non-reference type, and e is an element of the 17967 // set of potential results of a discarded-value expression to which 17968 // the lvalue-to-rvalue conversion is not applied 17969 // 17970 // We check the first bullet and the "potentially-evaluated" condition in 17971 // BuildDeclRefExpr. We check the type requirements in the second bullet 17972 // in CheckLValueToRValueConversionOperand below. 17973 switch (NOUR) { 17974 case NOUR_None: 17975 case NOUR_Unevaluated: 17976 llvm_unreachable("unexpected non-odr-use-reason"); 17977 17978 case NOUR_Constant: 17979 // Constant references were handled when they were built. 17980 if (VD->getType()->isReferenceType()) 17981 return true; 17982 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 17983 if (RD->hasMutableFields()) 17984 return true; 17985 if (!VD->isUsableInConstantExpressions(S.Context)) 17986 return true; 17987 break; 17988 17989 case NOUR_Discarded: 17990 if (VD->getType()->isReferenceType()) 17991 return true; 17992 break; 17993 } 17994 return false; 17995 }; 17996 17997 // Mark that this expression does not constitute an odr-use. 17998 auto MarkNotOdrUsed = [&] { 17999 S.MaybeODRUseExprs.remove(E); 18000 if (LambdaScopeInfo *LSI = S.getCurLambda()) 18001 LSI->markVariableExprAsNonODRUsed(E); 18002 }; 18003 18004 // C++2a [basic.def.odr]p2: 18005 // The set of potential results of an expression e is defined as follows: 18006 switch (E->getStmtClass()) { 18007 // -- If e is an id-expression, ... 18008 case Expr::DeclRefExprClass: { 18009 auto *DRE = cast<DeclRefExpr>(E); 18010 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 18011 break; 18012 18013 // Rebuild as a non-odr-use DeclRefExpr. 18014 MarkNotOdrUsed(); 18015 return DeclRefExpr::Create( 18016 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 18017 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 18018 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 18019 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 18020 } 18021 18022 case Expr::FunctionParmPackExprClass: { 18023 auto *FPPE = cast<FunctionParmPackExpr>(E); 18024 // If any of the declarations in the pack is odr-used, then the expression 18025 // as a whole constitutes an odr-use. 18026 for (VarDecl *D : *FPPE) 18027 if (IsPotentialResultOdrUsed(D)) 18028 return ExprEmpty(); 18029 18030 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 18031 // nothing cares about whether we marked this as an odr-use, but it might 18032 // be useful for non-compiler tools. 18033 MarkNotOdrUsed(); 18034 break; 18035 } 18036 18037 // -- If e is a subscripting operation with an array operand... 18038 case Expr::ArraySubscriptExprClass: { 18039 auto *ASE = cast<ArraySubscriptExpr>(E); 18040 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 18041 if (!OldBase->getType()->isArrayType()) 18042 break; 18043 ExprResult Base = Rebuild(OldBase); 18044 if (!Base.isUsable()) 18045 return Base; 18046 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 18047 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 18048 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 18049 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 18050 ASE->getRBracketLoc()); 18051 } 18052 18053 case Expr::MemberExprClass: { 18054 auto *ME = cast<MemberExpr>(E); 18055 // -- If e is a class member access expression [...] naming a non-static 18056 // data member... 18057 if (isa<FieldDecl>(ME->getMemberDecl())) { 18058 ExprResult Base = Rebuild(ME->getBase()); 18059 if (!Base.isUsable()) 18060 return Base; 18061 return MemberExpr::Create( 18062 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 18063 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 18064 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 18065 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 18066 ME->getObjectKind(), ME->isNonOdrUse()); 18067 } 18068 18069 if (ME->getMemberDecl()->isCXXInstanceMember()) 18070 break; 18071 18072 // -- If e is a class member access expression naming a static data member, 18073 // ... 18074 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 18075 break; 18076 18077 // Rebuild as a non-odr-use MemberExpr. 18078 MarkNotOdrUsed(); 18079 return MemberExpr::Create( 18080 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 18081 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 18082 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 18083 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 18084 return ExprEmpty(); 18085 } 18086 18087 case Expr::BinaryOperatorClass: { 18088 auto *BO = cast<BinaryOperator>(E); 18089 Expr *LHS = BO->getLHS(); 18090 Expr *RHS = BO->getRHS(); 18091 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 18092 if (BO->getOpcode() == BO_PtrMemD) { 18093 ExprResult Sub = Rebuild(LHS); 18094 if (!Sub.isUsable()) 18095 return Sub; 18096 LHS = Sub.get(); 18097 // -- If e is a comma expression, ... 18098 } else if (BO->getOpcode() == BO_Comma) { 18099 ExprResult Sub = Rebuild(RHS); 18100 if (!Sub.isUsable()) 18101 return Sub; 18102 RHS = Sub.get(); 18103 } else { 18104 break; 18105 } 18106 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 18107 LHS, RHS); 18108 } 18109 18110 // -- If e has the form (e1)... 18111 case Expr::ParenExprClass: { 18112 auto *PE = cast<ParenExpr>(E); 18113 ExprResult Sub = Rebuild(PE->getSubExpr()); 18114 if (!Sub.isUsable()) 18115 return Sub; 18116 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 18117 } 18118 18119 // -- If e is a glvalue conditional expression, ... 18120 // We don't apply this to a binary conditional operator. FIXME: Should we? 18121 case Expr::ConditionalOperatorClass: { 18122 auto *CO = cast<ConditionalOperator>(E); 18123 ExprResult LHS = Rebuild(CO->getLHS()); 18124 if (LHS.isInvalid()) 18125 return ExprError(); 18126 ExprResult RHS = Rebuild(CO->getRHS()); 18127 if (RHS.isInvalid()) 18128 return ExprError(); 18129 if (!LHS.isUsable() && !RHS.isUsable()) 18130 return ExprEmpty(); 18131 if (!LHS.isUsable()) 18132 LHS = CO->getLHS(); 18133 if (!RHS.isUsable()) 18134 RHS = CO->getRHS(); 18135 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 18136 CO->getCond(), LHS.get(), RHS.get()); 18137 } 18138 18139 // [Clang extension] 18140 // -- If e has the form __extension__ e1... 18141 case Expr::UnaryOperatorClass: { 18142 auto *UO = cast<UnaryOperator>(E); 18143 if (UO->getOpcode() != UO_Extension) 18144 break; 18145 ExprResult Sub = Rebuild(UO->getSubExpr()); 18146 if (!Sub.isUsable()) 18147 return Sub; 18148 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 18149 Sub.get()); 18150 } 18151 18152 // [Clang extension] 18153 // -- If e has the form _Generic(...), the set of potential results is the 18154 // union of the sets of potential results of the associated expressions. 18155 case Expr::GenericSelectionExprClass: { 18156 auto *GSE = cast<GenericSelectionExpr>(E); 18157 18158 SmallVector<Expr *, 4> AssocExprs; 18159 bool AnyChanged = false; 18160 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 18161 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 18162 if (AssocExpr.isInvalid()) 18163 return ExprError(); 18164 if (AssocExpr.isUsable()) { 18165 AssocExprs.push_back(AssocExpr.get()); 18166 AnyChanged = true; 18167 } else { 18168 AssocExprs.push_back(OrigAssocExpr); 18169 } 18170 } 18171 18172 return AnyChanged ? S.CreateGenericSelectionExpr( 18173 GSE->getGenericLoc(), GSE->getDefaultLoc(), 18174 GSE->getRParenLoc(), GSE->getControllingExpr(), 18175 GSE->getAssocTypeSourceInfos(), AssocExprs) 18176 : ExprEmpty(); 18177 } 18178 18179 // [Clang extension] 18180 // -- If e has the form __builtin_choose_expr(...), the set of potential 18181 // results is the union of the sets of potential results of the 18182 // second and third subexpressions. 18183 case Expr::ChooseExprClass: { 18184 auto *CE = cast<ChooseExpr>(E); 18185 18186 ExprResult LHS = Rebuild(CE->getLHS()); 18187 if (LHS.isInvalid()) 18188 return ExprError(); 18189 18190 ExprResult RHS = Rebuild(CE->getLHS()); 18191 if (RHS.isInvalid()) 18192 return ExprError(); 18193 18194 if (!LHS.get() && !RHS.get()) 18195 return ExprEmpty(); 18196 if (!LHS.isUsable()) 18197 LHS = CE->getLHS(); 18198 if (!RHS.isUsable()) 18199 RHS = CE->getRHS(); 18200 18201 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 18202 RHS.get(), CE->getRParenLoc()); 18203 } 18204 18205 // Step through non-syntactic nodes. 18206 case Expr::ConstantExprClass: { 18207 auto *CE = cast<ConstantExpr>(E); 18208 ExprResult Sub = Rebuild(CE->getSubExpr()); 18209 if (!Sub.isUsable()) 18210 return Sub; 18211 return ConstantExpr::Create(S.Context, Sub.get()); 18212 } 18213 18214 // We could mostly rely on the recursive rebuilding to rebuild implicit 18215 // casts, but not at the top level, so rebuild them here. 18216 case Expr::ImplicitCastExprClass: { 18217 auto *ICE = cast<ImplicitCastExpr>(E); 18218 // Only step through the narrow set of cast kinds we expect to encounter. 18219 // Anything else suggests we've left the region in which potential results 18220 // can be found. 18221 switch (ICE->getCastKind()) { 18222 case CK_NoOp: 18223 case CK_DerivedToBase: 18224 case CK_UncheckedDerivedToBase: { 18225 ExprResult Sub = Rebuild(ICE->getSubExpr()); 18226 if (!Sub.isUsable()) 18227 return Sub; 18228 CXXCastPath Path(ICE->path()); 18229 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 18230 ICE->getValueKind(), &Path); 18231 } 18232 18233 default: 18234 break; 18235 } 18236 break; 18237 } 18238 18239 default: 18240 break; 18241 } 18242 18243 // Can't traverse through this node. Nothing to do. 18244 return ExprEmpty(); 18245 } 18246 18247 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 18248 // Check whether the operand is or contains an object of non-trivial C union 18249 // type. 18250 if (E->getType().isVolatileQualified() && 18251 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 18252 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 18253 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 18254 Sema::NTCUC_LValueToRValueVolatile, 18255 NTCUK_Destruct|NTCUK_Copy); 18256 18257 // C++2a [basic.def.odr]p4: 18258 // [...] an expression of non-volatile-qualified non-class type to which 18259 // the lvalue-to-rvalue conversion is applied [...] 18260 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 18261 return E; 18262 18263 ExprResult Result = 18264 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 18265 if (Result.isInvalid()) 18266 return ExprError(); 18267 return Result.get() ? Result : E; 18268 } 18269 18270 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 18271 Res = CorrectDelayedTyposInExpr(Res); 18272 18273 if (!Res.isUsable()) 18274 return Res; 18275 18276 // If a constant-expression is a reference to a variable where we delay 18277 // deciding whether it is an odr-use, just assume we will apply the 18278 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 18279 // (a non-type template argument), we have special handling anyway. 18280 return CheckLValueToRValueConversionOperand(Res.get()); 18281 } 18282 18283 void Sema::CleanupVarDeclMarking() { 18284 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 18285 // call. 18286 MaybeODRUseExprSet LocalMaybeODRUseExprs; 18287 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 18288 18289 for (Expr *E : LocalMaybeODRUseExprs) { 18290 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 18291 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 18292 DRE->getLocation(), *this); 18293 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 18294 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 18295 *this); 18296 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 18297 for (VarDecl *VD : *FP) 18298 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 18299 } else { 18300 llvm_unreachable("Unexpected expression"); 18301 } 18302 } 18303 18304 assert(MaybeODRUseExprs.empty() && 18305 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 18306 } 18307 18308 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 18309 VarDecl *Var, Expr *E) { 18310 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 18311 isa<FunctionParmPackExpr>(E)) && 18312 "Invalid Expr argument to DoMarkVarDeclReferenced"); 18313 Var->setReferenced(); 18314 18315 if (Var->isInvalidDecl()) 18316 return; 18317 18318 // Record a CUDA/HIP static device/constant variable if it is referenced 18319 // by host code. This is done conservatively, when the variable is referenced 18320 // in any of the following contexts: 18321 // - a non-function context 18322 // - a host function 18323 // - a host device function 18324 // This also requires the reference of the static device/constant variable by 18325 // host code to be visible in the device compilation for the compiler to be 18326 // able to externalize the static device/constant variable. 18327 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) { 18328 auto *CurContext = SemaRef.CurContext; 18329 if (!CurContext || !isa<FunctionDecl>(CurContext) || 18330 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() || 18331 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() && 18332 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>())) 18333 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var); 18334 } 18335 18336 auto *MSI = Var->getMemberSpecializationInfo(); 18337 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 18338 : Var->getTemplateSpecializationKind(); 18339 18340 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 18341 bool UsableInConstantExpr = 18342 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 18343 18344 // C++20 [expr.const]p12: 18345 // A variable [...] is needed for constant evaluation if it is [...] a 18346 // variable whose name appears as a potentially constant evaluated 18347 // expression that is either a contexpr variable or is of non-volatile 18348 // const-qualified integral type or of reference type 18349 bool NeededForConstantEvaluation = 18350 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 18351 18352 bool NeedDefinition = 18353 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 18354 18355 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 18356 "Can't instantiate a partial template specialization."); 18357 18358 // If this might be a member specialization of a static data member, check 18359 // the specialization is visible. We already did the checks for variable 18360 // template specializations when we created them. 18361 if (NeedDefinition && TSK != TSK_Undeclared && 18362 !isa<VarTemplateSpecializationDecl>(Var)) 18363 SemaRef.checkSpecializationVisibility(Loc, Var); 18364 18365 // Perform implicit instantiation of static data members, static data member 18366 // templates of class templates, and variable template specializations. Delay 18367 // instantiations of variable templates, except for those that could be used 18368 // in a constant expression. 18369 if (NeedDefinition && isTemplateInstantiation(TSK)) { 18370 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 18371 // instantiation declaration if a variable is usable in a constant 18372 // expression (among other cases). 18373 bool TryInstantiating = 18374 TSK == TSK_ImplicitInstantiation || 18375 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 18376 18377 if (TryInstantiating) { 18378 SourceLocation PointOfInstantiation = 18379 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 18380 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18381 if (FirstInstantiation) { 18382 PointOfInstantiation = Loc; 18383 if (MSI) 18384 MSI->setPointOfInstantiation(PointOfInstantiation); 18385 // FIXME: Notify listener. 18386 else 18387 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18388 } 18389 18390 if (UsableInConstantExpr) { 18391 // Do not defer instantiations of variables that could be used in a 18392 // constant expression. 18393 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 18394 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 18395 }); 18396 18397 // Re-set the member to trigger a recomputation of the dependence bits 18398 // for the expression. 18399 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18400 DRE->setDecl(DRE->getDecl()); 18401 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 18402 ME->setMemberDecl(ME->getMemberDecl()); 18403 } else if (FirstInstantiation || 18404 isa<VarTemplateSpecializationDecl>(Var)) { 18405 // FIXME: For a specialization of a variable template, we don't 18406 // distinguish between "declaration and type implicitly instantiated" 18407 // and "implicit instantiation of definition requested", so we have 18408 // no direct way to avoid enqueueing the pending instantiation 18409 // multiple times. 18410 SemaRef.PendingInstantiations 18411 .push_back(std::make_pair(Var, PointOfInstantiation)); 18412 } 18413 } 18414 } 18415 18416 // C++2a [basic.def.odr]p4: 18417 // A variable x whose name appears as a potentially-evaluated expression e 18418 // is odr-used by e unless 18419 // -- x is a reference that is usable in constant expressions 18420 // -- x is a variable of non-reference type that is usable in constant 18421 // expressions and has no mutable subobjects [FIXME], and e is an 18422 // element of the set of potential results of an expression of 18423 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 18424 // conversion is applied 18425 // -- x is a variable of non-reference type, and e is an element of the set 18426 // of potential results of a discarded-value expression to which the 18427 // lvalue-to-rvalue conversion is not applied [FIXME] 18428 // 18429 // We check the first part of the second bullet here, and 18430 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 18431 // FIXME: To get the third bullet right, we need to delay this even for 18432 // variables that are not usable in constant expressions. 18433 18434 // If we already know this isn't an odr-use, there's nothing more to do. 18435 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 18436 if (DRE->isNonOdrUse()) 18437 return; 18438 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 18439 if (ME->isNonOdrUse()) 18440 return; 18441 18442 switch (OdrUse) { 18443 case OdrUseContext::None: 18444 assert((!E || isa<FunctionParmPackExpr>(E)) && 18445 "missing non-odr-use marking for unevaluated decl ref"); 18446 break; 18447 18448 case OdrUseContext::FormallyOdrUsed: 18449 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 18450 // behavior. 18451 break; 18452 18453 case OdrUseContext::Used: 18454 // If we might later find that this expression isn't actually an odr-use, 18455 // delay the marking. 18456 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 18457 SemaRef.MaybeODRUseExprs.insert(E); 18458 else 18459 MarkVarDeclODRUsed(Var, Loc, SemaRef); 18460 break; 18461 18462 case OdrUseContext::Dependent: 18463 // If this is a dependent context, we don't need to mark variables as 18464 // odr-used, but we may still need to track them for lambda capture. 18465 // FIXME: Do we also need to do this inside dependent typeid expressions 18466 // (which are modeled as unevaluated at this point)? 18467 const bool RefersToEnclosingScope = 18468 (SemaRef.CurContext != Var->getDeclContext() && 18469 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 18470 if (RefersToEnclosingScope) { 18471 LambdaScopeInfo *const LSI = 18472 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 18473 if (LSI && (!LSI->CallOperator || 18474 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 18475 // If a variable could potentially be odr-used, defer marking it so 18476 // until we finish analyzing the full expression for any 18477 // lvalue-to-rvalue 18478 // or discarded value conversions that would obviate odr-use. 18479 // Add it to the list of potential captures that will be analyzed 18480 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 18481 // unless the variable is a reference that was initialized by a constant 18482 // expression (this will never need to be captured or odr-used). 18483 // 18484 // FIXME: We can simplify this a lot after implementing P0588R1. 18485 assert(E && "Capture variable should be used in an expression."); 18486 if (!Var->getType()->isReferenceType() || 18487 !Var->isUsableInConstantExpressions(SemaRef.Context)) 18488 LSI->addPotentialCapture(E->IgnoreParens()); 18489 } 18490 } 18491 break; 18492 } 18493 } 18494 18495 /// Mark a variable referenced, and check whether it is odr-used 18496 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 18497 /// used directly for normal expressions referring to VarDecl. 18498 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 18499 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 18500 } 18501 18502 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 18503 Decl *D, Expr *E, bool MightBeOdrUse) { 18504 if (SemaRef.isInOpenMPDeclareTargetContext()) 18505 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 18506 18507 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 18508 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 18509 return; 18510 } 18511 18512 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 18513 18514 // If this is a call to a method via a cast, also mark the method in the 18515 // derived class used in case codegen can devirtualize the call. 18516 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 18517 if (!ME) 18518 return; 18519 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 18520 if (!MD) 18521 return; 18522 // Only attempt to devirtualize if this is truly a virtual call. 18523 bool IsVirtualCall = MD->isVirtual() && 18524 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 18525 if (!IsVirtualCall) 18526 return; 18527 18528 // If it's possible to devirtualize the call, mark the called function 18529 // referenced. 18530 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 18531 ME->getBase(), SemaRef.getLangOpts().AppleKext); 18532 if (DM) 18533 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 18534 } 18535 18536 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 18537 /// 18538 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 18539 /// handled with care if the DeclRefExpr is not newly-created. 18540 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 18541 // TODO: update this with DR# once a defect report is filed. 18542 // C++11 defect. The address of a pure member should not be an ODR use, even 18543 // if it's a qualified reference. 18544 bool OdrUse = true; 18545 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 18546 if (Method->isVirtual() && 18547 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 18548 OdrUse = false; 18549 18550 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 18551 if (!isConstantEvaluated() && FD->isConsteval() && 18552 !RebuildingImmediateInvocation) 18553 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 18554 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 18555 } 18556 18557 /// Perform reference-marking and odr-use handling for a MemberExpr. 18558 void Sema::MarkMemberReferenced(MemberExpr *E) { 18559 // C++11 [basic.def.odr]p2: 18560 // A non-overloaded function whose name appears as a potentially-evaluated 18561 // expression or a member of a set of candidate functions, if selected by 18562 // overload resolution when referred to from a potentially-evaluated 18563 // expression, is odr-used, unless it is a pure virtual function and its 18564 // name is not explicitly qualified. 18565 bool MightBeOdrUse = true; 18566 if (E->performsVirtualDispatch(getLangOpts())) { 18567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 18568 if (Method->isPure()) 18569 MightBeOdrUse = false; 18570 } 18571 SourceLocation Loc = 18572 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 18573 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 18574 } 18575 18576 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 18577 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 18578 for (VarDecl *VD : *E) 18579 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true); 18580 } 18581 18582 /// Perform marking for a reference to an arbitrary declaration. It 18583 /// marks the declaration referenced, and performs odr-use checking for 18584 /// functions and variables. This method should not be used when building a 18585 /// normal expression which refers to a variable. 18586 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 18587 bool MightBeOdrUse) { 18588 if (MightBeOdrUse) { 18589 if (auto *VD = dyn_cast<VarDecl>(D)) { 18590 MarkVariableReferenced(Loc, VD); 18591 return; 18592 } 18593 } 18594 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 18595 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 18596 return; 18597 } 18598 D->setReferenced(); 18599 } 18600 18601 namespace { 18602 // Mark all of the declarations used by a type as referenced. 18603 // FIXME: Not fully implemented yet! We need to have a better understanding 18604 // of when we're entering a context we should not recurse into. 18605 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 18606 // TreeTransforms rebuilding the type in a new context. Rather than 18607 // duplicating the TreeTransform logic, we should consider reusing it here. 18608 // Currently that causes problems when rebuilding LambdaExprs. 18609 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 18610 Sema &S; 18611 SourceLocation Loc; 18612 18613 public: 18614 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 18615 18616 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 18617 18618 bool TraverseTemplateArgument(const TemplateArgument &Arg); 18619 }; 18620 } 18621 18622 bool MarkReferencedDecls::TraverseTemplateArgument( 18623 const TemplateArgument &Arg) { 18624 { 18625 // A non-type template argument is a constant-evaluated context. 18626 EnterExpressionEvaluationContext Evaluated( 18627 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 18628 if (Arg.getKind() == TemplateArgument::Declaration) { 18629 if (Decl *D = Arg.getAsDecl()) 18630 S.MarkAnyDeclReferenced(Loc, D, true); 18631 } else if (Arg.getKind() == TemplateArgument::Expression) { 18632 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 18633 } 18634 } 18635 18636 return Inherited::TraverseTemplateArgument(Arg); 18637 } 18638 18639 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 18640 MarkReferencedDecls Marker(*this, Loc); 18641 Marker.TraverseType(T); 18642 } 18643 18644 namespace { 18645 /// Helper class that marks all of the declarations referenced by 18646 /// potentially-evaluated subexpressions as "referenced". 18647 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 18648 public: 18649 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 18650 bool SkipLocalVariables; 18651 18652 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 18653 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {} 18654 18655 void visitUsedDecl(SourceLocation Loc, Decl *D) { 18656 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 18657 } 18658 18659 void VisitDeclRefExpr(DeclRefExpr *E) { 18660 // If we were asked not to visit local variables, don't. 18661 if (SkipLocalVariables) { 18662 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 18663 if (VD->hasLocalStorage()) 18664 return; 18665 } 18666 18667 // FIXME: This can trigger the instantiation of the initializer of a 18668 // variable, which can cause the expression to become value-dependent 18669 // or error-dependent. Do we need to propagate the new dependence bits? 18670 S.MarkDeclRefReferenced(E); 18671 } 18672 18673 void VisitMemberExpr(MemberExpr *E) { 18674 S.MarkMemberReferenced(E); 18675 Visit(E->getBase()); 18676 } 18677 }; 18678 } // namespace 18679 18680 /// Mark any declarations that appear within this expression or any 18681 /// potentially-evaluated subexpressions as "referenced". 18682 /// 18683 /// \param SkipLocalVariables If true, don't mark local variables as 18684 /// 'referenced'. 18685 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 18686 bool SkipLocalVariables) { 18687 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 18688 } 18689 18690 /// Emit a diagnostic that describes an effect on the run-time behavior 18691 /// of the program being compiled. 18692 /// 18693 /// This routine emits the given diagnostic when the code currently being 18694 /// type-checked is "potentially evaluated", meaning that there is a 18695 /// possibility that the code will actually be executable. Code in sizeof() 18696 /// expressions, code used only during overload resolution, etc., are not 18697 /// potentially evaluated. This routine will suppress such diagnostics or, 18698 /// in the absolutely nutty case of potentially potentially evaluated 18699 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 18700 /// later. 18701 /// 18702 /// This routine should be used for all diagnostics that describe the run-time 18703 /// behavior of a program, such as passing a non-POD value through an ellipsis. 18704 /// Failure to do so will likely result in spurious diagnostics or failures 18705 /// during overload resolution or within sizeof/alignof/typeof/typeid. 18706 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 18707 const PartialDiagnostic &PD) { 18708 switch (ExprEvalContexts.back().Context) { 18709 case ExpressionEvaluationContext::Unevaluated: 18710 case ExpressionEvaluationContext::UnevaluatedList: 18711 case ExpressionEvaluationContext::UnevaluatedAbstract: 18712 case ExpressionEvaluationContext::DiscardedStatement: 18713 // The argument will never be evaluated, so don't complain. 18714 break; 18715 18716 case ExpressionEvaluationContext::ConstantEvaluated: 18717 // Relevant diagnostics should be produced by constant evaluation. 18718 break; 18719 18720 case ExpressionEvaluationContext::PotentiallyEvaluated: 18721 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18722 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 18723 FunctionScopes.back()->PossiblyUnreachableDiags. 18724 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 18725 return true; 18726 } 18727 18728 // The initializer of a constexpr variable or of the first declaration of a 18729 // static data member is not syntactically a constant evaluated constant, 18730 // but nonetheless is always required to be a constant expression, so we 18731 // can skip diagnosing. 18732 // FIXME: Using the mangling context here is a hack. 18733 if (auto *VD = dyn_cast_or_null<VarDecl>( 18734 ExprEvalContexts.back().ManglingContextDecl)) { 18735 if (VD->isConstexpr() || 18736 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 18737 break; 18738 // FIXME: For any other kind of variable, we should build a CFG for its 18739 // initializer and check whether the context in question is reachable. 18740 } 18741 18742 Diag(Loc, PD); 18743 return true; 18744 } 18745 18746 return false; 18747 } 18748 18749 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 18750 const PartialDiagnostic &PD) { 18751 return DiagRuntimeBehavior( 18752 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD); 18753 } 18754 18755 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 18756 CallExpr *CE, FunctionDecl *FD) { 18757 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 18758 return false; 18759 18760 // If we're inside a decltype's expression, don't check for a valid return 18761 // type or construct temporaries until we know whether this is the last call. 18762 if (ExprEvalContexts.back().ExprContext == 18763 ExpressionEvaluationContextRecord::EK_Decltype) { 18764 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 18765 return false; 18766 } 18767 18768 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 18769 FunctionDecl *FD; 18770 CallExpr *CE; 18771 18772 public: 18773 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 18774 : FD(FD), CE(CE) { } 18775 18776 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18777 if (!FD) { 18778 S.Diag(Loc, diag::err_call_incomplete_return) 18779 << T << CE->getSourceRange(); 18780 return; 18781 } 18782 18783 S.Diag(Loc, diag::err_call_function_incomplete_return) 18784 << CE->getSourceRange() << FD << T; 18785 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 18786 << FD->getDeclName(); 18787 } 18788 } Diagnoser(FD, CE); 18789 18790 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 18791 return true; 18792 18793 return false; 18794 } 18795 18796 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 18797 // will prevent this condition from triggering, which is what we want. 18798 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 18799 SourceLocation Loc; 18800 18801 unsigned diagnostic = diag::warn_condition_is_assignment; 18802 bool IsOrAssign = false; 18803 18804 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 18805 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 18806 return; 18807 18808 IsOrAssign = Op->getOpcode() == BO_OrAssign; 18809 18810 // Greylist some idioms by putting them into a warning subcategory. 18811 if (ObjCMessageExpr *ME 18812 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 18813 Selector Sel = ME->getSelector(); 18814 18815 // self = [<foo> init...] 18816 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 18817 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18818 18819 // <foo> = [<bar> nextObject] 18820 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 18821 diagnostic = diag::warn_condition_is_idiomatic_assignment; 18822 } 18823 18824 Loc = Op->getOperatorLoc(); 18825 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 18826 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 18827 return; 18828 18829 IsOrAssign = Op->getOperator() == OO_PipeEqual; 18830 Loc = Op->getOperatorLoc(); 18831 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 18832 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 18833 else { 18834 // Not an assignment. 18835 return; 18836 } 18837 18838 Diag(Loc, diagnostic) << E->getSourceRange(); 18839 18840 SourceLocation Open = E->getBeginLoc(); 18841 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 18842 Diag(Loc, diag::note_condition_assign_silence) 18843 << FixItHint::CreateInsertion(Open, "(") 18844 << FixItHint::CreateInsertion(Close, ")"); 18845 18846 if (IsOrAssign) 18847 Diag(Loc, diag::note_condition_or_assign_to_comparison) 18848 << FixItHint::CreateReplacement(Loc, "!="); 18849 else 18850 Diag(Loc, diag::note_condition_assign_to_comparison) 18851 << FixItHint::CreateReplacement(Loc, "=="); 18852 } 18853 18854 /// Redundant parentheses over an equality comparison can indicate 18855 /// that the user intended an assignment used as condition. 18856 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 18857 // Don't warn if the parens came from a macro. 18858 SourceLocation parenLoc = ParenE->getBeginLoc(); 18859 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 18860 return; 18861 // Don't warn for dependent expressions. 18862 if (ParenE->isTypeDependent()) 18863 return; 18864 18865 Expr *E = ParenE->IgnoreParens(); 18866 18867 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 18868 if (opE->getOpcode() == BO_EQ && 18869 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 18870 == Expr::MLV_Valid) { 18871 SourceLocation Loc = opE->getOperatorLoc(); 18872 18873 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 18874 SourceRange ParenERange = ParenE->getSourceRange(); 18875 Diag(Loc, diag::note_equality_comparison_silence) 18876 << FixItHint::CreateRemoval(ParenERange.getBegin()) 18877 << FixItHint::CreateRemoval(ParenERange.getEnd()); 18878 Diag(Loc, diag::note_equality_comparison_to_assign) 18879 << FixItHint::CreateReplacement(Loc, "="); 18880 } 18881 } 18882 18883 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 18884 bool IsConstexpr) { 18885 DiagnoseAssignmentAsCondition(E); 18886 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 18887 DiagnoseEqualityWithExtraParens(parenE); 18888 18889 ExprResult result = CheckPlaceholderExpr(E); 18890 if (result.isInvalid()) return ExprError(); 18891 E = result.get(); 18892 18893 if (!E->isTypeDependent()) { 18894 if (getLangOpts().CPlusPlus) 18895 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 18896 18897 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 18898 if (ERes.isInvalid()) 18899 return ExprError(); 18900 E = ERes.get(); 18901 18902 QualType T = E->getType(); 18903 if (!T->isScalarType()) { // C99 6.8.4.1p1 18904 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 18905 << T << E->getSourceRange(); 18906 return ExprError(); 18907 } 18908 CheckBoolLikeConversion(E, Loc); 18909 } 18910 18911 return E; 18912 } 18913 18914 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 18915 Expr *SubExpr, ConditionKind CK) { 18916 // Empty conditions are valid in for-statements. 18917 if (!SubExpr) 18918 return ConditionResult(); 18919 18920 ExprResult Cond; 18921 switch (CK) { 18922 case ConditionKind::Boolean: 18923 Cond = CheckBooleanCondition(Loc, SubExpr); 18924 break; 18925 18926 case ConditionKind::ConstexprIf: 18927 Cond = CheckBooleanCondition(Loc, SubExpr, true); 18928 break; 18929 18930 case ConditionKind::Switch: 18931 Cond = CheckSwitchCondition(Loc, SubExpr); 18932 break; 18933 } 18934 if (Cond.isInvalid()) { 18935 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 18936 {SubExpr}); 18937 if (!Cond.get()) 18938 return ConditionError(); 18939 } 18940 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 18941 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 18942 if (!FullExpr.get()) 18943 return ConditionError(); 18944 18945 return ConditionResult(*this, nullptr, FullExpr, 18946 CK == ConditionKind::ConstexprIf); 18947 } 18948 18949 namespace { 18950 /// A visitor for rebuilding a call to an __unknown_any expression 18951 /// to have an appropriate type. 18952 struct RebuildUnknownAnyFunction 18953 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 18954 18955 Sema &S; 18956 18957 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 18958 18959 ExprResult VisitStmt(Stmt *S) { 18960 llvm_unreachable("unexpected statement!"); 18961 } 18962 18963 ExprResult VisitExpr(Expr *E) { 18964 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 18965 << E->getSourceRange(); 18966 return ExprError(); 18967 } 18968 18969 /// Rebuild an expression which simply semantically wraps another 18970 /// expression which it shares the type and value kind of. 18971 template <class T> ExprResult rebuildSugarExpr(T *E) { 18972 ExprResult SubResult = Visit(E->getSubExpr()); 18973 if (SubResult.isInvalid()) return ExprError(); 18974 18975 Expr *SubExpr = SubResult.get(); 18976 E->setSubExpr(SubExpr); 18977 E->setType(SubExpr->getType()); 18978 E->setValueKind(SubExpr->getValueKind()); 18979 assert(E->getObjectKind() == OK_Ordinary); 18980 return E; 18981 } 18982 18983 ExprResult VisitParenExpr(ParenExpr *E) { 18984 return rebuildSugarExpr(E); 18985 } 18986 18987 ExprResult VisitUnaryExtension(UnaryOperator *E) { 18988 return rebuildSugarExpr(E); 18989 } 18990 18991 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 18992 ExprResult SubResult = Visit(E->getSubExpr()); 18993 if (SubResult.isInvalid()) return ExprError(); 18994 18995 Expr *SubExpr = SubResult.get(); 18996 E->setSubExpr(SubExpr); 18997 E->setType(S.Context.getPointerType(SubExpr->getType())); 18998 assert(E->getValueKind() == VK_RValue); 18999 assert(E->getObjectKind() == OK_Ordinary); 19000 return E; 19001 } 19002 19003 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 19004 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 19005 19006 E->setType(VD->getType()); 19007 19008 assert(E->getValueKind() == VK_RValue); 19009 if (S.getLangOpts().CPlusPlus && 19010 !(isa<CXXMethodDecl>(VD) && 19011 cast<CXXMethodDecl>(VD)->isInstance())) 19012 E->setValueKind(VK_LValue); 19013 19014 return E; 19015 } 19016 19017 ExprResult VisitMemberExpr(MemberExpr *E) { 19018 return resolveDecl(E, E->getMemberDecl()); 19019 } 19020 19021 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19022 return resolveDecl(E, E->getDecl()); 19023 } 19024 }; 19025 } 19026 19027 /// Given a function expression of unknown-any type, try to rebuild it 19028 /// to have a function type. 19029 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 19030 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 19031 if (Result.isInvalid()) return ExprError(); 19032 return S.DefaultFunctionArrayConversion(Result.get()); 19033 } 19034 19035 namespace { 19036 /// A visitor for rebuilding an expression of type __unknown_anytype 19037 /// into one which resolves the type directly on the referring 19038 /// expression. Strict preservation of the original source 19039 /// structure is not a goal. 19040 struct RebuildUnknownAnyExpr 19041 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 19042 19043 Sema &S; 19044 19045 /// The current destination type. 19046 QualType DestType; 19047 19048 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 19049 : S(S), DestType(CastType) {} 19050 19051 ExprResult VisitStmt(Stmt *S) { 19052 llvm_unreachable("unexpected statement!"); 19053 } 19054 19055 ExprResult VisitExpr(Expr *E) { 19056 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19057 << E->getSourceRange(); 19058 return ExprError(); 19059 } 19060 19061 ExprResult VisitCallExpr(CallExpr *E); 19062 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 19063 19064 /// Rebuild an expression which simply semantically wraps another 19065 /// expression which it shares the type and value kind of. 19066 template <class T> ExprResult rebuildSugarExpr(T *E) { 19067 ExprResult SubResult = Visit(E->getSubExpr()); 19068 if (SubResult.isInvalid()) return ExprError(); 19069 Expr *SubExpr = SubResult.get(); 19070 E->setSubExpr(SubExpr); 19071 E->setType(SubExpr->getType()); 19072 E->setValueKind(SubExpr->getValueKind()); 19073 assert(E->getObjectKind() == OK_Ordinary); 19074 return E; 19075 } 19076 19077 ExprResult VisitParenExpr(ParenExpr *E) { 19078 return rebuildSugarExpr(E); 19079 } 19080 19081 ExprResult VisitUnaryExtension(UnaryOperator *E) { 19082 return rebuildSugarExpr(E); 19083 } 19084 19085 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 19086 const PointerType *Ptr = DestType->getAs<PointerType>(); 19087 if (!Ptr) { 19088 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 19089 << E->getSourceRange(); 19090 return ExprError(); 19091 } 19092 19093 if (isa<CallExpr>(E->getSubExpr())) { 19094 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 19095 << E->getSourceRange(); 19096 return ExprError(); 19097 } 19098 19099 assert(E->getValueKind() == VK_RValue); 19100 assert(E->getObjectKind() == OK_Ordinary); 19101 E->setType(DestType); 19102 19103 // Build the sub-expression as if it were an object of the pointee type. 19104 DestType = Ptr->getPointeeType(); 19105 ExprResult SubResult = Visit(E->getSubExpr()); 19106 if (SubResult.isInvalid()) return ExprError(); 19107 E->setSubExpr(SubResult.get()); 19108 return E; 19109 } 19110 19111 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 19112 19113 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 19114 19115 ExprResult VisitMemberExpr(MemberExpr *E) { 19116 return resolveDecl(E, E->getMemberDecl()); 19117 } 19118 19119 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 19120 return resolveDecl(E, E->getDecl()); 19121 } 19122 }; 19123 } 19124 19125 /// Rebuilds a call expression which yielded __unknown_anytype. 19126 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 19127 Expr *CalleeExpr = E->getCallee(); 19128 19129 enum FnKind { 19130 FK_MemberFunction, 19131 FK_FunctionPointer, 19132 FK_BlockPointer 19133 }; 19134 19135 FnKind Kind; 19136 QualType CalleeType = CalleeExpr->getType(); 19137 if (CalleeType == S.Context.BoundMemberTy) { 19138 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 19139 Kind = FK_MemberFunction; 19140 CalleeType = Expr::findBoundMemberType(CalleeExpr); 19141 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 19142 CalleeType = Ptr->getPointeeType(); 19143 Kind = FK_FunctionPointer; 19144 } else { 19145 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 19146 Kind = FK_BlockPointer; 19147 } 19148 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 19149 19150 // Verify that this is a legal result type of a function. 19151 if (DestType->isArrayType() || DestType->isFunctionType()) { 19152 unsigned diagID = diag::err_func_returning_array_function; 19153 if (Kind == FK_BlockPointer) 19154 diagID = diag::err_block_returning_array_function; 19155 19156 S.Diag(E->getExprLoc(), diagID) 19157 << DestType->isFunctionType() << DestType; 19158 return ExprError(); 19159 } 19160 19161 // Otherwise, go ahead and set DestType as the call's result. 19162 E->setType(DestType.getNonLValueExprType(S.Context)); 19163 E->setValueKind(Expr::getValueKindForType(DestType)); 19164 assert(E->getObjectKind() == OK_Ordinary); 19165 19166 // Rebuild the function type, replacing the result type with DestType. 19167 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 19168 if (Proto) { 19169 // __unknown_anytype(...) is a special case used by the debugger when 19170 // it has no idea what a function's signature is. 19171 // 19172 // We want to build this call essentially under the K&R 19173 // unprototyped rules, but making a FunctionNoProtoType in C++ 19174 // would foul up all sorts of assumptions. However, we cannot 19175 // simply pass all arguments as variadic arguments, nor can we 19176 // portably just call the function under a non-variadic type; see 19177 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 19178 // However, it turns out that in practice it is generally safe to 19179 // call a function declared as "A foo(B,C,D);" under the prototype 19180 // "A foo(B,C,D,...);". The only known exception is with the 19181 // Windows ABI, where any variadic function is implicitly cdecl 19182 // regardless of its normal CC. Therefore we change the parameter 19183 // types to match the types of the arguments. 19184 // 19185 // This is a hack, but it is far superior to moving the 19186 // corresponding target-specific code from IR-gen to Sema/AST. 19187 19188 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 19189 SmallVector<QualType, 8> ArgTypes; 19190 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 19191 ArgTypes.reserve(E->getNumArgs()); 19192 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 19193 Expr *Arg = E->getArg(i); 19194 QualType ArgType = Arg->getType(); 19195 if (E->isLValue()) { 19196 ArgType = S.Context.getLValueReferenceType(ArgType); 19197 } else if (E->isXValue()) { 19198 ArgType = S.Context.getRValueReferenceType(ArgType); 19199 } 19200 ArgTypes.push_back(ArgType); 19201 } 19202 ParamTypes = ArgTypes; 19203 } 19204 DestType = S.Context.getFunctionType(DestType, ParamTypes, 19205 Proto->getExtProtoInfo()); 19206 } else { 19207 DestType = S.Context.getFunctionNoProtoType(DestType, 19208 FnType->getExtInfo()); 19209 } 19210 19211 // Rebuild the appropriate pointer-to-function type. 19212 switch (Kind) { 19213 case FK_MemberFunction: 19214 // Nothing to do. 19215 break; 19216 19217 case FK_FunctionPointer: 19218 DestType = S.Context.getPointerType(DestType); 19219 break; 19220 19221 case FK_BlockPointer: 19222 DestType = S.Context.getBlockPointerType(DestType); 19223 break; 19224 } 19225 19226 // Finally, we can recurse. 19227 ExprResult CalleeResult = Visit(CalleeExpr); 19228 if (!CalleeResult.isUsable()) return ExprError(); 19229 E->setCallee(CalleeResult.get()); 19230 19231 // Bind a temporary if necessary. 19232 return S.MaybeBindToTemporary(E); 19233 } 19234 19235 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 19236 // Verify that this is a legal result type of a call. 19237 if (DestType->isArrayType() || DestType->isFunctionType()) { 19238 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 19239 << DestType->isFunctionType() << DestType; 19240 return ExprError(); 19241 } 19242 19243 // Rewrite the method result type if available. 19244 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 19245 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 19246 Method->setReturnType(DestType); 19247 } 19248 19249 // Change the type of the message. 19250 E->setType(DestType.getNonReferenceType()); 19251 E->setValueKind(Expr::getValueKindForType(DestType)); 19252 19253 return S.MaybeBindToTemporary(E); 19254 } 19255 19256 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 19257 // The only case we should ever see here is a function-to-pointer decay. 19258 if (E->getCastKind() == CK_FunctionToPointerDecay) { 19259 assert(E->getValueKind() == VK_RValue); 19260 assert(E->getObjectKind() == OK_Ordinary); 19261 19262 E->setType(DestType); 19263 19264 // Rebuild the sub-expression as the pointee (function) type. 19265 DestType = DestType->castAs<PointerType>()->getPointeeType(); 19266 19267 ExprResult Result = Visit(E->getSubExpr()); 19268 if (!Result.isUsable()) return ExprError(); 19269 19270 E->setSubExpr(Result.get()); 19271 return E; 19272 } else if (E->getCastKind() == CK_LValueToRValue) { 19273 assert(E->getValueKind() == VK_RValue); 19274 assert(E->getObjectKind() == OK_Ordinary); 19275 19276 assert(isa<BlockPointerType>(E->getType())); 19277 19278 E->setType(DestType); 19279 19280 // The sub-expression has to be a lvalue reference, so rebuild it as such. 19281 DestType = S.Context.getLValueReferenceType(DestType); 19282 19283 ExprResult Result = Visit(E->getSubExpr()); 19284 if (!Result.isUsable()) return ExprError(); 19285 19286 E->setSubExpr(Result.get()); 19287 return E; 19288 } else { 19289 llvm_unreachable("Unhandled cast type!"); 19290 } 19291 } 19292 19293 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 19294 ExprValueKind ValueKind = VK_LValue; 19295 QualType Type = DestType; 19296 19297 // We know how to make this work for certain kinds of decls: 19298 19299 // - functions 19300 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 19301 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 19302 DestType = Ptr->getPointeeType(); 19303 ExprResult Result = resolveDecl(E, VD); 19304 if (Result.isInvalid()) return ExprError(); 19305 return S.ImpCastExprToType(Result.get(), Type, 19306 CK_FunctionToPointerDecay, VK_RValue); 19307 } 19308 19309 if (!Type->isFunctionType()) { 19310 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 19311 << VD << E->getSourceRange(); 19312 return ExprError(); 19313 } 19314 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 19315 // We must match the FunctionDecl's type to the hack introduced in 19316 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 19317 // type. See the lengthy commentary in that routine. 19318 QualType FDT = FD->getType(); 19319 const FunctionType *FnType = FDT->castAs<FunctionType>(); 19320 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 19321 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 19322 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 19323 SourceLocation Loc = FD->getLocation(); 19324 FunctionDecl *NewFD = FunctionDecl::Create( 19325 S.Context, FD->getDeclContext(), Loc, Loc, 19326 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 19327 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(), 19328 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 19329 19330 if (FD->getQualifier()) 19331 NewFD->setQualifierInfo(FD->getQualifierLoc()); 19332 19333 SmallVector<ParmVarDecl*, 16> Params; 19334 for (const auto &AI : FT->param_types()) { 19335 ParmVarDecl *Param = 19336 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 19337 Param->setScopeInfo(0, Params.size()); 19338 Params.push_back(Param); 19339 } 19340 NewFD->setParams(Params); 19341 DRE->setDecl(NewFD); 19342 VD = DRE->getDecl(); 19343 } 19344 } 19345 19346 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 19347 if (MD->isInstance()) { 19348 ValueKind = VK_RValue; 19349 Type = S.Context.BoundMemberTy; 19350 } 19351 19352 // Function references aren't l-values in C. 19353 if (!S.getLangOpts().CPlusPlus) 19354 ValueKind = VK_RValue; 19355 19356 // - variables 19357 } else if (isa<VarDecl>(VD)) { 19358 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 19359 Type = RefTy->getPointeeType(); 19360 } else if (Type->isFunctionType()) { 19361 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 19362 << VD << E->getSourceRange(); 19363 return ExprError(); 19364 } 19365 19366 // - nothing else 19367 } else { 19368 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 19369 << VD << E->getSourceRange(); 19370 return ExprError(); 19371 } 19372 19373 // Modifying the declaration like this is friendly to IR-gen but 19374 // also really dangerous. 19375 VD->setType(DestType); 19376 E->setType(Type); 19377 E->setValueKind(ValueKind); 19378 return E; 19379 } 19380 19381 /// Check a cast of an unknown-any type. We intentionally only 19382 /// trigger this for C-style casts. 19383 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 19384 Expr *CastExpr, CastKind &CastKind, 19385 ExprValueKind &VK, CXXCastPath &Path) { 19386 // The type we're casting to must be either void or complete. 19387 if (!CastType->isVoidType() && 19388 RequireCompleteType(TypeRange.getBegin(), CastType, 19389 diag::err_typecheck_cast_to_incomplete)) 19390 return ExprError(); 19391 19392 // Rewrite the casted expression from scratch. 19393 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 19394 if (!result.isUsable()) return ExprError(); 19395 19396 CastExpr = result.get(); 19397 VK = CastExpr->getValueKind(); 19398 CastKind = CK_NoOp; 19399 19400 return CastExpr; 19401 } 19402 19403 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 19404 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 19405 } 19406 19407 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 19408 Expr *arg, QualType ¶mType) { 19409 // If the syntactic form of the argument is not an explicit cast of 19410 // any sort, just do default argument promotion. 19411 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 19412 if (!castArg) { 19413 ExprResult result = DefaultArgumentPromotion(arg); 19414 if (result.isInvalid()) return ExprError(); 19415 paramType = result.get()->getType(); 19416 return result; 19417 } 19418 19419 // Otherwise, use the type that was written in the explicit cast. 19420 assert(!arg->hasPlaceholderType()); 19421 paramType = castArg->getTypeAsWritten(); 19422 19423 // Copy-initialize a parameter of that type. 19424 InitializedEntity entity = 19425 InitializedEntity::InitializeParameter(Context, paramType, 19426 /*consumed*/ false); 19427 return PerformCopyInitialization(entity, callLoc, arg); 19428 } 19429 19430 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 19431 Expr *orig = E; 19432 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 19433 while (true) { 19434 E = E->IgnoreParenImpCasts(); 19435 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 19436 E = call->getCallee(); 19437 diagID = diag::err_uncasted_call_of_unknown_any; 19438 } else { 19439 break; 19440 } 19441 } 19442 19443 SourceLocation loc; 19444 NamedDecl *d; 19445 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 19446 loc = ref->getLocation(); 19447 d = ref->getDecl(); 19448 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 19449 loc = mem->getMemberLoc(); 19450 d = mem->getMemberDecl(); 19451 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 19452 diagID = diag::err_uncasted_call_of_unknown_any; 19453 loc = msg->getSelectorStartLoc(); 19454 d = msg->getMethodDecl(); 19455 if (!d) { 19456 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 19457 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 19458 << orig->getSourceRange(); 19459 return ExprError(); 19460 } 19461 } else { 19462 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 19463 << E->getSourceRange(); 19464 return ExprError(); 19465 } 19466 19467 S.Diag(loc, diagID) << d << orig->getSourceRange(); 19468 19469 // Never recoverable. 19470 return ExprError(); 19471 } 19472 19473 /// Check for operands with placeholder types and complain if found. 19474 /// Returns ExprError() if there was an error and no recovery was possible. 19475 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 19476 if (!Context.isDependenceAllowed()) { 19477 // C cannot handle TypoExpr nodes on either side of a binop because it 19478 // doesn't handle dependent types properly, so make sure any TypoExprs have 19479 // been dealt with before checking the operands. 19480 ExprResult Result = CorrectDelayedTyposInExpr(E); 19481 if (!Result.isUsable()) return ExprError(); 19482 E = Result.get(); 19483 } 19484 19485 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 19486 if (!placeholderType) return E; 19487 19488 switch (placeholderType->getKind()) { 19489 19490 // Overloaded expressions. 19491 case BuiltinType::Overload: { 19492 // Try to resolve a single function template specialization. 19493 // This is obligatory. 19494 ExprResult Result = E; 19495 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 19496 return Result; 19497 19498 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 19499 // leaves Result unchanged on failure. 19500 Result = E; 19501 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 19502 return Result; 19503 19504 // If that failed, try to recover with a call. 19505 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 19506 /*complain*/ true); 19507 return Result; 19508 } 19509 19510 // Bound member functions. 19511 case BuiltinType::BoundMember: { 19512 ExprResult result = E; 19513 const Expr *BME = E->IgnoreParens(); 19514 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 19515 // Try to give a nicer diagnostic if it is a bound member that we recognize. 19516 if (isa<CXXPseudoDestructorExpr>(BME)) { 19517 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 19518 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 19519 if (ME->getMemberNameInfo().getName().getNameKind() == 19520 DeclarationName::CXXDestructorName) 19521 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 19522 } 19523 tryToRecoverWithCall(result, PD, 19524 /*complain*/ true); 19525 return result; 19526 } 19527 19528 // ARC unbridged casts. 19529 case BuiltinType::ARCUnbridgedCast: { 19530 Expr *realCast = stripARCUnbridgedCast(E); 19531 diagnoseARCUnbridgedCast(realCast); 19532 return realCast; 19533 } 19534 19535 // Expressions of unknown type. 19536 case BuiltinType::UnknownAny: 19537 return diagnoseUnknownAnyExpr(*this, E); 19538 19539 // Pseudo-objects. 19540 case BuiltinType::PseudoObject: 19541 return checkPseudoObjectRValue(E); 19542 19543 case BuiltinType::BuiltinFn: { 19544 // Accept __noop without parens by implicitly converting it to a call expr. 19545 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 19546 if (DRE) { 19547 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 19548 if (FD->getBuiltinID() == Builtin::BI__noop) { 19549 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 19550 CK_BuiltinFnToFnPtr) 19551 .get(); 19552 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 19553 VK_RValue, SourceLocation(), 19554 FPOptionsOverride()); 19555 } 19556 } 19557 19558 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 19559 return ExprError(); 19560 } 19561 19562 case BuiltinType::IncompleteMatrixIdx: 19563 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 19564 ->getRowIdx() 19565 ->getBeginLoc(), 19566 diag::err_matrix_incomplete_index); 19567 return ExprError(); 19568 19569 // Expressions of unknown type. 19570 case BuiltinType::OMPArraySection: 19571 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 19572 return ExprError(); 19573 19574 // Expressions of unknown type. 19575 case BuiltinType::OMPArrayShaping: 19576 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 19577 19578 case BuiltinType::OMPIterator: 19579 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 19580 19581 // Everything else should be impossible. 19582 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 19583 case BuiltinType::Id: 19584 #include "clang/Basic/OpenCLImageTypes.def" 19585 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 19586 case BuiltinType::Id: 19587 #include "clang/Basic/OpenCLExtensionTypes.def" 19588 #define SVE_TYPE(Name, Id, SingletonId) \ 19589 case BuiltinType::Id: 19590 #include "clang/Basic/AArch64SVEACLETypes.def" 19591 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 19592 case BuiltinType::Id: 19593 #include "clang/Basic/PPCTypes.def" 19594 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 19595 #include "clang/Basic/RISCVVTypes.def" 19596 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 19597 #define PLACEHOLDER_TYPE(Id, SingletonId) 19598 #include "clang/AST/BuiltinTypes.def" 19599 break; 19600 } 19601 19602 llvm_unreachable("invalid placeholder type!"); 19603 } 19604 19605 bool Sema::CheckCaseExpression(Expr *E) { 19606 if (E->isTypeDependent()) 19607 return true; 19608 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 19609 return E->getType()->isIntegralOrEnumerationType(); 19610 return false; 19611 } 19612 19613 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 19614 ExprResult 19615 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 19616 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 19617 "Unknown Objective-C Boolean value!"); 19618 QualType BoolT = Context.ObjCBuiltinBoolTy; 19619 if (!Context.getBOOLDecl()) { 19620 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 19621 Sema::LookupOrdinaryName); 19622 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 19623 NamedDecl *ND = Result.getFoundDecl(); 19624 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 19625 Context.setBOOLDecl(TD); 19626 } 19627 } 19628 if (Context.getBOOLDecl()) 19629 BoolT = Context.getBOOLType(); 19630 return new (Context) 19631 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 19632 } 19633 19634 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 19635 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 19636 SourceLocation RParen) { 19637 19638 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 19639 19640 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 19641 return Spec.getPlatform() == Platform; 19642 }); 19643 19644 VersionTuple Version; 19645 if (Spec != AvailSpecs.end()) 19646 Version = Spec->getVersion(); 19647 19648 // The use of `@available` in the enclosing function should be analyzed to 19649 // warn when it's used inappropriately (i.e. not if(@available)). 19650 if (getCurFunctionOrMethodDecl()) 19651 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 19652 else if (getCurBlock() || getCurLambda()) 19653 getCurFunction()->HasPotentialAvailabilityViolations = true; 19654 19655 return new (Context) 19656 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 19657 } 19658 19659 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 19660 ArrayRef<Expr *> SubExprs, QualType T) { 19661 if (!Context.getLangOpts().RecoveryAST) 19662 return ExprError(); 19663 19664 if (isSFINAEContext()) 19665 return ExprError(); 19666 19667 if (T.isNull() || !Context.getLangOpts().RecoveryASTType) 19668 // We don't know the concrete type, fallback to dependent type. 19669 T = Context.DependentTy; 19670 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 19671 } 19672